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) What is the output of given code?

 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
 



Related Posts:--
1) String Interview Questions and Answers
2) Exception Handling Interview questions and answers
3) Interface and Abstract Class Interview Questions and Answers

Saturday, 24 October 2015

Difference Between Loose Coupling and Tight Coupling in Java with Examples

     Before understanding the difference between loose coupling and tight coupling, it is important to understand what these concepts mean and why loose coupling is preferred.

In simple terms, loose coupling means minimizing the dependencies between classes so that one class does not depend directly on the implementation of another class. Tight Coupling, on the other hand, means that classes and objects are highly dependent on one another.

In general, tight coupling is not recommended because it reduces the flexibility, maintainability, reusability, and testability of the code. It also makes the application more difficult to modify, extend, and maintain. Loose coupling helps create a more modular design, making the code easier to test, maintain, and enhance.


Tight Coupling:-


       A tightly coupled object is one that has a strong dependency on other objects and relies heavily on their implementations or interfaces. As a result, changes made to one class often require corresponding changes in several other classes that depend on it.

In a small application, these dependencies are usually easy to identify and manage. However, in large applications, such interdependencies can become difficult to track. This increases the likelihood of introducing bugs or overlooking required changes during development and maintenance(Source: Adapted from discussions on Stack Overflow).

The following example demonstrates 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 example, the Journey class depends directly on the Car class to provide its functionality to the end user (through the main class).

Since the Journey class is tightly coupled to the Car class, any changes made to the Car class may require corresponding changes in the Journey class. For example, if the travel() method in the Car class is renamed to journey(), you must also update the startJourney() method in the Journey class to call journey() instead of travel().

The following example demonstrates how to achieve loose coupling.


  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 principle that aims to minimize the dependencies between components of a system. Its primary goal is to reduce the likelihood that changes in one component will require changes in other components. By reducing these dependencies, loose coupling makes the system more flexible, maintainable, reusable, and easier to test.

Loose coupling is a fundamental concept in object-oriented design and is widely used to build scalable and robust applications.

The following example demonstrates 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 design makes it easier for your application to adapt to changing requirements and future growth. When an application is designed with a loosely coupled architecture, changes in one component typically affect only a small part of the system. In contrast, a tightly coupled architecture often requires changes in multiple components, making it more difficult to identify and manage the impact of those changes.

In short, the benefits of loose coupling include:

  1. Improves testability by making individual components easier to test in isolation.

  2. Encourages the SOLID and GoF design principle of programming to interfaces rather than implementations.

  3. Makes components interchangeable, allowing implementations to be replaced or extended with minimal changes to the rest of the application.

  4. Increases flexibility and maintainability, as changes in one module are less likely to affect other modules unexpectedly.

  5. Enhances code reusability, enabling components to be reused across different parts of the application.

  6. Simplifies maintenance and future enhancements, making the application easier to evolve over time.



Related Post:- 
1) Spring Annotations
2) Spring MVC with Hibernate CRUD Example
3) Spring MVC workflow with example
4) Factory Design Pattern in Java
5) String Interview Questions and Answers
6) What is IOC Container in Spring? Difference between BeanFactory and ApplicationContext
7) Java Date and Calendar Examples
8) Exception Handling Interview questions and answers
9) Java Program to Count Occurrence of Word in a Sentence

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