Labs ICT
โญ Pro Login

Variables

Variables are where you store data. Think of them as labeled boxes โ€” you put a value in a box, give it a name, and later you can look inside or change what is there.

Declaring and Assigning

In Java, you have to tell the compiler what type of data a variable will hold before you use it. You do that with a declaration.

public class Main {
  public static void main(String[] args) {
    int age;
    age = 25;
    System.out.println(age);
  }
}

Line 4 declares age as an int (integer). Line 5 assigns the value 25 to it. You can also combine declaration and assignment in one line โ€” most people do it that way:

int age = 25;
String name = "Amina";
double price = 19.99;

Variable Naming Rules

Java has some rules about what you can name your variables. Here is the deal:

  • Names can contain letters, digits, underscores (_), and dollar signs ($)
  • Names must start with a letter, underscore, or dollar sign โ€” not a digit
  • Names are case sensitive โ€” age and Age are different
  • You cannot use reserved keywords like int, class, public
  • By convention, variable names start with a lowercase letter and use camelCase
public class Main {
  public static void main(String[] args) {
    String firstName = "Musa";
    String lastName = "Suleiman";
    int totalScore = 95;
    double averageScore = 87.5;
    System.out.println(firstName + " " + lastName);
  }
}

The final Keyword

Sometimes you want a variable that never changes. Maybe it is a constant like PI or the maximum number of students allowed. Use the final keyword to make a variable unchangeable.

public class Main {
  public static void main(String[] args) {
    final int MAX_LOGIN_ATTEMPTS = 5;
    System.out.println("Max attempts: " + MAX_LOGIN_ATTEMPTS);
  }
}

If you try to change a final variable later, Java will give you a compilation error. By convention, final variables are written in ALL_CAPS with underscores between words.

๐Ÿงช Quick Quiz

Which is a valid variable name in Java?