nerdexam
Oracle

1Z0-811 · Question #73

Given the contents of the Test.java file: class MyClass { private int var1 = 100; public int var2 = 200; public void doCalc() { var1 = 100 2; var2 = 200 2; } } public class Test { public static void…

The correct answer is C. A compilation error occurs at line n2. Option C is correct because var1 is declared private in MyClass, meaning it can only be accessed from within that class - attempting to read x.var1 directly in Test.main() (line n2) violates access control and causes a compilation error. Option A ("200 : 400") and D ("100…

Object-Oriented Programming Principles

Question

Given the contents of the Test.java file: class MyClass { private int var1 = 100; public int var2 = 200; public void doCalc() { var1 = 100 * 2; var2 = 200 * 2; } } public class Test { public static void main(String[] args) { MyClass x = new MyClass(); x.doCalc(); System.out.println (x.var1 + " " + x.var2); // line n2 } } What is the result?

Options

  • A200 : 400
  • BA compilation error occurs at line n1.
  • CA compilation error occurs at line n2.
  • D100 : 400

How the community answered

(40 responses)
  • A
    5% (2)
  • B
    8% (3)
  • C
    85% (34)
  • D
    3% (1)

Explanation

Option C is correct because var1 is declared private in MyClass, meaning it can only be accessed from within that class - attempting to read x.var1 directly in Test.main() (line n2) violates access control and causes a compilation error.

Option A ("200 : 400") and D ("100 : 400") are wrong because the code never compiles in the first place - runtime output is impossible. Option B is wrong because doCalc() is public, so calling x.doCalc() is perfectly legal; no error occurs before line n2.

Memory tip: The rule is "private = class-only." If you see x.someField or x.someMethod() used outside the class where it's defined, ask yourself: "Is it private?" If yes, it's a compile-time error, not a runtime one.

Topics

#Access Modifiers#Private Keyword#Field Visibility#Encapsulation

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice