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.

💡 Analogy time: Think of a variable like a labeled storage box.

  • The data type determines the kind of box (e.g., a small fragile box vs. a heavy-duty crate). You wouldn't put a heavy bowling ball in a flimsy cardboard box meant for feathers!
  • The variable name is the label written on the outside of the box so you can easily find it later.
  • The data value is the actual item you put inside the box.

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

Variable Naming Rules & Best Practices

Java has strict rules on what you can and cannot name a variable.

Rules (If you break these, your code will crash):

Best Practices (If you break these, other developers will judge you):


Advanced Notes: Variables


Exercise

?

Which keyword is used to declare a constant variable that cannot be changed?