Non Static variable in java: – These Variable a created outside the method but inside the class without the static keyword.
- There are also called instance variables.
- If not initialize non-static variable depend on variable automatically default value can be stored.
Note 1: – Without creating an object non-static members cannot access and hence the below program an error.
Non Static variable in java best Example
public class A {
int x=10;
public static void main(String[] args) {
System.out.println(x); // Error
}
}
Example 2
public class A {
int x=10;
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1.x);
}
}
Output : 10
Note 2 : Every time we create an object copy of a non-static member will get loaded into the object.
Example 1
public class A {
int x=100;
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
A a3 = new A();
System.out.println(a1.x);
System.out.println(a2.x);
System.out.println(a3.x);
}
}
Output :
100
100
100
You Also Learn –
- What is Abstract Class in Java
- What is Lambda Expression in Java 8
- What is Exception Handling in Java
- Types of Exceptions in Java
- What is inheritance in Java
- What is Final Keyword in Java
- What is Interface in Java
- What is Wrapper Class in Java
- Break Keyword in Java with Example
- What is Method In Java With Example
- What is Constructor in Java With Example
- What is Polymorphism in java
Note 3: Changing the value of the variable object will not change the original non-static variable as shown below example.
public class A {
int x=10;
public static void main(String[] args) {
A a1 = new A();
a1.x =20;
A a2 = new A();
System.out.println(a1.x);
System.out.println(a2.x);
}
}
Output :
20
10
Note 4: If not initialize non-static variable depend on variable automatically default value can be stored.
public class A {
int x;
public static void main(String[] args) {
A a1 = new A();
System.out.println(a1.x);
}
}
Output : 0