Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Java - Classes and Objects
What will be the output of this code?
class Box {
  int length = 5;
  int width = 3;
}

public class Test {
  public static void main(String[] args) {
    Box b = new Box();
    b.length = 10;
    System.out.println(b.length + b.width);
  }
}
A8
B13
C10
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze instance variable values

    Initially, length=5 and width=3. Then length is changed to 10.
  2. Step 2: Calculate sum of length and width

    Sum is 10 + 3 = 13.
  3. Final Answer:

    13 -> Option B
  4. Quick Check:

    Instance variables updated correctly = 13 [OK]
Quick Trick: Instance variables can be changed per object anytime. [OK]
Common Mistakes:
  • Adding old length value instead of updated.
  • Confusing instance variables with static variables.
  • Expecting compilation error due to assignment.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes