Java for Beginners · Module 2: Building Blocks
🎯 Two Small Topics, Two Common Doubts
This lesson covers two things that cause many small mistakes: escape characters (how to print quotes, tabs and new lines) and variable scope (where a variable can be used).
1️⃣ Escape Characters
Some characters cannot be typed directly inside a String. A double quote would end the String, and pressing Enter would break the line of code. Java solves this with a backslash \ followed by a letter. The pair is called an escape sequence.
| Escape | Meaning | Example | Prints |
\n | new line | "A\nB" | A, then B on the next line |
\t | tab (jump to next tab stop) | "A\tB" | A B |
\" | double quote inside a String | "Say \"Hi\"" | Say “Hi” |
\' | single quote inside a char | '\'' | ‘ |
\\ | one backslash | "C:\\Java" | C:\Java |
\u0041 | Unicode character by code | "\u0041" | A |
Figure 1: The escape sequences you will use most.
Program 1: Escape sequences in action
public class EscapeDemo {
public static void main(String[] args) {
System.out.println("Name:\tAjay");
System.out.println("Course:\tJava");
System.out.println("Line one\nLine two");
System.out.println("He said \"Hello\"");
System.out.println("It's fine");
System.out.println('\'');
System.out.println("C:\\Users\\Ajay");
System.out.println("Unicode: \u0041\u0042");
}
}
Name: Ajay
Course: Java
Line one
Line two
He said “Hello”
It’s fine
‘
C:\Users\Ajay
Unicode: AB
\tjumps to the next tab stop, so “Ajay” and “Java” line up in a column.\nstarts a new line in the middle of a String.\"puts a double quote inside a String. A single quote inside a String needs no escape, as in “It’s fine”.- Inside a
char, a single quote must be escaped:'\''. - A backslash itself must be doubled:
\\prints one\. This matters for file paths on Windows. \u0041is a Unicode escape. 0041 is the hexadecimal code of ‘A’.
Another way to start a new line is System.out.println(), which already adds a line break after the text. System.out.print does not.
2️⃣ What Is Scope?
A variable is not available everywhere. Scope is the part of the program where a variable can be used. It begins where the variable is declared and ends at the closing brace } of the block that contains it.
static variable: lives for the whole program
local variable: lives until the method ends
inside { }: lives until the closing brace
Figure 2: Scope: an inner area can see the outer variables, but not the other way round.
Local, instance and static variables
| Kind | Declared | Gets a default? | Lives until |
| Local variable | inside a method or block | No: must be given a value | the block or method ends |
| Instance variable | in a class, without static | Yes (0, false, null) | the object is destroyed |
| Static variable | in a class, with static | Yes (0, false, null) | the program ends |
Figure 3: The three kinds of variables and their scope.
Instance variables belong to objects, which Lesson 29 introduces. For now, you work with local variables and static variables.
Program 2: Class, method and block scope
public class ScopeDemo {
static int classLevel = 100; // class (static) variable
public static void main(String[] args) {
int methodLevel = 10; // local to main
System.out.println("classLevel = " + classLevel);
System.out.println("methodLevel = " + methodLevel);
if (methodLevel > 5) {
int blockLevel = 50; // local to this block
System.out.println("blockLevel = " + blockLevel);
System.out.println("inside block, methodLevel = " + methodLevel);
}
for (int i = 0; i < 3; i++) {
System.out.println("loop i = " + i);
}
}
}
classLevel = 100
methodLevel = 10
blockLevel = 50
inside block, methodLevel = 10
loop i = 0
loop i = 1
loop i = 2
classLevelis declared in the class, so every method can see it.methodLevelis visible insidemainand also inside the innerifblock, because the block is inside the method.blockLevelexists only between the braces of theif. The loop variableiexists only inside thefor.
3️⃣ Default Values
Class-level variables get a default value if you do not set one. Local variables never do.
public class DefaultValues {
static int count;
static double price;
static boolean done;
static char letter;
static String text;
public static void main(String[] args) {
System.out.println("int : " + count);
System.out.println("double : " + price);
System.out.println("boolean : " + done);
System.out.println("char code: " + (int) letter);
System.out.println("String : " + text);
}
}
int : 0
double : 0.0
boolean : false
char code: 0
String : null
- Numbers default to 0, boolean to
false, char to the character with code 0 (so we print its number). - Any object type, such as
String, defaults tonull, which means “no object”.
4️⃣ Shadowing: Same Name, Different Variable
A local variable may have the same name as a class variable. Inside its scope the local one hides the class one. This is called shadowing.
public class ShadowDemo {
static int x = 5; // class variable
static void show() {
int x = 99; // local variable hides the class variable
System.out.println("local x = " + x);
System.out.println("class x = " + ShadowDemo.x);
}
public static void main(String[] args) {
show();
System.out.println("main sees x = " + x);
}
}
local x = 99
class x = 5
main sees x = 5
- Inside
show, plainxmeans the local one (99). ShadowDemo.xreaches the hidden class variable (5).mainhas no localx, so it sees the class variable.- Shadowing is legal but confusing. Prefer different names.
5️⃣ Errors Beginners Meet
Using a variable outside its block
public class OutOfScope {
public static void main(String[] args) {
if (true) {
int inside = 10;
}
System.out.println(inside);
}
}
OutOfScope.java:6: error: cannot find symbol
System.out.println(inside);
^
symbol: variable inside
location: class OutOfScope
1 error
insidedied at the closing brace. Declare it before theifif you need it after.
Using a local variable before giving it a value
public class Uninit {
public static void main(String[] args) {
int total;
System.out.println(total);
}
}
Uninit.java:4: error: variable total might not have been initialized
System.out.println(total);
^
1 error
- Locals get no default. Write
int total = 0;.
Declaring the same local name twice
public class Dup {
public static void main(String[] args) {
int marks = 80;
int marks = 90;
System.out.println(marks);
}
}
Dup.java:4: error: variable marks is already defined in method main(String[])
int marks = 90;
^
1 error
- Declare once with a type, then change it later with
marks = 90;(no type).
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
"C:\Java" | \J is not a valid escape | Write "C:\\Java" |
| Quote inside a String without a backslash | The String ends early | Use \" |
| Using a block variable after the block | cannot find symbol | Declare it outside the block |
| Reading an unassigned local variable | might not have been initialized | Give it a starting value |
| Redeclaring a local variable | already defined | Declare once, then assign |
Writing /n for a new line | Prints /n as text | Use \n (backslash) |
❓ Frequently Asked Questions
Q1. What is the difference between println and \n?println adds a line break after the text. \n puts a line break anywhere inside the text.
Q2. Can two methods use the same local variable name?
Yes. Each method has its own locals, so int i in one does not clash with int i in another.
Q3. Why can loops reuse the name i?
The loop variable’s scope ends with the loop, so a second loop can declare it again.
Q4. Is there a global variable in Java?
Not exactly. The nearest thing is a static variable of a class.
✅ Key Takeaways
- Escape sequences begin with a backslash:
\n,\t,\",\\,\u0041. - Scope is the region where a variable is visible, from its declaration to the closing brace.
- Local variables must be given a value before use. Class-level variables get defaults (0, false, null).
- A local variable can hide a class variable of the same name (shadowing).
- Declare a variable in the smallest scope that works.
🎓 Practice questions: (1) Print the text: He said “Java is fun” using escape sequences. (2) Print a table of three names and marks aligned with\t. (3) Why does a variable declared inside a for loop disappear after the loop? (4) What are the default values of anint, abooleanand aStringfield? (5) Predict the output ofShadowDemoif the lineint x = 99;is removed.
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