Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 11: Escape Characters and Variable Scope in Java

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.

📌 An escape sequence starts with a backslash and stands for one special character, such as a new line (\n), a tab (\t) or a quote (\”).
EscapeMeaningExamplePrints
\nnew line"A\nB"A, then B on the next line
\ttab (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
\u0041Unicode 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");
    }
}
🖥️ Output:
Name: Ajay
Course: Java
Line one
Line two
He said “Hello”
It’s fine
‘
C:\Users\Ajay
Unicode: AB
  • \t jumps to the next tab stop, so “Ajay” and “Java” line up in a column.
  • \n starts 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.
  • \u0041 is 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.

Class level
static variable: lives for the whole program
Method level
local variable: lives until the method ends
Block level
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

KindDeclaredGets a default?Lives until
Local variableinside a method or blockNo: must be given a valuethe block or method ends
Instance variablein a class, without staticYes (0, false, null)the object is destroyed
Static variablein a class, with staticYes (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);
        }
    }
}
🖥️ Output:
classLevel = 100
methodLevel = 10
blockLevel = 50
inside block, methodLevel = 10
loop i = 0
loop i = 1
loop i = 2
  • classLevel is declared in the class, so every method can see it.
  • methodLevel is visible inside main and also inside the inner if block, because the block is inside the method.
  • blockLevel exists only between the braces of the if. The loop variable i exists only inside the for.

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);
    }
}
🖥️ Output:
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 to null, 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);
    }
}
🖥️ Output:
local x = 99
class x = 5
main sees x = 5
  • Inside show, plain x means the local one (99).
  • ShadowDemo.x reaches the hidden class variable (5).
  • main has no local x, 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);
    }
}
🖥️ Compiler message:
OutOfScope.java:6: error: cannot find symbol
System.out.println(inside);
^
symbol: variable inside
location: class OutOfScope
1 error
  • inside died at the closing brace. Declare it before the if if 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);
    }
}
🖥️ Compiler message:
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);
    }
}
🖥️ Compiler message:
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

MistakeProblemFix
"C:\Java"\J is not a valid escapeWrite "C:\\Java"
Quote inside a String without a backslashThe String ends earlyUse \"
Using a block variable after the blockcannot find symbolDeclare it outside the block
Reading an unassigned local variablemight not have been initializedGive it a starting value
Redeclaring a local variablealready definedDeclare once, then assign
Writing /n for a new linePrints /n as textUse \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 an int, a boolean and a String field? (5) Predict the output of ShadowDemo if the line int x = 99; is removed.
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