Sunday, 24 January 2016

Java one year experience interview questions

1. Explain System.out.println()?
  • The system is a class That is present in java.lang package.
  • Out is a static final field (variable) of  Printstream class
    Println(): method of Printstream Class
  • Class System{
    public static final Printstream Out;
    }
  • Class Printstream{
    public void println(){}}

 2. What happens When System.out.println(null)?
  • Compilation Error -This is because you can pass an Object or a String or char[]. Since null can fit in both, the compiler doesn't know which method to use, leading to compile error.
  • Method Overloading:
        1.public void prinltln(String str) { }
        2.public void prinltln(char[] ch){ }
        3.public void prinltln(Object ch){ 
  • It seems the call System.out.print(null) is ambiguous to the compiler because print(null) here will find the two best specific matches i.e. print(String) and print(char[]). So the compiler is unable to determine which method to call here.
  • Compilation Error:
       System.out.println(null)
  • Compile Fine:
         System.out.println((String)null);//null
         System.out.println((char[])null);
         System.out.println((Object)null);//null
  • It's the compiler type-checking the parameters of the method call.
  • But here we need to know one more thing  System.out.println((char[])null); will compile fine but at run time will throw runtime exception.
 
3. What are the oops concepts in Java

Oops:
Oops, concepts are the rules which are supposed to be satisfied by a programing language in order to call that programing language as an Object Oriented Programing Language.


1. The 3 oops concepts are
    I. Encapsulation
    ii. Polymorphism
    iii. Inheritance

Encapsulation:

The process of binding the data with corresponding methods
  • The concept of binding the data along with its related and corresponding methods is known as Encapsulation.
  • The concept of restricting the availability of the data only to its related areas and related functions it is known as binding.
  • Because of binding, we can restrict the availability of data to the unrelated methods
  • So that unrelated functions cannot access the data 
  • Class is the base for encapsulation 

Polymorphism:

Defining multiple methods with the same name is known as Polymorphism.
  1. Static polymorphism (Compile time polymorphism ):
    The concept of defining multiple methods with the same name and with different parameters within the same class is known as static polymorphism.
  2. Dynamic polymorphism (Run time polymorphism ):
    The concept of defining multiple methods with the same name and with the same signature in super class and subclass is known as Dynamic polymorphism.

Inheritance:

Getting the properties from one class object to another class object is known as Inheritance.
  1. Multiple inheritance:
    Getting the properties from one class object to another class object level-wise with different priorities.
  2. Multilevel inheritance: Getting the properties from one class object to another class object with the same priority.

4. What are classes and Objects in Java?

Class
  • Class is a structure.
  • Binding the data with its related and corresponding functions.
  • Class is the base for encapsulation.
  • Class is a user-defined data type in Java.
  • The class will act as the base for encapsulation and implement the concept of encapsulation through objects.
  • Any Java application looks like a collection of classes but whereas a c- application looks like a collection of functions.
public class Example{

         //variable declaration
          int id;

      // methods
        public int getId() {
          return id;
         }

    public void setId(int id) {
        this.id = id;
    }

}

Object

  • An object is nothing but an instance (dynamic memory allocation) of a class.
  • The dynamic memory allocated at run time for the members [non-static variables] of the class is known as an object.

What is a Reference variable?

  • A reference variable is a variable that would be representing the address of the object.
  • Reference will act as a pointer and handler to the object.
  • Since the reference variable always points to an object.
  • In practice, we call the reference variable also an object.
  • We can create an object by using a new operator.
  • If we want to call any method inside the class we need an object
               Syntax: A obj= new A();

Example program:

      public class A {
         int a;
         public  void Print(){
            System.out.println("value of a="+a);
        }
        public static void main(String[] args) {
            A obj=new A();
           obj.print();
        }
}

Output: the value of a=0 
 
What Object Contains?
  • The object of any class contains only data.
  • Apart from the data object of a class would not contains anything else.
  • An object of a class would not contain any functionalities or logic.
  • Thus object of a class would be representing only data and not represent logic.

What is the state of the Object?

The data present inside the object of a class at that point in time is known as the state of the object.

What is the behavior of the object? 

  • The functionalities associated with the object => Behavior of the object.
     The state of the object changes from time to time depending on the functionalities that are executed on that object but whereas the behaviour of the object would not change.

Naming conventions for declaring a class:

  • The class name should be relevant.
  • Use UpperCamelCase for class names. //StudentDemoClass
  • For Methods names follow camelCase(); //getName();
  • Declare variables in the lowercase first letter. // int rollNumber
  • To declare final static variables means they will act like constants
    MIN_WIDTH=10;
    MAX_AGE=18;


5. Can you define an abstract class without any abstract methods?

  • Yes.
  • Declaring a class abstract without abstract methods means that you don't allow it to be instantiated on its own.
  • The abstract class used in Java signifies that you can't create an object of the class directly.
  • This will work:
    public abstract class abs {

    protected int s=0;

    public void display() {
        System.out.print("hello");
    }

    }

6. what are the differences between Final, finally Finalize ()?

Final:

  •  Any variable declare along with the final modifier then those variables treated as final variables
  • if we declare final variables along with static will become constants.
  • public final String name = "foo"; //never change this value
  • If you declare a method as final that method is also known as final methods. Final methods are not overridden. means we can't override that method in any way.
  • public final void add(){
     }
     public class A{
     void add(){
     //Can't override
     }

     }
  • If you declare class is final that class is also known as final classes.Final classes are not extended.means we can't extens that calss in anyway.
  • public final class indhu{
     }
     public class classNotAllowed extends indhu {...} //not allowed

Finally:

  • Finally, blocks are followed by a try or catch. finally, blocks are compulsory executable blocks. But finally is useful for more than just exception handling.
  •  it allows the programmer to avoid having cleanup code accidentally bypassed by a return,
     continue, or break, Closing streams, network connection, database connection. Putting cleanup code in a finally block is always a good practice even when no exceptions are anticipated
  •  where finally doesn't execute e.g. returning a value from the finally block, calling System. exit from try block etc
  • finally, the block always executes, except in case of JVM dies i.e. calling System. exit().

     lock.lock();
    try {
      //do stuff
    } catch (SomeException se) {
      //handle se
    } finally {
      lock.unlock(); //always executed, even if Exception or Error or se
      //here close the database connection and any return statements like that we have to write
    }

Finalize():

  • finalize() is a method that is present in Java.lang.Object class.
  •  Before an object is garbage collected, the garbage collector calls this finalize() of the object. Any unreferenced before destroying if that object has any connections with the database or anything. It will remove the connections and it will call finalize() of object. It will destroy the object.
  • If you want to explicitly call this garbage collector you can use System.gc() or Runtime.gc() objects are there for a long time the garbage collector will destroy that objects.
  • public void finalize() {
      //free resources (e.g. un allocate memory)
      super.finalize();
    }

7. What is Exception? difference between Exception and Error? and types of Exceptions?
  • Exceptions are the objects representing the logical errors that occur at run time and make 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.
  • 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.
  • few of the subclasses of 
  • Error
  • AnnotationFormatError - Thrown when the annotation parser attempts to read an annotation from a class file and determines that the annotation is malformed.
  • AssertionError- Thrown to indicate that an assertion has failed.    
  • LinkageError - Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.
  • VirtualMachineError - Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.
  •  There are really three important subcategories of Throwable:
  • Error - Something severe enough has gone wrong the most applications should crash rather than try to handle the problem,
  • Unchecked Exception (aka RuntimeException) - Very often a programming error such as a NullPointerException or an illegal argument. Applications can sometimes handle or recover from this Throwable category -- or at least catch it at the Thread's run() method, log the complaint and continue running.
  • Checked Exception (aka Everything else) - Applications are expected to be able to catch and meaningfully do something with the rest, such as FileNotFoundException and TimeoutException
   
 8. Differences between method overloading and method overriding
  • Method overloading is nothing but defining multiple functionalities with the same name with
    different parameters are known as method overloading
  • while compile time itself we know which method is executed
  • Overloading gives better performance compared to overriding. The reason is that the
    binding of overridden methods is being done at runtime.
  • The argument list should be different while doing method overloading.
  • Polymorphism does not apply to overloading. The return type of overloaded methods should be the same.
    static binding is used for overloaded methods
public class A{
   public void show(int a){
      S.o.p("indhu");
   }
   public void show(int a,int b){
     S.o.p("sindhu");
   }

   public void show(float a){
     S.o.p("lavanya");
   }
   public static void main(String args[]){

       A a=new A();
       a.show(10);
      a.show(1,2);
     a.show(1.2);
   }
}
  • Method overriding is nothing but defining multiple functionalities with the same name with
    the same definition in superclass and subclass is known as Method overriding.
    While Run time only now which method is Executed.
  • Overriding gives slower performance compared to overloading. The reason is that the
    binding of overridden methods is being done at run time.
  • The argument list should be the same while doing method overriding.
    Polymorphism applies to overriding. 
  • In method overriding the return type of the overriding method can be different from overridden
    method.
  • Dynamic binding is used for method-overriding methods
public class A{
    public void display(){
      S.o.p("Indhu");
    }
}

Public class B extends A{
   public void display(){
     S.o.p("Sindhu");
   }
   public sttaic void main(String args[]){
      A a =new B();
      a.display();
   }
}


9. How to write custom Exceptions?
  • "MyException" is our exception class name. You can give any name of your choice.
    An important thing to be noted is our class extends the "Exception" class. This is all we need to do to make a custom-defined exception
    "Now we define a constructor of my class. This constructor takes a "String" argument. We call the super class' constructor(super class here is "Exception class") and pass this string to it. Not Java creates a new Exception with the message as in the string passed.

    •   public class MyException extends Exception

      {

          public MyException(String message)        

          { 

              super(message);       

          }     

      }
public class ExceptionDemo 
    {     
        public static void main(String args[]) throws Exception   
        {         
            ExceptionDemo exceptionDemo = new ExceptionDemo();        
            exceptionDemo.displayNumbers();   
        }     
        public void displayNumbers() throws MyException   
        {         
            for(int i=0;i<10;i++)      
            {     
               try{       
                System.out.print(i);          
                if(i==6)          
                {                 
                  throw new MyException("My ExceptionOccurred");             
                }
               catch(Exception e){
              System.out.println(e);
            }    
        }
    }


Output: 1 2 3 4 5 6  My exception occurred


10. What is serialization?

Serializable means transferable
  • The concept of transferring an object of a class from one location to another location is known as Serialization.
  • All the Java classes can be divided into two. 
  • The classes whose objects can be transferable.  Objects of all classes  that are implementing serializable  interface can be transferable
  • The classes whose objects can't be transferable.  Objects of all classes which are not implementing serializable interface cant be transferable.
  • To transfer the object need to convert it to byte stream:  serializing 
  • To receive an Object need to convert from byte stream to Object: deserializing
  • Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

public class Student implements java.io.Serializable
{
   public String name;
   public int number ;
   
}
 
import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "harsha";
       
     e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/student.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
} 
     Deserialization
     
import java.io.*;
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Student e = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Student ) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("student class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized student...");
      System.out.println("Name: " + e.name);

      System.out.println("Number: " + e.number);
By default all the variables in the object is converted to persistent state. In some cases, you may want to avoid persisting some variables because you don’t have the necessity to transfer across the network. So, you can declare those variables as transient. - See more at: http://www.javabeat.net/what-is-transient-keyword-in-java/#sthash.TMBQ2f9K.dpuf

    }
} 
 

