Home »
Java programming language
Java Variables With Types and Examples
Java Variables: In this tutorial, we are going to learn about the variables, various types of variables in Java.
By Karan Ghai Last updated : January 02, 2024
Java Variables
Java variables are the user-defined names of the memory blocks, and their values can be changed at any time during program execution. They play an important role in a class/program as they help in to store, retrieve a data value.
Declaring a variable
To declare a variable, write the variable name followed by the type and assign a value (if you want to initialize it).
Syntax
type variable_name;
type variable_name = value;
Types of Java Variables
There are three types of Java variables,
- Instance Variables
- Local Variables
- Class/Static Variables
1. Java Instance Variables
- Instance variables are declared in a class but outside a Method, Block or Constructor.
- Instance variables have a default value 0.
- These variables can be created only when the object of a class is created.
Java example of instance variables
public class Bike {
public String color;
Bike(String c) {
color = c;
}
public void display() {
System.out.println("color of the bike is " + color);
}
public static void main(String args[]) {
Bike obj = new Bike("Red");
obj.display();
}
}
Output
Color of the bike is Red
2. Java Local Variables
- Local variables are the variables which are declared in a class method.
- We can use these variables within a block only.
Java example of local variables
public class TeacherDetails {
public void TeacherAge() {
int age = 0;
age = age + 10;
System.out.println("Teacher age is : " + age);
}
public static void main(String args[]) {
TeacherDetails obj = new TeacherDetails();
obj.TeacherAge();
}
}
Output
Teacher age is : 10
3. Java Class/Static Variables
- This can be called Both Class and Static Variable.
- These variables have only one copy that is shared by all the different objects in a class.
- It is created during the start of program execution and destroyed when the program ends.
- Its Default value is 0.
Java example of class/static variables
public class Bike {
public static int tyres;
public static void main(String args[]) {
tyres = 6;
System.out.println("Number of tyres are " + tyres);
}
}
Output
Number of tyres are 6