• No results found

Selenium Java Interview Questions

N/A
N/A
Protected

Academic year: 2021

Share "Selenium Java Interview Questions"

Copied!
22
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

Advantage of Selenium over QTP

1 Free (No license fees is required)

2 Support large number of browser(QTP support only 3)

3 Support large number of programming language(C#, Java, Python, Perl etc), QTP support only VB script 4 With the help of grid we can execute multiple test cases in parallel, ultimately we are saving lot of execution time, this kind of feature not available in QTP

Advantage of QTP over Selenium

1 User Friendly, Easy to work on

2 Can develop test cases in much faster way as compared to Selenium 3 Support all type of application(client-server, window , web)

4 Limited programming skills are required

Difference between Selenium IDE, RC and WebDriver

Selenium IDE

Selenium RC

Selenium WebDriver

It only works in Mozilla

browser.

It supports with all browsers

like Firefox, IE, Chrome, Safari,

Opera etc.

It supports with all browsers

like Firefox, IE, Chrome, Safari,

Opera etc.

It supports Record and

playback

It doesn’t supports Record and

playback

It doesn’t supports Record and

playback

Doesn’t required to start server

before executing the test script.

Required to start server before

executing the test script.

Doesn’t required to start server

before executing the test script.

It is a GUI Plug-in

It is standalone java program

which allow you to run Html

test suites.

It actual core API which has

binding in a range of languages.

Core engine is Javascript based

Core engine is Javascript based

Interacts natively with browser

application

Very simple to use as it is

record & playback.

It is easy and small API

As compared to RC, it is bit

complex and large API.

It is not object oriented

API’s are less Object oriented

API’s are entirely Object

oriented

It doesn’t supports of moving

mouse cursors.

It doesn’t supports of moving

mouse cursors.

It supports of moving mouse

cursors.

Need to append full xpath with

‘xpath=\\’ syntax

Need to append full xpath with

‘xpath=\\’ syntax

No need to append full xpath

with ‘xpath=\\’ syntax

It does not support to test

iphone/Android applications

It does not support to test

iphone/Android applications

It support to test

iphone/Android applications

(3)

Firefox

FirefoxDriver driver = new FirefoxDriver();

Chrome Driver

System.setProperty("webdriver.chrome.driver", "path of chrome driver executable"); ChromeDriver driver = new ChromeDriver();

IE Driver

System.setProperty("webdriver.ie.driver", "path of ie driver executable"); InternetExplorerDriver driver = new InternetExplorerDriver();

All Supported Element Locators in Selenium

Supported in RC

Supported in Webdriver

Element Locator

id= findElementById Id name= findElementByName Name identifier= Not Available Identifier link= findElementByLinkText findElementByPartialLinkText Link css= findElementByCssSelector CSS dom= Not Available DOM xpath=// findElementByXpath XPATH class= findElementByClassName Class Name Not available findElementByTagName Tag Name

What is Annotation

Annotation can be defined as metatag, which holds information about methods which are placed next to it. Unit Testing tool like Junit and TestNg support Annotations

Annotations in Junit

@Test

@Test (timeout=500)

(4)

@Before : Will execute before every @Test Annotation @After : Will execute after every @Test Annotation

@BeforeClass : Will execute before executing any other annotation, execute only once at the start @AfterClass : Will execute after executing all other annotation, execute only once at the end @Ignore : Used with @Test annotation, will skip execution of particular test method

@Parameterized : Used for running my test case with multiple data

Order of Execution

@BeforeClass → @Before → @Test → @After → @AfterClass

Annotations Supported in TestNg

@Test : Marks a class or a method as part of the test.

@BeforeSuite : The annotated method will be run before all tests in this suite have run. @AfterSuite : The annotated method will be run after all tests in this suite have run.

@BeforeTest : The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.

@AfterTest : The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.

@BeforeGroups : The list of groups that this configuration method will run before. This method is guaranteed to run before the first test method that belongs to any of these groups is invoked.

@AfterGroups : The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.

@BeforeClass : The annotated method will be run before the first test method in the current class is invoked.

@AfterClass : The annotated method will be run after all the test methods in the current class have been run.

@BeforeMethod : The annotated method will be run before each test method. @AfterMethod : The annotated method will be run after each test method.

Order of Execution

@BeforeSuite → @BeforeTest → @BeforeGroup → @BeforeClass --> @BeforeMethod @Test → @AfterMethod → @AfterClass → @AfterGroup → @AfterTest→ @AfterSuite

Difference between Junit & TestNg

Junit

TestNg

For reports, we need to use ANT Generate html reports automatically

We can’t create report of 1 test case, only reports for test suites can be generated

Can generate report for test case as well as test suite

Support annotation Support more annotations than Junit, make it more

flexible

Can’t set order of execution of multiple test annotation in single class file

Can set order of execution of multiple test annotation in single class file using priority

(5)

No concept of group execution Can execute particular group of test cases

Build.xml is complex and difficult to understand TestNg.xml is very simple and easy to understand

Can’t set multiple threads(parallel execution) We have option to set threads for parallel

execution(used in Grid)

Different ways to open URL in Webdriver

get() and navigate() both are used to open URL/application in webdriver

Difference is that in case of get() method, we can just open a URL while in case of navigate() method, we can use forward and back button of browser

Navigate() method Get() method driver.navigate().to("http://rediff.com"); driver.navigate().back(); driver.navigate().forward(); driver.get("http://rediff.com");

Wait in Webdriver Or Ajax handling in Selenium Webdriver

1 Thread.sleep(10)

Thread is a java class, we are calling sleep method of that class It will add a forcefully wait at particular point

This is used when we want to always pause our execution at specific point

2 ImplicitWait

Implicitly wait are mainly used when our element on page are taking some time to load

It we don’t add any wait in our script, then our driver will search for element and if not found immediately failed that step

In case of implicitly wait, our driver will wait for specified time(time mentioned in implicitly wait) for that element to be present

This wait will be applicable for “findElements” commands only

This need to placed at the start of test case, will be applied on all “findElements” commands FirefoxDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 3 Explicit Wait (WebdriverWait class)

Explicitly wait (WebdriverWait class), is mainly used when we want to wait in script until a specified condition is satisfied or max timeout we have given

FirefoxDriver driver = new FirefoxDriver();

WebDriverWait wait = new WebDriverWait(driver, 10);

wait.until(ExpectedConditions.textToBePresentInElement(By.id("f_id"), "Hello")); 4 Fluent Wait

It implements Wait interface and we create object of FluentWait class

Here we can set maximum time we should wait for element to be present(withTimeout method) Here we can set after how much time, it will check for element to be present (pollingEvery method) Here we can ignore any exception if it comes at runtime while waiting (ignoring method)

(6)

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(30, SECONDS)

.pollingEvery(5, SECONDS)

.ignoring(NoSuchElementException.class); Working with LIST AND DROPDOWN in selenium

Selenium RC Selenium WEBDRIVER

// Working with List

selenium.addSelection("ElementLocator", "Value"); // Working with Dropdown

selenium.select("ElementLocator", "Value"); // To Work on dropdown or List we need to create object

of Select class

Select dateselect = new

Select(driver.findElementById("f_mydata")); // Here we have 3 options to select an element dateselect.selectByIndex(1);

dateselect.selectByValue("15");

dateselect.selectByVisibleText("MyData");

Taking snapshot in Webdriver

// Creating webdriver object

FirefoxDriver driver = new FirefoxDriver(); driver.get("http://rediff.com");

// Taking screenshot in Webdriver File outSnapshot =

driver.getScreenshotAs(OutputType.FILE); // Use FileUtils class to copy snapshot taken in //previous step to my disk

FileUtils.copyFile(outSnapshot, new File("C:\\snaps.png"));

Difference between Assert and Verify

V

erify: If verify got failed, it will fail that particular step and execution will move to next step, remaining steps will execute of that test case

A

ssert : If assert got failed, execution of that test case will halt on that step, no more steps of that test case will execute

Multiple Windows handling in Webdriver

// Creating webdriver object

FirefoxDriver driver = new FirefoxDriver(); driver.get("http://rediff.com");

// getWindowHandles method of driver class return //a string

// this string is a unique key referencing all //browsers/opend by our webdriver, //we save all values in a Set

Set<String> hs = driver.getWindowHandles(); // Iterating to the set and picking all available values Iterator<String> iter = hs.iterator();

// Setting iterator to work until value exist there while(iter.hasNext())

{

// Here we can perform different actions on window' // here in code we are just moving to the windows // and closing all windows opened by webdriver driver.switchTo().window((String) iter.next()).close(); }

(7)

In selenium, first we pick element locator of all elements on which we are supposed to perform our action and place in a property file(Here property file behave as Object Repository for Selenium)

Now wherever in our test case, element locator value is required. We fetch element locator value from properties file (this is called properties file because extension of this file is .properties)

To fetch value of element locator from property file, we need to create object of “ResourceBundle” class and by that object we can use getString method.

What are Desired Capabilities?

Desired Capabilities help to set properties for the Web Driver. A typical use case would be to set the path for the Firefox Driver if your local installation doesn't correspond to the default settings.

DesiredCapabilities capabilities = DesiredCapabilities.firefox(); capabilities.setCapability(CapabilityType.PROXY, proxy); How to perform Keyboard and Mouse Operations in Selenium Or

How to Handle Page onLoad Authentication

For attachment and downloading we need to perform some keyboard or mouse operations, for that we have few options in Selenium

2 Through Actions class of Selenium Webdriver  To perform keyboard operation  To perform mouse operation  Perform Right Click

 Perform double click  Drag and Drop

 Scroll Up and down the window Actions action = new Actions(driver); action.click();

action.doubleClick();

action.dragAndDrop(By.id("sourceelementlocator"), By.id("destinationelementlocator"));

action.contextClick(); // Right Click action.keyDown(Keys.CONTROL);

// Move cursor to the Other Element WebElement mnEle =

dr.findElement(By.id("shop"));

action.moveToElement(mnEle).perform(); 1. Through ROBOT Class of JAVA

 To perform keyboard operation  To perform mouse operation Robot action = new Robot();

action.keyPress(KeyEvent.VK_0); action.keyRelease(KeyEvent.VK_0);

action.mousePress(MouseEvent.MOUSE_CLICKED); action.mouseMove(10, 20);

3 AutoIT (Page Onload authentication and Keyboard and Mouse Operations)

Sometimes when you are Automating Web pages, you may come across Page onload Authentication window. This window is not java popup/div. It is windows popup. Selenium directly cannot handle this windows popup. This tool can also be used to handle windows that’s comes while attaching and downloading attachment with email.

What is POM in Selenium ? What is its advantage ?

POM refers to Page Object Model which encapsulate the internal state of a page into a single page

object. UI changes only affect to a single Page Object, not to the actual test codes.

Advantages :

(8)

Reduces the amount of duplicated code.

How can we get the font size, font color, font type used for a particular text on a webpage using

Selenium web driver?

driver.findelement(By.Xpath("Xpath ").getcssvalue("font-size” or “font-colour” or “font-type”);

How to overcome same origin policy through web driver?

DesiredCapabilities capability=new DesiredCapabilities();

capability.setCapability(CapabilityType.PROXY,"http://wpadnod.microsft.com/wpad.dat");

FirefoxDriver f = new FirefoxDriver(capability);

How to Get page title in selenium webdriver ?

driver.getTitle();

How to Get Current Page URL In Selenium WebDriver

driver.getCurrentUrl();

Check Whether Element is Enabled Or Disabled In Selenium Web driver.

boolean fname = driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();

System.out.print(fname);

Above syntax will verify that element (text box) fname is enabled or not. You can use it for any input

element.

Does WebDriver support file uploads?

Yes, You can't interact with the native OS file browser dialog directly, but we do some magic so that

if you call WebElement#sendKeys("/path/to/file") on a file upload element, it does the right thing.

Make sure you don't WebElement#click() the file upload element, or the browser will probably hang.

Difference between Absolute path & Relative path.

Absolute path will start with root path (/) and Relative path will from current path (//)

How do you verify if the checkbox/radio is checked or not ?

driver.findElement(By.xpath("xpath of the checkbox/radio button")).isSelected();

How do you handle alert pop-up ?

To handle alert pop-ups, we need to 1st switch control to alert pop-ups then click on ok or cancle

then move control back to main page.

Syntax-String mainPage = driver.getWindowHandle();

Alert alt = driver.switchTo().alert(); // to move control to alert popup

alt.accept(); // to click on ok.

alt.dismiss(); // to click on cancel.

//Then move the control back to main web

page-driver.switchTo().window(mainPage); → to switch back to main page.

How to get typed text from a textbox ?

(9)

What is WebDriverBackedSelenium ?

WebDriverBackedSelenium is a kind of class name where we can create an object for it as below:

Selenium wbdriver= new WebDriverBackedSelenium(WebDriver object name, "URL ")

The main use of this is when we want to write code using both WebDriver and Selenium RC, we

must use above created object to use selenium commands.

How to get the number of frames on a page ?

List &lt;WebElement&gt; framesList = driver.findElements(By.xpath("//iframe"));

int numOfFrames = frameList.size();

(10)
(11)

Why JAVA code is machine and platform independent?

When we compile java code, it convert java file to byte code (class file) rather than machine code,

byte code is machine and platform independent (.class file). We can interpret these class file to any

machine having JVM, JVM is used to interpret class file and convert it to machine dependent code

and then execute it.

What are different types of access

modifiers?-Access modifiers are used while creating class, method or variable.

public: Any thing declared as public can be accessed from anywhere.

private: Any thing declared as private can be accessed inside class only can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages.

Default : Can be accessed only to classes in the same package. What is Garbage Collection and how to call it

explicitly?-When an object is no longer referred to by any variable, java/JVM automatically reclaims memory used by that object. This is known as garbage collection.

System. gc() method may be used to call it explicitly.

What do you understand by keywords String , StringBuffer and StringBuilder ?

Strings can be handled by 3 classes in Java: String, StringBuffer, StringBuilder

String

StringBuffer

StringBuilder

String Class is immutable

StringBuffer is mutable

StringBuilder is mutable

object cannot be modified (all

changes that we are

doing(uppercase, lowercase,

substring etc) on string object,

is creating a new string object

and old data still persist and

become garbage(lot of garbage

is generating, impact on

performance)

objects can be modified

objects can be modified

StringBuffer is thread

safe(synchronized) but slow

StringBuilder is not thread safe(not synchronized) and fast

This keyword in java

This keyword can be used with variable, with the help of this keyword we can set which one is class variable and which one is local variable(this.variable name shows , this is a class variable)

This keyword can also be used to call current class overloaded constructor. This keyword can be used to call current class methods

(12)

Static keyword in Java

Static keyword in Java can be used with variable, method and nested class(class inside another class)

static variable: static variable holds single memory location independent to number of objects we have created, all objects will access data from same memory location.

static methods: static methods are like static variable holds single memory location for all objects. STATIC methods/variable can be called by the class name itself without creating object of the class Static nested class object created without creating object of its outer class

Methods, variables which are not static is called instance variable/methods Super keyword in Java

Super keyword in java is used to call parent class override method or parent class constructor Super Class Method Calling

1--> In case child class override, parent class method. When we create child class object and call override method it will access child class method but if we want to access parent class method, we are going to use super keyword

Super Class Constructor Calling

2--> super keyword is used to call parent class constructor as well Difference between

:-`

Abstract Method Concrete Method

Methods which are just declared not defined or method without body.

Methods which are declared and defined as well or method with body.

Abstract Class Concrete Class

Class with abstract & concrete methods. Having at least 1 abstract method

Class with concrete methods only

Cannot create object of abstract class Can create object of concrete class

Abstract Class Interface

Class with Abstract + Concrete methods Interface can have only abstract methods Can have constants as well as variable Variable declared are by default final(means

constants)

We can inherit only 1 class We can inherit multiple interface(by this way java is supporting multiple inheritance)

(13)

JAVA OOPS Concepts

Polymorphism: means same name multiple use.

Overloading and Overriding concept in java implements polymorphism 2 type polymorphism: Compile Time and RunTime

Overriding is a runtime polymorphism as 2 methods are having same name and signature so at the run time it is decided which method to call

Overloading is a compile time polymorphism, as while compiling JVM knows which method is to call by number and type of arguments

Inheritance: With the help of inheritance, we can transfer the properties of a class to child class Data Encapsulation: Wrapping up of data and function in a single unit is called encapsulation. In java class implements the concept of encapsulation

Data Abstraction: Make class/ methods abstract

Abstract class and Interface implements the concept of Data Abstraction

What is method overloading and method overriding?-Method Overloading:

When more than 1 method in a class having the same method name but different signature

(Different signature means different number and type of arguments) is said to be method overloading. Method Overriding:

When patent and child class have same name and same signature (signature means number and type of arguments) method, this is called method overriding.

(Method overriding exist in case of inheritance only, when we are making parent-child relationship between classes)

Inheritance

With the help of inheritance we can transfer the properties of a class to another class Class which is inherited is called Parent Class or Super Class

Class which inherit other class is called Child Class or Sub Class

After inheritance, child class objects can access parent class method and variables . extends is the keyword which is used to inherit class

implements is the keyword which is used to inherit interface Type of Inheritance

Single/Simple Inheritance

Multilevel Inheritance Multiple Inheritance Hybrid Inheritance

Supported in Java Supported in Java Not directly supported (supported through interface)

Not directly supported (supported through interface)

(14)

Constructors

Constructor can be defined as a group of code (same like method) which is used for initialization Initialization means anything that we want to perform at start

Points to

remember:- Constructor name is always same as class name

 Constructor does not return any value so we don’t write void while creating constructor

 Constructors are automatically called when object is created we need not to call them explicitly as we do in methods( as constructor is automatically called when object is created so all code pasted inside constructed is executed before we use class object to call any other methods, that’s why it is called initialization)

We can have more than 1 constructor in a class with different signature, this is called constructor

overloading

Exception handling in Java

1>> throws keyword : we can place throws keyword in front of our method definition and we can mention classes of all exception which we want to handle or we can mention parent class Exception

2>> Try –catch -- finally block

Code that can throw exception, need to be placed in try block

After getting exception, whenever the action we want to perform will be placed in catch block

If we want to perform some task at the end does not matter exception came or not we will paste that code in finally block

We can use try block then catch block

try block then finally block(we can skip catch block) try block then catch block then finally block

Difference between Throw and Throws in Exception handling

1--> Throws is used in Method Signature while Throw is used in Java Code (send the instance of Exception class) 2--> Throws, we can mention multiple type of exception, separated by comma while in throw we can set only 1 exception class instance

3-->Throws keyword just throws exception need not to handle it, throw pass exception instance to caller program

What do you understand by keywords final, finalize and

finally?-final :

final keyword can be used for class, method and variables. A final class cannot be inherited, a final method can’t be override. A final variable becomes constant, we can’t change its value finally :

finally, keyword used in exception handling.

It is used with a block of code that will be executed after a try/catch block has completed The finally block will execute whether or not an exception is thrown.

Means if exception is not throws then Try execute then Finally will execute, in case when exception is thrown finally will execute after catch e

Example : Like we have written DB connection code in try block but exception comes

In that case connection persist with DB and no other user are allowed to create connection, So in that kind of scenario we want whatever the condition comes, may be exception or not, my DB connection should break, for that I’ll paste connection breaking code in finally() block

(15)

finalize() : finalize() method is used to code something that we want to execute just before garbage collection is performed by JVM

Generic Method/ Classes in Java

In java Generic can be used with Methods and Classes

Generic means we create generic method which serves our multiple purposes like we can use same method for multiple tasks like, sorting an integer array, String array etc.

Generic Methods : We can create generic methods which can be called by different type of arguments, methods will server request on the behalf of type of argument coming with request

Collection in Java OR List in Java OR Set in Java or MAP in Java

Collection is a interface, which gives architecture to hold multiple data by same name In JAVA, Collection interface is implemented by Set, List and Map

SET

LIST

MAP

-It is used to hold multiple data (same or different data type)

-Cannot hold duplicate values -Can have maximum 1 null value

-It is used to hold multiple data (same or different data type) - Can hold duplicate values

-Values can be accessed by index same like Array

Map holds data in the form of key value pair

Difference between Array and ArrayList

Array

ArrayList

Use to hold multiple data of single data type Use to hold multiple data of single/diff data type Need to define size of array Need not to define size, size automatically increase

/decrease as we add/remove element Can access data through index Can access data through Iterator

(16)

How to Iterate on HashMap?

Answer: Iterating to List and Set is very simple but in case of HashMap we have to use an extra method "keySet" which pass hashmap object to Iterator

package mypack;

import java.util.HashMap; import java.util.Iterator; import org.junit.Test;

import org.openqa.selenium.ie.InternetExplorerDriver; public class MyClas {

public static void main(String aa[]){ HashMap hp = new HashMap(); hp.put("K1", "Val1");

hp.put("K2", "Val2");

Iterator itr= hp.keySet().iterator(); while(itr.hasNext()){

String k = itr.next().toString(); System.out.println(hp.get(k)); }}}

(17)

Java Programs for Selenium Interview

Interchanging Values of 2 variable without using 3rd Variable

package org.abc;

public class Tst1 {

public static void main(String aa[])

{

int i,j;

i=100;

j=300;

i=i+j ; // 400

j=ij;//

400300

=100 Now j=100

i=ij;

//400100

=300 Now i=300

// Here we can see values exchanged successfully without using 3rd variable

System.out.println(i);

System.out.println(j);

}

}

Printing * Triangle

*

* *

* * *

package mypack;

public class MyClas {

public static void main(String aa[])

{

int Num=3;

int i,j,k;

System.out.println("Star Triangle up to "+Num+" line is below" );

// Here First loop is created for switching line

for(i=0;i<=(Num1);i++) // Taken (num1)here because we started lo0p from 0

{

// Here this loop is created for printing spaces in every line

for(j=5;j>i;j)

{

System.out.print(" ");

}

// Here this loop is created for printing * in every line

for(k=0;k<=i;k++)

{

System.out.print(" * ");

}

(18)

}}}

Print * Triangle

* * * *

* * *

* *

*

package mypack;

public class MyClas {

public static void main(String aa[])

{

int i,j,k;

// Here First loop is created for switching

line

for(i=0;i<=5;i++)

{

// Here this loop is created for

printing spaces in every line

for(j=0;j<=i;j++)

{

System.out.print(" ");

}// inner for loop close

// Here this loop is created for

printing * in every line

for(k=5;k>=i;k)

{

System.out.print(" * ");

}// inner for loop close

System.out.println("");

// Here we are switching to next

line after printing *

}// outer for loop close

}}

Printing Right angle * triangle

*

* *

* * *

package mypack;

public class MyClas {

public static void main(String aa[])

{

int i,j,k;

for(i=0;i<=5;i++)

// Here First loop is created for switching

line

{

for(j=0;j<=2;j++)

// Here this loop is created for

printing spaces in every line

{

System.out.print(" ");

}// inner for loop close

for(k=0;k<=i;k++)

// Here this loop is created for

printing * in every line

{

System.out.print(" * ");

}// inner for loop close

System.out.println("");

// Here we are switching to next

line after printing *

}// outer for loop close

}}

Search Integer element in Array

package mypack;

public class MyClas {

public static void main(String aa[])

{

int datatofind=6, flag=0;

int[] i={2,4,6,78,6,7};

for(int j=0;j<i.length;j++)

if(i[j]==datatofind){

flag=1;

System.out.println("Element

exist in system at index "+ j);

break;

}// if close

if(flag==0)

System.out.println("Element is not

Sorting an Array

package mypack;

public class MyClas {

public static void main(String aa[]){

int datatofind=6, flag=0;

int[] i={2,4,6,78,6,1};

for(int j=0;j<(i.length);j++) {

for(int k=j+1;k<(i.length);k++ ){

if(i[j]>i[k])

{

i[j]=i[j]+i[k];

i[k]=i[j]i[k];

i[j]=i[j]i[k];

}}}

System.out.print("Sorted List ");

for(int j=0;j<(i.length);j++)

(19)

found");

}}

System.out.print(i[j] + " ");

}}

Fabonacci Series upto 100

package mypack;

public class MyClas {

public static void main(String aa[])

{

// Fabonnaci series upto 100

// Fabonacci Series 0,1,1,2,3,5

(next number = add of last 2 numbers)

int a=0,b=1,z=0;

System.out.print(a + " , " + b );

while (z<100)

{

z=a+b;

a= b;

b=z;

if(z<=100)

{

System.out.print(", "+z);

}

}

}

}

All Prime Numbers upto 100

package mypack;

public class MyClas {

public static void main(String aa[])

{

int flag=0;

System.out.print(2 );

for(int k=3;k<=100;k++)

{

for(int j=2;j<k;j++)

{

if(k%j==0)

{

flag=1;

break;

}

}

if(flag==0)

System.out.print(" , "+ k);

else

flag=0;

}// for loop close

}// main () close

Check a number is prime or not

package mypack;

public class MyClas {

public static void main(String aa[])

{

int i=23, m;

// Here i is the number which we want to

test is prime or not

int flag=0;

for(int j=2;j<(i/2);j++)

{

m=i%j;

if(m==0)

{

System.out.println("This

is not a prime number,

divided by " +j);

flag=1;

break;

}

}// for loop close

if(flag==0)

{

System.out.println("This is a

prime number");

}

}}

Check Palendrome

package mypack;

public class MyClas {

public static void main(String aa[])

{

String a="nitin";

String b="";

int k = a.length();

for(int i=(k1); i>=0;i)

b=b+a.charAt(i);

if(a.equals(b))

System.out.println("Palendrome");

else

System.out.println("Not palendrome");

}//main () close

}// class close

(20)

}// class close

Find SubString using logic

package mypack;

public class MyClas {

public static void main(String aa[])

{

String a="Hello World";

String b ="llo W";

int flag=0, lenb= b.length();

try{

for(int j=0;j<(a.length()b.length());j++){

if(a.charAt(j)==b.charAt(0))

{

String sub1= a.substring(j,(j+lenb));

if(b.equals(sub1))

{

flag=1;

System.out.println("Sub String is

Found");

break;

}// inner if close

}// outer if close

}// for loop close

if(flag==0)

System.out.println("Substring not

found");

}// try block close

catch(Exception ex){

System.out.println(ex.getMessage());

}

}}

Search Element in String Array

public class MyClas {

public static void main(String aa[]){

int flag=0;

String datatofind="is";

String[] i={"my","data","is","here"};

for(int j=0;j<i.length;j++){

if(i[j].equals(datatofind)){

flag=1;

System.out.println("Element

exist in system at index "+ j);

break;

}}

if(flag==0)

Reverse a String

Logic 1:

package mypack;

public class MyClas {

public static void main(String aa[])

{

String a="Hello World";

int x=a.length();

System.out.println(x);

// display length of string

for(int j=0;j<(x);j++)

System.out.print(a.charAt((xj1)));

} }

Logic 2:

package mypack;

public class MyClas {

public static void main(String aa[])

{

String a="Hello World";

String b="";

int x=a.length();

System.out.println(x);

// display length of string

for(int j=0;j<(x);j++)

b=b+a.charAt((xj1));

System.out.println(b);

}}

Sorting of String Array

public class Case1 {

public static void main(String aa[]) throws

AWTException{

int i,j;

String[]arrString={"Nitin","Amit","Sumit","Kapil"};

for(i=0;i<(arrString.length1);i++){

for(j=(i+1);j<arrString.length;j++){

if(arrString[i].compareTo(arrString[j])>0)

{

String s=arrString[i];

arrString[i]=arrString[j];

arrString[j]=s;

}

}

}

for(i=0;i<(arrString.length);i++)

(21)

System.out.println("Element is not

found");

}}

System.out.println(arrString[i]);

}}

(22)

References

Related documents

The same re- sult was found from the estimation of the error correction model in previous section 5.2 in table 4, which is reassuring for the robustness of our findings: Brazil’s

AACSB: Analytic AICPA BB: Critical Thinking AICPA FN: Reporting, Measurement Bloom's: Apply Difficulty: Medium Learning Objective: 06-05 Analyze and interpret the

If a super class method is protected then overriding method _________. Select

The ABC Program uses an automated self-service-based border clearance kiosk solution (the “ABC System”) to partially automate the processing of eligible travellers

Da, Decentralized sliding mode adaptive controller design based on fuzzy neural networks for interconnected uncertain nonlinear systems, IEEE Trans. Morris, Fuzzy neural networks

The purpose of this study was to evaluate whether domestic dishwashers used in small establishments that generate a low volume of utensils per day are capable of staying within

Jazz Degrees: Jazz Minor (for music majors only), Bachelor’s of Music in Music Performance, Music Business, Music Education, or Musical Studies (Composition or Music

or receive regular instruction by a private tutor who fails to have the child enrolled in school or who fails to send the child to school, or to have him or her instructed by