Java Variables

Java Variables

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.


Declaring and Initializing Variables

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;

Declaring Variables

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);
  }
}

Types of Variables

Java has different types of variables, for example:

We will explore these data types in more detail in the next chapter.


Final Variables (Constants)

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.

Final Variables

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);
  }
}

Declaring Multiple Variables

You can declare multiple variables of the same type in a single line by separating them with commas.

Multiple Declarations

int x = 5, y = 10, z = 15;
System.out.println(x + y + z);