Skip to content

Instantly share code, notes, and snippets.

@simplytunde
Last active August 29, 2015 14:12
Show Gist options
  • Save simplytunde/b6dc185df3c9eb866520 to your computer and use it in GitHub Desktop.
Save simplytunde/b6dc185df3c9eb866520 to your computer and use it in GitHub Desktop.
Java:Class Key Notes

Java class key notes

  • Non static block called for every object created
public class HelloWorld{
      public String a;
      public String b;   
      {
         a="A";
         b="B";
         System.out.println("non-static block is called for every object created");
      }
     public static void main(String []args){
        HelloWorld h=new HelloWorld();
        System.out.println(h.a);
        System.out.println(h.b);
        h=new HelloWorld();
     }
}
  • static initialization block is called when you first access any static member
public class HelloWorld{
      static   String a;
      static   String b;   
     static{
         a="A";
         b="B";
         System.out.println("Static block is called once");
     }
     public static void main(String []args){
        System.out.println(HelloWorld.a);
        System.out.println(HelloWorld.b);
     }
}
  • JVM load .class file when even you access class static member(including constructor)
  • variables get initialize first even before constructor is called either to default or whatever value you provide.
  • class primitives variable get default value and object reference get null as default value.
  • finalize() is only called when program needs memory and is being garbage collected. Use finalize is you need to release(free()) some c or c++ memory you previously allocated.
  • You can call a constructor from another constructor using this but it must be first and only in the constructor.
class House{
    private String owner;
    private String location;
    public House(String owner,String location){
        this.owner=owner;
        this.location=location;
    }
    public House(String owner){
        this(owner,""); //It must be first and only
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment