Static and Non-Static Variable

Non-Static

Non-static variable is created outside method but inside class without using static keyword.

Without creating object, non-static variable can not be accessed. Hence below program will give an error.

				
					public class Test {
    int x = 10;
    public static void main(String[] args) {
        System.out.println(x); // This line will give error
    }
}
				
			

In the above program you will get an error like “Non Static field x can not be referenced from static context.”

To resolve this error we have to create Object of class Test.

				
					public class Test {
    int x = 10;
    public static void main(String[] args) {
        Test t = new Test();
        System.out.println(t.x); // 10
    }
}
				
			
Scroll to Top