Transient Keyword: 

  • The keyword transient in Java is used to indicate that the variable should not be serialized
  • By default, all the variables in the object are converted to a persistent state. In some cases, you may want to avoid persisting some variables because you don’t have the necessity to transfer across the network. So, you can declare those variables as transient.
  • If the variable is declared as transient, then it will not be persisted. It is the main purpose of the transient keyword.
 
11. What are abstract classes and interfaces?

Abstract Class:
  • An abstract class means hiding the implementation  and showing the function definition to the user is known as Abstract class
  • Abstract classes having Abstract methods and normal methods (non-abstract methods) will be there.
  • Abstract classes having methods will be anything that means public, private, or protected.
    In Abstract classes, variables will be anything( public, private, protected)
    For Abstract classes, we are not able to create objects directly. But Indirectly we can create objects using sub-class objects.
  • A Java abstract class should be extended using the keyword “extends”.
  • A Java abstract class can have instance methods that implement a default behaviour.
    If you know the requirements and partial implementation you can go for Abstract classes.
    an abstract class can extend from a class or from an abstract class.
  • An abstract class can extend only one class or one abstract class at a time. so Abstract classes can't support multiple inheritances.
  • In comparison with Java Interfaces, java Abstract classes are fast.
    If you add a new method to the abstract class, you can provide a default implementation of it. So you don’t need to change your current code.
  • Abstract classes can have constructors.
    We can run an abstract class if it has a main() method.

Interface :

  • The interface is nothing but some set of rules.
  • Interfaces have only Abstract methods.it is purely Achieve Abstraction.
  • In Interfaces, by default, the methods will be public abstract methods.
  • In Interfaces, by default, the variables will be static final.
  • For Interfaces, we can't create objects directly or Indirectly but we can give sub-class object references to the interface.
  • Java interface should be implemented using the keyword “implements”. 
  • methods of a Java interface are implicitly abstract and cannot have implementations.
  • If u don't know any requirements and any implementation you can go for Interfaces.
  • The interface can extend only from an interface
  • The interface can extend any number of interfaces at a time. so interfaces can support multiple inheritance(syntactically not implementation of multiple inheritance).
  • In comparison with Java abstract classes, java interfaces are slow as it requires extra indirection.
  • if  you add a new method to the interface, you have to change the classes which are implementing that interface
  • Interface having no constructor.
    we can’t run an interface because they can’t have the main method implementation.

 12. How to call garbage collectors explicitly?
  • When there are no more references to an object, the object is finalized and when the Garbage Collections starts these finalized objects get collected this will be done automatically by JVM.
  • But if we want to call  Garbage collection explicitly, There are methods
    1.System.gc();
    2.Runtime.gc(); 
How to prove it?
  • The java.lang.Runtime.freeMemory() method returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by free memory
Class GcDemo{

public static void main(String args[]){
System.out.println(Runtime.getRuntime().freeMemory());

    for (int i=0;i<= 100000;i++) {
    Double d = new Double(225);
    }
    System.out.println(Runtime.getRuntime().freeMemory());
    System.gc();
    System.out.println(Runtime.getRuntime().freeMemory());
}

13. Difference between ArrayList and vector?
  • Vector was introduced in the first version of Java. that's the reason only vector is a legacy class.
  • ArrayList was introduced in Java version1.2, as part of the Java collections framework.
  • Synchronization and Thread-Safe:
  • The vector is synchronized. Synchronization and thread-safe means at a time only one thread can access the code. In the Vector class, all the methods are synchronized. That's why the Vector object is already synchronized when it is created.
  • ArrayList is not synchronized.
How To Make ArrayList Synchronized:
  • We have a direct method in the collections class to make Arrraylist Synchronized.
  • List li=new ArrayList();
  • Collections.synchronized list(li);
Automatic Increase in Capacity:
  • A Vector defaults to doubling the size of its array.
  • ArrayList increases its size by 50%.
Performance:
  • Vector is slower than ArrayList.
  • ArrayList is faster than Vector.

14. Different ways to create objects in Java

   There are four different ways to create objects in Java:

  1.     Using new keyword
  2.     Using Class.forName():
  3.     Using clone():
  4.     Using Object Deserialization: 

Using new keyword:

This is the most common way to create an object in Java. Almost 99% of objects are created in this way.

MyObject object=new Object();

Using Class.forName():

  • If we know the name of the class & if it has a public default constructor we can create an object in this way.
  • Syntax:
  • Myobject obj=(MyObject) class.forName("object").newInstance();

Using clone():

  • The clone() can be used to create a copy of an existing object.
  • Syntax:
  • MyObject obj=new MyObject();
  • MyObject object=(MyObject )obj.clone();

Using Object Deserialization:

  • Object deserialization is nothing but creating an object from its serialized form.
  • Syntax:
  • objectInputStream istream=new objectInputStream(some data);
  • MyObject object=(MyObject) instream.readObject();

Java Program on creating an object using the new keyword:

    package com.instanceofjava;
    
    public class Employee
    {
    
          private int id;
          private String name;
    
          Employee(int id,String name){
          this.id=id;
          this.name=name;
    }
    
    public void display(){
          System.out.println(id+" "+name);
    }
    
    public static void  main (String args[]){

    Emploee e=new Employee(1,"Indhu");
    Employee e1=new Employee(2,"Sindhu");
    
    e.display();
    e1.display();
    
    }
    }

 Output:

    Indhu
    Sindhu

Java Program on creating objects using the clone() method:

    package com.instanceofjava;
    
    public class Empcloneable implements Cloneable {
    
      int a;
      String name;
    
    Empcloneable(int a,String name){
    
     this.a=a;
     this.name=name;
    
    }
    
     public Empcloneable clone() throws CloneNotSupportedException{
    
      return (Empcloneable) super.clone();
    
     }
    
    public static void main(String[] args) {

    Empcloneable e=new Empcloneable(2,"Indhu");
    System.out.println(e.name);
    
    try {

    Empcloneable b=e.clone();
    System.out.println(b.name);
    
    } catch (CloneNotSupportedException e1) {
    
     e1.printStackTrace();
    }
    
    }
    }

 Output:

    Indhu
    Indhu

Java Program on creating an object using Deserialization

    package com.instanceofjava;
    import java.io.*;
    public class Files
    {
    
    public static void main(String [] args)
    {
    
     Employee e = null;
    
    try
    {
    
    FileInputStream fileIn = new FileInputStream("/E/employee.txt");
    ObjectInputStream in = new ObjectInputStream(fileIn);
    
    e = (Employee) in.readObject();
    in.close();
    fileIn.close();
    
    }catch(IOException i)
    {
    i.printStackTrace();
    return;
    
    }catch(ClassNotFoundException c)
    {
    System.out.println("Employee class not found");
    c.printStackTrace();
    return;
    }
    
    System.out.println("Deserialized Employee...");
    System.out.println("Name: " + e.name);
    
    }
    
    }


 Output:

    Name: Indhu

Java Program on creating an object using class.forName();


    package com.instanceofjava;
    public class Sample{
    
    public static void main(String args[]){
    
    try {
    
     Class s= Class.forName("com.instanceofjava.Sample");
     Sample obj=(Sample) s.newInstance(); 
     System.out.println(obj.hashcode());
    
     } catch (Exception e) {
    
      e.printStackTrace();
    
    }
    
    }
    
    }

 Output:

    2007759836

15. Why Java does not support multiple inheritance?

Inheritance:

  • The concept of getting properties of one class object to another class object is known as inheritance.
  • Here properties mean variable and methods.

Types of Inheritance:

  1. Multiple inheritance.
  2. Multilevel inheritance.

 Multiple inheritance:

  • The concept of Getting the properties from multiple class objects to sub-class objects with the same priorities is known as multiple inheritances.
  • Java Doesn't Support multiple Inheritance.

Diamond problem:

  • In multiple inheritances there is every chance of multiple properties of multiple objects with the same name available to the sub-class object with the same priorities leads to ambiguity. 
  1. //Multiple inheritance program
  2. Class A{
  3. }
  4. Class B extends A{
  5. public void show(){
  6. }
  7. }
  8. Class C extends A{
  9. public void show(){
  10. }
  11. }
  12. Class D extends B, C{  // not supported by Java leads to a syntax error.
  13. }
  •  We have two classes B and c which are inheriting A class properties.
  • Here Class D inherits B class and C class So properties present in those classes will be available in Java.
  • But both classes are at the same level with the same priority.
  • If we want to use the show() method that leads to ambiguity
  • This is called the diamond problem.
  • Because of multiple inheritances, there is a chance of the root object getting created more than once.
  • Always the root object i.e. object of the object class has to be created only once.
  • Because of above mentioned reasons multiple inheritance would not be supported by Java.
  • Thus in Java, a class can not extend more than one class simultaneously. At most, a class can extend to only one class.
So these are the reasons that Java does not support multiple inheritances. Even though having this many reasons some people say that we also get some doubts when we are using interfaces. lets me clear this one also. our immediate question should be.

Is Java supports multiple inheritances using interfaces?

  • Before that, we need to know about interfaces.
  • Interfaces having fully abstract functionality.
  • This means methods in interfaces by default public abstract methods so we need to implement these methods in classes that are extending this interface.
   
  1. /Multiple inheritance program
  2. interface A{
  3. public void  show();
  4. }
  5. interface B{
  6. public void  display();
  7. }
  8. Class C Implements A,B{
  9. }

  • Here it seems we are achieving multiple inheritances by using interfaces. but we are not.
  • Syntactically it seems to be multiple inheritance but the actual implementation of multiple inheritance is not there. how can I say that? let me clear

Difference between interfaces and inheritance: in multiple inheritances

  • Inheritance means getting the properties from one class object to another class object.
  • This means if any class extends another class then the superclass methods can be used in sub-classes happily.
  • But in interfaces the methods in interfaces are fully abstract so we need to provide functionality in our extended class and use it .seems both are opposites right? yes.
  • That is the reason we can say interfaces only supports syntactical multiple inheritance which is not the implementation of multiple inheritance.
So finally java supports only the syntax of multiple inheritance and does not supports the implementation of multiple inheritance.
Inheritance is like debit and interface is like credit but the interface has its own importance in other concepts like server-side programming

16. Difference between throw and throws in Java

Throw: 

  • throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
  • If we are having our own validations in our code we can use this throw keyword.
  • For Ex: BookNotFoundException, InvalidAgeException (user defined) 
  1. //Custom exception
  2. package com.instanceofjavaforus;
  3. public class InvalidAgeException extends Exception {
  4.  InvaidAgeException(String msg){
  5.  super(msg);
  6.  }
  7. }
     

  1. package com.instanceofjavaforus;
  2. public class ThrowDemo {
  3. public boolean isValidForVote(int age){
  4.  try{
  5.    if(age<18){
  6.   throw new InvalidAgeException ("Invalid age for voting");
  7. }
  8.  }catch(Exception e){
  9.  System.out.println(e);
  10.  }
  11.   return false;
  12.  }
  13.   public static void main(String agrs[]){
  14.  ThrowDemo obj= new ThrowDemo();
  15.    obj.isValidForVote(17);
  16.   }
  17. }
We can throw predefined exceptions also

  1. package com.instanceofjavaforus;
  2. public class ThrowDemo {
  3. public void method(){
  4.  try{
  5.   
  6.   throw new NullPointerException("Invalid age for voting");
  7. }
  8.  }catch(Exception e){
  9.  System.out.println(e);
  10.  }
  11.  }
  12.   public static void main(String agrs[]){
  13.  ThrowDemo obj= new ThrowDemo();
  14.    obj.method();
  15.   }
  16. }
Like this, we can throw checked exceptions and unchecked exceptions also. But the throw keyword is mainly used to throw used defined exceptions/custom exceptions.

Throws:

  • The functionality of the throws keyword is only to explicitly mention that the method is proven to transfer un handled exceptions to the calling place.
  1. package com.instanceofjavaforus;
  2. public class ThrowSDemo {
  3. public void method(int a,int b) Throws ArithmeticException{
  4.  
  5. inc c= a/b;
  6.  }
  7.   public static void main(String agrs[]){
  8.  ThrowDemo obj= new ThrowDemo();
  9.    try{
  10. obj.method(1,0);
  11. }catch(Exception e){
  12.  System.out.println(e);
  13. }
  14.   }
  15. }

 Uses of throws keyword:

  • Using the throws keyword we can explicitly provide the information about unhand-led exceptions of the method to the end user, Java compiler, or JVM.
  • Using the throws keyword we can avoid try-catch with respect to the statements which are proven to generate checked exceptions.
  • It is highly recommended not to avoid try-catch with respect to the statements which are proven to generate exceptions in the main method using the throws keyword to the main() method.

