What is Java Variable?
In Java, a variable is a container that holds data which can be changed during the execution of a program. Each variable in Java has a specific data type that determines the type and size of data it can hold. Variables are essential for storing data, manipulating it, and passing it within the program.
Declaration and Initialization #
To use a variable in Java, you must first declare it and then optionally initialize it with a value. The general syntax for declaring a variable is:
dataType variableName;
And for initializing a variable:
dataType variableName = value;
Example #
Let’s look at an example to understand variables in Java better:
public class Main {
public static void main(String[] args) {
// Declaration of variables
int age;
double salary;
String name;
// Initialization of variables
age = 25;
salary = 50000.50;
name = "John Doe";
// Output the values of the variables
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Explanation #
- int age;
- This declares an integer variable named age.
2. double salary;
- This declares a double variable named salary, which can hold decimal values.
3. String name;
- This declares a String variable named name, which can hold a sequence of characters.
After declaring the variables, they are initialized with values:
- age = 25;
- This assigns the integer value 25 to the variable age.
2. salary = 50000.50;
- This assigns the double value 50000.50 to the variable salary.
3. name = “John Doe”;
- This assigns the string value “John Doe” to the variable name.
Finally, the values of the variables are printed to the console using System.out.println.