Single Post

Header

Monday, December 21, 2015

Java Simple Programs - 1


1. This Program  contains variables declaration and operators

public class JavaBasics {

public static void main(String[] args)
{
System.out.println("welcome to java");
        int a=20,b=30;  //This is Single Line Comment
        System.out.print("the value of a is "+a+" and b is "+b);
        int c=a+b; int d=a*b; float e=a/b; float f=a%b;
       // System.out.println(c+" "+d+" "+e+" "+f);
        int  x=c=a;
        System.out.println("c ="+c+" x= "+x);
        int y;
        x=1;
        y=x++;
        System.out.println("y ="+y+" x is "+x);
        x=1;
        y=++x;
        System.out.println("y ="+y+" x is "+x);
        boolean i =true;
        boolean j =false;
        System.out.println("or value is "+(i|j)+"and value is "+(i&j));  
}
}
output:
welcome to java
the value of a is 20 and b is 30c =20 x= 20
y =1 x is 2
y =2 x is 2
or value is trueand value is false

2.This Program contains the if-else statement,for and do-while loops

public class JavaLoops {


public static void main(String[] args)
{
int a=10,b=20,c=30;
if(a!=20) { System.out.println("a value is "+a); }
if(a>20){ System.out.println("a value is greater than 20 ");
} else { System.out.println("a value is less than 20 "); }
if(a>b && a>c) {
System.out.println("a is the biggest "+a);
} else if (b>a && b>c) {System.out.println("b is the biggest "+b); } 
else {System.out.println("c is the biggest "+c); }
for(int i=0;i<5;i=i+2) { System.out.println("i value is "+i); }
int x=7;
        while(x<9) { 
        System.out.println("x value is "+x); 
        x=x+1 ; }
        do { 
        System.out.println("x value is "+x);
             x++; } while(x<11) ; 
           
}
}

output:
i value is 4
x value is 7
x value is 8
x value is 9
x value is 10

Simple Java Programs

Simple Java Programs Covering Many Basic Concepts :

1.JavaPractise.java

package JavaBasics;

public class JavaPractise {

   
    public static void main(String[] args)
    {
        // Switch and Do While
        int a=20;
        switch(a)
        {
        case 19: System.out.println("This is 19");
                 break;
        case 20: case 21: System.out.println("This is 20 ");
                 break;
        default : System.out.println("This is default");
        }
      
        do {
            System.out.println("welcome to do while");
            a++;
        } while(a<23);
       
        // Arrays Examples
        int[] arr={23,34,45,55};
        System.out.println(arr[3]);
        String[] str={"india","welcome","java"};
        System.out.println(str[0]);
        int arr1[]=new int[4];
        arr1[2]=22;
        System.out.println(arr1[2]+ " " + arr1[0]);
        String[] s=new String[6];
        s[1]="java";
        System.out.println(s[1]+" "+s[0]);
       
       
    }

}

Output:

This is 20
welcome to do while
welcome to do while
welcome to do while
55
india
22 0
java null

2.StringClass.java

package JavaBasics;

public class StringClass {

   
    public static void main(String[] args)
    {
        char ch='a'; char ch1='c';
        int index,index1,index2;
        String str="Welcome";
        String str2="me";
        index=str.indexOf('a');
        index1=str.indexOf('c');
        index2=str.indexOf(str2);
        System.out.println(str.toUpperCase());
        System.out.println("the not found index is "+index);
        System.out.println("the char index is "+index1);
        System.out.println("the string index is "+index2);
       
       
        String dot=".com";
        String email="meme@me.com";
        if(email.endsWith(dot))
            {
            System.out.println("Valid email address");
            }
       String sub=email.substring(5,7);
       System.out.println(sub);
     //  int x=23; int y=34;
       String s1="abcd";
       String s2="Abcd";
       if(s1.equals(s2))
       {
           System.out.println("both are equal");
            
       }
       if(s1.contains("ab"))
       {
           System.out.println("the given sub string is present");
       }
       char c1=s1.charAt(0);
       System.out.println(c1);
      
       String trim="   Welcome to Java  ";
       System.out.println(trim);
       String aftertrim=trim.trim();
       System.out.println(aftertrim);
       String replace=trim.replace("Java","C++");
       System.out.println(replace);
      
         
    }

}

Output:

WELCOME
the not found index is -1
the char index is 3
the string index is 5
Valid email address
me
the given sub string is present
a
   Welcome to Java 
Welcome to Java
   Welcome to C++ 


3.StaticPublic.java

package JavaBasics;

public class StaticPublic {

    static int a=5;
    int b;
    int c=5;
    StaticPublic()
    {
        a++;
        System.out.println(a);
    }
    static {
        System.out.println("This will execute before the main method");
    }
    static int myMethod()
    {
           return ++a;
    }
   
      public static void main(String[] args)
    {
         StaticPublic obj=new StaticPublic();
    //      System.out.println(b);  Static method can not use non static members directly
          System.out.println("does this execute "+a+" and "+obj.b+obj.c);
          System.out.println("test"+a+obj.c+"test");
          System.out.println(a+obj.c);
          StaticPublic obj1=new StaticPublic();
          StaticPublic obj2=new StaticPublic();
          int r= StaticPublic.myMethod();
          System.out.println("Static method return value "+r);
         
    }

}

Output:
This will execute before the main method
6
does this execute 6 and 05
test65test
11
7
8
Static method return value 9

4.Broom.java

package JavaBasics;

class Cover

{
         static class InnerCover
             {
              void go()
                  {
                       System.out.println("I am the first Static Inner Class");
                  }
            }
 }

class Broom

{
         static class InnerBroom
        {
                  void go1()
                   {
                         System.out.println("I am second Static Inner Class");
                    }
         }

         public static void main(String[] args)
         {

            // You have to use the names of both the classes

            Cover.InnerCover demo = new Cover.InnerCover();

            demo.go();

           // Here we are accessing the enclosed class

            InnerBroom innerBroom = new InnerBroom ();

            innerBroom .go1();

          }
}


Output:

I am the first Static Inner Class
I am second Static Inner Class

5.ArrayListCollections.java

package JavaBasics;
import java.util.*;
public class ArrayListCollections {

  // use an ArrayList when you're not sure how many elements are going to be in a list of items.
    public static void main(String[] args)
    {
        ArrayList ls=new ArrayList();
        ls.add("book");
        ls.add("pen");
        ls.add("pc");
        // To go through each item in your ArrayList you can set up something called an Iterator.
        // This class can also be found in the java.util library
        Iterator ir=ls.iterator();
        while(ir.hasNext())
        {
            System.out.println(ir.next());
        }
        System.out.println("whole list is: "+ls);
        ls.remove(1);
        System.out.println("whole list is: "+ls);
        ls.remove("book");
        System.out.println("whole list is: "+ls);
        System.out.println("Single item is: "+ls.get(0));
    }

}

Output:

book
pen
pc
whole list is: [book, pen, pc]
whole list is: [book, pc]
whole list is: [pc]
Single item is: pc

6.InheritanceOverriding.java

package JavaBasics;

class A
{
    int x;
    public void method(int a)
    {
        System.out.println("This is in class A"+a);
    }
    public void sample()
    {
        System.out.println("This is sample method");
    }
}
class B extends A
{
    public void method(int b)
    {  
        x=6;
        System.out.println("This is in class B "+b+ "and x is "+x);
    }
}

public class InheritanceOverriding
{

    public static void main(String[] args)
    {
        B obj=new B();
       
        obj.method(8);
        obj.sample();
    }

}

Output:

This is in class B 8and x is 6
This is sample method

7.ReadTextFile.java

package JavaBasics;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.*;

public class ReadTextFile
{

    public int nooflines() throws IOException
    {
        FileReader fr=new FileReader("D:\\sample.txt");
        BufferedReader br=new BufferedReader(fr);
        String line1;
        int i=0;
        while((line1=br.readLine())!=null)
        {
            i++;
        }
   
        br.close();
        return i;
    }
   
    public void writeFile() throws IOException
    {
        try {
        FileWriter fw=new FileWriter("D:\\file2.txt");
        BufferedWriter bw=new BufferedWriter(fw);
        fw.write("I am writing this line to file");
        fw.append("This is for appending further");
       
        fw.close();
        }
        catch(Exception e)
        {
            System.out.println("Error Message"+e.getMessage());
        }
    }
   
