What is Synchronization?

  • The concept of avoiding multiple threads entering into a common functionality of common object  simultaneously is known as thread safe or synchronization.
  • we implement the concept of thread safe  using synchronized keyword. The functionality of Synchronized keyword is to avoid multiple threads entering into a common functionality of common functionality. 

Producer consumer problem:

Common   class:

package com.instanceofjavaforus;

public class Common {
    int x;
   
    boolean flag=true;
    //if flag is true producer thread has to produce
    // if flag is false consumer thread has to produce

    synchronized public void produce(int i){
       
        if(flag){
           
            x=i;
            System.out.println("producer thread has produced "+i);
            flag=false;
            notify();
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }      
        }
     }
   

    synchronized public int consume(){
        if(flag){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }
        flag=true;
        notify();
        return x;
    }
   
}

package com.instanceofjavaforus;

public class ProducerThread extends Thread {
    Common c;
   
    ProducerThread(Common c){
        this.c=c;
    }
   
    public void run(){
        int i=0;
        while(true){
           
            i++;
            c.produce(i);
           
           
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    } 
}

ConsumerThread:

package com.instanceofjavaforus;

public class ConsumerThread extends Thread {
   
    Common c;
   
    ConsumerThread(Common c){
        this.c=c;
    }
   
    public void run(){
       
        while(true){
           
            int x=c.consume();
            System.out.println("Consumer consumes"+x);
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    }
}

ProducerConsumerTest:

package com.instanceofjavaforus;

public class ProducerConsumerTest {
   
    public static void main(String args[]){
        Common c= new Common();
        ProducerThread pt=new ProducerThread(c);
        ConsumerThread ct= new ConsumerThread(c);
        pt.start();
        ct.start();
    }
}

Output:

producer thread has produced 1
Consumer consumed 1
producer thread has produced 2
Consumer consumed 2
producer thread has produced 3
Consumer consumed 3
producer thread has produced 4
Consumer consumed 4
producer thread has produced 5
Consumer consumed 5
producer thread has produced 6
Consumer consumed 6

what is the difference between method overloading and method overriding?

Method Overloading in java

  • Method overloading is nothing but defining multiple methods with same name with
    different parameters is known as method overloading
  • while compile time itself we know which method going to get executed.
  • Overloading gives better performance compared to overriding. The reason is that the
    binding of overridden methods is being done at runtime.
  • Argument list should be different while doing method overloading.
  • Return type of overloaded methods should be same.
    static binding is used for overloaded methods
Method overloading interview questions java  

  1. package com.instanceofjava;
  2. class A{
  3.  
  4. public void show(int a){
  5. System.out.println("saidesh");
  6. }
  7.  
  8. public void show(int a,int b){
  9. System.out.println("ajay");
  10. }
  11.  
  12. public void show(float a){
  13. System.out.println("vinod");
  14. }
  15. public static void main(String args[]){
  16.  
  17. A a=new A();
  18.  
  19. a.show(10);
  20. a.show(1,2);
  21. a.show(1.2);
  22.  
  23. }
  24. }
Output:

  1. saidesh
  2. ajay
  3. vinod

Method Overriding in java:
  • Method overriding is nothing but defining multiple methods with same name with
    same definition in super class and sub class 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.
  • Argument list should be same while doing method overriding.
    Polymorphism applies to overriding. 
  • In method overriding the return type of overriding method can be different from overridden
    method.
  • Dynamic binding used for method overriding methods
Top 10 Interview Programs and questions on method overriding in java  


difference between overloading and overriding in java

What is abstract class and interfaces ?

Abstract Class:

  • 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 means public ,private,protected.
    In Abstract classes  variables will be anything( public, private, protected)
    For Abstract classes we not able to create object directly.But Indirectly we can create object using sub class object.
  • A Java abstract class should be extended using keyword “extends”.
  • A Java abstract class can have instance methods that implements a default behavior.
    If you know requirement and partially implementation you can go for Abstract classes.
    abstract  class  can extend from a class or from an abstract class.
  • Abstract class can extend only one class or one abstract class at a time. so Abstract classes can't support multiple inheritance.
  • In comparison with java Interfaces, java Abstract classes are fast.
    If you add new method to abstract class, you can provide 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 main() method.

Interface :

  • Interface nothing but some set of rules.
  • Interfaces having 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 object directly or Indirectly but we can give sub class object reference to interface .
  • Java interface should be implemented using keyword “implements”. 
  • methods of a Java interface are implicitly abstract and cannot have implementations.
  • If u don't know Any requirement and any implementation you can go for Interfaces.
  • Interface can extend only from an interface
  • Interface can extend any number of interfaces at a time. so interfaces can support multiple inheritance(syntactical not implementation of multiple inheritance).
  • In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
  • if  you add new method to 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 main method implementation.

     Click here for more points with example

    How to call garbage collector explicitly?

    • When there are no more references to an object, the object is finalized and when the Garbage Collections starts these finalized objects gets collected this will 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?
    • 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 freeMemory
    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());
    }

    what is cloning? difference between shallow copy/shallow cloning and deep copy /deep cloning?

    Shallow copy:

    • Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.


    Example Program:
    take a sample class
    Step 1:
    public class Sample {

    int a;
    int b;

    Sample(int a, int b){
        this.a=a;
        this.b=b;
    }

    }
    Step 2:
    package com.oops;

    public class empclone implements Cloneable {

        Sample s;
        int a;
       
        empclone(int a, Sample s){
            this.a=a;
            this.s=s;
          
        }
       
        public Object clone()throws CloneNotSupportedException{
          
            return super.clone();
            }
              
       
        public static void main(String[] args) {
        
            empclone a= new empclone(2, new Sample(3,3));
            empclone b=null;
       
            try {
                 b=(empclone)a.clone();
              
            } catch (CloneNotSupportedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(a.s.a);
            System.out.println(b.s.a);
          
            a.s.a=12;
            System.out.println(a.s.a);
            System.out.println(b.s.a);
        }

    }

    Output:
    3
    3
    12
    12
    whenever we implements cloneable interface and ovverides clone() method
    public Object clone()throws CloneNotSupportedException{         
            return super.clone();
            } 
    By default it will give shallow copy means if any objects presents in orninal class it simply gives reference so if we change anything in original object changes will made to copied/cloned object
    because both are pointing to same object

    Deep copy:

    •  A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers. 


    Example Program:
    take a sample class
    Step 1:
    public class Sample {

    int a;
    int b;

    Sample(int a, int b){
        this.a=a;
        this.b=b;
    }

    }
    Step 2:
    package com.oops;

    public class empclone implements Cloneable {

        Sample s;
        int a;
       
        empclone(int a, Sample s){
            this.a=a;
            this.s=s;
          
        }
       
     public Object clone()throws CloneNotSupportedException{ 
          return new empclone(this.a, new Sample(this.s.a,this.s.a));

              
       
        public static void main(String[] args) {
        
            empclone a= new empclone(2, new Sample(3,3));
            empclone b=null;
       
            try {
                 b=(empclone)a.clone();
              
            } catch (CloneNotSupportedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(a.s.a);
            System.out.println(b.s.a);
          
            a.s.a=12;
            System.out.println(a.s.a);
            System.out.println(b.s.a);
        }

    }

    Output:
    3
    3
    12
    3


    whenever we implements cloneable interface and ovverides clone() method and instead of calling super.clone();
    create new object with same data
    new empclone(this.a, new Sample(this.s.a,this.s.a));
    so it will create new object instead referring to same object as shallow
     public Object clone()throws CloneNotSupportedException{ 
          return new empclone(this.a, new Sample(this.s.a,this.s.a));

    now we write our login in clone(); method
    so complete object will be copied
    this is deep cloning

    What is class and Object 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.
    • Class will act as the base for encapsulation and implement the concept of encapsulation through objects.
    • Any java applications looks like collection of classes but where as c- application looks like collection of functions

    Object:

    • Object is nothing but 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 object.

    For more points click here

    Select Menu