17. What is the difference between equals() method and == operator

== operator:

  •  == operator used to compare objects references.
  • used to compare data of primitive data types
  • if we are comparing two objects using the "==" operator if the reference of both is the same then it will return true otherwise returns false.
  • obj1==obj2;
  • If we are comparing primitive data type variables then it compares data of those two variables
  • Ex: int a=12; int b=12; if(a==b) returns true

Comparing primitive values: 

  1. package com.instanceofjava;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {

  6. int a=12;
  7. int b=13;
  8. int c=12;
  9.  
  10. if(a==b){
  11. System.out.println("a and b are equal");
  12.  
  13. if(b==c){
  14. System.out.println("a and b are equal");
  15.  
  16. }
  17. }

Comparing Objects:

  1. package com.instanceofjavaforus;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  Demo obj1= new Demo();
  8. Demo obj2=new Demo();
  9.  
  10. if(obj1==obj2){ // here both are two different objects(memory allocation wise);
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1=new String("abc");
  8. String s2=new String("abc");
  9.  
  10. if(s1==s2){ // here it returns false
  11. System.out.println("obj1 and obj2 are referring to same address");
  12. }else{
  13.  System.out.println("obj1 and obj2 are referring to different address");
  14.  
  15. }
  16. }

Comparing String Literals:

  •  If we declared two string literals with the same data then those will refer to the same reference.
  • means if we create any object using a string literal then it will be created in the string pool 
  • then if we are created another literal with the same data then it won't create another object but rather refers to the same object in the pool.
  • so if compare two string literals with the same data using the "==" operator then it returns true.
  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringLiteralDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1="abc";
  8. String s2="abc";
  9.  
  10. if(s1==s2){ // here it returns true
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

equals() method:

  • equals() method defined in the "object" class.
  • By default equals methods behave like the "==" operator when comparing objects.
  • By default equals() method compares references of objects.
  • But All wrapper classes and String classes override this equals method and comparing data.
  • This means in the String class and in All wrapper classes this equals() method is overridden to compare data of those class objects. 

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.       String s1=new String("ABC");
  8.       String s2=new String("ABC");
  9.  
  10.       if(s1.equals(s2)){ // here it returns true
  11.  
  12.                System.out.println(" data present in obj1 and obj2 is same");
  13.  
  14.      }else{
  15.  
  16.                System.out.println(" data present in obj1 and obj2 is different");
  17.  
  18.      }
  19. }
  20. }

 Comparing custom objects:

  • If we want to compare custom objects means our own objects' data.
  • Then we need to override the equals method and in that, we need to compare data.

  1. package com.instanceofjavaforus;

    public class Patient {
       String name;
       Patient(String name){
           this.name=name;
       }
          public boolean equals(Patient obj){
          
           if(this.name.equals(obj)){
               return true;
           }else{
               return false;
           }
       }
           public static void main(){
            Patient obj1= new Patient("sam");
           
            Patient obj2= new Patient("sam");
           
            System.out.println(obj1.equals(obj2)); //returns true
        }
           
    }

Important points to note about equals() and "==":

  • "==" used to compare data for primitive data type variables .
  • "==" operator compares objects references
  • By default equals() method behaves like the "==" operator for objects means comparing objects references.
  • All wrapper classes and String class override this equals() method and compares data of two objects. if the same returns true.(whenever we override the equals() method we need to override the hashcode() method too and if two objects on an equal method same then both should have the same hashcode).
  • And in the equals() method in string class logic includes the "==" operator too.

  1. package com.instanceofjava;
  2.  
  3. public boolean equals(Object anObject) {
  4.    if (this == anObject) {
  5.       return true;
  6.      }
  7.  if (anObject instanceof String) {
  8.      String anotherString = (String) anObject;
  9.      int n = value.length;
  10.     if (n == anotherString.value.length) {
  11.     char v1[] = value;
  12.      char v2[] = anotherString.value;
  13.   int i = 0;
  14. while (n-- != 0) {
  15.    if (v1[i] != v2[i])
  16.            return false;
  17.            i++;
  18.        }
  19.          return true;
  20.         }
  21.     }
  22.        return false;
  23.   }

18. Differences between HashMap and Hash-table

Differences between HashMap and Hash-table
  •  Synchronization or Thread Safe: One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization. Java 5 introduced ConcurrentHashMap which is an alternative to Hashtable and provides better scalability than Hashtable in Java. Synchronized means only one thread can modify a hash table at one point in time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for the lock to be released.
  • Null keys and null values: The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap permits one null key and multiple null values.
    Hashtable doesn't permit any sort of nulls (key or values).).
  • Iterating the values: The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM with the best effort. This is also an important difference between Enumeration and Iterator in Java.
  • Default Capacity: 
  •  Hashmap: static final int DEFAULT_INITIAL_CAPACITY =16  static final float DEFAULT_LOAD_FACTOR = 0.75f;  
  • Hashtable:  static final int DEFAULT_INITIAL_CAPACITY = 11;   static final float DEFAULT_LOAD_FACTOR = 0.75f;
  • HashMap does not guarantee that the order of the map will remain constant over time.
HashMap can be synchronized by using Collections.synchronizedMap() method
Map m = Collections.synchronizedMap(hashMap);
Example:

import java.util.HashMap;

import java.util.Hashtable;

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

 

        Hashtable<String,String> hashtableobj = new Hashtable<String, String>();
        hashtableobj.put("name", "ramu");
        hashtableobj.put("petname", "ram");
        System.out.println("Hashtable object output :"+ hashtableobj);



        HashMap hashmapobj = new HashMap();
        hashmapobj.put("name", "ramu"); 
        hashmapobj.put("pertname", "ram");
        System.out.println("HashMap object output :"+hashmapobj);

 }
}











Tuesday, 18 August 2015

Why Java doesn't support multiple inheritance

1)