    public static void main(String[] args) throws IOException
    {
        FileReader fr=new FileReader("D:\\sample.txt");
        BufferedReader br=new BufferedReader(fr);
        String line1=br.readLine();
       
        System.out.println(line1);
        String str[]=new String[10];
        for(int i=0;i<4;i++)
        {
            str[i]=br.readLine();
        }
        System.out.println(str.length);
        for(int j=0;j<str.length;j++)
        {
            System.out.println(str[j]);
        }
        br.close();
        ReadTextFile n=new ReadTextFile();
        int number=n.nooflines();
        System.out.println("the number of lines in the text file is "+number);
        n.writeFile();
    }

}

Output:
abcd
10
bcde
cdef
null
null
null
null
null
null
null
null
the number of lines in the text file is 3

8.ThisJavaProgram.java

package JavaBasics;
/*
 1.this keyword is used to refer current class instance variables
 2.Used to call current class constructor and this() should put at the beginning
*/

public class ThisJavaProgram
{
   int a;
   double b;
  
   ThisJavaProgram(int a,double b)
   {
       this(); 
       this.b=b;
     
   }
   ThisJavaProgram()
   {
       System.out.println("default constructor");
   }
   public void display()
   {
       System.out.println(a+ " "+b);
   }
   public void test()
   {
       display();
   }
   
    public static void main(String[] args)
   {
        ThisJavaProgram obj=new ThisJavaProgram(20,30);
        obj.display();
        obj.test();

    }

}

Output:
default constructor
0 30.0
0 30.0

9.SuperClass.java

package JavaBasics;

/*
 1.super is  used to refer to the parent class instance variable
 2.super() is used to invoke parent class constructors
 3.super is used to invoke immediate parent class methods
 */

class ParentClass
{
    int a=10;
    ParentClass(int x)
    {
        System.out.println("This is ParentClass Constructor "+x);
    }
    public void display()
    {
        System.out.println("This is ParentClass Method");
    }
   
}

class BaseClass extends ParentClass
{
    int a=20;
    BaseClass()
    {
        super(5);
        System.out.println("This is Child Class Constuctor");
        System.out.println("The value of a in ParentClass is "+super.a);
        super.display();
    }
   
   
}

public class SuperClass
{

    public static void main(String[] args)
    {
        BaseClass obj=new BaseClass();
       

    }

}

Output:
This is ParentClass Constructor 5
This is Child Class Constuctor
The value of a in ParentClass is 10
This is ParentClass Method


10. (a) OnlyClass.java

package JavaBasics;

public class OnlyClass
{
   public int a;
   public String str;
   public void myMethod()
   {
       a=20;
       str="india";
       System.out.println(a+" "+str);
              
   }
   
}

(b) AnotherClass.java

package JavaBasics;

public class AnotherClass {

    public String myMethod2()
    {
        return "java";
    }
   
    public static void main(String[] args)
    {
        OnlyClass obj=new OnlyClass();  // Since it is in the same package, import is not required
        obj.myMethod();
        AnotherClass obj2=new AnotherClass();
        System.out.println(obj2.myMethod2());
    }

}

Output:
20 india
java





Java interview programs

Java interview programs

1.
public class Program1 {
public static void main(String args[]) {
int x=5;
boolean b1 = true ;
boolean b2 = false;
if ((x==4) && !b2)
   System.out.print("1 ");
System.out.print("2 ");
if((b2=true) && b1)
System.out.print("3");
}

}

Output:
2 3

2.
public class Program2 {
static String s1 = "java";
     static String s2 = "java";
 
public static void main(String[] args) {
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
}
}

Output:
true
true

3.
public class Program3 {
String s1 = "java";
     String s2 = "java";
public static void main(String[] args) {
System.out.print(s1==s2);
}
}

Output:Excption occurs
Cannot make a static reference to the non-static field s1
Cannot make a static reference to the non-static field s2

4.
public class Program4 {

public static void main(String[] args) {
String s1 = "java";
   String s2 = "java";
System.out.print(s1==s2);
}
}

Output:
true

5.
public class Program5 {
public static void main(String[]  args) {
String str1 = "123";
str1 += "10";
System.out.println(str1);
String str2 = "234";
str2.concat("10");
System.out.println(str2);
String str3 = "345";
str3=str3.concat("10");
System.out.println(str3);
}
}

Output:
12310
234
34510


6.
interface myInterface {
    int a= 8;
    void sample() ;
}

public class InterfaceA implements myInterface {
 //   a = 12;  syntax error
public void sample() {
System.out.println("test");
}
public static void main(String[]  args) {
InterfaceA obj = new InterfaceA();
obj.sample();
}

}

Output:
test

7.
 class A {
public void test() {
System.out.println("class A");
}
}

 class B extends A {
public void test() {
System.out.println("class B");
}
}

public class Overriding {

public static void main(String[] args) {
A a = new A();
a.test();
B b = new B();
b.test();
A a1 = new B();
a1.test();
// B b1 = new A(); cannot convert from A to B
    // b1.test();

}

}

Output:
class A
class B
class B


Java interview programs - Part2

1.Find Maximum and Minium number in the given array.
public class ArrayMinMax {

public static void main(String[] args) {

int numbers[] = { 7, 4, 9, 1, 3, 8, 6 };
int max = numbers[0];
for (int i = 0; i < numbers.length; i++) {
if (max < numbers[i]) {
max = numbers[i];
}
}
System.out.println("max number is " + max);

int min = numbers[0];
for (int i = 0; i < numbers.length; i++) {
if (min > numbers[i]) {
min = numbers[i];
}
}
System.out.println("min number is " + min);

}

}

Output:
max number is 9
min number is 1

2.Sorting the numbers using bubble sort algorithm
public class BubbleSort {

public static void main(String[] args) {

int numbers[] = { 7, 4, 9, 1, 3, 8, 6 };
for (int i = 0; i < numbers.length; i++) {
for (int j = 1; j < (numbers.length - i); j++) {
if (numbers[j - 1] > numbers[j]) {
int temp = numbers[j];
numbers[j] = numbers[j - 1];
numbers[j - 1] = temp;
}
}
}

for (int i = 0; i < numbers.length; i++)
System.out.print(numbers[i] + " ");

}

}

Output:
1 3 4 6 7 8 9 

3.Find factorial of a given number
public class Factorial {

public static void main(String args[]) {
int n = 6;
int fact = 1;
for (int i = 2; i <= n; i++) {
fact = fact * i;
}
System.out.println("The factorial value is " + fact);
}

}

Output:
The factorial value is 720

4.Find Fibonacci series upto given count.
public class Fibonacci {
public static void main(String args[]) {
int f0 = 0, f1 = 1, f2 = 1;
int count = 10;
int i = 0;
System.out.print(f0 + " " + f1 + " " + f2);
while (i <= count) {
f0 = f1;
f1 = f2;
f2 = f0 + f1;
System.out.print(" " + f2);
i++;
}

}

}

Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233

5.Swap two numbers without using 3rd variable
public class Swap {

public static void main(String args[]) {
int a = 30;
int b = 40;
a = a + b;
b = a - b;
a = a - b;
System.out.println(a + "  " + b);
}
}

Output:
40  30

6.TypeCasting program
public class TypeCasting {

public static void main(String[] args) {

int a = 10;
// A data type of lower size is assigned to a data type of higher size
double b = a; // Implicit type casting.
System.out.println(b); // 10.0

// byte –> short –> int –> long –> float –> double

double c = 10.2;
int d = (int) c; // Explicit type casting
System.out.println(d); // 10

long e = 20;
float f = e; // Implicit type casting.
System.out.println(f);

boolean m = true;
// int n = (int) m; // boolean is incompatible for conversion
boolean o = m;
System.out.println(o); // true

float x = 10.2f;
if (x == 10.2) {
System.out.println("same");
}
if (x == 10.2f) {
System.out.println("now float same");
}

double y = 10.2;
if (y == 10.2) {
System.out.println("double same");
}

}

}

Output:
10.0
10
20.0
true
now float same
double same

7.Read text file
package javaprograms;

import java.io.BufferedReader;
import java.io.FileReader;

public class ReadFile {

public static void main(String args[]) throws Exception {
FileReader file = new FileReader("E:\\Selenium\\testFile.txt");
BufferedReader buffered = new BufferedReader(file);
String str;
while((str=buffered.readLine())!=null) {
System.out.println(str);
}
buffered.close();
}

}

Output:
janardhan
bhaskar

8.Reverse Char Array :

