Categories
Java Software Testing

Java try catch finally block example | Exception Handling in Java

Before we start to know about try Catch Finally, we should know about Exceptions and its handling in Java.

In Java, according to Oracle’s Java documentation, An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

For example, If a program is trying to read/write a file from a location, and if the file is not found or not accessible then we get FileNotFoundException exception.

Another example where most of the developer face issue in real time is NullPointerException also referred as NPE.One scenario when we get NPE is, when we try to updated an object which is null, then Java will through NPE. That’s why it is recommended to add null checks before updating any Java Object.

These are some of the exceptions which we face in our day to day life. There are many other exceptions available, which are out of the scope for this post. So, the main idea is when a program is being executed and when unintended event happens, Java will through Exception. When the exceptions are thrown, we may get issues like program halts or in Web applications user will see stack trace of an exception, which end users don’r know about.

To avoid these issues, we can handle Exceptions programmatically and if any unexpected event happens, then we can show the meaning full messages to users and log the required details for developer to debug.

This can be done by the trio called “try-Catch-Finally”.

These 3 try, catch and Finally are the building blocks of Exceptions handling. Let us see on by one

Try Block

Try block is the place where we have actual logic implemented. For example, File handling or updating the Objects and so on…

Try block is the place where Exceptions get generated.

When we suspect that particular code may have chance of throwing the Exception we surround that code with try block

Below is the example of try block

Private void printStringLength(String name){
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
}

As we see in above example, first line in try block is trying to get the length of a String. Here if String is not empty, then everything works fine. But what if String is null, User will get unexceptced NPE error.

To avoid this, we need to surround the code where we suspect there is a chance of exception, with try block like below

private void printStringLength(String name){
       try{
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
     }
}

catch block

catch block are where we handle the Exception thrown from try block. Code written in catch block are executed only when there is an Exception raised in try block, otherwise catch block is skipped.

In General when we developing application, we don’t want to show the user error messages which are not user friendly like “java.lang.NullPointerException” with some stack trace. Instead we want to show some meaningful information like “Given Name is empty” and then log the stack trace for developer to debug.

Above process of displaying meaningfull message to user/client is handled in catch block.

Below example of catch block

private void printStringLength(String name){
        try{
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
        }catch(Exception e){
           System.out.println(“ Exception occurred while getting length“);
        }
}

finally block

Finally block, as the name suggest, is executed after executing try and/or catch blocks.

Usually we use finally if we want to perform some operation irrespective of whether an exception occurred or not.

For example,

We want to close a DB connection after performing some task in try block, but If any exception occurred there is a chance that rest of the code doesn’t execute, in that scenario we want to close connection. To close the connection, we can put the code in finally block.

Finally block make sure whatever code inside is executed 100% whether an exception occurs or not.

private void printStringLength(String name){
        try{
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
        }catch(Exception e){
            System.out.println(“Exception occurred while getting length “);
        }finally{
            System.out.println(“In Finally “)
        }
}


Above is just a brief idea on how try catch finally works, still there is a vast amount of information left, which can be found in Oracle java docs and other places.

Categories
Java

What are Operators in Java Programing language? Explain all the Operators in Java

In Java Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.
Java supports various operators, and they can be classified into following categories.

  1. Arithmetic Operators
  2. Increment and Decrement Operators
  3. Relational Operators
  4. Logical Operators
  5. Assignment Operators
  6. Ternary Conditional Operator
  7. Bitwise Operator

Arithmetic Operators in Java

In Java we use Arithmetic Operators to perform basic operations like addition, subtraction, multiplication and division.
They are used in mathematical expressions, in the same way they are used in algebra. Some of the operators are

  • Addition Operator :-
    This operator is used to add two integer values. Like we add two values:
    a = 5 and b = 10 so, a+b = 15 or b+a = 15
  • Subtraction Operator :-
    This operator will subtract the left value from the right value. Like:
    a – b where a = 20 and b = 10 so the result will be 10.
  • Multiplication Operator :-
    In this operator it will multiply the two values. Like:
    a*b or b*a such as a = 2 and b = 4 so the result will be a*b = 8 and b*a = 8.
  • Division Operator :-
    In this operator the left hand operand is divided by the right hand operand, based on the value which variable value is greater. Like:
    a = 10 and b = 5 so, a/b = 10/5 = 2.
  • Modulus Operator :-
    In this operator the left hand operand is divided by the right hand operand and it returns the remainder, based on the value which value is greater. Like:
    a%b where a = 10 and b = 5 so, a%b = 0, the remainder will be 0.

