Automation Using Selenium Webdriver

Tuesday, 22 November 2016

Top 13 Java Interview Questions on Static keyword

1.what is static in java?

  • Static is a keyword in java.
  • One of the Important keyword in java.
  • Clear understanding of static keyword is required to build projects.
  • We have static variables, static methods , static blocks. 
  • Static means class level.

2.Why we use static keyword in java?

  • Static keyword is mainly used for memory management.
  • Static variables get memory when class loading itself.
  • Static variables can be used to point common property all objects.

3.What is static variable in java?

  • Variables declared with static keyword is known as static variables.
  • Static variables gets memory on class loading.
  • Static variables are class level.
  • If we change any static variable value using a particular object then its value changed for all objects means it is common to every object of that class.
  • static int a,b;

  1. package com.instanceofjavastatic;
  2. class StaticDemo{
  3.  
  4. static int a=40;
  5. static int b=60;
  6.  
  7. }


  • We can not declare local variables as static it leads to compile time error "illegal start of expression".
  • Because being static variable it must get memory at the time of class loading, which is not possible to provide memory to local variable at the time of class loading.
  • We can not declare local variables as static it leads to compile time error "illegal start of expression".
  • Because being static variable it must get memory at the time of class loading, which is not possible to provide memory to local variable at the time of class loading.

  1. package com.instanceofjava;
  2. class StaticDemo{
  3.  
  4. static int a=10;
  5. static int b=20;
  6.  public static void main(String [] args){
  7.  
  8.    //local variables should not be static
  9.  static int a=10;// compile time error: illegal start of expression
  10. }
  11. }

4. what is static method in java with example

  • Method which is having static in its method definition is known as static method.

  1. static void show(){
  2.  
  3. }
  • JVM will not call these static methods automatically. Develioper needs to call these static methods from main method or static block or variable initialization.
  • Only Main method will b called by JVM automatically.
  • We can call these static methods by using class name itself no need to create object.
Read more 

 5.what is static block in java?

  •  Static blocks are the blocks which will have braces and with static keyword.
  • These static blocks will be called when JVM loads the class.
  • Static blocks are the blocks with static keyword.
  • Static blocks wont have any name in its prototype.
  • Static blocks are class level.
  • Static block will be executed only once.
  • No return statements.
  • No arguments.
  • No this or super keywords supported.

 6.What is the need of static block?

  • Static blocks will be executed at the time of class loading.
  • So if you want any logic that needs to be executed at the time of class loading that logic need to place inside the static block so that it will be executed at the time of class loading.

7.Why main method is static in java?
  • To execute main method without creating object then the main method should be static so that JVM will call main method by using class name itself.

8.Can we overload static methods in java?

  • Yes we can overload static methods in java.
Read more  

9.Can we override static methods in java?

  • NO we can not override static methods in java.
Read more  

10.Can we write static public void main(String [] args)?


  • Yes we can define main method like static public void main(String[] args){}
  •  Order of modifiers we can change.

  1. package instanceofjava;
  2. public MainDemo{
  3. static public void main(String [] args){
  4.  
  5. }
  6. }
11.Can we call super class static methods from sub class?
  • Yes we can call super class static methods from sub class.
  • Read more 

TestNG XML example to execute Multiple Classes

TestNG XML example to execute Multiple Classes

In testng.xml file we can specify multiple name (s) which needs to be executed.

In a project there may be many classes, but we want to execute only the selected classes.

We can pass class names of multiple packages also. If say suppose, we want to execute two classes
in one package and other class from some other package.

The below is the example testng.xml which will execute the class names that are specified.

Example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="example suite 1" verbose="1" >
  <test name="Regression suite 1" >
    <classes>
      <class name="com.first.example.Demo1"/>
      <class name="com.first.example.Demo2"/>
      <class name="com.second.example.Demo3"/>
    </classes>
 </test>
</suite>
We need to specify the class names along with packages in between the classes tags.

