Try your hand at the sample questions below for a free preview of what to expect from the SCJP exam. These questions and answers are provided courtesy of Whizlabs Software, a company that specializes in IT certification training software. See the article Resourcesto learn more about Whizlabs and other organizations that offer IT certification training.
What will happen when you attempt to compile and run the following code? (Assume that the code is compiled and run with assertions enabled.)
public class AssertTest
{
public void methodA(int i)
{
assert i >= 0 : methodB();
System.out.println(i);
}
public void methodB()
{
System.out.println("The value must not be negative");
}
public static void main(String args[])
{
AssertTest test = new AssertTest();
test.methodA(-10);
}
}
|
Choices
A. It will print -10.
B. It will result in an assertion error showing the message: "The value must not be negative".
C. The code will not compile.
D. None of the above.
Correct choice: C
Explanation: Choice C is correct. An assert statement can take one of these two forms:
assert Expression1; assert Expression1 : Expression2; |
In the second form, the second part of the statement must be an expression, that is,
Expression2 . In this code, the
methodB() returns void, which is not an expression and hence it results in a compile-time error. The code will compile if
methodB() returns any value such as int or String. Also, in both forms of the assert statement,
Expression1 must have type boolean or a compile-time error will occur.
What is displayed when the following code is executed?
class Parent
{
private void method1()
{
System.out.println("Parent's method1()");
}
public void method2()
{
System.out.println("Parent's method2()");
method1();
}
}
class Child extends Parent
{
public void method1()
{
System.out.println("Child's method1()");
}
public static void main(String args[])
{
Parent p = new Child();
p.method2();
}
}
|
Choices
A. Compile-time error
B. Run-time error
C. Prints:
Parent's method2() Parent's method1() |
D. Prints:
Parent's method2() Child's method1() |
Correct choice: C
Explanation: Choice C is correct. The code will compile and
run without error. The variable
p refers
to the
Child class object. The statement
p.method2() on execution will first look
for
method2() in the
Child class. Since there is no
method2() in the child class, the
method2() of
Parent
class will be invoked, which will result in "
Parent's method2() " being printed.
Note that from the
method2() , there is
a call to
method1() . Because
method1() of the
Parent class is private, it will be invoked. Had
method1() of the
Parent class been public, protected, or friendly
(default), the
Child 's method would have
been called.
Source: Whizlabs Java Certification (SCJP 1.4) Exam Simulator. Whizlabs Softwarewas cofounded by the author of this article.