Nearby lessons

32 of 125

Java - Variable Scope

📌 What You Will Learn
  • The small building blocks of Java: tokens
  • All 8 primitive data types with their ranges
  • Type casting — implicit and explicit
  • Control statements: if, switch, loops
  • Arrays — single, double and jagged
  • Variable length arguments (var-args)

Variable Scope is a core concept of the Java language. This lesson explains Default Values of Variables and The final Keyword with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Default Values of Variables

If we declare a variable but do not give it a value, it gets a default value. But this is only for instance (member) variables — local variables inside methods have no default value and must be initialized before use.

TypeDefault value
byte, short, int0
long0L
float0.0f
double0.0
char'\u0000' (blank)
booleanfalse
Any object/array referencenull
Example01
JCode Cell
1class DefaultValues {
2 int x; // instance variable -> default 0
3 boolean flag; // instance variable -> default false
4 public static void main(String[] args) {
5 DefaultValues d = new DefaultValues();
6 System.out.println(d.x + " " + d.flag); // 0 false
7 
8 int y; // local variable
9 System.out.println(y); // ERROR! y not initialized
10 }
11}

The final Keyword

Used withEffect
final variableValue cannot be changed once assigned (constant).
final methodCannot be overridden by a child class.
final classCannot be extended (no child class allowed). Example: String class.
Example02
JCode Cell
1final int MAX = 100;
2// MAX = 200; // ERROR! cannot change a final variable
3 
4final class MathConstants { }
5// class Child extends MathConstants { } // ERROR! final class cannot be extended
📝 Key Takeaways
  • Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
  • Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
  • Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
  • if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
  • Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
  • Var-args (int... x) lets a method take any number of arguments.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1