Java Tutorial | Groovy Tutorial | Java Interivew Questions | Automation Testing | data structures and algorithms in java tutorial

Wednesday, 24 May 2017

Exception Handling In Java With Example Program

Exception Handling in Java- Exception in java is a runtime error that cause due to logical mistake because of wrong input given by user.
Technically exception is a object instance of throwable or its one of subclasses.
When exception raise programme execution terminated abnormally, abnormal means the statement placed after exception causing statement will not be executed.

Example-

We are going to atm to withdraw money suppose in your account you have 500rs but your withdraw amount is 1000 then atm machine will display insufficient fund in your account that is user understandable message but internally it throws InsufficientFundException.There is no predefined exception with name InsufficientFundException but this can be custom exception.

public class StringBufferDemo {
    public static void main(String[] args) {


        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = a/b;
        

        System.out.println("Result :"+c);
    }
}

Input- 10 0
Output- Exception in thread “main” java.lang.ArithematicException.

The above java exception message is not understandable by end-user because it is java programmer related message. It is programmer responsibility to print user understandable message i.e pure English message.
For this purpose we must catch exception in the program itself, we should not allow it to propagate to JVM. After catching exception we must print user a message to take correct values from end user.

Exception Handling Syntax in Java Programming-

// Try With Catch
try
{
...
}
catch(Exception e)
{
}


// Try With Catch And Finally
try
{
...
}
catch(Exception e)
{
...
}
finally
{
...
}


// Try With Only Finally
try
{
...
}
finally
{
...
}


Note-  A try can have multiple Catch blocks but it can have only one finally block.

public class Exception {

    public static void main(String[] args) {

       try {

           int a = Integer.parseInt(args[0]);

           int b = Integer.parseInt(args[1]);

           int c = a/b;

           System.out.println("Result :"+c);

       }catch (ArithmeticException ae) {

           System.out.println("Java Exception Do not pass second value as 0");

       }

    }

}
Input- 10, 0
Output- Java Exception Do not pass second value as 0

Hierarchy of Java Exception Classes-

exception hierarchy in java

When an exception can occur?

Java Exception can occur at runtime (known as runtime exceptions) as well as at compile-time (known as Compile-time exceptions).

Type of Exception in Java-
  • Checked Exception- Directly subclass of exception are checked exception, these exception are called pure checked exception.
  • Unchecked Exception- Error & Runtime Error are unchecked exception it is optional to report.
Exception Rule-
  • ·    Catch block parameter type should be Throwable & any of its subclass if we use other type it lead compile time error incompatible type.
try {
}
catch(ArithmeticException ae){}
catch(String s){}  //Not allowed will throw exception

  • ·    We should not duplicate catch block & also we should not place parent class parameter catch block before child class parameter catch block. It leads to Compile Time Error Exception has already been caught
try {
throw new ArithematicExcpetion();
throw new ArrayIndexOutOfBoundException();
 }
         Catch(ArithmeticException ae) { }
         Catch(ArrayIndexOutOfBoundException aoi){ }
  • ·    After throw keyword we should not place any java statement directly it leads Compiler Error unreachable statement because throw keyword is a transfer statement.
         class A {
           void m1() {
                System.out.println(“hello”);
                throw new ArithmeticException();
                System.out.println(“JavaTechWorld”); //C.E Unreacble Exception
                }
            }

  • After throw keyword we should only place throwable calss object or any of its subclass object. if we place normal object compiler throws imcopatible type error.
         throw new ArithmeticException(); //correct
         throw "abc"; //C.E Incompatible type
  • if we are throwing a checked exception using throw keyworld or receiving a checked exception by method call we must handle that exception eithe by catching using try-catch or by reporting using throws keyword else it leads C.E unreported exception must be caught or declared to be thrown.
         class Test {
                   void m1() {
                           throw new ClassNotFoundException(); //C.E
                     }
            }

           class Test {
                    void m1() {
                          try {
                                throw new ClassNotFoundException();
                          }
                          catch(ClassNotFoundException cnfe) {  //correct way
                                   cnfe.printStackTrace();
                          }
                    }
            }

  • We should not write catch block for checked exception without throwing it from its corresponding try block it leads C.E "Exception never thrown from corresponding try block"
         try {
           }
           catch(ArithematicException ae) {
           }
           catch(ClassNotFoundException cnfe) { /*checked exception not allowed with                                                                                         throwing from its corresponding try block*/
           }  

  • We should not use throw keyword in method prototype & throws keyword in method body leads C.E ';' expected & illegal start od expression.
  • The variable declare in try-catch-finally can not be acess from outside of these block because the variable become local to that block & it is destroy after block execution.
The Throws/Throw Keyword-
Sometimes we explicitly want to create exception object and then throw it to stop the normal processing of the program. throw keyword is used to throw exception to the runtime to handle it.
When we are throwing any checked exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.

The finally Keyword
Typically, we expect the try/catch block to do something or handle exceptions that occurs, then continues the flow of code. What happens if the catch block throws an exception? It is okay to add an other try/catch block inside the catch block. Yet, the code will look confusing if there are several nested catch blocks.
Fortunately, Java allows you to specify a block of code that should be executed whatever happens inside the try/catch block. This block is called the finally  block.

In other words, a finally block help ensure that however the method exit, some cleanup code will be executed.
Example-
public class FinallyExample {
    public static void main(String args[]){
        try{
            int n=30/5;
            System.out.println(n);
        }
        catch(NullPointerException e){System.out.println(e);}
        finally{System.out.println("finally block in java");}
        System.out.println("exception in java -> rest of the code...");
    }
Creating custom checked exception-
Creating your own exception class in java is very simple. All you need
to do is just extend "Exception" class or its subclasses for checked
custom exception and extend RuntimeException or its subclasses for unchecked
custom exception.
Example-
class MyCustomException extends Exception {
    MyCustomException(String s) {
        super(s);
    }
}

Read More
    0

Tuesday, 23 May 2017

StringBuffer and StringBuilder in Java

StringBuffer in Java- It is a thread safe mutable sequence of characters. A string buffer is like a string but can be modified in the same memory location.

In StringBuffer in Java class we have below 4 constructors

1.   public StringBuffer()
Creates empty StringBuffer object with default capacity 16 buffers, it means it has 16 empty location

Example:
StringBuffer sb = new StringBuffer();
System.out.println(“ sb: “ +sb);
System.out.println(“ sb capacity : “+sb.capacity()); //16

2.   public StringBuffer(int capacity)
Creates empty StringBuffer object with the given capacity

Example:
StringBuffer sb1 = new StringBuffer(3);
System.out.println(“ sb1 : “+sb1);
System.out.println(“ sb1 capacity : ”+sb1.capacity()); //3

3.   public StringBuffer(String s)
Creates StringBuffer object with given String object data. It performs string copy from String to StringBuffer object. The default capacity is [16 + s.length()]

Example:
StringBuffer sb2 = new StringBuffer(“abc”);
System.out.println(“ sb2 : “+sb2);  //abc
System.out.println(“ sb2 capacity : “+sb3.capacity());  //19

4.   public StringBuffer(CharSequence cs)
Creats new StringBuffer object with the given CS object characters, it also performs string copy from CS object to StringBuffer object. Its capacity is [16 + cs.lenght() ]

Example:
StringBuffer sb3 = new StringBuffer(“abc”);
StringBuffer sb4 = new StringBuffer(sb3);

System.out.println(“ sb3 : “+sb3); //abc
System.out.println(“ sb4 : “+sb4); //abc
System.out.println( “ sb3 capacity : “+sb3.capacity());  //19
System.out.println( “ sb4 capacity : “+sb4.capacity());  //19
System.out.println( “ sb3 == sb4);  //false
   
StringBuffer Java object creation

In the below diagram as you can see StringBuffer object is created with value "abc" and sb is a refernce variable pointing to 1010 memory location, internally StringBuffer create char[] object with size 3, once we append string buffer object with value "d" new char[] object will be created and it will copy old char[] element into new char[] with appended value "d" this process will repeaat again once we append stringbuffer object with value "e".


StringBuffer Object Diagram
StringBuilder in Java-

StringBuilder in java class is introduced in java 5 version to develop non syncronized StringBuffer object Except this there is no difference between StringBuffer and StringBuilder operation are exactly same.

Operation that we can perform on StringBuffer and StringBuilder Java classes-
  1. Append
  2. insert
  3. Delete
  4. Reverse
  5. Replacing character at given index
Java StringBuffer Example-

/** * Created by namdeva on 24/05/2017. */
public class StringBufferDemo {
    public static void main(String[] args) {
        
        //stringbuffer append        
        StringBuffer sb1 = new StringBuffer("abc");
        StringBuffer sb2 = sb1.append("d");
        System.out.print(sb1+" "+sb2);
        System.out.print(sb1==sb2);

        //stringbuffer insert        
        StringBuffer sb3 = new StringBuffer("12345");
        System.out.print(sb3); //12345
        sb3.insert(2,'/');
        System.out.print(sb3); //12/345
        
        //stringbuffer delete        
        StringBuffer sb4 = new StringBuffer("Java Tech World");
        System.out.print(sb4); // Java World

        sb4.delete(sb4.indexOf("Tech"),sb4.indexOf("Tech")+4);
        System.out.println(sb4);
        
        //stringbuffer reverse       
        StringBuffer sb5 = new StringBuffer("javatechworld");
        sb1.reverse();
        System.out.println(sb5); //dlrowhcetavaj
      //ensureCapacity
        StringBuffer sb =  new StringBuffer();
        System.out.println(sb.capacity());  //16
        sb.ensureCapacity(17);   //16*2+2=34 -> (34>17)
        System.out.println(sb); //34
    }
}

StringBuilder in Java has same StringBuffer parameter constructor as shown below-
  1. public StringBuilder()
  2. public StringBuilder(int capacity)
  3. public StringBuilder(String s)
  4. public StringBuilder(CharSequence cs)
Why StringBuIlder class is given when we have StringBuffer object ?

StringBuffer Java is syncronized objecct means mutiple threads can't access this object at a time.In single thread model application it leads performance issue because of object locking and unlocking machanism.

So StringBuilder create non-syncronized StringBuffer object to use in single thread model application with high performance.

String, StringBuffer and StringBuilder in java-

String is a immutable sequence of character object placed in " " is of type java.lang.String.
it is called as string literal.
StringBuffer in java is a thread safe mutable sequence of character object.
StringBuilder in java is a non-thread sequence of character object.

What are the difference in creating String object with literal and constructor ?
There are two difference.
  1. No. of object creation
  2. String pooling - Follow String Handling Chapter.
No. of object creation- 
String s="abc"; creates only one object.
String s1 = new String("abc"); creates two string object 
  • Argument string object if it is not yet created.
  • Current string object by copying argument string object character.
If you have any question comment below or feel free to rach out to me here

Read More
    0

Saturday, 20 May 2017

String Handling






String in java- String is sequence of character placed in double quote (" "). Performing different operation on string data is called String Handling. All String literals in java program, such as "xyz" are implementd as instance of this class. String are constant; their value can't be changed in the same memory after they are created.
So string is defined as it is an immutable sequence of character. 
In java.lang package we have below three classes to store and perform differnet operation on string of characters.
  1. String
  2. StringBuffer
  3. StringBuilder
All these classes are siblings, and they are subclasses of CharSequence interface.Below digram shows the inheritance realtion of these three classes.
String Inheritance Diagram
Note :
  •  All these classes are final classes.
  • Threse three classes are also subclasses of java.io.Serializable interface.
  • Java String class is a subclass of Comparable interface.
Why String class is given when we have char array is available ?

The limitation of arrays is size. Once array is created with particular size then its size can not be modified so if we use character array them we can only store character up to its size.
If we want to store new character beyond its size then we have to create character array with new size and copy old charachter array to new array. We should repeat the same process every time when array is filled which is time consuming and performance of the application will decrease.

Possible ways to create java String object -
We can create Java String object in two ways
  • String literal directly like String s="xyz";
  • Using string class constructors.
Below are the 8 important constructors of java string.
  1.  String()
    Creates empty string object.
    Example:
    String s = new String();
    System.out.println(s);