Example Java program on Arithmetic Operators

public class arithmetic{ 
        public static void main(String[] args) {
               System.out.println("Some arithmetic operators are:");
               
               int a = 5 + 10;
               int b = a - 10;
               int c = b * 5;
               int d = c / 5;
               
               System.out.println("Value of addition = " +a );
               System.out.println("Value of subtraction = " + b);
               System.out.println("Value of multiplication = " + c);
               System.out.println("Value of division = " + d);
        }
}

Increment and Decrement Operators

In Java, we use increment and decrement operators to increase and decrease the value.

  • Increment Operator – In this operator the value will be incremented by 1. Like, a = 3 so after increment a++ the value of a will be 4.
  • Decrement Operator – In this operator the value will be decremented by 1. Like, a = 7 so after decrement a- – the value of a will be 6.

Example Java program on Increment and Decrement Operators

public class incredecre{
         public static void main(String[] args) {          
                 int a = 11;
                 int b = 10;
                 a++;
                 ++b;
                 
                 System.out.println("a = " +a);
                 System.out.println("b = " + b);
                 
                 int c = a--;
                 int d = --b;
                 
                 System.out.println("c = " + c);
                 System.out.println("d = " + d);
              }
       }

Relational Operators

In Java we use relational operator to compare 2 variable values Below are some of the Java’s relational operators

  • Equal to (= =) – In this operator it checks whether both the values are equal are not, if both the values are equal then the condition is true. Like a = 10 and b = 10 so a= = b, the condition is true.
  • Not equal to (!=) – In this operator it also checks whether both the values are equal or not but if the values are not equal then the condition is true. Like a= 10 and b = 20 so a != b, the condition is true.
  • Greater than (>) – In this operator it checks that the left operand value is greater than the right operand or not. If the value is greater than the condition is true, if it is not than the condition is false. Like a = 20 and b = 10 so a>b then the condition is true.
  • Less than (<) – In this operator it checks whether the left operand value is less than the right operand. If the value is less than the right operand then the condition is true. Like a = 10 and b = 20 so a<b then the condition is true.
  • Greater than or equal to (>=) – In this operator it checks whether the left operand value is greater than or equal to the right operand and if it is then the condition is true. Like a = 30 and b = 20 so a>= b so the condition is true.
  • Less than or equal to (<=) – In this operator it checks whether the left operand value is less than or equal to the right operand and if it is true then the condition is true. Like a = 20 and b = 30 so a<=b so the condition is true

Let us have a look on the example in Java

public class relational {
   public static void main(String args[]) {
      int x = 30;
      int y = 20;
      System.out.println(" The value of x == y is =  " +(x==y) );
      System.out.println("The value of x != y is = " + (x != y) );
      System.out.println("The value of x &gt; y is = " + (x &gt; y) );
      System.out.println("The value of x &lt; y is = " + (x &lt; y) ); System.out.println("The value of x &gt;= y is = " + (x &gt;= y) );
      System.out.println("The value of x &lt;= y is = " + (x &lt;= y) );
   }
}

Logical Operators

The logical operators are also known as Boolean operator where it operates only on Boolean operands and return Boolean value. In this we combine two or more condition into a single expression to form a resultant Boolean value, i.e. true to false or vice versa. Some of the logical operators provided in Java are:

  • Logical AND – In the logical AND operator it returns the value 1 if both the operands value are 1 and 0 if the values are not same.
    For example:
    1010     //binary conversion of 10
    0111     //binary conversion of 7
    0010     //binary conversion of 2
  • Logical OR – In the logical OR operator it returns the value 1 if either of the value of the operand is 1 and if not then the value will be 0. For example:
    1010    //binary conversion of 10
    0110    //binary conversion of 6
    1110    //binary conversion of 14
  • Logical NOT – In the logical NOT operator it will convert the value it will make 1 to 0 and vice versa.
    For example:
    1010   //binary conversion of 10
    It will convert this value into:
    0101   //binary conversion of 5
  • Logical XOR – In the logical XOR operator if there is exactly one operand value 1 then it will return 1 otherwise the result will be 0.
    For example:
    1010   //binary conversion of 10
    0111   //binary conversion of 7
    1101   //binary conversion of 13

