Author: AlinaIoana Florea
Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/java-static-non-inner-classes
Question 289 / 297:  (SCJP 6) Find the errors in:
Choose 3
static class X // line 1

{

static { a = 3; } // line 2

static X() {} // line 1

int a;

static int b;

void doX(){ System.out.println("In X" + a + b); } // line 3

static void doStuff() { System.out.println("In X" + /*a*/ + b); } // line 4

}

public class Test extends X

{

public static void main(String[] args)

{

X x = new X();

doStuff();

x.doStuff(); // line 5

X.doStuff(); // line 5.2

}

void doStuff() // line 6

{

System.out.println("In Test");

}

}

<< First < Previous Next > Last >>
Explanation:

Code marked with "static" belongs only to the class(will not be created per obj). Therefor in a static method you can call only static vars, as the non-static/object ones might not exist yet.

So it's possible to call static members on their class without an obj: line 5.2.

But it's OK to call it on an obj too: line 5 (as all objs can access everything inside their class).

line 1 - a constructor is used only when an object is created with the "new" operator

line 2 - a static initialization block runs to initialize the static vars, so after the class and its static vars are created for the first time in memory by the JVM.

lines 4 - the comments are needed bc in a static method you can NOT use non-static vars. The reverse is valid: non-static methods can use static vars bc they exist already since the class was created.

If the app is corrected it will print:

In Test

In X3

In X3

Exam Home Page
https://www.jobilize.com/java-certification-questions

Oracle Certified Professional Java Programmer

Author:

Access: Public Instant Grading

Ask
Keyaira Braxton
Start Exam
Marion Cabalfin
Start Test
Anonymous User
Start Quiz
Subramanian Divya
Start Quiz
Copy and paste the following HTML code into your website or blog.
<iframe src="https://www.jobilize.com/embed/java-certification-questions" width="600" height="600" frameborder="0" marginwidth="0" marginheight="0" scrolling="yes" style="border:1px solid #CCC; border-width:1px 1px 0; margin-bottom:5px" allowfullscreen webkitallowfullscreen mozallowfullscreen> </iframe>