A variable is a container that holds a data value. In Java, all variables must be declared before they can be used. This involves giving the variable a name and specifying the type of data it will store.
To declare a variable, you specify its type, followed by its name. To assign a value, you use the equals sign =.
Syntax: type variableName = value;
public class Main {
public static void main(String[] args) {
// Declare a String variable and initialize it
String name = "John Doe";
System.out.println("Name: " + name);
// Declare an integer (int) variable
int age = 25;
System.out.println("Age: " + age);
// You can also declare first and assign later
int salary;
salary = 50000;
System.out.println("Salary: " + salary);
// Change the value of a variable
age = 26;
System.out.println("New Age: " + age);
}
}
Java has different types of variables, for example:
String - stores text, such as "Hello". String values are surrounded by double quotes.int - stores integers (whole numbers), without decimals, such as 123 or -123.float - stores floating point numbers, with decimals, such as 19.99 or -19.99.char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes.boolean - stores values with two states: true or false.We will explore these data types in more detail in the next chapter.
If you don't want the value of a variable to be changed, you can use the final keyword. This will declare the variable as "final" or "constant", which means it's unchangeable and read-only.
By convention, the names of constant variables are written in all uppercase letters.
public class Main {
public static void main(String[] args) {
final double PI = 3.14159;
// PI = 3.14; // This would cause a compiler error!
System.out.println("The value of PI is: " + PI);
}
}
You can declare multiple variables of the same type in a single line by separating them with commas.
int x = 5, y = 10, z = 15; System.out.println(x + y + z);