- 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
}
}