Automation Using Selenium Webdriver

Thursday, 1 December 2016

Java Interview programs on Strings

1.Reverse a String Without using String API?


package com.java;

public class ReverseString {

public static void main(String[] args) {

String str="Hello world";
String revstring="";

for(int i=str.length()-1;i>=0;--i){
revstring +=str.charAt(i);
}

System.out.println(revstring);
}
}


Program:

output: dlrow olleH.

2)Sorting the String without using String API?


package com.java;

public class SortString {

 public static void main(String[] args) {

  String original = "edcba";
 int j=0;
   char temp=0;

     char[] chars = original.toCharArray();
     for (int i = 0; i <chars.length; i++) {
         for ( j = 0; j < chars.length; j++) {
         if(chars[j]>chars[i]){
             temp=chars[i];
             chars[i]=chars[j];
              chars[j]=temp;
          }
     }
  }

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

 }
}

program:

output:abcde.

3.Sort the String with using String API?

program:
package com.java;

 public class SortString {

 public static void main(String[] args) {
   String original = "edcba";

   char[] chars = original.toCharArray();
   Arrays.sort(chars);

    String sorted = new String(chars);
     System.out.println(sorted);

}
}




OutPut:abcde

4.Check String is palindrome or not?

program:

Solution #1:

package com.java;

public class PalindromeDemo{

public static void main(String[] args) {

String str="MADAM";
String revstring="";

for(int i=str.length()-1;i>=0;--i){
revstring +=str.charAt(i);
}

System.out.println(revstring);

if(revstring.equalsIgnoreCase(str)){
System.out.println("The string is Palindrome");
}
else{
System.out.println("Not Palindrome");
}

}

}



  Output:

The string is Palindrome

Solution #2:

package com.java;

  import java.util.Scanner;

 public class Palindrome {

public static void main(String[] args)
{

Scanner in = new Scanner(System.in);

 System.out.println("Enter a string");
 String str=in.nextLine();

StringBuffer strone=new StringBuffer(str);
 StringBuffer strtwo=new StringBuffer(strone);

  strone.reverse();

System.out.println("Orginal String ="+strtwo);
System.out.println("After Reverse ="+strone);

if(String.valueOf(strone).compareTo(String.valueOf(strtwo))==0)
   System.out.println("Result:Palindrome");
   else
    System.out.println("Result:Not Palindrome");

   }

}
 Output:

Enter a string
MOOM
Orginal String =MOOM
After Reverse =MOOM

Result:Palindrome

5.Program to Check given number is palindrome or not?

Program:

 package com.java;

import java.util.Scanner;

public class Palindrome {

public static void main(String[] args)
{

System.out.println("Please Enter a number : ");
      int givennumber = new Scanner(System.in).nextInt();
      int number=givennumber;
       int reverse=0;
        while (number != 0) {
           int remainder = number % 10;
            reverse = reverse * 10 + remainder;
            number = number / 10;
        }        
if(givennumber == reverse)
   System.out.println("Result:Palindrome");
    else
    System.out.println("Result:Not Palindrome");
    }

}

 Output:

Please Enter a number :
535
Result:Palindrome.

Super keyword interview questions java

Super Keyword:



The functionality of super keyword is only to point the immediate super class object of the current object.
super keyword is applicable only in the non static methods and super keyword not applicable in the static methods.
super keyword used to access the members of the super class object.
super.member;
It is used to store super class non static members memory reference through current sub class object for separating super class members from subclass members.
We can call super class constructor in sub class using super() call.
We can access super class methods and variables in sub class using super.variable_name, super.method();

Uses of super :


1. By using super keyword we can access super class variables in sub class.

Using super keyword we can access super class variables from sub class.
super.variable_name.
package com.superkeywordinjava;
 public Class SuperDemo{

int a,b;

}

package com.superkeywordinjava;
public Class Subdemo extends SuperDemo{
int a,b;
void disply(){

System.out.println(a);
System.out.println(b);
super.a=10;
super.b=20;

System.out.println(super.a);
System.out.println(super.b);

}

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

obj.a=1;
obj.b=2;

obj.disply();



}
}

Output:

1
2
10
20

2. By using super keyword we can access super class methods in sub class.
Using super keyword we can call super class methods from sub class.
super.method();.

package com.instanceofjavaforus;
 public Class SuperDemo{
int a,b;

public void show() {

System.out.println(a);
System.out.println(b);

}
}

package com.instanceofjavaforus;
public Class Subdemo extends SuperDemo{
int a,b;
void disply(){

System.out.println(a);
System.out.println(b);

super.a=10;
super.b=20;

 super.show();

}

public static void main (String args[]) {

 Subdemo obj= new Subdemo();

obj.a=1;
obj.b=2;

obj.disply();


}
}

Output:

1
2
10
20

3. We can call super class constructor from class constructor:
 By using super keyword we can able to call super class constructor from sub class constructor.
Using super();
For  the super(); call must be first statement in sub class constructor.

package com.superinterviewprograms;
public Class SuperDemo{

int a,b;

SuperDemo(int x, int y){
 a=x;
b=y
System.out.println("Super class constructor called ");
}


}




package com.superinterviewprograms;

public Class Subdemo extends SuperDemo{

int a,b;

SubDemo(int x, int y){
super(10,20);
 a=x;
b=y
System.out.println("Sub class constructor called ");
}

public static void main (String args[]) {
 Subdemo obj= new Subdemo(1,2);


}
}
Output:
Super class constructor called
Sub class constructor called

key points:

Super(); call must be first statement inside constructor.
By default  in every class constructor JVM adds super(); call in side the constructor as first statement which calls default constructor of super class, if we are not not calling it.
If we want to call explicitly we can call at that time default call wont be there.

4.What will happen if  we are calling super() in constructor but our class does not extending any class?

 if our class not extending any class Yes still we can use super(); call in our class
Because in java every class will extend Object class by default this will be added by JVM.
But make sure we are using only super(); default call we can not place parameterized super call because Object class does not have any parameterized constructor.

package com.superinterviewprograms;

public Class Sample{

Sample(){
super();
System.out.println("Sample class constructor called ");

}

public static void main (String args[]) {

 Sample obj= new Sample();

}
}

Output:

Sample class constructor called


5.What if there is a chain of extended classes and 'super' keyword is used


package com.superinterviewprograms;
public Class A{

A(){
 System.out.println("A class constructor called ");
}


}

package com.superinterviewprograms;
public Class B extends A{

B(){

 System.out.println("B class constructor called ");

}


}

package com.superinterviewprograms;
public Class C extends B{

C(){
 System.out.println("C class constructor called ");
}


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


}
}

Output:

A class constructor called
B class constructor called
C class constructor called

6. Can we call super class methods from static methods of sub class?

No we can not use super in static methods of sub class Because super belongs to object level so we can not use super in static methods.
If we try to use in sub class static methods compile time error will come.



Wednesday, 30 November 2016

Advanced Selenium Keypress Using Robot API (JAVA)


