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.
20Figure 1: A variable is a named box in memory.
1️⃣ Declaring, Initialising and Changing
| Step | Code | Meaning |
| Declare | int total; | create the box; it has no value yet |
| Initialise | total = 0; | put the first value in it |
| Both at once | int total = 0; | the usual way |
| Change | total = total + 5; | replace the old value using the old value |
| Constant | final 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));
}
}
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. charuses single quotes (‘A’), andStringuses double quotes (“Asha”).age = 21;has no type in front, because the variable already exists. Writingintagain 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
a name for a place in memory; its value can change
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
| Type | Literal examples | Notes |
| int | 42, 0b101010, 052, 0x2A, 1_000_000 | decimal, binary (0b), octal (leading 0), hex (0x); _ for readability |
| long | 9_000_000_000L | needs L at the end |
| float | 3.14f | needs f at the end |
| double | 2.5, 2.5e3 | default for decimals; e3 means × 10³ |
| char | 'A', 65 | single quotes; a number can also stand for a character |
| boolean | true, false | only these two |
| String | "Java" | double quotes |
| null | null | “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);
}
}
42 42 42 42
1000000 9000000000
3.14 2500.0
A A false Java
- All four forms 42,
0b101010,052and0x2Aare the same number, so the first line prints 42 four times. - The underscore in
1_000_000is only for readability and does not change the value. 9_000_000_000Lis too big for anint, so it needs alongand anLat the end.2.5e3means 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));
}
}
Tax = 180.0
Total = 1180.0
GST_RATEis 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
| Step | a | b | temp |
| Start | 5 | 10 | ? |
| int temp = a; | 5 | 10 | 5 |
| a = b; | 10 | 10 | 5 |
| b = temp; | 10 | 5 | 5 |
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);
}
}
Before: a = 5, b = 10
After : a = 10, b = 5
- If we wrote only
a = b;the old value ofawould be lost, so we first save it intemp. - Read the trace table in Figure 5 from top to bottom to follow each step.
6️⃣ Default Values
| Kind of variable | Gets 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) |
| Type | Default |
| int, long, short, byte | 0 |
| float, double | 0.0 |
| boolean | false |
| char | the character with code 0 |
| String and other objects | null |
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);
}
}
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);
}
}
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);
}
}
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);
}
}
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
| Mistake | Problem | Fix |
|---|---|---|
| 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 String | Use 'A' |
float f = 3.14; | 3.14 is a double | Write 3.14f |
long n = 9000000000; | The number is too large for an int | Add L: 9000000000L |
Changing a final variable | Compile error | Remove 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 withage = 21;. - A literal is a fixed value in the code:
20,'A',"Asha",true,3.14f,10L. - Use
finalfor 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) Indouble 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 doesfloat f = 3.14;fail? (4) Write a program that swaps two variables without usingtemp(hint: use + and -), and check it with a trace table. (5) Make a program with afinalconstant 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
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java