Popular Posts

Friday, June 17, 2011

Static in Java

The static variables or static blocks in a class will be initialised before the class gets instantiated. Also, we all know that the static variables are not tied up with the instances. So even if we have the reference as null, the variable s value had already been initalised to "hello". So calling it that way will print the values Inside Method and Hello as the variable call will be made with the class name as they are tied up with the class. If you make the variable non - static, you will get a NPE.
public class staticClass { 
public static void printH(){
System.out.println("entered into static class");
}
}
public class staticTest {
public static void main(String[] args){
staticClass sc = new staticClass();
sc.printH();
staticClass.printH();
sc=null;
sc.printH();
  staticClass scNull = null;
scNull.printH();
}
}
Output :
entered into static class
entered into static class
entered into static class
entered into static class

No comments:

Post a Comment