In Java, a variable is a container that holds data. Variables are used to store values that can be used and modified during the execution of a program. Each variable in Java must be declared with a specific data type, and the type of value it can hold depends on that data type. Variables must be initialized before they can be used in the program.
To declare a variable in Java, you need to specify the data type followed by the variable name. Here is the syntax:
// Syntax to declare a variable in Java dataType variableName;
public class VariableExample {
public static void main(String[] args) {
int age; // Declare an integer variable
double salary; // Declare a double variable
char grade; // Declare a character variable
age = 25; // Initialize the variable 'age'
salary = 50000.75; // Initialize the variable 'salary'
grade = 'A'; // Initialize the variable 'grade'
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Grade: " + grade);
}
}
A variable can be declared and initialized at the same time. This is commonly done to set the initial value of the variable. Here is the syntax:
// Syntax for declaring and initializing a variable in Java dataType variableName = initialValue;
public class VariableInitializationExample {
public static void main(String[] args) {
int age = 30; // Declare and initialize the 'age' variable
double salary = 55000.50; // Declare and initialize the 'salary' variable
char grade = 'B'; // Declare and initialize the 'grade' variable
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Grade: " + grade);
}
}
There are three types of variables in Java:
static keyword and belong to the class rather than instances of the class. They can be accessed without creating an object of the class.
public class VariableTypesExample {
// Instance variable
int instanceVar = 10;
// Static variable
static int staticVar = 20;
public void display() {
// Local variable
int localVar = 30;
System.out.println("Local Variable: " + localVar);
System.out.println("Instance Variable: " + instanceVar);
System.out.println("Static Variable: " + staticVar);
}
public static void main(String[] args) {
VariableTypesExample obj = new VariableTypesExample();
obj.display();
}
}
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!