The first reason is ambiguity around Diamond problem, consider a class A has foo() method and then B and C derived from A and has there own foo() implementation and now class D derive from B and C using multiple inheritance and if we refer just foo() compiler will not be able to decide which foo() it should invoke.

This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below

A foo()
/ \
/ \
foo() B C foo()
\ /
\ /
D
foo()

In my opinion even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.

Some times if you give this reason to interviewer he asks if C++ can support multiple inheritance than why not Java. 

hmmmmm in that case I would try to explain him the second reason which I have given below that its not because of technical difficulty but more to maintainable and clearer design was driving factor though this can only be confirmed by any of java designer and we can just speculate.

2)

Second and more convincing reason to me is that multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity.

Also java avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.

Tuesday, 4 August 2015

What is the output of following program?

  1. package com.javastepbystep;

  2. class A
  3. {
  4.  
  5.      static int method1(int i)
  6.     {
  7.          return method2(i *= 11);
  8.      }
  9.  
  10.       static int method2(int i)
  11.      {
  12.           return method3(i /= 11);
  13.       }
  14.  
  15.        static int method3(int i)
  16.       {
  17.            return method4(i -= 11);
  18.       }
  19.  
  20.       static int method4(int i)
  21.      {
  22.          return i += 11;
  23.      }
         
  24.      public static void main(String [] args)
  25.     {
  26.           System.out.println(method1(11));
  27.      }
  28.  
  29. }

Ans: 11

Sunday, 2 August 2015

What is the output of following program?

 public class B{
    
      B b= new B();
    
     public int show(){
          return (true ? null : 0);
     }
    
     public static void main(String[] args)  {
    
            B b= new B();
            b.show();
        }
    
    }

Output:
  1. Exception in thread "main" java.lang.StackOverflowError
  2. at com.instanceofjava.B.<init>(B.java:3)
  3. at com.instanceofjava.B.<init>(B.java:5)
  4. at com.instanceofjava.B.<init>(B.java:5) 

Explanation:

  • Whenever we create the object of any class constructor will be called first and memory allocated for all non-static variables
  • Here  B b= new B(); the variable is an object and assigned to a new object of the same class
  • B b= new B(); statement leads to recursive execution of constructor will create infinite objects so at the run time an exception will be raised
  • Exception in thread "main" java.lang.StackOverflowError
  • The common cause for a stack overflow exception is a bad recursive call. Typically this is caused when your recursive functions don't have the correct termination condition

Thursday, 30 July 2015

What will be the output of java program

public class Test {
    public static void main(String[] args) {
        System.out.println(Math.min(Double.MIN_VALUE, 0.0d));
    }
}
Answer: 

This question is tricky because unlike the Integer, where MIN_VALUE is negative, both the MAX_VALUE and MIN_VALUE of the Double class are positive numbers.

The Double.MIN_VALUE is 2^(-1074), a double constant whose magnitude is the least among all double values. So unlike the obvious answer, this program will print 0.0 because of Double.MIN_VALUE is greater than 0.

Difference between == and .equals()

They both differ very much in their significance. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects.

Whereas the '==' operator is expected to check the actual object instances are same or not.

For example, lets say, you have two String objects and they are being pointed by two different reference variables s1 and s2.


 s1 = new String("abc");
 s2 = new String("abc");

Now, if you use the "equals()" method to check for their equivalence as


 if(s1.equals(s2))
      System.out.println("s1.equals(s2) is TRUE");
 else
      System.out.println("s1.equals(s2) is FALSE");
You will get the output as TRUE as the 'equals()' method check for the content equivality.

Lets check the '==' operator.


if(s1==s2)
     System.out.printlln("s1==s2 is TRUE");
   else
     System.out.println("s1==s2 is FALSE");

Now you will get the FALSE as output because both s1 and s2 are pointing to two different objects even though both of them share the same string content.

It is because of 'new String()' everytime a new object is created.

Try running the program without 'new String' and just with


   String s1 = "abc";
   String s2 = "abc";

You will get TRUE for both the tests.

Monday, 13 July 2015

Java Creating a Thread

In the most general sense, you create a thread by instantiating an object of type Thread. Java identifies two ways in which this can be accomplished:

(i) You can implement the Runnable interface.

(ii) You can extend the Thread class, itself.

1. Implementing Runnable


The easiest way to create a thread is to create a class that implements the Runnable interface. To implement Runnable, a class need only implement a single method called run():

public void run()

Inside the run() method, you will define the code that constitutes the new thread. The run() can call other methods, use other classes and declare variables, just like the main thread.

The only difference is that run() establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run() returns.

After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class using one of the following constructors:

Thread(Runnable threadObj)

Thread(Runnable threadObj, String threadName)

Here threadObj is the object whose run method is called and threadName is the name of the new thread.

After the new thread is created, it will not start running until you call start() method. The start() method puts the thread in the ready queue (runnable state). Whenever the thread gets scheduled its execution will start from the run() method.

Example:

class X implements Runnable
      public void run()
     { 
          for(int i=1; i<=5; i++)
          { 
               System.out.println("Child Thread: " + I);
          }

          System.out.println("Exiting child thread");

      }

}

class RunnableTest
     public static void main(String args[])
     { 
         X runnable  = new X();

         Thread ct = new Thread(runnable);

          ct.start();

          System.out.println("main thread exiting");

      }

}

Output:

main thread exiting

Child Thread: 1

Child Thread: 2

Child Thread: 3

Child Thread: 4

Child Thread: 5

Exiting child thread

Example:

class NewThread implements Runnable
     Thread t;

      NewThread()
     { 
         t = new Thread(this, "Demo Thread");

         System.out.println("Child thread: " + t);

         t.start();

     }

     public void run()
     { 
           for(int i=5; i>0; i--)
           {
                 try
                 { 
                       System.out.println("Child Thread: " + I);
                 }
                 catch(InterruptedException e)
                { 
                     System.out.println(e);
                }
      }

      System.out.println("Exiting child thread”);

      Thread.sleep(500);

    }

}

