Variables

Variables

A school program needs reliable data and clear rules. A variable gives a value a name and a type. The school can store a mark, update it after a correction and use the latest value in a report.

  1. Understand

    A variable gives a value a name and a type.

  2. Apply

    Trace the Java example, predict its output and explain the result before running it.

  3. Avoid mistakes

    A local variable must be assigned before it is read. Assignment replaces its value; it does not permanently link it to the expression on the right.

Variables in Java

In Java, a variable is a named container used to store data that can be changed during the execution of a program. Think of it as a labeled box where you can keep values—whether that's numbers, text, or more complex objects.

How to Declare a Variable in Java

Declaring a variable means telling Java what type of data the variable will hold and giving it a name. The basic syntax is:

datatype variableName;

Example:

int age;
String name;
double price;

How to Initialize a Variable

Initialization means assigning a value to the declared variable. You can do this at the time of declaration or later in your code.

1. Declare and Then Initialize

int age;
age = 25;

2. Declare and Initialize Together

String name = "Alice";

Variable Types in Java

Java is a statically-typed language, which means every variable must have a data type. Here are some commonly used types:

Data TypeDescription
intStores integers (whole numbers), e.g., 1, 100
doubleStores decimal numbers, e.g., 3.14
charStores a single character, e.g., 'A'
booleanStores true or false
StringStores sequences of characters, e.g., "Hello"

Java Variable Naming Rules

Here’s what you need to know to name your variables properly, along with examples for better understanding:

1. Names can contain letters, digits, underscores, and dollar signs

// Valid variable names
int total_Amount = 100;
double price2 = 49.99;
String user$name = "John";

2. Names must begin with a letter, not a digit

// Correct
int count1 = 5;

// Incorrect (will cause a compile-time error)
int 1count = 5;

3. Names are case-sensitive (value and Value are different)

int value = 10;
int Value = 20;

System.out.println(value); // Outputs: 10
System.out.println(Value); // Outputs: 20

4. Names should not be Java reserved keywords

// Invalid variable names (these are reserved by Java)
int class = 1;   // Error
boolean public = true; // Error

// Correct alternative names
int classNumber = 1;
boolean isPublic = true;

Example: Declaring and Using Variables

public class VariableDemo {
    public static void main(String[] args) {
        int age = 30;
        String name = "John";
        boolean isAdult = true;
        
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Is Adult? " + isAdult);
    }
}
Name: John
Age: 30
Is Adult? true

Why Are Variables Important?

Variables make your program flexible and dynamic. They allow you to write code that can adapt based on inputs, conditions, or changing data. Without variables, programming would be static and manual.

Checkpoints for Beginners

Java · example discussed here

public class VariableDemo {
    public static void main(String[] args) {
        int age = 30;
        String name = "John";
        boolean isAdult = true;
        
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Is Adult? " + isAdult);
    }
}
  • Always declare a variable with its correct type. A mistake like int name = "Alice"; will throw a compile-time error.
  • Uninitialized variables cannot be used. For instance, trying to print a variable before assigning a value will result in a compile error.
  • Be mindful of types during assignments. For example, you can't directly assign a double to an int without casting.

Best Practices

  • Use meaningful variable names like totalAmount, isAvailable, rather than x or data.
  • Stick to camelCase naming (e.g., userAge, itemPrice) for variables.
  • Initialize variables when possible to avoid accidental use of undefined values.

Important boundaries and mistakes

A local variable must be assigned before it is read. Assignment replaces its value; it does not permanently link it to the expression on the right.

Try the school example

Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: A local variable must be assigned before it is read.

Java 17 · Main.java · complete practice program

public class Main  {
  public static void main(String[] args)  {
    int marks = 70;
    marks = marks + 2;
    System.out.println(marks);
  }
}

Now change one thing: Start marks at 60 instead of 70. Predict the new behavior before checking the worked variation.

Worked answer and reasoning

Java 17 · Main.java · source repeated for this answer

public class Main  {
  public static void main(String[] args)  {
    int marks = 70;
    marks = marks + 2;
    System.out.println(marks);
  }
}

Expected output

72

A variable gives a value a name and a type. The school can store a mark, update it after a correction and use the latest value in a report.

A local variable must be assigned before it is read. Assignment replaces its value; it does not permanently link it to the expression on the right.

Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.

Worked variation: Start marks at 60 instead of 70. The update adds 2, so the final mark must be 62.

Check your understanding

For the complete practice program in this lesson, which output is expected on Java 17?
Choose one answer. You can try again.

Answer and explanation

72

A variable gives a value a name and a type. The school can store a mark, update it after a correction and use the latest value in a report. A local variable must be assigned before it is read. Assignment replaces its value; it does not permanently link it to the expression on the right.

Check a common mistake

Does assigning int copy = marks make copy track later changes to marks?
Choose one answer. You can try again.

Answer and explanation

No. The assignment copies the current primitive value.

Later primitive assignments change their own variables. A final declaration restricts assignment; it does not create a live formula.

What to remember

A variable gives a value a name and a type. The school can store a mark, update it after a correction and use the latest value in a report. A local variable must be assigned before it is read. Assignment replaces its value; it does not permanently link it to the expression on the right.

Related explanations: Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide and Java 17 language specification.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Literals →