In the above xml, we have specified class name as “com.first.example.” and “com.first.example.demoOne”
 which are in “com.first.example” package. And class name demoThree is in package “com.second.example.”

All the classes specified in the xml will get executes which have TestNG annotations.

Below are the two example classes under “com.first.example” package which is executed.

Package: “com.first.example”
Classname: Demo1
package com.first.example;

import org.testng.annotations.Test;

public class Demo1 {

@Test
public void firstTestCase()
{
System.out.println("im in first test case from demoOne Class");
}

@Test
public void secondTestCase()
{
System.out.println("im in second test case from demoOne Class");
}
}
Classname: Demo2
package com.first.example;

import org.testng.annotations.Test;

public class Demo2 {

@Test
public void firstTestCase()
{
System.out.println("im in first test case from demoTwo Class");
}

@Test
public void secondTestCase()
{
System.out.println("im in second test case from demoTwo Class");
}
}
Package: “com.second.example”
Classname: Demo3
package com.second.example;

import org.testng.annotations.Test;

public class Demo3 {

@Test
public void firstTestCase()
{
System.out.println("im in first test case from demoThree Class");
}
@Test
public void secondTestCase()
{
System.out.println("im in second test case from demoThree Class");
}
}
We need to run the testng.xml file. (Right click on testng.xml and select Run as ‘TestNG Suite”)
The below is the output for the above example code.

Monday, 21 November 2016

Program to print prime numbers in java

package com.instaceofjava;
public class primenumbers {

public static void main(String[] args) {

int num=50;
int count=0;

for(int i=2;i<=num;i++){

count=0;

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

if(i%j==0){
count++;
break;
}

}

if(count==0){

System.out.println(i);

}

}

}

}
Output:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

Enum in java Example

Java Enum:
  • In this tutorial I will explain what is enum, how to use enum in different areas of a Java program and an example program on it.
  • An Enum type is a special data type which is added in Java 1.5 version. It is an abstract class in Java API which implements Cloneable and Serializable interfaces. It is used to define collection of constants. When you need a predefined list of values which do not represent some kind of numeric or textual data, at this moment, you have to use an enum.
  • Common examples include days of week (values of SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY), directions, and months in a year. Etc.
  • You can declare simple Java enum type with a syntax that is similar to the Java class declaration syntax. Let’s look at several short Java enum examples to get you started.

Enum declaration Example 1:

  1. public enum Day {
  2.  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 
  3. }

