Saturday, 31 October 2015

Difference between logical and bitwise operators in Java(&&,|| and &,|)

       The logical(non-bitwise) operators && and || are short-circuit operators. In other words, with && if the LHS(Left Hand Side) is false, the RHS(Right Hand Side) will never be evaluated. With || if the LHS is true, then the RHS will never be evaluated.  On the other hand, the bitwise operators & and | are non short-circuit, will always evaluate both the LHS and RHS.
     This is especially useful in guarding against nullness.

            String x = null;
            if ( x != null && x.equals("xyz") {
                   then do something with x...
            }
                
      The above condition is the best example for handle the null exception. If u put first condition is not equal to null then only it will check for other conditions.
 

            String x = null;
            if ( x != null & x.equals("xyz") {
                   then do something with x...
            }
  
      In the above example (bitwise & operator) ,it will check the all conditions in the if statements, so it will throw the NullPointerException.
       One main difference between & and && is, bitwise &  you can use with both integral and boolean but && you can use with only boolean operands.

Some Programs based on logical & bitwise operators:--

1) what is the output of given code?

 class OperatorExOne {
      public static void main (String[] args) {
             String a = null;
             if(a != null && a.equals("Java")) {
                   System.out.println("Inside If Statement");
             } else {
                    System.out.println("Inside else Statement");
             }
      }
 }

 Output:- Inside else Statement
       
       In the above code it will print else part i.e "Inside else Statement". In if statement there are two conditions with && operator. In logical AND operator it will check the first condition if it is false then it won't check the 2nd condition and it will return false. In the above code first condition is false so it won't check the 2nd condition. In second condition it is exception but it won't check the condition at all.
      In the above code,if we changed the first condition of if statement, then it will throw NullPointerException, See below.

2)        class OperatorExTwo {
                     public static void main (String[] args) {
                            String a = null;
                            if(a.equals("a") && a != null ) {
                                   System.out.println("Inside If Statement");
                           }
                           else {
                                 System.out.println("Inside else Statement");
                          }
                   }
            }  


output:-java.lang.NullPointerException

     Above code will throw  NullPointerException because the first condition of if statement is true and it will check the second condition, and will throw NullPointerException.

3) what is the output of given code?

         class OperatorExThree {
                 public static void main (String[] args) {
                            int a = 2;
                            int b = 3;
                            int result = a & b;
                            System.out.println(result);
                 }
         }

output:- 2

4) what is the output of given code?

        class OperatorExFour {
                 public static void main (String[] args) {
                            int a = 2;
                            int b = 3;
                            int result = a && b;                //Compilation error.
                            System.out.println(result);
                 }
         }
 output:-  Compilation error, The operator && is undefined for the argument
                 type(s) int, int
 

Saturday, 24 October 2015

Difference between Loose Coupling and Tight Coupling in Java With Examples.

       First to understand what is Loose coupling and Tight coupling and also to know the  advantage of loose coupling.
    
        In short Loose coupling means reducing dependencies of a class that use different class directly . Tight coupling means classes and objects are dependent on one another. In general tight coupling is usually not good because it reduces flexibility and re-usability of code and it makes changes much more difficult and not easy to test.