Keypress event using Robot API (JAVA)
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class KeyBoardExample {
    public static void main(String[] args) {
        try {
            Robot robot = new Robot();
            robot.delay(3000);
            robot.keyPress(KeyEvent.VK_Q); //VK_Q for Q
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
}

With Selenium::

Sometimes we need to press any key in order to test the key press event on web application. For an instance to test the ENTER key on login form we can write something like below with Selenium WebDriver
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class LoginTest {
 
    @Test
    public void testEnterKey() throws InterruptedException
    {
        WebDriver driver=new FirefoxDriver();      
        Robot robot=null;      
        driver.get("test-url");
        driver.manage().window().maximize();
        driver.findElement(By.xpath("xpath-expression")).click();
        driver.findElement(By.xpath("xpath-expression")).sendKeys("username");
        driver.findElement(By.xpath("xpath-expression")).sendKeys("password");      
        try {
            robot=new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }
        //Keyboard Activity Using Robot Class
        robot.keyPress(KeyEvent.VK_ENTER);
    }
}

Mouse Event using Robot API (JAVA)

import java.awt.Robot;
public class MouseClass {
 public static void main(String[] args) throws Exception {
     Robot robot = new Robot();

     // SET THE MOUSE X Y POSITION
     robot.mouseMove(300, 550);
     }
}import java.awt.Robot;

public class MouseClass {
 public static void main(String[] args) throws Exception {
     Robot robot = new Robot();

     // SET THE MOUSE X Y POSITION
     robot.mouseMove(300, 550);
     }
}


Press left/right button of mouse::

import java.awt.Robot;
import java.awt.event.InputEvent;

public class MouseEvent {
 public static void main(String[] args) throws Exception {
     Robot robot = new Robot();

     // LEFT CLICK
     robot.mousePress(InputEvent.BUTTON1_MASK);
     robot.mouseRelease(InputEvent.BUTTON1_MASK);

     // RIGHT CLICK
     robot.mousePress(InputEvent.BUTTON3_MASK);
     robot.mouseRelease(InputEvent.BUTTON3_MASK);
     }
}

Click and scroll the wheel::

import java.awt.Robot;
import java.awt.event.InputEvent;

public class MouseClass {
 public static void main(String[] args) throws Exception {
     Robot robot = new Robot();

     // MIDDLE WHEEL CLICK
     robot.mousePress(InputEvent.BUTTON3_DOWN_MASK);
     robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);

     // SCROLL THE MOUSE WHEEL
     robot.mouseWheel(-100);
     }
}

Pattern Program in java Part-2

#4 Java Program to print Numbers in Below pattern

1 2 3 4 5 6 7 8 9 
 1 2 3 4 5 6 7 8 
  1 2 3 4 5 6 7 
   1 2 3 4 5 6 
    1 2 3 4 5 
     1 2 3 4 
      1 2 3 
       1 2 
        1 
  1. package com.Java;
  2. public class NumbersFormat {
  3. public static void main(String[] args) {
  4.  
  5. int r, c1,c2;
  6.  
  7. for (r = 1; r <= 10; r++) {
  8.  
  9. for (c1 = 1; c1 <r; c1++) {
  10.   System.out.print(" ");
  11. }
  12.  
  13. for (c2 = 1; c2 <= 10 - r; c2++) {
  14.     System.out.print(c2 + " ");
  15. }
  16.  
  17. System.out.println("");
  18. }
  19.  
  20. }
  21.  
  22. }

Output:
  1. 1 2 3 4 5 6 7 8 9  
  2. 1 2 3 4 5 6 7 8 
  3.   1 2 3 4 5 6 7 
  4.    1 2 3 4 5 6 
  5.     1 2 3 4 5 
  6.      1 2 3 4 
  7.       1 2 3 
  8.        1 2 
  9.         1 




#5 Java Program to Print Numbers in Below pattern:

        1 
       1 2 
      1 2 3 
     1 2 3 4 
    1 2 3 4 5 
   1 2 3 4 5 6 
  1 2 3 4 5 6 7 
 1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 9 10 


  1. package com.Java;
  2. public class NumbersFormat {
  3. public static void main(String[] args) {
  4.  
  5. int r, c1,c2;
  6.  
  7. for (r = 1; r <= 10; r++) {
  8.  
  9. for (c1 = 1; c1 <10-r; c1++) {
  10.   System.out.print(" ");
  11. }
  12.  
  13. for (c2 = 1; c2 <= r; c2++) {
  14.     System.out.print(c2 + " ");
  15. }
  16.  
  17. System.out.println("");
  18. }
  19.  
  20. }
  21.  
  22. }

Output:
  1.         1 
  2.        1 2 
  3.       1 2 3 
  4.      1 2 3 4 
  5.     1 2 3 4 5 
  6.    1 2 3 4 5 6 
  7.   1 2 3 4 5 6 7  
  8. 1 2 3 4 5 6 7 8 
  9. 1 2 3 4 5 6 7 8 9 
  10. 1 2 3 4 5 6 7 8 9 10 


Sunday, 27 November 2016

Java Example Programs Interview

3 different ways to print exception message in java

In Java there are three ways to find the details of the exception .
They are
Using an object of java.lang.Exception
Using public void printStackTrace() method
Using public String getMessage() method.

1.Using an object of java.lang.Exception

 An object of Exception class prints the name of the exception and nature of the exception.
Write a Java program get detailed message details using exception class object

package exceptions;
public class ExceptionDetails {

/**
 *
 **/
 public static void main(String[] args) {

try {

int x=1/0;
         
} catch (Exception e) {
            System.out.println(e);
}

}

}
OUTPUT:
java.lang.ArithmeticException: / by zero
 2.Using  public void printStackTrace() method


This is the method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error class and java.lang.Exception class
This method will display the name of the exception and nature of the message and line number where exception has occurred.

Write a simple java example program to print exception message to console using printStacktrace() method
package exceptions;
public class ExceptionDetails {

    /**
     *
     */
public static void main(String[] args) {


 try {
          int a[]= new int[1];
            a[1]=12
         
} catch (Exception e) {
   e.printStackTrace();
         
 }
}

}

 Output:


java.lang.ArrayIndexOutOfBoundsException: 1
    at exceptions.ExceptionDetails.main(ExceptionDetails.java:13)
  3.Using public String getMessage() method

 This is also a method which is defined in java.lang.Throwable class and it is inherited in to both java.lanf.Error and java.lang.Exception classes.
This method will display the only exception message


Write a Java program print exception message using getMessage() method.
package exceptions;
public class ExceptionDetails {

    /**
     *
     */
    public static void main(String[] args) {


        try {
            int x=1/0;
         
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}

 Output:


 / by zero



How can we count upper case letter in String  java ?
How to find uppercase letters in String  java?
How to find capital letters in string in java?
How u discover the capital letter given sentence?
Yes We can find uppercase or capital letters in a String using isUpperCase() method of Character class 
in java
In order to find number of uppercase letters in a string of all capital letters in a string we need to 
iterate all characters of a string in a loop and check individual characters are uppercase letters or 
not using Character class provided isUpperCase() method.
Program #1: Java example program to find all capital letters / Uppercase letters in a String 


package findUppercaseletters.String;
public class FinfUppercaseLetters {
    /**
     * 
     */
 public static void main(String[] args) {
        
        
  String str= "How to Print Uppercase Letters in Java";
    for (int i = 0; i < str.length(); i++) {
    
            if(Character.isUpperCase(str.charAt(i))){    
            System.out.println(str.charAt(i));
            }
            
 }
}
}
OUTPUT::
H
P
U
L
J

Java program to remove vowels from string java


java program to remove vowels from a string
To remove vowels from a string we can use predefined method of string  replaceAll()
By passing all vowels to the method replaceAll() with empty it will replaces all vowels with empty. 
Check below topic for more programs on string 
Java Experience interview programs on strings

 Program #1: Java example program to remove all vowels from a String



package inheritanceInterviewPrograms;
public class RemoveVowels {
    /**
     * 
     * @String interview programs asked in interviews
     * @Remove vowels from a string in java
     */
 public static void main(String[] args) {
        String str = "RemoveVowels";
        String resustr = str.replaceAll("[aeiouAEIOU]", "");
        System.out.println(resustr);
    }
}

 Output:


RmvVwls


Java example program to reverse vowels in a string.
One more java string interview question for freshers and experienced 
Check below topic for more programs on string 
Java Experience interview programs on strings

Program : Java example program to Reverse Vowels  in a String

package inheritanceInterviewPrograms;
/*
 */
public class ReverseVowels {
    public static String reverseVowels(String string) {
        String vowelsStr = "aeiouAEIOU";
        int lo = 0;
        int hi = string.length() - 1;
        char[] ch = string.toCharArray();
 while (lo < hi) {
     if (!vowelsStr.contains(String.valueOf(string.charAt(lo)))) {
                lo++;
                continue;
       }
    if (!vowelsStr.contains(String.valueOf(string.charAt(hi)))) {
                hi--;
                continue;
       }
    // swaping variables
     swap(ch, lo, hi);
            lo++;
            hi--;
      }
        return String.valueOf(ch);
    }
private static void swap(char[] ch, int lo, int hi) {
        char temparray = ch[lo];
        ch[lo] = ch[hi];
        ch[hi] = temparray;
 }
    
public static void main (String args[]) {
        
         
 System.out.println("After reversing vowels in a string="reverseVowels("InstanceOfjava"));
        
         
}
}
Output:


After reversing vowels in a string=anstancOefjavI
Swap two numbers without using third variable

1. Java Interview Program to Swap two numbers without using third variable in java

package com.instaceofjava;
public class SwapTwoNumbers {
public static void main(String[] args) {
int number1=20;
int number2=30;
System.out.println("Before Swapping");
System.out.println("Value of number1 is :" + number1);
System.out.println("Value of number2 is :" +number2); 
number1=number1+number2;
number2=number1-number2;
number1=number1-number2;
System.out.println("After Swapping");
System.out.println("Value of number1 is :" + number1);
System.out.println("Value of number2 is :" +number2);
}
}
Output:

Before Swapping
Value of number1 is :20
Value of number2 is :30
After Swapping
Value of number1 is :30
Value of number2 is :20
2. Java Program to Swap two numbers by using division and multiplication.


package com.instaceofjava;
public class SwapTwoNumbers {
public static void main(String[] args) {
int number1=20;
int number2=30;
System.out.println("Before Swapping");
System.out.println("Value of number1 is :" + number1);
System.out.println("Value of number2 is :" +number2); 
number1=number1*number2;
number2=number1/number2;
number1=number1/number2;
System.out.println("After Swapping");
System.out.println("Value of number1 is :" + number1);
System.out.println("Value of number2 is :" +number2);
}
}
Output:

Before Swapping
Value of number1 is :20
Value of number2 is :30
After Swapping
Value of number1 is :30
Value of number2 is :20


3. Java Program to Swap two integers by using bit wise operators


package com.instaceofjava;
public class SwapTwoNumbers {
public static void main(String[] args) {
int number1=2;
int number2=4;
System.out.println("Before Swapping");
System.out.println("Value of number1 is :" + number1);
System.out.println("Value of number2 is :" +number2); 
number1=number1^number2;
number2=number1^number2;
number1=number1^number2;
System.out.println("After Swapping");
System.out.println("Value of number1 is :" + number1);
System.out.println("Value of number2 is :" +number2);
}
}
Output:

Before Swapping
Value of number1 is :2
Value of number2 is :4
After Swapping
Value of number1 is :4
Value of number2 is :2

Friday, 25 November 2016

How to Check All the Checkboxes Present in a Page Using Selenium

This post tells you how to check all the checkboxes present in the page.
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;


public class testng_3 {
@Test
public void checkbox() throws Exception
{
FirefoxDriver fd= new FirefoxDriver();
fd.manage().window().maximize();
fd.get(“http://www.flipkart.com/laptops/lenovo~brand/pr?sid=6bo,b5g&otracker=hp_nmenu_sub_electronics_0_Lenovo&#8221;);
Thread.sleep(10000);
List checkBoxes = fd.findElements(By.xpath(“//input[@type=’Checkbox’]”));
System.out.println(checkBoxes.size());
for(int i=0; i<checkBoxes.size(); i++){
System.out.println(checkBoxes.get(i).getText());
checkBoxes.get(i).click();
}
fd.close();
}
}

Java Program to find Max occurred character in a string



  • How to print duplicate characters from string in java?
  • Java program to count number of repeated characters in a string.
  • Java program for printing a repetitive letters in a string
  • count occurrences of each character in string java

  1. package com.javatutorial;
  2.  
  3. public class MaxOccuranceOfChar{
  4.    
  5. public static String MaxOccuredChar(String str) {
  6.  
  7.         char[] array = str.toCharArray();
  8.         int maxCount = 1;
  9.         char maxChar = array[0];
  10.  
  11.   for(int i = 0, j = 0; i < str.length() - 1; i = j){
  12.        int count = 1;
  13.    while (++j < str.length() && array[i] == array[j]) {
  14.           count++;
  15.         }
  16.  
  17.   if (count > maxCount) {
  18.      maxCount = count;
  19.      maxChar = array[i];
  20.  }
  21.  
  22.   }
  23.  
  24.         return (maxChar + " = " + maxCount);
  25.  }

  26.  public static void main(String[] args) {
  27.   
  28.   String str1=MaxOccuredChar("instanceofjava");
  29.   System.out.println(str1);
  30.  
  31.   String str2=MaxOccuredChar("aaaabbbccc");
  32.   System.out.println(str2);
  33.  
  34.   String str3=MaxOccuredChar("ssssiiinnn");
  35.   System.out.println(str3);
  36.  
  37.   String str4=MaxOccuredChar("jaaaavvvvvvvvaaaaaaaaaa");
  38.   System.out.println(str4);
  39.  
  40. }

  41. }


Output:
  1. i = 1
  2. a = 4
  3. s = 4
  4. a = 10