Bird
0
0

What will be the output of the following Java code?

medium📝 Predict Output Q4 of 15
Java - Constructors
What will be the output of the following Java code?
class Example {
  int val = 7;
  void display(int val) {
    System.out.println(val);
    System.out.println(this.val);
  }
}
public class Main {
  public static void main(String[] args) {
    Example e = new Example();
    e.display(15);
  }
}
A7 15
B15 7
C7 7
D15 15
Step-by-Step Solution
Solution:
  1. Step 1: Identify local and instance variables

    The method parameter val shadows the instance variable val.
  2. Step 2: Understand the print statements

    System.out.println(val); prints the local parameter (15).
    System.out.println(this.val); prints the instance variable (7).
  3. Final Answer:

    15 7 -> Option B
  4. Quick Check:

    Local variable shadows instance variable; use this to access instance [OK]
Quick Trick: Local shadows instance; this accesses instance [OK]
Common Mistakes:
  • Assuming both print statements print the same value
  • Confusing local and instance variables
  • Ignoring the use of this keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes