Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 7: Variables and Literals

Java for Beginners · Module 2: Building Blocks


🎯 Why Do We Need Variables?

Think of labelled jars in a kitchen: sugar, salt, rice. You do not say “the white powder on the second shelf”. You say “sugar”. A variable is a labelled jar for a value in your program. It lets you store something, use it later, and change it when needed.

📌 A variable is a named memory location that stores a value of a particular type. A literal is a fixed value written directly in the code.
int age = 20;
name: age
20
type: int · 4 bytes
A variable has a name, a type (decides the size and kind of value) and a value.

Figure 1: A variable is a named box in memory.

1️⃣ Declaring, Initialising and Changing

StepCodeMeaning
Declareint total;create the box; it has no value yet
Initialisetotal = 0;put the first value in it
Both at onceint total = 0;the usual way
Changetotal = total + 5;replace the old value using the old value
Constantfinal int MAX = 100;value can never change

Figure 2: Declaring, initialising and changing a variable.

Program 1: Variables of different types

public class VariableBasics {
    public static void main(String[] args) {
        int age = 20;                    // declare and initialise
        double height = 5.9;
        char grade = 'A';
        boolean passed = true;
        String name = "Asha";

        System.out.println(name + " is " + age + " years old.");
        System.out.println("Height: " + height + ", Grade: " + grade + ", Passed: " + passed);

        age = 21;                        // change the value
        System.out.println("Next year: " + age);

        int a = 1, b = 2, c = 3;         // several variables of the same type
        System.out.println("a + b + c = " + (a + b + c));
    }
}
🖥️ Output:
Asha is 20 years old.
Height: 5.9, Grade: A, Passed: true
Next year: 21
a + b + c = 6
  • Each variable has a type first, then a name, then = and a value.
  • char uses single quotes (‘A’), and String uses double quotes (“Asha”).
  • age = 21; has no type in front, because the variable already exists. Writing int again would be an error.
  • int a = 1, b = 2, c = 3; declares three variables in one line. The parentheses in (a + b + c) make Java add the numbers before joining them to the text.

2️⃣ Variable vs Literal

int score = 90;
score is a variable
a name for a place in memory; its value can change
90 is a literal
a fixed value written directly in the code

Figure 3: Variable versus literal.

Beginners often mix these two up. In int score = 90;, score is the variable and 90 is the literal. You can change score later, but you cannot change what 90 means.

3️⃣ Literals

TypeLiteral examplesNotes
int42, 0b101010, 052, 0x2A, 1_000_000decimal, binary (0b), octal (leading 0), hex (0x); _ for readability
long9_000_000_000Lneeds L at the end
float3.14fneeds f at the end
double2.5, 2.5e3default for decimals; e3 means × 10³
char'A', 65single quotes; a number can also stand for a character
booleantrue, falseonly these two
String"Java"double quotes
nullnull“refers to nothing” (for objects)

Figure 4: The kinds of literals in Java.

Program 2: Every kind of literal

public class LiteralsDemo {
    public static void main(String[] args) {
        int decimal = 42;
        int binary = 0b101010;
        int octal = 052;
        int hex = 0x2A;
        int million = 1_000_000;
        long big = 9_000_000_000L;
        float ratio = 3.14f;
        double sci = 2.5e3;
        char letter = 'A';
        char fromCode = 65;
        boolean flag = false;
        String text = "Java";

        System.out.println(decimal + " " + binary + " " + octal + " " + hex);
        System.out.println(million + " " + big);
        System.out.println(ratio + " " + sci);
        System.out.println(letter + " " + fromCode + " " + flag + " " + text);
    }
}
🖥️ Output:
42 42 42 42
1000000 9000000000
3.14 2500.0
A A false Java
  • All four forms 42, 0b101010, 052 and 0x2A are the same number, so the first line prints 42 four times.
  • The underscore in 1_000_000 is only for readability and does not change the value.
  • 9_000_000_000L is too big for an int, so it needs a long and an L at the end.
  • 2.5e3 means 2.5 × 1000 = 2500.0.
  • char fromCode = 65; stores the character with code 65, which is ‘A’.

4️⃣ Constants with final

If a value should never change, such as a tax rate, declare it with final. The compiler then stops any attempt to change it. By convention, constant names are in UPPER_CASE.

public class ConstantDemo {
    public static void main(String[] args) {
        final double GST_RATE = 0.18;
        double price = 1000;
        double tax = price * GST_RATE;
        System.out.println("Tax   = " + tax);
        System.out.println("Total = " + (price + tax));
    }
}
🖥️ Output:
Tax = 180.0
Total = 1180.0
  • GST_RATE is fixed at 0.18. If you try to assign to it later, the program will not compile.
  • 1000 × 0.18 = 180.0, and 1000 + 180.0 = 1180.0.

5️⃣ Swapping Two Variables

Stepabtemp
Start510?
int temp = a;5105
a = b;10105
b = temp;1055
temp keeps a copy of the old a, so it is not lost when a is overwritten.

Figure 5: Swapping a = 5 and b = 10 with a temporary variable.

public class SwapDemo {
    public static void main(String[] args) {
        int a = 5, b = 10;
        System.out.println("Before: a = " + a + ", b = " + b);

        int temp = a;
        a = b;
        b = temp;

        System.out.println("After : a = " + a + ", b = " + b);
    }
}
🖥️ Output:
Before: a = 5, b = 10
After : a = 10, b = 5
  • If we wrote only a = b; the old value of a would be lost, so we first save it in temp.
  • Read the trace table in Figure 5 from top to bottom to follow each step.

6️⃣ Default Values

Kind of variableGets a default value?
Local variable (inside a method)✘ No. You must give it a value before using it.
Static or instance field (inside a class)✔ Yes: 0, 0.0, false, null (see table below)
TypeDefault
int, long, short, byte0
float, double0.0
booleanfalse
charthe character with code 0
String and other objectsnull

Figure 6: Default values apply only to fields, never to local variables.

public class DefaultValues {
    static int count;
    static double average;
    static boolean done;
    static String title;

    public static void main(String[] args) {
        System.out.println("int     : " + count);
        System.out.println("double  : " + average);
        System.out.println("boolean : " + done);
        System.out.println("String  : " + title);
    }
}
🖥️ Output:
int : 0
double : 0.0
boolean : false
String : null
  • These four variables belong to the class (they are fields), so Java fills them with default values.
  • Variables declared inside a method are different. They get no default value, as the next section shows.

7️⃣ Errors You Will Meet

Using a local variable before giving it a value

public class Unset {
    public static void main(String[] args) {
        int total;
        System.out.println(total);
    }
}
🖥️ Compiler message:
Unset.java:4: error: variable total might not have been initialized
System.out.println(total);
^
1 error

Declaring the same name twice

public class Twice {
    public static void main(String[] args) {
        int score = 10;
        int score = 20;
        System.out.println(score);
    }
}
🖥️ Compiler message:
Twice.java:4: error: variable score is already defined in method main(String[])
int score = 20;
^
1 error

Changing a constant

public class Const {
    public static void main(String[] args) {
        final int MAX = 100;
        MAX = 200;
        System.out.println(MAX);
    }
}
🖥️ Compiler message:
Const.java:4: error: cannot assign a value to final variable MAX
MAX = 200;
^
1 error
  • These errors help you. Java refuses to run a program that could use a missing value or change a protected one.

⚠️ Common Mistakes

MistakeProblemFix
Using a variable before giving it a value“might not have been initialized”Initialise when you declare it
Writing the type again when changing a value“already defined”Write score = 20;, not int score = 20;
char c = "A";Double quotes make a StringUse 'A'
float f = 3.14;3.14 is a doubleWrite 3.14f
long n = 9000000000;The number is too large for an intAdd L: 9000000000L
Changing a final variableCompile errorRemove final or do not change it

❓ Frequently Asked Questions

Q1. Can a variable change its type?
No. Once you declare int age, it always holds an int.

Q2. What is the difference between = and ==?
= assigns a value. == compares two values. You will use == in Lesson 13.

Q3. What does var do?
Since Java 10, var x = 5; lets the compiler work out the type from the value. The type is still fixed. Beginners should write the type explicitly for now.

Q4. Is the underscore in 1_000_000 allowed everywhere?
Only between digits. It cannot start or end a number.

✅ Key Takeaways

  • A variable has a type, a name and a value.
  • Declare and initialise: int age = 20;. Change later with age = 21;.
  • A literal is a fixed value in the code: 20, 'A', "Asha", true, 3.14f, 10L.
  • Use final for values that must not change, and write their names in UPPER_CASE.
  • Local variables have no default value, so initialise them. Fields do get defaults.
  • A swap needs a temporary variable.
🎓 Practice questions: (1) In double price = 49.5;, which part is the variable and which is the literal? (2) Declare variables to store your name, roll number, CGPA and whether you are a hostel resident. (3) Why does float f = 3.14; fail? (4) Write a program that swaps two variables without using temp (hint: use + and -), and check it with a trace table. (5) Make a program with a final constant for the number of days in a week and print the number of days in 4 weeks.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision