LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Predict the Output · Question 7

A constructor parameter shadowing a field Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following Java program?

Main.java
class Laptop {
    String brand;
    int ram;

    Laptop(String brand, int ram) {
        brand = brand;           // the parameter, not the field
        this.ram = ram;
    }
}

public class Main {
    public static void main(String[] args) {
        Laptop l = new Laptop("Dell", 16);
        System.out.println(l.brand + " " + l.ram);
    }
}
  • A null 16 Correct
  • B Dell 16
  • C null 0
  • D Compilation error
Correct Answer: Option A

Inside the constructor, brand means the parameter, so the field keeps its default null.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links