Tight Coupling:-


      Tightly coupled object is an object that needs to know quite a bit about other objects and are usually highly dependent on each other's interfaces. Changing one object in a tightly coupled application often requires changes to a number of other objects. In a small application we can easily identify the changes and there is less chance to miss anything. But in large applications these inter-dependencies are not always known by every programmer and there is chance of overlooking changes.(Source- from StackOverflow).
         See below code is for tight coupling.

   public class Journey {
         Car car = new Car();
         public void startJourney() {
               car.travel();
         }
   }

   public class Car {
         public void travel () {
              System.out.println("Travel by Car");
         }
   }
 
         In the above code the Journey class is dependents on Car class to provide service to the end user(main class to call this Journey class).
         In the above case Journey class is tightly coupled with Car class it means if any change in the Car class requires Journey class to change. For example if Car class travel() method change to journey() method then you have to change the startJourney() method will call journey() method instead of calling travel() method.
        
      See below code,


  public class Journey {
        Car car = new Car();
        public void startJourney() {
               car.journey();
        }
  }

  public class Car {
        public void journey () {
              System.out.println("Travel by Car");
        }
  } 

         The best example of tight coupling is RMI(Remote Method Invocation)(Now a days  every where using web services and SOAP instead of using RMI, it has some disadvantages).

 Loose Coupling:-


        Loose coupling is a design goal that seeks to reduce the inter-dependencies between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component. Loose coupling is much more generic concept intended to increase the flexibility of system, make it more maintainable and makes the entire framework more stable.
        Below code is an example of loose coupling,


   public interface Vehicle {
        void start();
   }
         
   public class Car implements Vehicle {
        @Override
        public void start() {
              System.out.println("Travel by Car");
        }
   }

   public class Bike implements Vehicle {
         @Override 
         public void start() {
               System.out.println("Travel by Bike");
         }
   }
             
    // create main class Journey
   public class Journey {
         public static void main(String[] args) {
               Vehicle v = new Car();
               v.start();
         }
   } 

        In the above example, Journey and Car objects are loosely coupled. It means Vehicle is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user.

        The examples of Loose coupling are Interface, JMS, Spring IOC(Dependency Injection, it can reduce the tight coupling).

Advantages Of Loose coupling:-

         A loosely coupled will help you when your application need to change or grow. If you design with loosely coupled architecture, only a few parts of the application should be affected when requirements change. With too a tight coupled architecture, many parts will need to change and it will be difficult to identify exactly which parts will be affected. In short,

 1) It improves the testability.                                                          
 2) It helps you follow the GOF principle of program to interfaces, not implementations.
 3) The benefit is that it's much easier to swap other pieces of code/modules/objects/components when the pieces are not dependent on one another.
 4) It's highly changeable. One module doesn't break other modules in unpredictable ways.


Related Post:- 
1) Spring Annotations
2)  Spring MVC with Hibernate CRUD Example
3) Spring MVC workflow with example
4) What is dependency Injection in Spring ? give me types and advantages with examples

Tuesday, 6 October 2015

What is PermGen in Java? How to solve the Java.Lang.OutOfMemoryError: PermGen Space

          The java.lang.OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and JVM throws java.lang.OutOfMemoryError when it ran out of memory in heap. When you will try to create an object and there is not enough space in heap to allocate that object then you will get OutOfMemoryError.

         Types of OutOfMemoryError in Java

1) Java.lang.OutOfMemoryError: Java heap space

2) Java.lang.OutOfMemoryError: PermGen space


Now we will discuss about PernGen space,

PermGen stands for Permanent Generation.

       Java applications are only allowed to use a limited amount of memory. The exact amount of memory your particular application can use is specified during application startup. To make things more complex, Java memory is separated into Young, Tenured and PermGen regions.
   
      The size of all these is set during the JVM launch. If you didn't set the sizes of these regions then platform specific default will be used(The default PermGen Space allocated is 64 MB for server mode and 32 MB for client mode).



Causes:

       The mainly the permanent generation consists of class declarations loaded and stored into PermGen. This includes the name and fields of the class, methods with the method bytecode, constant pool information, object arrays and type arrays associated with a class and Just In Time compiler optimizations.

        From the above paragraph, we can say that the main cause for  the java.lang.OutOfMemoryError: PermGen space is that either too many classes or too big classes are loaded to the permanent generation.



Solution:--

          As explained in above, this OutOfMemory error in java comes when Permanent generation of heap filled up.
         To fix this OutOfMemoryError in Java you need to increase heap size of  Perm space by using JVM option   "-XX:MaxPermSize".
         You can also specify initial size of Perm space by using    "-XX:PermSize" and keeping both initial and maximum Perm Space you can prevent some full garbage collection which may occur when Perm Space gets re-sized. Here is how you can specify initial and maximum Perm size in Java:

export JVM_ARGS="-XX:PermSize=64M -XX:MaxPermSize=256m"

Note:-
      In Java 8, PermGen area has been replaced by MetaSpace area, which is more efficient and is unlimited by default (or more precisely - limited by amount of native memory, depending on 32 or 64 bit jvm and OS virtual memory availability) .


Related Post :--
How to generate the StackOverflowError and OutOfMemoryError programmatically in Java