1. How to capture screenshot in selenium?
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//The below method will save the screen shot in d drive with name "screenshot.png"
FileUtils.copyFile(scrFile, new File("D:\\screenshot.png"));
2. How to handle SSL certificate in selenium?
//Creating Firefox profile
FirefoxProfile profile=new FirefoxProfile();
// This will set the true value for untrusted connection
profile.setAcceptUntrustedCertificates(true);
// This will open firefox browser using above created profile
WebDriver driver=new FirefoxDriver();
3. How to change the port number in selenium RC?
java -jar selenium-server.jar -port 7777
4. What are the locators available in selenium RC?
6. How to create default selenium object and what are the parameters required to be passed for that?
DefaultSelenium selenium = new DefaultSelenium(“localhost”,4444,”*firefox”,”http://”);
//localhost – It is the machine name and selenium server should be configured in the specific machine
//4444 – It’s selenium port number.
//*firefox – Its is the command to launch firefox
//http:// – Protocol to open URL
10. How to launch FF,Safari and Opera with webdriver?
Mozilla Firefox:
Download WebDriver jar files for Mozilla Firefox. Add all jar files in your project
// Initialize driver
WebDriver dr = new FirefoxDriver();
//Go to URL
dr.get("http://www.google.com");
Safari:
Download Selenium WebDriver for Safari. Add jar file in your project
//Set System property
System.setProperty("webdriver.safari.driver","C:/safaridriver.exe")
// Initialize driver
WebDriver dr = new SafariDriver();
//Go to URL
dr.get("http://www.google.com");
Opera:
Download Selenium WebDriver for Opera. Add jar file in your project
//Set System property
System.setProperty("webdriver.opera.driver", "D:/Ripon/operadriver_win64/operadriver.exe");
// Initialize Opera driver
WebDriver driver = new OperaDriver();
//Go to URL
dr.get("http://google.com");
11. How to launch IE?
System.setProperty("webdriver.ie.driver", driverPath+"IEDriverServer.exe");
driver = new InternetExplorerDriver();
12. How to launch Google Chrome?
System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
driver = new ChromeDriver();
15. How to handle multiple windows?
//To close all the other windows
public static boolean closeAllWindows()
{
Set<String> WindowHandles = driver.getWindowHandles();
for (String currentWindow : WindowHandles)
{
driver.switchTo().window(currentWindow);
driver.close();
}
}
16. How to execute scripts on other machine remotely?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.net.URL;
class RemoteRunTest {
public static void main(String[] args) throws Exception {
URL server = new URL("http://127.0.0.1:4444/wd/hub");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName("firefox");
System.out.println("Connecting to " + server);
WebDriver driver = new RemoteWebDriver(server, capabilities);
driver.get("http://www.google.com");
driver.quit();
}
}
19. How to count total no. of rows of a table using selenium 2.0?
List<WebElement> totalrows = driver.findElements(By.xpath(".//table[@id='TableID']/tbody/tr"));
System.out.println("Total number of rows :"+ totalrows.size());
22. How to verify response 200 code using slenium 2.0?
String url = "http://www.google.com/";
WebClient webClient = new WebClient();
HtmlPage htmlPage = webClient.getPage(url);
//verify response
Assert.assertEquals(200,htmlPage.getWebResponse().getStatusCode());
Assert.assertEquals("OK",htmlPage.getWebResponse().getStatusMessage());
26. What are the ways to use thread in java?
Create a Thread by Implementing a Runnable Interface
Step 1
Implement a run() method provided by a Runnable interface.
public void run( )
Step 2
Instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String tName);
Where, threadObj is an instance of a class that implements the Runnable interface and tName is the name given to the new thread.
Step 3
Call start() method, which executes a call to run( ) method.
void start();
Example:
class RunnableExample implements Runnable {
private Thread t;
private String tName;
RunnableExample( String name) {
tName = name;
System.out.println("Creating " + tName );
}
public void run() {
System.out.println("Running " + tName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + tName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + tName + " interrupted.");
}
System.out.println("Thread " + tName + " exiting.");
}
public void start () {
System.out.println("Starting " + tName );
if (t == null) {
t = new Thread (this, tName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
RunnableExample R1 = new RunnableExample( "Thread-1");
R1.start();
RunnableExample R2 = new RunnableExample( "Thread-2");
R2.start();
}
}
The second way to create a thread is to create a new class that extends Thread class
Step 1
You will need to override run( ) method available in Thread class.
public void run( )
Step 2
Call start() method, which executes a call to run( ) method.
void start( );
Example
class ThreadExample extends Thread {
private Thread t;
private String tName;
ThreadExample( String name) {
tName = name;
System.out.println("Creating " + tName );
}
public void run() {
System.out.println("Running " + tName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + tName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + tName + " interrupted.");
}
System.out.println("Thread " + tName + " exiting.");
}
public void start () {
System.out.println("Starting " + tName );
if (t == null) {
t = new Thread (this, tName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
ThreadExample T1 = new ThreadExample( "Thread-1");
T1.start();
ThreadExample T2 = new ThreadExample( "Thread-2");
T2.start();
}
}
27. String s="Hello" and String s= new String("Hello")(Explain the difference)
String S1 = new String("Hello");
This statement creates a String object in the Heap Memory.
String S1 = "Hello";
This statement creates a String literal with value "Hello" in the String Pool.
Case 1. String Object and Literal
String s1 = "Hello";
String s2 = new String("Hello");
s1 points to String Pool's location
s2 points to Heap Memory location.
if(s1 == s2)
would return false, as the reference variables are checked.
Where as
s2.equals(s1)
will return true as equals function checks the individual characters in both the reference variables.
Case 2: Two String Literals:
Eg:
String s1 = "Hello";
String s2 ="Hello";
if(s1==s2)
will be true.
Case 3: One string object and anonymous literal
String s1 = new String("Hello");
if(s1 == "Hello")
will be false.
28. What is the difference between String and StringBuffer class?
1) Mutability: String is immutable (Once created, cannot be modified) while StringBuffer is mutable (can be modified).
Example –
String str = "Hello World";
str = "Hi World!";
In first statement an object is created using string literal “Hello World”.
In second statement a new object got created in memory.So basically both the objects “Hello World” and “Hi World!” exists in memory having different references(locations).
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
In the first statement StringBuffer object got created using string literal “Hello”
In second statement the value of the object got changed to “Hello World” from “Hello”.
Unlike Strings here the object got modified instead of creating the new object.
Hence String is immutable and StringBuffer is mutable.
29. What is difference between throws and throw?
1) Throw keyword is used to explicitly throw an exception whereas throws keyword is used to declare an exception.
2) Throw is followed by an instance while throws is followed by class.
4) Throw is used within the method while throws is used with the method signature.
5) We cannot throw multiple exceptions but can declare multiple exceptions using throws i.e IOException,SQLException.
Example:
public void test()throws ArithmeticException
{
throw new ArithmeticException("exception is thrown");
}
30. What is throwable?
Throwable is Exception's superclass.Throwable has two direct subclasses, Exception and Error
31. How to swap two numbers without using the third variable?
public class SwapNumWORefrence
{
public static void main(String a[])
{
int x = 10;
int y = 20;
System.out.println("Before swap values are:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
x = x+y;
y=x-y;
x=x-y;
System.out.println("After swap values are:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
}
}
32. What is fluent wait?
FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.
User can configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
// Waiting 60 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait wait = new FluentWait(driver)
.withTimeout(60, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement fw = wait.until(new Function() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("fw"));
}
}
33. Write a program to count number of characters in an array?
public class Countchar {
public static void main(String arg[]) {
String str = "aajoyyyyy";
char[] c = str.toCharArray();
int count = 0;
for (int i = 0; i < c.length; i++) {
// System.out.println(c[i]+" "+i);
boolean flag = true;
for (int k = 0; k < i; k++) {
if (c[i] == (str.charAt(k)))
flag = false;
}
if (flag) {
for (int j = 0; j < str.length(); j++) {
if (c[i] == str.charAt(j))
count = count + 1;
}
System.out.println(c[i] + " " + " " + (count));
count = 0;
}
}
}
}
40. Explain the line "public static void main (String args[])"
public -its the access specifier means from every where we can access it;
static -access modifier means we can call this method directly using class name without creating an object of it;
void - its the return type;
main - method name
string [] args - it accept only string type of argument and stores it in a string .
41. What are the ways in which a thread can enter the waiting state?
The thread can enter its waiting state by
1.invoking its sleep() method
2.invoking its suspend() method
3.whenever an i/o block occurs.
42. What is the difference between yielding and sleeping?
sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).
yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution.
45. What is difference between ArrayList and Linked List?
ArrayList internally uses dynamic array to store the elements.LinkedList internally uses doubly linked list to store the elements.
ArrayList is better for storing and accessing data(search).LinkedList is better for manipulating data(insert or delete).
46. What is difference between List and Set?
1) List is an ordered collection while Set is an unordered collection.
2) List allows duplicates while Set doesn’t allow duplicate elements. All the elements of a Set should be unique if you try to insert the duplicate element in Set it would replace the existing value.
3) List implementations: ArrayList, LinkedList while Set implementations: HashSet, LinkedHashSet, TreeSet etc.
4) List allows any number of null values while Set can have only a single null value at most.
5) Set should be used we want to keep only unique values While if there is a need to maintain the insertion order irrespective of the duplicity then List is a best option.
47. What is difference between Iterators and List Iterators?
1) Iterator can be used for traversing both List and Set while using ListIterator we cab traverse List only not Set.
2) We can traverse in only forward direction using Iterator while ListIterator can be used to traverese in both the directions (forward and Backward).
3) We cannot obtain indexes while using Iterator while we can obtain indexes at any point of time while traversing a list using ListIterator. (by using nextIndex() and previousIndex()).
4) We cannot add element to collection while traversing it using Iterator, it throws ConcurrentModificationException when you try to do it while we can add element at any point of time while traversing a list using ListIterator.
5) We cannot replace the existing element value when using Iterator while by using set(E e) method of ListIterator we can replace the last element returned by next() or previous() methods.
6) Methods of Iterator:
hasNext()
next()
remove()
Methods of ListIterator:
add(E e)
hasNext()
hasPrevious()
next()
nextIndex()
previous()
previousIndex()
remove()
set(E e)
48. What is the use of Super keyword?
super keyword in java is a reference variable that is used to refer immediate parent class object.
Whenever we create the instance of subclass, an instance of parent class is created implicitly i.e. referred by Super reference variable.
super can be used to:
refer immediate parent class instance variable.
invoke immediate parent class constructor(super()).
invoke immediate parent class method.
Example:
class TestSuper{
int x=50;
}
class TestSuper1 extends TestSuper{
int x=100;
void display(){
System.out.println(super.x);
}
public static void main(String args[]){
TestSuper1 b=new TestSuper1();
b.display();
}
}
49. What is the use of This keyword?
this keyword can be used:
to refer the current class instance variable
to invoke the current class constructor
to invoke the current class method
to pass as an argument in the method call
to pass as an argument in the constructor call
to return the current class instance
Example:
class TestThis{
int id;
String name;
TestThis(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
TestThis s1 = new TestThis(123,"Ajoy");
TestThis s2 = new TestThis(456,"Bysacar");
s1.display();
s2.display();
}
}
51. What are Generics?
Java Generic methods is used to specify a set of related methods with a single method declaration
It can also be used to specify a set of related types by using single class declaration
We can write a single generic method declaration that can be called with arguments of different types.
Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately.
Rules to define Generic Methods −
All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > ).
Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.
The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char).
Example
public class GenericMethodTest {
// generic method printArray
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String args[]) {
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("Array integerArray contains:");
printArray(intArray); // pass an Integer array
System.out.println("\nArray doubleArray contains:");
printArray(doubleArray); // pass a Double array
System.out.println("\nArray characterArray contains:");
printArray(charArray); // pass a Character array
}
}
52. What happens when String args[] is not written in main() method?
When main( ) method is written without String args[] as: Public static void main( )
The code will compile but JVM cannot run the code because it cannot recognize the main( ) as the method from were it should start execution of the Java program.
Remember JVM always looks for main( ) method with string type array as parameter.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//The below method will save the screen shot in d drive with name "screenshot.png"
FileUtils.copyFile(scrFile, new File("D:\\screenshot.png"));
2. How to handle SSL certificate in selenium?
//Creating Firefox profile
FirefoxProfile profile=new FirefoxProfile();
// This will set the true value for untrusted connection
profile.setAcceptUntrustedCertificates(true);
// This will open firefox browser using above created profile
WebDriver driver=new FirefoxDriver();
3. How to change the port number in selenium RC?
java -jar selenium-server.jar -port 7777
4. What are the locators available in selenium RC?
- Id
- Name
- Link
- DOM
- Xpath
- CSS
- UI-Elements
6. How to create default selenium object and what are the parameters required to be passed for that?
DefaultSelenium selenium = new DefaultSelenium(“localhost”,4444,”*firefox”,”http://”);
//localhost – It is the machine name and selenium server should be configured in the specific machine
//4444 – It’s selenium port number.
//*firefox – Its is the command to launch firefox
//http:// – Protocol to open URL
10. How to launch FF,Safari and Opera with webdriver?
Mozilla Firefox:
Download WebDriver jar files for Mozilla Firefox. Add all jar files in your project
// Initialize driver
WebDriver dr = new FirefoxDriver();
//Go to URL
dr.get("http://www.google.com");
Safari:
Download Selenium WebDriver for Safari. Add jar file in your project
//Set System property
System.setProperty("webdriver.safari.driver","C:/safaridriver.exe")
// Initialize driver
WebDriver dr = new SafariDriver();
//Go to URL
dr.get("http://www.google.com");
Opera:
Download Selenium WebDriver for Opera. Add jar file in your project
//Set System property
System.setProperty("webdriver.opera.driver", "D:/Ripon/operadriver_win64/operadriver.exe");
// Initialize Opera driver
WebDriver driver = new OperaDriver();
//Go to URL
dr.get("http://google.com");
System.setProperty("webdriver.ie.driver", driverPath+"IEDriverServer.exe");
driver = new InternetExplorerDriver();
12. How to launch Google Chrome?
System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
driver = new ChromeDriver();
15. How to handle multiple windows?
//To close all the other windows
public static boolean closeAllWindows()
{
Set<String> WindowHandles = driver.getWindowHandles();
for (String currentWindow : WindowHandles)
{
driver.switchTo().window(currentWindow);
driver.close();
}
}
16. How to execute scripts on other machine remotely?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.net.URL;
class RemoteRunTest {
public static void main(String[] args) throws Exception {
URL server = new URL("http://127.0.0.1:4444/wd/hub");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName("firefox");
System.out.println("Connecting to " + server);
WebDriver driver = new RemoteWebDriver(server, capabilities);
driver.get("http://www.google.com");
driver.quit();
}
}
19. How to count total no. of rows of a table using selenium 2.0?
List<WebElement> totalrows = driver.findElements(By.xpath(".//table[@id='TableID']/tbody/tr"));
System.out.println("Total number of rows :"+ totalrows.size());
22. How to verify response 200 code using slenium 2.0?
String url = "http://www.google.com/";
WebClient webClient = new WebClient();
HtmlPage htmlPage = webClient.getPage(url);
//verify response
Assert.assertEquals(200,htmlPage.getWebResponse().getStatusCode());
Assert.assertEquals("OK",htmlPage.getWebResponse().getStatusMessage());
26. What are the ways to use thread in java?
Create a Thread by Implementing a Runnable Interface
Step 1
Implement a run() method provided by a Runnable interface.
public void run( )
Step 2
Instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String tName);
Where, threadObj is an instance of a class that implements the Runnable interface and tName is the name given to the new thread.
Step 3
Call start() method, which executes a call to run( ) method.
void start();
Example:
class RunnableExample implements Runnable {
private Thread t;
private String tName;
RunnableExample( String name) {
tName = name;
System.out.println("Creating " + tName );
}
public void run() {
System.out.println("Running " + tName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + tName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + tName + " interrupted.");
}
System.out.println("Thread " + tName + " exiting.");
}
public void start () {
System.out.println("Starting " + tName );
if (t == null) {
t = new Thread (this, tName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
RunnableExample R1 = new RunnableExample( "Thread-1");
R1.start();
RunnableExample R2 = new RunnableExample( "Thread-2");
R2.start();
}
}
The second way to create a thread is to create a new class that extends Thread class
Step 1
You will need to override run( ) method available in Thread class.
public void run( )
Step 2
Call start() method, which executes a call to run( ) method.
void start( );
Example
class ThreadExample extends Thread {
private Thread t;
private String tName;
ThreadExample( String name) {
tName = name;
System.out.println("Creating " + tName );
}
public void run() {
System.out.println("Running " + tName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + tName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + tName + " interrupted.");
}
System.out.println("Thread " + tName + " exiting.");
}
public void start () {
System.out.println("Starting " + tName );
if (t == null) {
t = new Thread (this, tName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
ThreadExample T1 = new ThreadExample( "Thread-1");
T1.start();
ThreadExample T2 = new ThreadExample( "Thread-2");
T2.start();
}
}
String S1 = new String("Hello");
This statement creates a String object in the Heap Memory.
String S1 = "Hello";
This statement creates a String literal with value "Hello" in the String Pool.
Case 1. String Object and Literal
String s1 = "Hello";
String s2 = new String("Hello");
s1 points to String Pool's location
s2 points to Heap Memory location.
if(s1 == s2)
would return false, as the reference variables are checked.
Where as
s2.equals(s1)
will return true as equals function checks the individual characters in both the reference variables.
Case 2: Two String Literals:
Eg:
String s1 = "Hello";
String s2 ="Hello";
if(s1==s2)
will be true.
Case 3: One string object and anonymous literal
String s1 = new String("Hello");
if(s1 == "Hello")
will be false.
28. What is the difference between String and StringBuffer class?
1) Mutability: String is immutable (Once created, cannot be modified) while StringBuffer is mutable (can be modified).
Example –
String str = "Hello World";
str = "Hi World!";
In first statement an object is created using string literal “Hello World”.
In second statement a new object got created in memory.So basically both the objects “Hello World” and “Hi World!” exists in memory having different references(locations).
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
In the first statement StringBuffer object got created using string literal “Hello”
In second statement the value of the object got changed to “Hello World” from “Hello”.
Unlike Strings here the object got modified instead of creating the new object.
Hence String is immutable and StringBuffer is mutable.
29. What is difference between throws and throw?
1) Throw keyword is used to explicitly throw an exception whereas throws keyword is used to declare an exception.
2) Throw is followed by an instance while throws is followed by class.
4) Throw is used within the method while throws is used with the method signature.
5) We cannot throw multiple exceptions but can declare multiple exceptions using throws i.e IOException,SQLException.
Example:
public void test()throws ArithmeticException
{
throw new ArithmeticException("exception is thrown");
}
30. What is throwable?
Throwable is Exception's superclass.Throwable has two direct subclasses, Exception and Error
31. How to swap two numbers without using the third variable?
public class SwapNumWORefrence
{
public static void main(String a[])
{
int x = 10;
int y = 20;
System.out.println("Before swap values are:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
x = x+y;
y=x-y;
x=x-y;
System.out.println("After swap values are:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
}
}
32. What is fluent wait?
FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.
User can configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
// Waiting 60 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait wait = new FluentWait(driver)
.withTimeout(60, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement fw = wait.until(new Function() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("fw"));
}
}
33. Write a program to count number of characters in an array?
public class Countchar {
public static void main(String arg[]) {
String str = "aajoyyyyy";
char[] c = str.toCharArray();
int count = 0;
for (int i = 0; i < c.length; i++) {
// System.out.println(c[i]+" "+i);
boolean flag = true;
for (int k = 0; k < i; k++) {
if (c[i] == (str.charAt(k)))
flag = false;
}
if (flag) {
for (int j = 0; j < str.length(); j++) {
if (c[i] == str.charAt(j))
count = count + 1;
}
System.out.println(c[i] + " " + " " + (count));
count = 0;
}
}
}
}
40. Explain the line "public static void main (String args[])"
public -its the access specifier means from every where we can access it;
static -access modifier means we can call this method directly using class name without creating an object of it;
void - its the return type;
main - method name
string [] args - it accept only string type of argument and stores it in a string .
41. What are the ways in which a thread can enter the waiting state?
The thread can enter its waiting state by
1.invoking its sleep() method
2.invoking its suspend() method
3.whenever an i/o block occurs.
42. What is the difference between yielding and sleeping?
sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).
yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution.
45. What is difference between ArrayList and Linked List?
ArrayList internally uses dynamic array to store the elements.LinkedList internally uses doubly linked list to store the elements.
ArrayList is better for storing and accessing data(search).LinkedList is better for manipulating data(insert or delete).
46. What is difference between List and Set?
1) List is an ordered collection while Set is an unordered collection.
2) List allows duplicates while Set doesn’t allow duplicate elements. All the elements of a Set should be unique if you try to insert the duplicate element in Set it would replace the existing value.
3) List implementations: ArrayList, LinkedList while Set implementations: HashSet, LinkedHashSet, TreeSet etc.
4) List allows any number of null values while Set can have only a single null value at most.
5) Set should be used we want to keep only unique values While if there is a need to maintain the insertion order irrespective of the duplicity then List is a best option.
47. What is difference between Iterators and List Iterators?
1) Iterator can be used for traversing both List and Set while using ListIterator we cab traverse List only not Set.
2) We can traverse in only forward direction using Iterator while ListIterator can be used to traverese in both the directions (forward and Backward).
3) We cannot obtain indexes while using Iterator while we can obtain indexes at any point of time while traversing a list using ListIterator. (by using nextIndex() and previousIndex()).
4) We cannot add element to collection while traversing it using Iterator, it throws ConcurrentModificationException when you try to do it while we can add element at any point of time while traversing a list using ListIterator.
5) We cannot replace the existing element value when using Iterator while by using set(E e) method of ListIterator we can replace the last element returned by next() or previous() methods.
6) Methods of Iterator:
hasNext()
next()
remove()
Methods of ListIterator:
add(E e)
hasNext()
hasPrevious()
next()
nextIndex()
previous()
previousIndex()
remove()
set(E e)
48. What is the use of Super keyword?
super keyword in java is a reference variable that is used to refer immediate parent class object.
Whenever we create the instance of subclass, an instance of parent class is created implicitly i.e. referred by Super reference variable.
super can be used to:
refer immediate parent class instance variable.
invoke immediate parent class constructor(super()).
invoke immediate parent class method.
Example:
class TestSuper{
int x=50;
}
class TestSuper1 extends TestSuper{
int x=100;
void display(){
System.out.println(super.x);
}
public static void main(String args[]){
TestSuper1 b=new TestSuper1();
b.display();
}
}
49. What is the use of This keyword?
this keyword can be used:
to refer the current class instance variable
to invoke the current class constructor
to invoke the current class method
to pass as an argument in the method call
to pass as an argument in the constructor call
to return the current class instance
Example:
class TestThis{
int id;
String name;
TestThis(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
TestThis s1 = new TestThis(123,"Ajoy");
TestThis s2 = new TestThis(456,"Bysacar");
s1.display();
s2.display();
}
}
51. What are Generics?
Java Generic methods is used to specify a set of related methods with a single method declaration
It can also be used to specify a set of related types by using single class declaration
We can write a single generic method declaration that can be called with arguments of different types.
Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately.
Rules to define Generic Methods −
All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > ).
Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.
The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char).
Example
public class GenericMethodTest {
// generic method printArray
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String args[]) {
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("Array integerArray contains:");
printArray(intArray); // pass an Integer array
System.out.println("\nArray doubleArray contains:");
printArray(doubleArray); // pass a Double array
System.out.println("\nArray characterArray contains:");
printArray(charArray); // pass a Character array
}
}
52. What happens when String args[] is not written in main() method?
When main( ) method is written without String args[] as: Public static void main( )
The code will compile but JVM cannot run the code because it cannot recognize the main( ) as the method from were it should start execution of the Java program.
Remember JVM always looks for main( ) method with string type array as parameter.