class ThreadDemo
     public static void main(String args[])
    { 
          new NewThread();
          try
          { 
               for(int n=5; n>0; n--)
               {
                   System.out.println("Main Thread: " + n);
                   Thread.sleep(1000);
               }
           }
           catch(InterruptedException e)
           {
                System.out.println("main thread interrupted");
            }
           System.out.println("main thread exiting");
     }
}

Output:

Child thread: Thread[Demo Thread,5,main]

Main Thread: 5

Child Thread: 5

Child Thread: 4

Main Thread: 4

Child Thread: 3

Child Thread: 2

Main Thread: 3

Child Thread: 1

Exiting child thread

Main Thread: 2

Main Thread: 1

main thread exiting

2. Extending Thread class

The second way to create a thread is to create a new class that extends Thread and then create an instance of that class. The extending class must override the run() method, which is the entry point for the new thread. It must also call start() to begin the execution of the new thread.

Example:

public class NewThread extends Thread
     NewThread()
     { 
            super("Demo Thread");
            System.out.println("Child thread: " + this);
            start();
      }

      public void run()
      { 
          for(int i=5; i>0; i--)
          { 
              try
              {
                  System.out.println("Child Thread: " + I);
                  sleep(500);
              }
              catch(InterruptedException e)
              {

              }

          }
          System.out.println("Exiting child thread");
          System.out.println(e);
     }
}

class ExtendThread
        public static void main(String args[])
        { 
            new NewThread();
            try
            { 
                for(int n=5; n>0; n--)
                {
                     System.out.println("Main Thread: " + n);
                     Thread.sleep(1000);
                }
             }
            catch(InterruptedException e)
            {
                 System.out.println("main thread interrupted");
            }
            System.out.println("main thread exiting");
       }
}

Output:

Child thread: Thread[Demo Thread,5,main]

Main Thread: 5

Child Thread: 5

Child Thread: 4

Main Thread: 4

Child Thread: 3

Child Thread: 2

Main Thread: 3

Child Thread: 1

Exiting child thread

Main Thread: 2

Main Thread: 1

main thread exiting

Note: If the thread is not assigned any name, it will be something like Thread-1, Thread-2, Thread-3 etc.

3. Choosing an Approach

The thread class defines several methods that can be overridden by a derived class. Out of these methods, the only one that must be overridden is run().

That is, of course, the same method required when you implement the Runnable interface. Many Java programmers feel that classes should be extended only when they are being enhanced or modified in some way.

So, if you will not be overriding any of Thread’s other methods, it is probably best simply to implement a Runnable interface.

Java The main thread

When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program because it is the one that is executed when your programs begins.

The main thread is the thread from which other “child” threads are created.

Although the main thread is created automatically when your program is started, it can be controlled through a Thread object. To do so, you must obtain a reference to it by calling the method currentThread(), which is public static member of Thread class. This method returns a reference to the thread in which it is called.

Once you have a reference to the main method, you can control it just like any other thread.

Example: The following example demonstrates how we can acquire reference of main thread and then access its properties using methods of Thread class.

class CurrentThreadDemo
     public static void main(String args[])
     { 
           Thread t = Thread.currentThread();
           System.out.println("Current thread: " + t);

           System.out.println("Name: " + t.getName());
           System.out.println("Priority: " + t.getPriority());

            t.setName("My Thread");

            t.setPriority(10);

            System.out.println("After name and priority change : " + t);

             System.out.println("New Name: " + t.getName());

             System.out.println("New Priority: " + t.getPriority());

             try
             { 
                    for(int n=5; n>0; n--)
                    { 
                         System.out.println(n);
                    }
             }
             catch(InterruptedException e)
             { 
                  System.out.println("main thread interrupted");
             }

             Thread.sleep(1000);
     }

}

Output:

Current thread: Thread[main,5,main]

Name: main

Priority: 5

After name and priority change : Thread[My Thread,10,main]

New Name: My Thread

New Priority: 10

5

4

3

2

1

The sleep() method in Thread might throw an InterruptedException, which is a checked exception. This would happen if some other thread wanted to interrupt this sleeping one.

Notice the output produced when t (thread reference) is used as an argument to println(). This displays in order: the name of the thread, its priority, and the name of its group. Its priority is 5, which is the default value, and main is also the name of the group of thread to which this thread belongs.

A thread group is a data structure that controls the state of a collection of threads as a whole.

Java The Thread class and the Runnable interface

Java’s multi-threading system is built upon the Thread class, its methods, and its companion interface, Runnable. This class belongs to package java.lang and hence there is no need of explicitly importing it.

Thread encapsulates a thread of execution, since you cannot directly refer to the internal state of a running thread, you will deal with it through its proxy, the Thread instance that spawned it. To create a new thread your program will either extend Thread class or implement the Runnable interface.

The Thread class defines several methods that help manage threads:


Java Messaging

When programming with most other languages, you must depend on the O.S. to establish communication between threads. This, of course, adds overhead.

By contrast, Java provides a clean, low-cost way for two or more threads to talk to each other, via calls to predefined methods that all objects have.

Java’s messaging system allows a thread to enter a synchronized method on an object, and then wait there until some other thread explicitly notifies it to come out of wait state.

Java Synchronization

Because multi-threading introduces an asynchronous behaviour to your programs, there must be a way for you to enforce synchronization when you need it.

For example, if you want two threads to communicate and share a complicated data structure, such as a linked list, you need some way to ensure that they do not conflict with each other.

That is, you must prevent one thread from writing data while another thread is in the middle of reading it. Java uses monitor for inter-thread synchronization.

You can think of a monitor as a very small box that can hold only one thread.

Once a thread enters a monitor, all other threads must wait until that thread exits the monitor. In this way, a monitor can be used to protect a shared asset from being manipulated by more than one thread at a time.

Most multi-threaded systems expose monitors as objects that your program must explicitly acquired and lock. Java provides a cleaner solution.

There is no class "monitor", instead, each object has its own implicit monitor that is automatically entered when one of the object's synchronized method is called.

Once a thread is inside a synchronized method no other thread can call any other synchronized method on the same object. This enables you to write very clear and concise multi-threaded code, because synchronization support is built into the language.

Java Thread Priorities

Java assigns to each thread a priority that determines how that thread should be treated with respect to the others.

Thread priorities are integers that specify the relative priority of one thread to another. As an absolute value, a priority is meaningless; a higher-priority thread does not run any faster than a lower-priority thread if it is the only thread running. Instead, a thread’s priority is used to decide when to switch from one running thread to next. This is called a ontext switch.

The rules that determine when a context switch takes place are simple:

  • A thread can voluntarily (on its own) relinquish control. This is done by explicitly yielding, sleeping or blocking on pending I/O. In this scenario, all other threads are examined, and normally the highest-priority thread that is ready to run is given the CPU.

  • A thread can be pre-empted by a higher-priority thread. In this case, a lower priority thread that does not yield the processor is simply pre-empted no matter what it is doing, by a higher priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking. Some OS support non-preemptive priority based scheduling. In such case a high priority thread gets chance only when low priority thread completes.
  • In cases where two threads with the same priority are competing for CPU cycles, the situation is a bit complicated. For OS such as windows 98, threads of equal priority are normally time-sliced automatically in the round-robin fashion. For other types of OS's, thread of equal priority must voluntarily (on their own) yield (give) control to their peers. If they do not, the other threads will not run.

Note: Problems can arise from the differences in the way that O.S.’s context-switch threads of equal priority.

Java Thread Life Cycle (Thread States)

Thread exists in several states. A thread can be running. It can be ready to run as soon as it gets CPU time. A running thread can be suspended, which temporarily suspends its activity. A suspended thread can then be resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately. Once terminated a thread cannot be resumed.

1. Newborn State

When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state, we can do only one of the following things with it:

1. Schedule it for running using the start() method.

2. Kill it using stop() method

If scheduled, it moves to runnable state. If we attempt to use any other method at this stage, an exception will be thrown.

2. Runnable State

The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is, the thread has joined the queue of threads that are waiting for execution. If all threads are of equal priority, then normally they are given time slots for execution in round robin fashion. The thread that relinquishes control joins the queue at the end and again waits for its run. However, if we want a thread to relinquish control to another thread of equal priority before its turn comes, it can do so by invoking the yield() method.

3. Running State

Running means that the processor has given its time to the thread for its execution. The thread runs until it relinquishes control on its own or it is pre-empted by a higher priority thread.

A running thread may relinquish its control in one of the following situations:

  • Its time-slice is over
  • It is pre-empted by a higher priority thread
  • It yields i.e. voluntarily gives up control.
  • It has completed its execution
  • It is stopped by some other thread.
  • It has been suspended using suspend() method; a suspended thread can be revived by using the resume() method. This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it.
  • It has been made to sleep. We can put a thread to sleep for a specified time period using the static method sleep(time) of Thread class where time is in milli-seconds. This means that the thread is out of the queue during the time period. The thread re-enters the runnable state as soon as this time period is elapsed.
  • It has been told to wait until some event occurs. This is done using the wait() method. The thread can be scheduled to run again using the notify() method.
  • It is performing some I/O operation.

4. Blocked State

A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended, sleeping or waiting in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again.

5. Dead State

Every thread has a life cycle. A running thread ends its life when it has completed executing its run() method. It has a natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death. A thread can be killed as soon as it is born, or while it is running, or even when it is in “not runnable” (blocked condition).

Wednesday, 8 July 2015

Java Multi-Threaded Programming

1. Introduction

A thread is a single flow of control within a program. Thread is very much similar to a process. In fact, the thread is also called a lightweight process.

1.1 Thread v/s Process

Normally different processes occupy different memory space. When the CPU shifts from one process to another process, the state of the currently running process is saved and the state of another process is restored. No useful work is being done during state switch. This is referred to as context switch. The context switch time should be as less as possible to maximize the CPU utilization.

Threads are also like independent processes but they share the same memory and state. The separate threads also have separate state but the state is very small as compared to process state.

The state may contain just program counter and stack pointer. So switching from one thread to another thread takes very little time. Thus the context switch time for threads is very small as compared to the process. Hence CPU utilization is high in case of multiple threads as compared to the utilization in case of multiple processes. Threads are also referred to as light-weight process.

1.2 Multi-Threaded program

A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multi-threading is a specialized form of multi-tasking.

For example, a program may have three threads:

  • One handling the printing
  • One handling the editing
  • One downloading a file from the Internet.

All these threads might be running concurrently thus maximizing the CPU utilization.

1.3 Process-based Multi-tasking


Most of the operating systems allow you to run two or more programs at the same time. It is referred to as process-bases multi-tasking. For example, you can run a Java program and at the same time you may be editing a word document. The process-based multi-tasking ensures that there will be some program to be executed most of the time so it increases the CPU utilization.  

In process-based multi-tasking, a program is the smallest unit of code that can be dispatched by the scheduler.

1.4 Thread-based multi-tasking

Thread is the smallest unit of execution in a thread-based multi-tasking environment. A process can be divided into a number of threads executing concurrently. This allows us to handle more than one task concurrently in a single program. For example, you can edit a word document and at the same time print a portion of it or another document.

Thread-based multi-tasking improves CPU utilization just like process-based multi-tasking. But at the same time it effectively speeds up the execution of a single program by executing its different parts concurrently in separate threads.

Thus process based multi-tasking deals with the “big picture”, and thread-based multi-tasking handles the details.

1.5 The Java Thread Model

The Java run-time system depends on threads for many things, and all the class libraries are designed with multi-threading in mind. In fact, Java uses threads to enable the entire environment to be asynchronous. This helps reduce inefficiency by preventing the waste of CPU cycles.

Single threaded systems use an approach called an event loop with polling. In this model, a single thread of control runs in an infinite loop, polling a single event queue to decide what to do next. In a single threaded environment, when a thread blocks (that is, suspends execution) because it is waiting for some resource, the entire program stops running.

The benefit of Java's multi-threading is that the main loop/polling mechanism is eliminated.

When a thread blocks in Java program, only the single thread that is blocked pauses, all other threads continue to run.