Enum declaration Example 2:

  1.  public enum Month{
  2. JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER,
  3. OCTOBER, NOVEMBER, DECEMBER
  4. }
  • Enums are constants; they are by default static and final. That’s why the names of an enum type's fields are in uppercase letters.
  • Make a note that the enum keyword which is used in place of class or interface. The Java enum keyword signals to the Java compiler that this type definition is an enum.
    You can refer to the constants in the enum above like this:




  • Here the ‘day’ variable is of the type ‘Day’ which is the Java enum type defined in the example above. The ‘day’ variable can take one of the ‘Day’ enum constants as value (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY). In this case ‘day’ is set to MONDAY.
  • If you use enum instead of integers or String codes, you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.
  • How to use a Java enum type in various areas in a Java Program:
  • We have seen how to declare simple Java enum types, let’s take a look at how to use them in various areas. We have to use a Java enum type in a variety of situations, including in a Java 5 for loop, in a switch statement, in an if/else statement, and more. For simple, Enum comparison, there are 3 ways to do it. They are, Switch-Case Statement, == Operator, .equals() method. Like that there are other places where you have to use Enum.
  • Let's take a look at how to use our simple enum types with each of these Java constructs.
  1. Enum in IF statement
  2. Enum in Switch statement
  3. Enum Iteration in for-each loop 
  4. Enum Fields 
  5. Enum Methods

    1. Enum in IF statements:


    • We know Java Enums are constants. Sometimes, we have a requirement to compare a variable of Enum constant against the possible other constants in the Enum type. At this moment, we have to use IF statement as follows.
    • Day day = ----- //assign some Day constants to it.
       
    1. If(day ==Day.MONDAY){
    2. ….//your code
    3. } else if (day == Day.TUESDAY){
    4. ….//your code
    5. } else if (day == Day.WEDNESDAY){
    6. ….//your code
    7. } else if (day == Day. THURSDAY){
    8. ….//your code
    9. } else if (day == Day.FRIDAY){
    10. ….//your code
    11. } else if (day == Day.SATURDAY){
    12. ….//your code
    13. } else if (day == Day.SUNDAY){
    14. ….//your code
    15. }

    • Here, you can use “.equals()” instead of “==”. But, my preference is to use “==” because, it will never throws NullPointerException, safer at compile-time, runtime and faster.
    • The code snippet compares the ‘day’ variable against each of the possible other Enum constants in the ‘Day’ Enum.

    2. Enums in Switch Statements:


    • Just assume that your Enum have lot of constants and you need to check a variable against the other values in Enum. For a small Enum IF Statement will be OK. If you use same IF statement for lot of Enum constants then our program will be increased and it is not a standard way to write a Java program. At this Situation, use Switch Statement instead of IF statement.
    • You can use enums in switch statements as follows:
    • Day day = ...  //assign some Day constant to it

    1. switch (day) { 
    2.     
    3. case SUNDAY   : //your code; break; 
    4. case MONDAY //your code; break;
    5. case TUESDAY    : //your code; break;     
    6. case WEDNESDAY    : //your code; break;
    7. case THURSDAY: //your code; break;
    8. case FRIDAY    : //your code; break;
    9. case SATURDAY    : //your code; break;
    10.  
    11. }

    • Here, give your code in the comments, “//your code”. The code should be a simple Java operation or a method call..etc 






    Get collection values from hashtable example

    Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

    1.Basic java collection framework example program to get Value collection from hashtable

    •   Collection values()   This method used to get collection of values
    •  Important note is that if any value is removed from set the original hashtable key also removed
    1. package com.setviewHashtable;
    2.  
    3. import java.util.Hashtable;

    4. import java.util.Enumeration;
    5. import java.util.Iterator;
    6. import java.util.Set;
    7.  
    8. public class HashtableExample{
    9.  
    10. public static void main(String[] args) {
    11.   
    12.  //create Hashtable object
    13.        Hashtable<String,String> hashtable = new Hashtable<String,String>();
    14.        
    15. //add key value pairs to Hashtable
    16. hashtable.put("1","Java Interview Questions");
    17. hashtable.put("2","Java Interview Programs");
    18. hashtable.put("3","Concept and example program");
    19. hashtable.put("4","Concept and interview Questions");
    20. hashtable.put("5","Java Quiz");
    21. hashtable.put("6","Real time examples");
    22.  
    23.  
    24.  Collection c = hashtable.values();
    25.  System.out.println("Values of Collection created from Hashtable are :");
    26. //iterate through the Set of keys
    27.  
    28.  Iterator itr = c.iterator();
    29.  while(itr.hasNext())
    30.  System.out.println(itr.next());
    31.            
    32.  c.remove("Java Quiz");
    33.            
    34. System.out.println("Elements in hash table");
    35. Enumeration e=hashtable.elements();
    36.         
    37.  
    38.  while (e.hasMoreElements()) {
    39.         System.out.println(e.nextElement());
    40. }    

    41. }
    42.  
    43. }



    Output:

    1. Values of Collection created from Hashtable are :
    2. Real time examples
    3. Java Quiz
    4. Concept and interview Questions
    5. Concept and example program
    6. Java Interview Programs
    7. Java Interview Questions
    8. Elements in hash table
    9. Real time examples
    10. Concept and interview Questions
    11. Concept and example program
    12. Java Interview Programs
    13. Java Interview Questions

    You Might Like::