public class ReverseString {

public static void main(String[] args) {
char[] var = {'h','e','l','l','o'};
char ch;
for(int i=var.length-1,j=0;j<var.length/2;i--,j++) {
ch=var[i];
var[i] = var[j];
var[j]= ch;
}

for(char c : var) {
System.out.print(c);
}
System.out.println();

for(int k=0;k<var.length;k++) {
System.out.print(var[k]);
}
}


}

Output:
olleh
olleh

9.Try,Catch/Finally :

a.
public class TryCatch {

public void tryCatchArithmeticWrongException() {
try {
int a = 5/0;
System.out.println("This should require either catch/finally");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println("this will not execute");
}

public void tryCatchAnyType() {
try {
int a = 5/0;
System.out.println("This should require either catch/finally");
}
catch(Exception e) {
System.out.println(e);
}
System.out.println("this will execute");
}

public void tryCatchArithmetic() {
try {
int a = 5/0;
System.out.println("This should require either catch/finally");
}
catch(ArithmeticException e) {
System.out.println(e);
}
System.out.println("this will execute");
}

public static void main(String[] args) {
TryCatch obj = new TryCatch();
// obj.tryCatchArithmetic();
// obj.tryCatchAnyType();  // Then this also will not execute
obj.tryCatchAnyType();
obj.tryCatchArithmetic();
obj.tryCatchArithmeticWrongException();

}


}

Output:
java.lang.ArithmeticException: / by zero
this will execute
java.lang.ArithmeticException: / by zero
this will execute
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TryCatch.tryCatchArithmeticWrongException(TryCatch.java:5)
at TryCatch.main(TryCatch.java:42)

b.Try/Catch/Finally return types :

public class TryCatchFinally {

public static int divideone(int a) {
try {
int b=8/a;
System.out.println("this is try block "+b);
return 10;
}
catch(Exception e) {
System.out.println("this is catch block");
return 20;
}
finally {
System.out.println("this is in finally block");
   return 30;
}
}
public static int dividetwo(int a) {
try {
int b=8/a;
System.out.println("this is try block "+b);
return 10;
}
catch(Exception e) {
System.out.println("this is catch block");
return 20;
}
finally {
System.out.println("this is in finally block");
  // return 30;
}
// return a;  // gives error, since we already mentioned return in try block.
}
public static void main(String[] args) {
int value1 = TryCatchFinally.divideone(5);
System.out.println(value1);
TryCatchFinally.divideone(0);
System.out.println(value1);
int value2 = TryCatchFinally.dividetwo(5);
System.out.println(value2);
TryCatchFinally.dividetwo(0);
System.out.println(value2);
}

}

Output:
this is try block 1
this is in finally block
30
this is catch block
this is in finally block
30
this is try block 1
this is in finally block
10
this is catch block
this is in finally block
10


10.Difference between List and Set :

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class ListSet {


public static void main(String[] args) {

System.out.println("List Example");
// List<String> list = new List<String> // List is an interface.
List<String> list = new ArrayList<String>();
list.add("gitam");
list.add("college");
list.add("of");
list.add("engineering");
for(String value : list) {
System.out.print(value+" ");
}

System.out.println("\nSet Example");
Set<String> set = new HashSet<String>();
set.add("gitam");
set.add("college");
set.add("of");
set.add("engineering");
for(String value : set) {
System.out.print(value+" ");
}

System.out.println("List Allows duplicates Example");
// List<String> list = new List<String> // List is an interface.
List<String> duplicates = new ArrayList<String>();
duplicates.add("10");
duplicates.add("20");
duplicates.add("30");
duplicates.add("10");
for(String value : duplicates) {
System.out.print(value+" ");
}

System.out.println("The size of the list now is 3 or 4 : " + duplicates.size());

System.out.println("\nSet Does not allow duplicates Example");
Set<String> noduplicates = new HashSet<String>();
noduplicates.add("10");
noduplicates.add("20");
noduplicates.add("30");
noduplicates.add("10");
for(String value : noduplicates) {
System.out.print(value+" ");
}

System.out.println("The size of the set now is 3 or 4 : " + noduplicates.size());
}

}

Output:
List Example
gitam college of engineering
Set Example
of gitam college engineering List Allows duplicates Example
10 20 30 10 The size of the list now is 3 or 4 : 4

Set Does not allow duplicates Example
20 10 30 The size of the set now is 3 or 4 : 3




Bubble sort and remove duplicates in the list - Java

Bubble sort and remove duplicates in the list - Java

package javaprograms;

import java.util.ArrayList;

public class SortingProgram {


public static void main(String args[]) {

int[] numbers = { 5, 6, 3, 6, 1, 4, 8, 4, 2 };
bubbleSort(numbers);
eliminateDuplicates(numbers);

}

public static void bubbleSort(int numbers[]) {

for (int i = 0; i < numbers.length; i++) {
for (int j = 1; j < (numbers.length - i); j++) {
if (numbers[j - 1] > numbers[j]) {
int temp = numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = temp;
}
}
}

for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");

}
}

public static void eliminateDuplicates(int numbers[]) {

for (int i = 0; i < numbers.length; i++) {
for (int j = 1; j < (numbers.length - i); j++) {
if (numbers[j - 1] > numbers[j]) {
int temp = numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = temp;
}
}
}
        ArrayList<Integer> newArray = new ArrayList<Integer>();
for (int i = 0; i < numbers.length; i++) {
newArray.add(numbers[i]);
}
     
for (int i = 0; i < numbers.length; i++) {
for(int j=i+1; j<numbers.length; j++) {
if(numbers[i] == numbers[j]) {
newArray.remove(numbers[j]);
}
}
}
System.out.println();
for (int i = 0; i < newArray.size(); i++) {
System.out.print(newArray.get(i)+" ");
}
}

}

Output:
1 2 3 4 4 5 6 6 8
1 2 3 4 5 6 8

How to Debug a Java Program

Debugging a Java Program


1.Double click on LeftSide bar  - Icon would come

2.Rht side top corner- Select mode "Debug mode"

3.Click on debugger icon left to run button

4.F6 for debug program line by line execution

5.f8 will execute the program normally.
If two break points are there.f8 would lead to next break point.

There will be "Variables" output values of variables

"Console"  contains  Output of program line by line

Print which values are not present in the second Array

Find which values are not present in the second Array

public class NotPresentInSecondArray {

public static void main(String args[]) {
int[] array1 = {1,2,3,4,5};
int[] array2 = {2,3,1,0,5};
int j;
for (int i=0; i<array1.length;i++) {
int count = 0;
for (j=0; j<array2.length; j++) {
if (array1[i] == array2[j]) {
break;
}
count++;
}
if (count == array2.length) {
System.out.println("The value which is not present in the second array is "
+ array2[i]);
}
}
}
}

Output:
The value which is not present in the second array is 0



Java - Find top two max numbers in the given array

How to find top two max numbers in the given array 

public class TopTwoMaxNumbersInArray {

public static void main(String args[]) {
int[] numbers = {23,34,12,7,90,37,45,52};
int maxFirst = 0;
int maxSecond = 0;
for (int n : numbers) {
if (maxFirst < n) {
maxSecond = maxFirst;
maxFirst = n;
}
else if (maxSecond < n) {
maxSecond = n;
}
}
System.out.println("The first max number is "+ maxFirst);
System.out.println("The second max number is "+ maxSecond);
}
}


Ouput:
The first max number is 90
The second max number is 52



Tuesday, December 8, 2015

Java - Static Feature Examples

Java - Static Feature Examples

package javaPrograms;


public class StaticMemoryManagement {
  int a =20;
  static int b = 30;
  void add() {
    a=a+20;
    b=b+20;
    System.out.println("a is "+a);
    System.out.println("b is "+b);
  }
  static {
    System.out.println("static block is invoked before main method");
  }
  static void staticMethod() {
    System.out.println("static method would be called without need of creating object of a class");
  }
  void nonStaticMethod() {
    System.out.println("test"+b); // Static members are accessible directly by non static methods within class
  }
  public static void main(String args[]) {
    StaticMemoryManagement obj1 = new StaticMemoryManagement();
    obj1.add();
    StaticMemoryManagement obj2 = new StaticMemoryManagement();
    obj2.add();
    StaticMemoryManagement.staticMethod(); // It also works
    staticMethod(); // This also works
    obj1.nonStaticMethod();
    System.out.println(b);  // Static data members are accessible directly by static methods within same class
    System.out.println(obj1.a); // Non static members are accessible through objects only
  }


}


Output :
static block is invoked before main method
a is 40
b is 50
a is 40
b is 70
static method would be called without need of creating object of a class
static method would be called without need of creating object of a class
test70
70
40