    2.    String(String value)
    Creates String object with given string object characters. It perform String copy operation.
    Example:
    String s=”xyz”;
    String s1 = new String(s); //string copy

    //creating direct string literal
    String s2= new String(“abc”);

    3.    String(StringBufffer sb)
    Creates new String object with the given StringBuffer object data.

    4.    String(StringBuilder sb)
    Creates new String object with the given StringBuilder object content.

    5.    String(char[] ch)
    Creates String object with the given char array values.
    Example:
    Char[] ch= {‘x’,’y’,’z’};
    String s1=new String(ch);
    System.out.println(“ value is: ”+s1);

    6.    String(char[] ch, int offset, int count)
    Create new String object with the given count number of characters from the given offset in the char[] object. Here offset is the starting index from which characters must be copied.
    Example:
    Char [] ch = {‘a’, ‘b’, ‘c’, ‘d’, ’e’, ‘f’, ‘g’, ‘h’};
    String s1= new String(ch, 2,4};
    System.out.println(“s1: “ +s1);  // cdef


    7.    String(byte[] b)
    Creates new string object by copying the given byte[] number by converting them into their ASCII characters.
    Example:
    byte[] b= {101,102,103,104};
    String s= new String(b);
    System.out.println(s); //efgh

    8.    String(byte [] b, int offset, int count)
    Create new String object with the given count number of bytes from the given offset in the byte[].
    Example:
    byte[] b = {101,102,103,104,105};
    String s = new String(b,2,2);
    System.out.println("value of s: "+s);
Why String object is immutable?
Because of String pooling concept.

What is Java String Pool?
If we create String object by assigning same string literal, only one object is created and all reference variable are intialized with that same String object reference. Then all referenced variables are pointing to same String object. This is reason Sring Object become immutable.

Below diagram show String Pooling with JVM architechture-
String Pooling with JVM Architechture
import java.util.*;
/** * Created by namdeva on 20/05/2017. */
public class StringPooling {
    String s="abc";
    String s1="abc";

