Arrays and Strings · Introduction to Java Programming

Initializing Instance Variables

Watch lectures

Initializing Instance Variables

1. What Are Instance Variables? (beginner)

Instance vars = data inside object (each house own copy!): name, balance. vs local (method temp, dies!) vs static (shared by ALL objects!). Default values auto: numbers→0, boolean→false, objects→null!

2. Three Ways to Init (exam list!)

class Student {
    int marks = 50;      // WAY 1: at declaration (default for all!)
    String name;         // null until set!
    // WAY 2: constructor (custom per object! — next topic!)
    Student(String n, int m) { name = n; marks = m; }
    // WAY 3: direct after new (beginner style, breaks encapsulation!)
}
Student s1 = new Student("Asha", 87); // custom!
Student s2 = new Student("Ravi", 70); // different!

Init block (rare, exam mention!):

class Demo {
    int x;
    { x = 100; } // runs BEFORE constructor, every object!
}

3. Defaults Table (exam trap!)

Variable kind Default? Example
Instance int marks; 0 (auto!) prints 0 (no error!)
Instance String name; null name.length() → NPE!
Local int x; (in method) NONE (must assign!) use before assign → ERROR!
class T { int a; void m() { int b; System.out.println(a); /*0*/ /*System.out.println(b);*/ /*ERROR!*/ } }

4. Traps

  • Locals need manual init (compiler forces!). Instance auto-zero (beginners rely, pros set explicitly!).
  • Direct s.marks = -5; bypasses guard (use constructor/setter!).

5. Exam Points

  • Three ways + defaults table — 5 marks, frequent.
  • Local vs instance default — 3-5 marks, favourite trap.
Budget AppAndroid App

Pocketly on Android

Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.

← All Introduction to Java Programming modules