Monday, November 23, 2015

How to fetch all links and click one of those links one by one using selenium webdriver

How to get all the links on a webpage and click the matching website

import java.util.List;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class LinksAllTypesMethods {

@Test
public void seleniumLinkMethods() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
Thread.sleep(3000);

// Using tag name "a" , we get all the links
List<WebElement> links = driver.findElements(By.tagName("a"));

// Get how many web links are present on a web page
int numberOfWebLinks = links.size();

// Get the text from the links
for (WebElement link : links) {
System.out.println("The link is "+link.getText());
}

// Using for loop
for (int i=0; i<numberOfWebLinks; i++) {
System.out.println(links.get(i).getText());
System.out.println(links.get(i).getAttribute("href"));
}

// Using tag name "a" , we get all the links
List<WebElement> allLinks = driver.findElements(By.tagName("a"));

// Click on a particular link and break it
   for(WebElement singleLink : allLinks) {
    if (singleLink.getText().equals("हिन्दी")) {
    singleLink.click();
    Thread.sleep(3000);
    break;
    }
   }

driver.close();
}
}


Output :
The link is
The link is Gmail
The link is Images
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is
The link is Sign in
The link is ×
The link is Yes, show me
The link is
The link is
The link is
The link is
The link is हिन्दी
The link is বাংলা
The link is తెలుగు
The link is मराठी
The link is தமிழ்
The link is ગુજરાતી
The link is ಕನ್ನಡ
The link is മലയാളം
The link is ਪੰਜਾਬੀ
The link is Privacy
The link is Terms
The link is Settings
The link is
The link is
The link is
The link is
The link is
The link is Advertising
The link is Business
The link is About

https://www.google.co.in/setprefs?suggon=2&prev=https://www.google.co.in/&sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D
Gmail
https://mail.google.com/mail/?tab=wm
Images
https://www.google.co.in/imghp?hl=en&tab=wi&ei=sHV6Vr-PK8eouQTw07jYBw&ved=0EKouCBIoAQ

https://www.google.co.in/intl/en/options/

https://myaccount.google.com/?utm_source=OGB

https://www.google.co.in/webhp?tab=ww&ei=sHV6Vr-PK8eouQTw07jYBw&ved=0EKkuCAEoAQ

https://maps.google.co.in/maps?hl=en&tab=wl

https://www.youtube.com/?gl=IN

https://play.google.com/?hl=en&tab=w8

https://news.google.co.in/nwshp?hl=en&tab=wn&ei=sHV6Vr-PK8eouQTw07jYBw&ved=0EKkuCAUoBQ

https://mail.google.com/mail/?tab=wm

https://drive.google.com/?tab=wo

https://www.google.com/calendar?tab=wc

https://plus.google.com/?gpsrc=ogpy0&tab=wX

https://translate.google.co.in/?hl=en&tab=wT

https://photos.google.com/?tab=wq

https://www.google.co.in/intl/en/options/

https://docs.google.com/document/?usp=docs_alc

https://books.google.co.in/bkshp?hl=en&tab=wp&ei=sHV6Vr-PK8eouQTw07jYBw&ved=0EKkuCA0oDQ

https://www.blogger.com/?tab=wj

https://www.google.com/contacts/?hl=en&tab=wC

https://www.google.co.in/intl/en/options/
Sign in
https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.co.in/
×
javascript:void(0)
Yes, show me
https://www.google.com/url?q=https://www.google.com/homepage/hp-firefox.html%3Futm_source%3Dgoogle.com%26utm_medium%3Dcallout%26utm_campaign%3DFFDHP&source=hpp&id=5082229&ct=7&usg=AFQjCNGpJYJLVlrP4aS5wSlNy1fQs3_xmg

https://www.google.co.in/webhp?hl=en

https://support.google.com/websearch/answer/186645?hl=en-IN

https://www.google.co.in/search?site=&q=%27Tis+the+season!&oi=ddle&ct=holidays-2015-day-1-6575248619077632-hp&hl=en&sa=X&ved=0ahUKEwjoy72y4fHJAhXMC44KHVivBi4QNggD

javascript:void(0);
हिन्दी
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=hi&source=homepage
বাংলা
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=bn&source=homepage
తెలుగు
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=te&source=homepage
मराठी
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=mr&source=homepage
தமிழ்
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=ta&source=homepage
ગુજરાતી
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=gu&source=homepage
ಕನ್ನಡ
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=kn&source=homepage
മലയാളം
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=ml&source=homepage
ਪੰਜਾਬੀ
https://www.google.co.in/setprefs?sig=0_Qa6VBRR6zqKEKCiglQ9kpgson64%3D&hl=pa&source=homepage
Privacy
https://www.google.co.in/intl/en/policies/privacy/?fg=1
Terms
https://www.google.co.in/intl/en/policies/terms/?fg=1
Settings
https://www.google.co.in/preferences?hl=en

https://www.google.co.in/preferences?hl=en-IN&fg=1

https://www.google.co.in/advanced_search?hl=en-IN&fg=1

https://www.google.co.in/history/optout?hl=en-IN&fg=1

https://support.google.com/websearch/?p=ws_results_help&hl=en-IN&fg=1

javascript:void(0)
Advertising
https://www.google.co.in/intl/en/ads/?fg=1
Business
https://www.google.co.in/services/?fg=1
About
https://www.google.co.in/intl/en/about.html?fg=1


Double click in selenium webdriver


How to double click using Selenium WebDriver

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class DoubleClickOnAnElement {

 @Test
 public void doubleClick() throws InterruptedException {
  WebDriver driver = new FirefoxDriver();
  driver.get("https://www.google.co.in/");
  Thread.sleep(3000);
  WebElement element = driver.findElement(By.name("btnI"));
  Actions action = new Actions(driver);
  action.moveToElement(element).doubleClick().perform();
  Thread.sleep(2000);
  driver.close();  
 }

}

org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up

When do we get "StaleElementReferenceException" while doing with Selenium Web Driver

package SeleniumPractise;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.List;

public class StaleElementReferenceException {

  @Test
  public void getStaleElementReferenceException() throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://docs.seleniumhq.org/");
    driver.manage().window().maximize();
    Thread.sleep(2000);
    List<WebElement> links = driver.findElements(By.tagName("a"));
    for(WebElement link : links) {
      System.out.println(link.getText());
    }
 
    for(WebElement link : links) {
  // We get error here, after click on link and come back to the link web element which is not available
 //  Because the page is moved to the other page where the link web element is not there
      if(link.getText().equals("Who made Selenium"))   {
        link.click();
        Thread.sleep(2000);
      }
    }
 
    driver.close();
  }

 @Test
  public void fixStaleElementReferenceException() throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://docs.seleniumhq.org/");
    driver.manage().window().maximize();
    Thread.sleep(2000);
    List<WebElement> links = driver.findElements(By.tagName("a"));
    for(WebElement link : links) {
      System.out.println(link.getText());
    }
 
    for(WebElement link : links) {
      if(link.getText().equals("Who made Selenium"))   {
        link.click();
        Thread.sleep(2000);
        break;
      }
    }
 
    driver.close();
  }


}


Error Logs for the first menthod above :

org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 18 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'vindukuri1.blr.corp.<company>.com', ip: '172.30.104.73', os.name: 'Linux', os.arch: 'amd64', os.version: '3.13.0-71-generic', java.version: '1.8.0-google-v7'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=43.0, platform=LINUX, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: b2af66d3-35e0-47f0-8e85-c3d05417812b
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:326)
at org.openqa.selenium.remote.RemoteWebElement.getText(RemoteWebElement.java:178)
at SeleniumPractise.getLinksOnPage.getAllLinksOnAWebPage(getLinksOnPage.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'vindukuri1.blr.corp.google.com', ip: '172.30.104.73', os.name: 'Linux', os.arch: 'amd64', os.version: '3.13.0-71-generic', java.version: '1.8.0-google-v7'
Driver info: driver.version: unknown
at <anonymous class>.fxdriver.cache.getElementAt(resource://fxdriver/modules/web-element-cache.js:9351)
at <anonymous class>.Utils.getElementAt(file:///tmp/anonymous5472246950201116367webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:8978)
at <anonymous class>.WebElement.getElementText(file:///tmp/anonymous5472246950201116367webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:11965)
at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///tmp/anonymous5472246950201116367webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12534)
at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///tmp/anonymous5472246950201116367webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12539)
at <anonymous class>.DelayedCommand.prototype.execute/<(file:///tmp/anonymous5472246950201116367webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12481)