Automation Using Selenium Webdriver

Tuesday, 15 November 2016

How to find uppercase letters in a string in java


  • 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 



  1. package findUppercaseletters.String;
  2. public class FinfUppercaseLetters {
  3.  
  4.     /**
  5.      * 
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.         
  11.   String str= "How to Print Uppercase Letters in Java";
  12.  
  13.     for (int i = 0; i < str.length(); i++) {
  14.     
  15.             if(Character.isUpperCase(str.charAt(i))){    
  16.             System.out.println(str.charAt(i));
  17.             }
  18.             
  19.  }
  20.  
  21. }
  22.  
  23. }

 Output:

  1. H
  2. P
  3. U
  4. L
  5. J


Sort ArrayList in descending order

Descending order:

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. public class SortArrayListDesc {
  7.  
  8.      public static void main(String[] args) {
  9.  
  10.             //create an ArrayList object
  11.             ArrayList arrayList = new ArrayList();
  12.  
  13.             //Add elements to Arraylist
  14.             arrayList.add(1);
  15.             arrayList.add(2);
  16.             arrayList.add(3);
  17.            arrayList.add(4);
  18.             arrayList.add(5);
  19.             arrayList.add(6);
  20.  
  21.             /*
  22.            Use static Comparator reverseOrder() method of Collections 
  23.         utility class to get comparator object
  24.            */
  25.  
  26.          Comparator comparator = Collections.reverseOrder();
  27.  
  28.           System.out.println("Before sorting  : "  + arrayList);
  29.         
  30.  
  31.            /*
  32.               use
  33.               static void sort(List list, Comparator com) method of Collections class.
  34.             */
  35.  
  36.             Collections.sort(arrayList,comparator);
  37.             System.out.println("After sorting  : + arrayList);
  38.  
  39.        }
  40.     }
     

  1. OutPut:
  2. Before sorting  : [1, 2, 3, 4, 5, 6]
  3. After sorting  : [6, 5, 4, 3, 2, 1]

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. public class SortArrayListAsc{
  7.  
  8.      public static void main(String[] args) {
  9.  
  10.             //create an ArrayList object
  11.             ArrayList arrayList = new ArrayList();
  12.  
  13.             //Add elements to Arraylist
  14.             arrayList.add(10);
  15.             arrayList.add(4);
  16.             arrayList.add(7);
  17.            arrayList.add(2);
  18.             arrayList.add(5);
  19.             arrayList.add(3);
  20.  
  21.           
  22.  
  23.           System.out.println("Before sorting  : "  + arrayList);
  24.         
  25.  
  26.            /*
  27.               use
  28.               static void sort(List list) method of Collections class.
  29.             */
  30.  
  31.             Collections.sort(arrayList);
  32.             System.out.println("After sorting  : + arrayList);
  33.  
  34.        }
  35.     }
     

Ascending order:

  1. OutPut:
  2. Before sorting  : [10, 4, 7, 2, 5, 3]
  3. After sorting  : [2, 3, 4, 5, 7, 10]

Monday, 14 November 2016

Top 20 Java Exception handling interview questions and answers

Top 20 Java Exception handling interview questions and answers

1.What is an exception?


>Exceptions are the objects representing the logical errors that occur at run time and makes JVM enters
into the state of  "ambiguity".
>The objects which are automatically created by the JVM for representing these run time errors are known
as Exceptions

2.What are the differences between exception and error.

An Error is a subclass of Throwable that indicates serious problems that a reasonable application
should not try to catch. Most such errors are abnormal conditions.

Difference between exception and error

3.How the exceptions are handled in java

Exceptions can  be handled using try catch blocks.
The statements which are proven to generate exceptions need to keep in try block so that whenever is there any exception identified in try block that will be assigned to corresponding exception class object in catch block
More information about try catch finally

4.What is the super class for Exception and Error

Throwable.


public class Exception extends Throwable implements Serializable


public class Error extends Throwable implements Serializable

5.Exceptions are defined in which java package

java.lang.Exception

6.What is throw keyword in java?

Throw keyword is used to throw exception manually.
Whenever it is required to suspend the execution of the functionality based on the user defined logical
error condition we will use this throw keyword to throw exception.
Throw keyword in java

7.Can we have try block without catch block

It is possible to have try block without catch block by using finally block
Java supports try with finally block
As we know finally block will always executes even there is an exception occurred in try block, Except
 System.exit() it will executes always.
Is it possible to write try block without catch block

8.Can we write multiple catch blocks under single try block?

Yes we can write multiple catch blocks under single try block.
Multiple catch blocks in java





9. What are unreachable blocks in java

The block of statements to which the control would never reach under any case can be called as unreachable blocks.
Unreachable blocks are not supported by java.
Unreachable blocks in java


10.How to write user defined exception or custom exception in java

By extending Exception class we can define custom exceptions.
We need to write a constructor for passing message .
User defined exception in java


class CustomException extends Exception { } // this will create Checked Exception
class CustomException extends IOExcpetion { } // this will create Checked exception
class CustomException extends NullPonterExcpetion { } // this will create UnChecked
exception

11.What are the different ways to print exception message on console.

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.
3 different ways to print exception message in java




12.What are the differences between final finally and finalize in java

Finally vs final vs finalize



13.Can we write return statement in try and catch blocks

Yes we can write return statement of the method in try block and catch block
We need to follow some rules to use it.Please check below link
Return statement in try and catch blocks



14. Can we write return statement in finally block


Yes we can write return statement of the method in finally block
We need to follow some rules to use it.Please check below link
Return statement in finally block




15. What are the differences between throw and throws


  •  throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
  • Using throws keyword we can explicitly provide the information about unhand-led exceptions of the method to the end user, Java compiler, JVM.
  • Throw vs throws

throw%2Bvs%2Bthrows

 16.Can we change an exception of a method with throws clause from unchecked to checked while overriding it? 


  •  No. As mentioned above already
  • If super class method throws exceptions in sub class if you want to mention throws  then use  same class  or its  sub class exception.
  • So we can not change from unchecked to checked 

 17.What are the rules we need to follow in overriding if super class method throws exception ?


  •  If sub class throws checked exception super class should throw same or super class exception of this.
  • If super class method  throws checked or unchecked exceptions its not mandatory to put throws in sub class overridden method.
  • If super class method throws exceptions in sub class if you want to mention throws  then use  same class  or its  sub class exception.



18.What happens if we not follow above rules if super class method throws some exception.

 Compile time error will come.

package MethodOverridingExamplePrograms;
public class Super{
public void add(){
 System.out.println("Super class add method");
}

}

package MethodOverridingInterviewPrograms;
public class Sub extends Super{
  
void add() throws Exception{ //Compiler Error: Exception Exception is not compatible with
throws clause in Super.add()
System.out.println("Sub class add method");

}

}

package ExceptionHandlingInterviewPrograms;
public class Super{
public void add(){
 System.out.println("Super class add method");
}

}

package ExceptionHandlingInterviewPrograms;
public class Sub extends Super{
  
void add() throws NullPointerException{ // this method throws unchecked exception so no
isuues
System.out.println("Sub class add method");

}

}

 19. Is it possible to write multiple exceptions in single catch block


It is not possible prior to java 7.
new feature added in java 7.


package exceptionsFreshersandExperienced;
public class ExceptionhandlingInterviewQuestions{
/**
 * 
 **/
 public static void main(String[] args) {

try {
// your code here
            
} catch (IOException | SQLException ex) {
            System.out.println(e);
}
}
}



20. What is try with resource block

One more interesting feature of Java 7 is try with resource 
In Java, if you use a resource like input or output streams or any database connection logic you always need to close it after using. 
It also can throw exceptions so it has to be in a try block and catch block. The closing logic  should be in finally block. This is a least the way until Java 7. This has several disadvantages:

    You'd have to check if your ressource is null before closing it
    The closing itself can throw exceptions so your finally had to contain another try -catch
    Programmers tend to forget to close their resources

The solution given by using try with resource statement.

try(resource-specification) 
{
//use the resource
}catch(Exception e)
{
//code

}

Top 20 Java Exception handling interview questions and answers for freshers and experienced










Find top two maximum numbers in a array java

  • Hi Friends today we will discuss about how to find top two maximum numbers in an array using java program.
  • For this we have written separate function to perform logic
  • findTwoMaxNumbers method takes integer  array as an argument
  • Initially take two variables to find top to numbers and assign to zero.
  • By using for each loop iterating array and compare current value with these values
  • If our value is less than current array value then assign current value to max1 
  • And assign maxone to maxtwo because maxtwo should be second highest.
  • After completion of all iterations maxone will have top value and maxtwo will have second maximum value.
  • Print first maximum and second maximum values.
  • So from main method create array and pass to findTwoMaxNumbers(int [] ar).


Program #1: Java interview programs to practice: find top two maximum numbers in an array without recursion 

package arraysInterviewPrograms.java;
public class FindTopTwo {
public void findTwoMaxNumbers(int[] array){
       
 int maxOne = 0;
 int maxTwo = 0;
for(int i:array){
    if(maxOne < i){
           maxTwo = maxOne;
           maxOne =i;
     } else if(maxTwo < i){
                maxTwo = i;
     }
}
        
  System.out.println("First Maximum Number: "+maxOne);
  System.out.println("Second Maximum Number: "+maxTwo);
}
     
public static void main(String a[]){
        int num[] = {4,23,67,1,76,1,98,13};
        FindTopTwo obj = new FindTopTwo();
        obj.findTwoMaxNumbers(num);
        obj.findTwoMaxNumbers(new int[]{4,5,6,90,1});
}
}


Output:


First Maximum Number: 98
Second Maximum Number: 76
First Maximum Number: 90
Second Maximum Number: 6

Calling static method from non static method in java

  • Static means class level and non static means object level.
  • Non static variable gets memory in each in every object dynamically.
  • Static variables are not part of object and while class loading itself all static variables gets memory.
  • Like static variables we have static methods. Without creating object we can access static methods.
  • Static methods are class level. and We can still access static methods in side non static methods.
  • We can call static methods without using object also by using class name.
  • And the answer to the question of  "is it possible to call static methods from non static methods in java" is yes.
  • If we are calling a static method from non static methods means calling a single common method using unique object of class which is possible. 


Program #1: Java example program to call static method from non static method. 


;
public class StaticMethodDemo {
void nonStaticMethod(){
        
        System.out.println("Hi i am non static method");
        staticMethod();
 }
    
 public static void staticMethod(){
        
        System.out.println("Hi i am static method");
  }
    
 public static void main(String[] args) {
        StaticMethodDemo obj= new StaticMethodDemo();
        
        obj.nonStaticMethod();
    }
}
 Output:

Hi i am non static method
Hi i am static method

In the above program we have created object of the class and called a non static method on that object and in side non static method called a static method.
So it is always possible to access static variables and static methods in side non static methods

 Program #2: Java example program to call static method from non static method.



Sunday, 13 November 2016

Collections List

List Interface:
List allows Duplicate Elements.
List having index.
List allows n number of null values.
List will display Insertion order with index.
List having classes like :
Vector
ArrayList
LinkedList
Vector:
Vector is a legacy class.
Vector is synchronized.
Vector initial capacity is 10.
Vector allows n number of null values
Vector can be accessible by index.
Vector allows Duplicate Elements.
Program for Vector:

package com.instanceofjavaforus;
import java.util.Enumeration;

import java.util.List;

import java.util.Vector;



public class A{

 public static void main(String[] args) {

 

 Vector vector=new Vector();



 vector.add("india");

 vector.add("jagan");

 vector.add("sam");

 vector.addElement(null);

 vector.addElement(null);
 
  Enumeration em=vector.elements();
 while(em.hasMoreElements()){
  System.out.println(em.nextElement());
 
 }
 }

}
Output:

india
jagan
sam
null

null



ArrayList:

ArrayList is not Synchronized.
Arraylist also allows Duplicate Elements.
ArrayList allows n number of null values.
Arraylist  having insertion order with index.
For retrieve purpose ArrayList is best choice.
ArrayList having Randaom Access Nature.
Program for ArrayList ;



package com.instanceofjava;
import java.util.ArrayList;
import java.util.ListIterator;

import java.util.List;



public class A{

 public static void main(String[] args) {

 

             ArrayList arrayList=new ArrayList();




 arrayList.add("jagan");

 arrayList.add("jagan");

 arrayList.add("upendra");

 arrayList.add(null);

 arrayList.add(null);
 
  ListIterator it=arrayList.listIterator();
 while(it.hasNext()){
  System.out.println(it.hasNext());
 
 }
 }
}

Output:
jagan
jagan
upendra
null
null

LinkedList:

LinkedList is not synchronized.
LinkedList allows n number of null values.
LinkedList allows Duplicate Elements.
LinkedList  having insertion order with index.
Insertion and Deletion purpose LinkedList is better choice.
LinkedList Follows Doubly linked list Structure.
Program for LinkedList:


package com.instanceofjava;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.List;

public class A{

 public static void main(String[] args) {

   LinkedList linkedList=new LinkedList();




 linkedList.add("jagan");

 linkedList.add("jagan");

 linkedList.add("naresh");

 linkedList.add(null);

 linkedList.add(null);


  ListIterator it=linkedList.listIterator();
  while(it.hasNext()){
  System.out.println(it.hasNext());
 
 }
 }
}

Output:


jagan
jagan
naresh
null
null
In List interface if you want  to add elements we can use add() method.
If you want  to remove elements we can use remove() method.

Using Keys Method to Perform Keyboard Actions in Suggestions List Box

There’s always a need to perform keyboard actions in Suggestion List.For that purpose we  can use this ‘org.openqa.selenium.Keys’ method. Here I am sharing the Code, how to do it.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class indianrail
{
public static void main(String[] args) throws Exception
{
FirefoxDriver fd=new FirefoxDriver();
fd.get(“http://www.indianrail.gov.in&#8221;);
fd.findElement(By.linkText(“Trains between Stations”)).click();
Thread.sleep(5000);
fd.findElement(By.id(“txtStationFrom”)).sendKeys(“hyd”);
fd.findElement(By.id(“txtStationFrom”)).sendKeys(Keys.ARROW_DOWN);
fd.findElement(By.id(“txtStationFrom”)).sendKeys(Keys.ENTER);
Thread.sleep(2000);
fd.findElement(By.id(“txtStationTo”)).sendKeys(“bangalo”);
fd.findElement(By.id(“txtStationTo”)).sendKeys(Keys.ARROW_DOWN);
fd.findElement(By.id(“txtStationTo”)).sendKeys(Keys.ARROW_DOWN);
fd.findElement(By.id(“txtStationTo”)).sendKeys(Keys.ENTER);
Thread.sleep(2000);
new Select(fd.findElement(By.name(“lccp_classopt”))).selectByVisibleText(“THIRD AC”);
Thread.sleep(2000);
fd.findElement(By.name(“submit2”)).click();
}
}