Let us have a look on the Java example on Logical Operator:

public class logical {
   public static void main(String args[]) {
      boolean a = true;
      boolean b = false;
      System.out.println("a &amp;&amp; b = " + (a&amp;&amp;b));
      System.out.println("a || b = " + (a||b) );
      System.out.println("!(a &amp;&amp; b) = " + !(a &amp;&amp; b));
      System.out.println("a ^ b = " + (a ^ b));
   }
}

Assignment Operators

The assignment operators are used to assign the value of a given expression to a variable. Some of the assignment operators in Java are:

  • Add and assign (+ =) – This operator is used to add the right operand to the left operand and assign the result to the left operand
  • Subtraction and assign (- =) – This operator is used to multiply the right operand from the left operand and assign the result to the left operand
  • Divide and assign (/=) – This operator is used to divide the left operand with the right operand and assign the result to the left operand
  • Modulus and assign (%=) – This operator is used to divide the left operand with right operand and assign the remainder as a result to the left operand
  • Shift left and assign (<<=) – This operator is used to shift the bits to left and assign the result to the operand
  • Shift right and assign (>>=) – This operator is used to shift the bits to right and assign the result to the operand

Let us have a look on the example:

public class Test {
   public static void main(String args[]) {
      int a = 20;
      int b = 10;
      int c = 0;

      c += a ;
      System.out.println("c += a  = " + c );

      c -= a ;
      System.out.println("c -= a = " + c );

      c *= a ;
      System.out.println("c *= a = " + c );

      a = 20;
      c = 15;
      c /= a ;
      System.out.println("c /= a = " + c );

      a = 20;
      c = 15;
      c %= a ;
      System.out.println("c %= a  = " + c );

      c &lt;&lt;= 2 ;
      System.out.println("c &lt;&lt;= 2 = " + c ); c &gt;&gt;= 2 ;
      System.out.println("c &gt;&gt;= 2 = " + c );    
   }
}

Bitwise Operators

There are many bitwise operators defined by Java which are used in the integer types like int, short, long etc. The bitwise operator works on bits and performs bit by bit operation. The java provides some of the bitwise operators like AND bitwise operation, OR bitwise operation, XOR bitwise operation, Complement operation, etc.

  • AND bitwise operation – The AND bitwise operator is similar to AND operator where it returns 1 when both the operands are 1 otherwise if the values are different then it returns 0. The difference in logical AND operator and AND bitwise operator is the sign, the AND operator is denoted by && whereas AND bitwise operator is denoted with &.
  • OR bitwise operation – The OR bitwise operator is similar to logical OR operator where it returns 1 if either of the value is 1 and if both the values of the operands are same then it returns 0. The difference between logical OR operator and OR bitwise operator is of sign, the logical OR operator is denoted with || whereas the OR bitwise operator is denoted with |.
  • XOR bitwise operation – The XOR bitwise operator will return 1 where both the values of the operands are different and will return 0 when both the values are same. The XOR bitwise operator can be denoted by using ^.
  • Compliment bitwise operation – The unary compliment bitwise operator changes the bits from 0 to 1 and 1 to 0. This operator can be applied only on integer types; it cannot be used on Boolean types. This operator can be denoted by using ~.
  • Fill right shift zero – In the fill right shift zero operator the left operand value is shifted right by the number of bits specified by the right operand and those shifted values are filled with zeros. The fill right shift zero can be denoted by >>>.
  • Left shift operation – In the left shift operator the values are moved left by the number of bits specified by the right operand. The left shift operator is denoted by <<.
  • Right shift operation – In the right shift operator the left operand value is shifted right by the number of bits specified by the right operand. The right shift operator is denoted by >>.

Let us understand these operators though an example:

public class bitwise{
   public static void main(String args[]) {
      int a = 10;
      int b = 5;	
      int c = 0;

      c = a &amp; b;        
      System.out.println("AND operation a &amp; b = " + c );

      c = a | b;        
      System.out.println("OR operation a | b = " + c );

      c = a ^ b;       
      System.out.println("XOR operation a ^ b = " + c );

      c = ~a;           
      System.out.println("Complement operation ~a = " + c );

      c = a &lt;&lt; 3;       
      System.out.println("Left shift a &lt;&lt; 3 = " + c ); c = a &gt;&gt; 3;      
      System.out.println("Right shift a &gt;&gt; 3  = " + c );

      c = a &gt;&gt;&gt; 3;     
      System.out.println("Zero fill right shift a &gt;&gt;&gt; 3 = " + c );
   }
}

Ternary Conditional Operator

The ternary conditional operator is used in the conditional expressions. This operator consists of three operands which are presented in this form:
exp1 ? exp2 : exp3
In the above expression the first operand represents the condition which is evaluated and it must be either true which is represented by second operand exp2 or false which is represented by exp3.

Let us have a look on the example:

public class ternary{
   public static void main(String args[]) {
      int a, b;
      a = 1;
      b = (a == 1) ? 2: 3;
      System.out.println( "The value of b is : " +  b );
      b = (a == 0) ? 2: 3;
      System.out.println( "The value of b is : " + b );
   }
}
Categories
Java

Java Virtual Machine Architecture details explained | JVM in JAVA – JVM Concept

As we know from earlier posts JRE is the implementation of Java Virtual Machine (JVM). So it is important to know the JVM architecture. In this post we will see the more details about JVM and its architecture.

What is JVM?

The Java Virtual Machine is heart of the Java architecture and it supports all the three features of the java. They are:

  • Platform Independence
  • Network Mobility
  • Security

When a java application starts, a runtime instance is born and when the application completes, the instance dies.Every Java application runs inside in its own Java Virtual Machine. Java Virtual Machine main work is to load class files and execute the bytecode.

JVM consists of class loader where it is used to load the class files from both the program and the Java API, and only those class files are loaded form the Java API which are required by a running program. The bytecodes are executed in an execution engine.

Given below is the figure of java virtual machine architecture.

Now we will understand this architecture in detail.

  • Class Loader: The class loader work is to load all the files which are required to execute the program. The class loader takes the .class file as the input to load the java bytecode. There are three types of java class loader built in java:
    • Bootstrap class loader – The bootstrap class loader will load the JDK internal classes i.e. rt.jar and other classes like java.lang.* package.
    • Extensions class loader – The extension class loader will load the classes from the JDK extension directory such as $JAVA_HOME/lib/ext directory.
    • System class loader – The system class loader will load the classes from the current classpath which can be set while invoking a program by using –cp or –classpath in command line.
  • Runtime Data Areas: In Java Virtual Machine there are various runtime data areas defined which are used during the execution of a program. Some of the data areas are created when the Java Virtual Machine starts and they get destroyed when the Java Virtual Machine exits. Some of the runtime data areas are:
    • Method Area: The method area is shared among all Java Virtual Machine threads. If the allocated memory area is not sufficient during the run time then the JVM will throw the OutOfMemoryError.
    • Heap: The heap is shared among all the Java Virtual Machine threads. It is a run time data area from which memory for all the class instances and array is allocated. Heap is a finite memory and can be configured at the time of setting up of runtime environment using non standard option.
    • Java Stacks: In the java virtual machine the every thread has a private Java Virtual Machine stack which is created at the time of thread is created. It stores frames. It is used to store the information of the methods and it is done at the execution time.
    • PC Registers: The PC Registers stands for program counter registers which contain the address of the next instruction that has to be executed. In the JVM every thread has its own program counter registers.
    • Native Method Stacks: The JVM supports the native method stacks which is used for native methods and is created per thread. If the native methods cannot be loaded by the JVM then it does not have the native method stacks.
  • Execution Engine: The execution engine is used to execute the bytecode which is assigned to the runtime data areas in the JVM via class loader. It reads the bytecode in the form of unit of instruction. The execution engine consists of Interpreter and JIT compiler which are used to convert the bytecode into machine code.
    • Interpreter: The interpreter read the bytecode stream and then executes the instructions one by one.
    • JIT compiler: The JIT stands for Just in Time compiler which is used to improve the performance. It compiles the bytecode and converts it to the native code.
  • Native Method Interface: It is a program which connects the native methods libraries with JVM for executing native methods like C header files.
  • Native Method Library: It holds the native libraries information required for the Execution Engine..