What is static variable in java with best example

static variable: – Static variable has global access which means it can be accessed anywhere in the program as shown in the below program.

static variable important points in java

  • a static variable created outside method but inside class using the static keyword.
  • static variable belongs to the class that is called a class variable also.
  • do not create an object to access the static variables.
  • the static variable value can be changed.

Static Variable in Java Program

Example 1

public class A{  
	static int x=10;
	public static void main(String[] args) {
 		
 		System.out.println(x);
		
	}
}
Output: 10

Note – the static variable value can be changed, as shown below example.

public class A{  
	static int x=10;
	public static void main(String[] args) {
		System.out.println(A.x);
		A.x =20;
		System.out.println(A.x);
		A.x =5;
		System.out.println(x);
	}
	
}
Output:
10
20
5

You Also Learn –

Example 2

public class A{  
	static int x=10;
	public static void main(String[] args) {
 		A a1= new A();
 		a1.test();
 		System.out.println(A.x);
		
	}
	public void test() {  // non ststic method
		System.out.println(A.x);
	}
}
Output: 
10
10

Note 1 – It is not mandatory to initialize static variables if we do not initialize then depending on datatype automatically default value can store it.

Example 3

public class A{  
	static int x;
	public static void main(String[] args) {
 		System.out.println(A.x);
		
	}
	
}
Output: 0

data types and their default values in java

Data TypeDefault Value
byte0
short0
int0
long0
float0.0
double0.0
charEmpty
booleanfalse
String ( class )null

Note 2 – There are three ways to access static variables.

First – ClassName.VariableName

public class A{  
	static int x=100;
	public static void main(String[] args) {
 		System.out.println(A.x);
		// ClassName.VariableName
	}
	
}

Second – VariableName

public class A{  
	static int x=100;
	public static void main(String[] args) {
 		System.out.println(x);
		//VariableName
	}
	
}

Third – ReferenceVariable.StaticVariable ( Wrong )

public class A{  
	static int x=100;
	public static void main(String[] args) {
 		A a1 = new A();
		System.out.println(a1.x);  // Worng
		//VariableName
	}
	
}

Leave a Comment