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 –
- 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 the Final Keyword in Java
- What is Interface in Java
- What is Wrapper Class in Java
- Break Keywords in Java with Example
- What is Method In Java With Example
- What is Constructor in Java With Example
- What is Polymorphism in java
- What is a non-static variable in java
- Types of access specifiers in java
- What is the local variable in java
- Types of loops in java with program
- Remove duplicate elements in an Array in java
- What is var type in java
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 Type | Default Value |
byte | 0 |
short | 0 |
int | 0 |
long | 0 |
float | 0.0 |
double | 0.0 |
char | Empty |
boolean | false |
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
}
}