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

What are the oops concepts in java?

  • Oops concepts are the rules which are supposed to be satisfied by a programming language in order to call that programming language as an Object Oriented Programming Language
  • The three oops concepts are
            i.Encapsulation
            ii. Polymorphism
            iii.Inheritance
  • Encapsulation:
    The process of binding the data with corresponding functions.
  • Polymorphism:
    Defining multiple methods with same name.
  • Inheritance:
    Getting the properties from one class object to another class object 

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 compiler because print(null) here will find the two best specific matches i.e. print(String) and print(char[]) . So compiler is unable to determine which method to call here .
  • Compilation Error:
       System.out.println(null)

Program #1: what will happen when we print System.out.println(null)


System out prinln 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.

 Program #2: what will happen when we print System.out.println(null) by type casting
  

  1. package com.systemoutprintn;
  2. public class Test {
  3.  
  4.     /**
  5.      * @Website: www.instanceofjava.com
  6.      * @category: System.out.println(null)
  7.      */
  8.  
  9. public static void main(String[] args) {
  10.  
  11.          System.out.println((String)null);//null
  12.          System.out.println((Object)null);//null
  13.          System.out.println((char[])null);
  14.             
  15.  
  16. }
  17.  
  18. }

 Output:
 

  1. null
  2. null
  3. Exception in thread "main" java.lang.NullPointerException
  4.     at java.io.Writer.write(Unknown Source)
  5.     at java.io.PrintStream.write(Unknown Source)
  6.     at java.io.PrintStream.print(Unknown Source)
  7.     at java.io.PrintStream.println(Unknown Source)
  8.     at com.systemoutprintn.Test.main(Test.java:13)


Explain System.out.println()?


  • System is a class Which 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(){}}




Final ,finally and finalize()?

Final:

  • Any variable declare along with final modifier then those variables treated as final variable.
  •  if we declare final variables along with static will became constants.
  • public final String name = "foo"; //never change this value
  • If you declare method as final that method also known as final methods.Final methods are not overridden.means we can't overridden that method in anyway.
  • 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 try or catch.finally blocks are complasary 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 value from finally block, calling System.exit from try block etc
  • finally block always execute, 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 which is present in Java.lang.Object class.
  •  Before an object is garbage collected, the garbage collector calls this finalize() of object.Any unreferncebefore destorying if that object having any connections with databse 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 from a long time the garbage collector will destroy that objects.
  • public void finalize() {
      //free resources (e.g. unallocate memory)
      super.finalize();
    }
Select Menu