nerdexam
Oracle

1Z0-808 · Question #71

Given: public class ScopeTest { int j, int k; public static void main(String[] args) { ew ScopeTest().doStuff(); } void doStuff() { int x = 5; doStuff2(); System.out.println("x"); } void doStuff2()…

The correct answer is A. j B. k. Fields (also called instance variables) are variables declared directly inside a class body, outside of any method or block. j and k are declared at the class level in ScopeTest, so they belong to every instance of the class - that makes them fields. x (choice C) is declared…

Java Basics

Question

Given: public class ScopeTest { int j, int k; public static void main(String[] args) { ew ScopeTest().doStuff(); } void doStuff() { int x = 5; doStuff2(); System.out.println("x"); } void doStuff2() { int y = 7; System.out.println("y"); for (int z = 0; z < y; z++) { System.out.println("z"); System.out.println("y"); } } } Which two items are fields?

Options

  • Aj
  • Bk
  • Cx
  • Dy
  • Ez

How the community answered

(25 responses)
  • A
    88% (22)
  • C
    4% (1)
  • D
    4% (1)
  • E
    4% (1)

Explanation

Fields (also called instance variables) are variables declared directly inside a class body, outside of any method or block. j and k are declared at the class level in ScopeTest, so they belong to every instance of the class - that makes them fields.

x (choice C) is declared inside doStuff(), making it a local variable that only exists while that method is executing. y (choice D) is similarly local to doStuff2(). z (choice E) is even more restricted - it's declared in a for loop header, giving it block scope that disappears after the loop ends.

Memory tip: Think "class-level = field, method-level = local." If the variable lives inside curly braces that belong to a method, constructor, or block, it's local. If it lives inside the class's own curly braces with no method wrapping it, it's a field.

Topics

#variable scope#fields#instance variables#local variables

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice