The basic difference between static and non-static variables
class Student { private int id; private String name; static String collegeName; }
For each non-static student object, the id and name attributes will be loaded into memory with its initial values (0 and null), the identifier and name may be different for each object. But collegeName will only load once when the class is loaded to execute. Thus, for each Student object there will be the same college name. This means static .
Access to static and non-static variables
class Student { private int id; private String name; static String collegeName; public static void main(String[] args) { String s1 = Student.collgeName; String s2 = collgeName; Student student = new Student(); String s3 = student.name; int id = student.id; } }
Static variables can be accessed directly using their name or using the class name. When a static global variable and a local variable exist, static should be used with the class name
public static void main(String[] args) { String s1 = Student.collgeName; String collgeName = "foo"; String output = collgeName; }
Here output will be set to " foo ". A local variable always takes precedence over a global static variable, and therefore String output = s1; will give the value for output as null .
Inside the non-static static block, you need to access the variables using reference variables (we need to create an object). The main method is static, so we had to create a Student object to access the id and name values, otherwise this would give a compile-time error.
Blind rule regarding non-static blocks
Each non-static block will use the default keyword this , which displays the current link to which the block is called when class variables (both static and non-static) are used. Java sample code
class Student { private int id; private String name; static String collegeName; void setData() { id = 1; name = "foo"; collegeName = "FooCollege"; } public static void main(String[] args) { Student student = new Student(); student.setData(); } }
This is what happens when the same code is compiled to get a class file
class Student { private int id; private String name; static String collegeName; void setData() { this.id = 1; this.name = "foo"; this.collegeName = "FooCollege";
Here, this represents the Student reference variable from the main method. Represents the reference variable to which the block is invoked.
Returning to the question, the main method creates a Test object and is called in its reference method1() . Thus, inside method1 this is nothing but the reference variable t created in the main method, and t is the local reference variable of the method. Now let's rewrite the code in the class file format
public void method1(int x) { Test t = new Test(); this.x = 22;