    System.out.println(s==s1); //true   
    System.out.println(s.equals(s1)); //ture
    String str= new String("abc");
    String str1= new String("abc");

    System.out.println(str==str1);      //false    
    System.out.println(str.equals(str1)); //true
}
This String pool memory management diagram in java is not applicalbe for String Object those are created using "new keyword and constructor".
Java String have seperate object and those string object are created in heap area directly.
Below given program for practice purpose Let me know your output in the comment box : 
class Practice {
    public static void main(String[] args) {
        String s1="abc";
        String s2="abc";
        String s3="abc";
        String s4="bc";
        String s5= new String("abc");
        String s6= new String("abc");
        
        String s7= "ab";
        String s8= s1+"b";
        String s9= "a"+"b";
        
        System.out.print(s1==s2);
        System.out.print(s5==s6);
        System.out.print(s7==s8);
        System.out.print(s7=s9);
    }
}
String object creation and memory structure:
String object  contain char[] object to store string character.
StringObjectDiagram

String Method in java:
  1. isEmpty()
  2. length()
  3. equalsIgnoreCase()
  4. compareTo
  5. startsWith() /endsWith()
  6. indexOf
  7. contain(String s)
  8. findWithIndexOf() /findWithIndexOf()
  9. substring()
  10. concat()
  11. replace(char oldChar , char newChar)
  12. trim()
  13. split()
  14.  
For more update keep visiting to this website you can post your query in the comment box i will try to response you as early as possible.
Read More
    0

Tuesday, 16 May 2017

How hash map works in java or How get() and put() method works internally

Hash Map in Java- Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map interface. it store value in key, value pair format. HashMap is known as HashMap because one ot it's technique i.e hashing.

HashMap
HashMap Example-
import java.util.*;class TestCollection13{
public static void main(String args[]){
 HashMap<Integer,String> hm=new HashMap<Integer, String>();  //line 4
hm.put(“ajay”,123456789);  //line 5
hm.put(“abhishek”,987654321);//line 6
hm.put(“abhinav”,234156748);//line 7
for(Map.Entry m:hm.entrySet()){
            System.out.println(m.getKey()+" "+m.getValue());
        }
    }
}  
Internal Implementation of HashMap-
Hashing- Hashing is a technique which convert large string into fixed length value it is alpha numeric value.
Example-
public class HelloWorld{
    public static void main(String []args){
        String s="abc";
        System.out.println(s.hashCode());
    }
}
In object class java has given equals method which says objects that are equal must have the same hash code within a running process here hashcode of string abc is 96354 this value might be different in your system.
To learn how to override equals and hascode method in java Click Here

If you check the above diagram HashMap internally implements hashtable and each index of and hastable has it’s own linked list implementation because there is a possibility object class hashcode method may return duplicate hashcode.

HashMap has an inner class Entry, which looks like this:

static class Entry<K ,V> implements Map.Entry<K ,V>
{
    final K key;
    V value;
    Entry<K ,V> next;
    final int hash;
    //Some code here
}

How put operation work in java- Using above algorithm we will understand how put() method internally work in HashMap.
Before inserting values in the array index there are some check which is performed by java program internally.
  • First of all, key object is checked for null. If key is null, value is stored in table[0] position. Because hash code for null is always 0.
  • Then on next step, a hash value is calculated using key’s hash code by calling its hashCode() method. This hash value is used to calculate index in array for storing Entry object. 
  • Now index for function is called to calculate exact index position for storing the Entry object.
  • Here comes the important concept two object can have same hash code value and these value will store in same array location because of each  index has it’s own linked list implementation. 
Note:-  Java HashMap allows null key, which always goes to index 0 as hash of 'null' is zero.

How get operation work in java:- In get operation we will call get('varun') then we will find hash of the key after that we will calculate index and check in which index value exist we will compare both hashcode and key at particular index once this is verified value will be returned.
Java Hash Map Design Diagram


Hope you have like this blog kindly suggest on the comment box for any other query contact me Here


Read More
    0
© 2014 JavaTechWorld. Designed by Bloggertheme9
Powered by Blogger.