Bird
0
0

What will be the output of this Java code?

medium📝 Predict Output Q5 of 15
Java - Classes and Objects
What will be the output of this Java code?
class Person {
  String name;
  Person(String n) {
    name = n;
  }
}

public class Main {
  public static void main(String[] args) {
    Person p = new Person("Alice");
    System.out.println(p.name);
  }
}
Anull
BAlice
CCompilation error
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor usage

    The Person class has a constructor that sets the name field to the passed argument.
  2. Step 2: Object creation and printing

    Creating Person p = new Person("Alice") sets name to "Alice". Printing p.name outputs "Alice".
  3. Final Answer:

    Alice -> Option B
  4. Quick Check:

    Constructor sets field value correctly [OK]
Quick Trick: Constructor initializes fields on object creation [OK]
Common Mistakes:
  • Expecting default null value
  • Missing constructor call
  • Confusing field initialization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes