Monday, July 21, 2008

Sun Certified Java Programmer 6 Mock Exams SCJP - Final and Abstract Exam Objectives

Which of the following statements it true about the following code:

public abstract final void goAndGetCertified() {}


The code will successfully compile and run.

The code will compile but not run.
A final method cannot be void, so the code will not compile.
A final method cannot be abstract, so the code will not compile.
A final method cannot be public, so the code will not compile.
A final method cannot be abstract, so the code will not compile.

############################

Which of the following statements it true about the following code:

public abstract void goAndGetCertified() {}

The code will successfully compile and run.

The code will compile but not run.
An abstract method cannot be void, so the code will not compile.
An abstract method cannot be public, so the code will not compile.
An abstract method cannot have a name, so the code will not compile.
An abstract method cannot have an implementation, so the code will not compile.

************************************

Which statement is true about the following code:

public class SCJP{

public static void main(String argv[]){

final int x = 10;
private short y = x ;

System.out.print(x);
System.out.println(y);
}
}

a) The code would compile but not run.
b) The code would compile, run, and print 1010 to the console.
c) The code will not compile as final variables are not allowed in static methods.
d) The code will not compiles as private variables are not allowed in static methods.
e) The code will not compile because an int value cannot be assigned to a short.

Option d) is correct.

#####################################

Which statement is true about the following code:

public class SCJP{

public static void main(String argv[]){

final int x = 10;
short y = x ;

System.out.print(x);
System.out.println(y);
}
}

a) The code would compile but not run.
b) The code would compile, run, and print 1010 to the console.
c) The code will not compile as final variables are not allowed in static methods.
d) The code will not compiles as private variables are not allowed in static methods.
e) The code will not compile because an int value cannot be assigned to a short.

Option b) is correct.

##########################################

Which statement is true about the following code:

public class SCJP{

public static void main(String argv[]){

final int x;
x = 10;
short y = x ;

System.out.print(x);
System.out.println(y);
}
}

a) The code would compile but not run.
b) The code would compile, run, and print 1010 to the console.
c) The code will not compile as final variables are not allowed in static methods.
d) The code will not compiles as private variables are not allowed in static methods.
e) The code will not compile because an int value cannot be assigned to a short.

Option e) is correct.

#############################################

Which statement is true about the following code:

public class SCJP6{

public static void main(String argv[]){

final int x = 35000;
short y = x ;

System.out.print(x);
System.out.println(y);
}
}


a) The code would compile but not run.
b) The code would compile, run, and print 1010 to the console.
c) The code will not compile as final variables are not allowed in static methods.
d) The code will not compiles as private variables are not allowed in static methods.
e) The code will not compile because an int value cannot be assigned to a short.

Optoin e) is correct.

This link on JavaRanch has some great info on this topic: JavaRanch thread.
Which of the following statements it true about the following code:

public abstract final void goAndGetCertified() {}


The code will successfully compile and run.

The code will compile but not run.
A final method cannot be void, so the code will not compile.
A final method cannot be abstract, so the code will not compile.
A final method cannot be public, so the code will not compile.
A final method cannot be abstract, so the code will not compile.

############################

Which of the following statements it true about the following code:

public abstract void goAndGetCertified() {}

The code will successfully compile and run.

The code will compile but not run.
An abstract method cannot be void, so the code will not compile.
An abstract method cannot be public, so the code will not compile.
An abstract method cannot have a name, so the code will not compile.
An abstract method cannot have an implementation, so the code will not compile.

Sunday, July 20, 2008

More SJCP 6.0 Mock Exams for JVM 1.6 Sample Test and Sample Quiz Answers

Give the following class and interface definitions:

interface Family {}

abstract class Ancestor implements Family {}
class Parent extends Ancestor {}
class Child extends Parent {}

Which lines of code would be valid after the declaration and initialization of Ancestor a?

public class SCJPTestClass {

public static void main(String args[]) {
Ancestor a = new Parent();

}
}

a) Child c = (Child) a;
b) Parent p = (Parent) a;
c) Family f = (Family) a;
d) Ancestor an = (Ancestor) a;

Options b) c) and d) are correct.

Option a) will not compile, as the object that Ancestor a refers to was created as a Parent object, and while a Parent can be cast into anything above it on the inheritance hierarchy, it cannot be cast into anything below it on the inheritance hierarchy, and the Child class is below the Parent class on the hierarchy chain. Option a) will generate a ClassCastException at runtime, although the code will compile just fine.

Option b) casts the ancestor reference a back into a Parent, which is fine, as the object was originally creates as a Parent instance.

Furthermore, a Parent shares an is-a relationship with the Family class through the fact that it inherits from Ancestor, and Ancestor implements the Family interface. So option c) is completely valid as well.

Option d) simply casts the ancestor reference into an ancestor, which is completely valid, although perhaps a bit redundant and unnecessary.




###############

Given the following code snippet, when will the contents of the finally block be executed?

public class SCJP6Certified {
public static void main(String args[]) {

String input = (new java.util.Scanner( System.in )).nextLine();

try{ Long haul = new Long(input); }
catch (Exception e) { e.printStackTrace(); }
finally{ System.out.println("finally"); }

}
}

a) Any time the try block throws a RuntimeException
b) Any time the try block runs runs without throwing an Exception
c) Any time the try block throws a checked Exception
d) Any time the try block throws an Error

Options b) c) and d) are correct.

The finally block will always execute whenever a try block is entered, that is, barring someone hasn't pulled the plug out of the computer while the code is executing.

The finally block is often used for cleaning up resources that may need special attention upon their destruction. It's a great place for doing such things, because the finally block is always executed so long as the corresponding try block is entered, regardless of whether the try block throws an exception, or runs to fruition.


Given the following code snippet, when will the contents of the catch block be executed?

public class SCJP6Certified {
public static void main(String args[]) {

String input = (new java.util.Scanner( System.in )).nextLine();

try{ Long haul = new Long(input); }
catch (Error e) { e.printStackTrace(); }
finally{ System.out.println("finally"); }

}
}

a) Any time the try block throws a NumberFormatException
b) Any time the try block runs runs without throwing an Exception
c) Any time the try block throws a checked Exception
d) Any time an abnormal condition generates an Error

Option d) is correct.

Since this try catch finally block only looks for an Error object, normal checked Exception instances and RuntimeException instances will be ignored by the catch block, and will cause termination of the program after the finally block is executed.

"An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. " Java 6 API JavaDoc java.lang.Error

The following are commonly seen subclasses of java.lang.Error:
AnnotationFormatError, AssertionError, AWTError, CoderMalfunctionError, FactoryConfigurationError, FactoryConfigurationError, IOError, LinkageError, ServiceConfigurationError, ThreadDeath, TransformerFactoryConfigurationError, VirtualMachineError

SCJP6 Mock Exam Questions: Exception Handling, Polymorphism and Inheritance

Given the following code, which of the following methods could be defined in the SunCertified class without causing a compile error?

public class Certified {

public void getCertified() throws GreatGrandChildException { }
}

class SunCertified extends Certified {
}

class ChildException extends Exception{}
class GrandChildException extends ChildException{}
class GreatGrandChildException extends GrandChildException {}


a) public void getCertified() throws Exception { }
b) public void getCertified() throws ChildException { }
c) public void getCertified() throws GrandChildException { }
d) public void getCertified() throws GreatGrandChildException { }

Option d) is correct.

An important rule in Java says that when you override a method in a subclass, you cannot throw any checked Exceptions other than those declared in the method you are overriding. So, since the parent, Certified class does not indicate any checked exceptions in the getCertified() method's throws clause, the overriding method in the SunCertified class is not allowed to throw any new Exceptions either.

Trying to override a method in a subclass, and subsequently throwing a new type of exception in the overriding method, will generate a compiler error such as this one:

C:\_jdk1.6\bin>javac Certified.java
Certified.java:9: getCertified() in SunCertified cannot override getCertified()
in Certified; overridden method does not throw java.lang.Exception
public void getCertified() throws Exception { }
^
1 error


###############################

Given the following code, which of the following methods could be defined in the SunCertified class without causing a compile error?

public class Certified {

public void getCertified() throws ChildException { }
}

class SunCertified extends Certified {
}

class ChildException extends Exception{}
class GrandChildException extends ChildException{}
class GreatGrandChildException extends GrandChildException {}


a) public void getCertified() throws Exception { }
b) public void getCertified() throws ChildException { }
c) public void getCertified() throws GrandChildException { }
d) public void getCertified() throws GreatGrandChildException { }

Options b) c) and d) are correct.

When a subclass overrides a method defined in a parent class, it cannot throw any checked exceptions that are not explicitly thrown by the method being overridden from the ancestor or parent class. However, polymorphism in Java dictates that whenever a certain instance of a class is needed, required or defined, any instance of a subclass can take its place. So, while the parent class, Certified, only throws the ChildException in its getCertified method, any overriding getCertified() method in a subclass is more than welcome to throw a more specific, subclass of the ChildException that is thrown in the ancestor class.

Polymorphism in Java indicates that any time a particular class is needed, and instance of that class, or instance of a subclass that wil share an is-a relationship with that requested class, will do.

##################################################

Given the following code, which of the following methods could be defined in the SunCertified class without causing a compile error?

public class Certified {
public void getCertified() throws ChildException { }
}

class SunCertified extends Certified {}

class ChildException extends Exception{}
class GrandChildException extends ChildException{}
class GreatGrandChildException extends GrandChildException {}


a) public void getCertified() throws Exception, ClassCastException { }
b) public void getCertified() throws ChildException, IllegalStateException { }
c) public void getCertified() throws GrandChildException, IllegalStateException { }
d) public void getCertified() throws GreatGrandChildException, NoClassDefFoundError { }


Options b) c) and d) are correct.

Since the getCertified() method in the ancestor class, Certified, throws java.lang.ChildException, any subclass overriding the getCertified() method must also throw an instance of the ChildException if it is to have a throws clause. Since GreandChildException and GreatGrandChildException are both subclasses of ChildException, they share an is-a relationship with the ChildException class, and as such, they are allowed in the throws clause of the method named getCertified().

However, you will notice that the getCertified() methods in options a) b) c) and d) all throw unchecked, runtime exceptions, that were not thrown in the method definition of the parent class. This is okay, as an overriding method can mention any number of unchecked, runtime exceptions that may or may not have been defined in the method being overridden from the parent class.

When it comes to throwing exceptions in overridden methods, you cannot throw any checked exceptions that don't share an is-a relationship with the exception thrown in the corresponding method defined in the parent class. However, this rule does not apply to unchecked, runtime exceptions, so an overridden method can throw any number of unchecked exceptions, regardless of whether they were defined by the method being overridden from the parent class or not.

The RuntimeException classes that are explicitly defined by the SCJP 6 exam objectives include:
ArrayIndexOutOfBoundsException, ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError and NoClassDefFoundError.




#######################################################

Given the following code, which of the following methods could be defined in the SunCertified class without causing a compile error?

public class Certified {

public void getCertified() throws GreatGrandChildException { }

}

class SunCertified extends Certified {

}

class ChildException extends Exception{}
class GrandChildException extends ChildException{}
class GreatGrandChildException extends GrandChildException {}

a) public void getCertified() { }
b) public void getCertified() throws ClassCastException { }
c) public void getCertified() throws ChildException, IllegalStateException { }
d) public void getCertified() throws GrandChildException, IllegalStateException { }
e) public void getCertified() throws GreatGrandChildException, NoClassDefFoundError { }


Options a) b) and e) are correct.

When you override a method that has a throws clause, it is completely valid for your overridden implementation of that method not to have a throws clause at all, making option a) correct.

Furthermore, an overridding method is allowed to throw any number of unchecked, RuntimeException or Error objects, regardless of whether the RuntimeException or Error object was thrown in the inherited method that is being overridden, making option b) completely valid.

Options c) and d) will not compile, as the overriding method tries to throw exceptions that are less specific than the one thrown by the getCertified() method in the parent class. ChildException and GrandChildException do not share an is-a relationship with the GreatGrandChildException, and as a result, throwing them in the overridding method generates a compile error.

Option e) will indeed compile, as both the overridding method and the overridden method both throw the exact same checked exception, the GreatGrandChildException. The overridden method also throws the NoClassDefFoundError, but overriding methods can throw any number of Errors that are not explicilty defined in the method being overridden, so this does not cause a problem when using option e).

###########################################

The following code does not compile. How should the getCertified() method be refactored to allow this code to compile?

public class Certified {


getCertified {

String input = (new java.util.Scanner( System.in )).nextLine();

if (input.equals("SCJA")) { throw new ChildException(); }
if (input.equals("SCJP")) { throw new RuntimeException(); }
if (input.equals("SCEA")) { throw new Error(); }

}
}

class ChildException extends Exception {}
class GrandChildException extends ChildException{}
class GreatGrandChildException extends GrandChildException {}

a) public static void getCertified()
b) public static void getCertified() throws Error, RuntimeException
c) public static void getCertified() throws Exception, Error
d) public static void getCertified() throws ChildException
e) public static void getCertified() throws RuntimeException, Error, GrandChildException

Options c) d) and are correct.

Any method that might throw a checked exception must state so explicitly in the throws clause of the method. Since ChildException is a checked exception, the ChildException, or any throwable parent of the ChildException, must be mentioned in the getCertified() method's throws clause. This makes options c) and d) correct.

Option a) is incorrect, as it does not mention the fact that the ChildException might be thrown when this method runs. This is the same reason that options b) and e) are incorrect as well. Option e) mentions that GrandChildException might be thrown, but this Exception is more specific, and below ChildException on the class hierarchy, meaning that handling the GrandChildException would not necessarily provide proper handling for situations where the parent, ChildException, might be thrown.

One thing to note is that while the getCertified() method may throw a checked Exception, an unchecked RuntimeException, or even an instance of an Error, only the checked Exception is absolutely required to be specified in the throws clause of the method.

Saturday, July 19, 2008

Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. SCJP 6.0 Mock Exam & Objectives

Section 6: Collections / Generics

* Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.

* Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.

-SCJP Exam Objectives


Which of the following interfaces provides a natural comparison method for implementing types?

a) java.util.Comparable
b) java.util.Comparator
c) java.lang.Comparable
d) java.lang.Comparator

Option c), java.lang.Comparable, is correct.

According to the Java 6 API JavaDoc, "The java.lang.Comparable interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method."

The Comparator interface is located in the java.util package. The comparator interface is used to impose ordering on a collection of objects that is different from the natural ordering you might obtain from java.lang.Comparable interface.

Which two abstract methods are defined by the Comparator interface?

a) boolean compare(T o1, T o2)
b) boolean equals(Object obj)
c) boolean compareTo(T o)
d) int compare(T o1, T o2)
e) int equals(Object obj)
f) int compareTo(T o)

Options b) and d) are correct for this answer.

The java.util.Comparator interface defines an equals method that returns a boolean value, and a compare method that returns an int value.

The java.lang.Comparable interface is the one that defines the compareTo method that returns an int value.

For both the compare and the compareTo methods of the Comparator and Comparable interfaces return an int value. A negative value indicates that the first argument passed to the method is, when being ordered in a list, less than the second argument passed. A zero value indicates that the two types passed in as arguments are equal to each other, and the positive value indicates that the first value passed into the method is, when being ordered, greater than the second argument passed into the method.

It is interesting to note that the Comparator interface defines a .equals method. Why is this interesting? Well, becuase it seems redundant, as you can't create an object in Java that doesn't already inherit a fully functional equals method from its parent class. Of course, the makers of Java 6 were fully aware of this. But the mention of the .equals method wasn't an oversight, but instead, was an attempt to emphasize the following poing:

"
Note that it is always safe not to override Object.equals(Object). However, overriding this method may, in some cases, improve performance by allowing programs to determine that two distinct comparators impose the same order. " -JavaDoc equals Comparator Interface

When two objects are being compared through the pertinent method of the Comparator interface, a negative return value idicates:

a) a processing error in performing the comparison
b) the first argument is greater than the second
c) the second argument is greater than the first
d) the two arguments are equal when being compared

Option c) is the correct answer.

The compareTo method takes two objects as parameters. If the first object is less than the second parameter, then a negative result is returned. This is the same as saying the second argument is greater than the first, as is stated by option c) in the answer.

When the opposite is true, a positive result is returned, and when the two objects passed to the Comparator's compareTo method are equal, a zero value is returned.


Which method is defined by the Comparable interface?

a) boolean compare(T o1, T o2)
b) boolean compareTo(T o1, T o2)
c) int compareTo(T o1, T o2)
d) int compareTo(T o)
e) int equals(Object obj)
f) boolean equals(Object obj)


Option d) is the correct anwer.

The java.lang.Comparable interface defines only one method that needs to be implemented, compareTo(T o), making option d) correct.

This method must be implemented in order for collection classes to be able to sort a collection of these object types according to a natural, logical ordering.

The Comparator interface defines the abstract int compare and boolean equals methods.

#########################################################

What would be the result of an attempt to run and compile the following code?


import java.util.*;
public class BeyondCompare {
public static void main (String args[]) throws Exception {
List players = new Vector(3);

players.add(new Player(01, 99, "Wayne"));
players.add(new Player(03, 07, "Tim"));
players.add(new Player(02, 88, "Mario"));

for (Player p : players) System.out.print( p.name() + " ");

}

}


class Player extends Object implements Comparator {

int id, number; String name;

Player(int id, int number, String name) {
this.id = id; this.number=number;
}

public int compareTo(Player p) {
return this.id - p.id;
}

public int compare(Player p1, Player p2) {
return p2.number - p1.number;
}

}

a) The code would not compile
b) The code would compile but not run
c) The code would print out Wayne Mario Tim
d) The code would print out Tim Mario Wayne
e) The code would print out Mario Tim Wayne

Option a) is correct.

The variable name is using method notation, and as a result, the compiler will attempt to link to a method called name() in the Player class, which does not exist. As a result, the code will not compile.

p.name() should be p.name

#################################################

What would be the result of running and compiling the following code?

import java.util.*;
public class BeyondCompare {
public static void main (String args[]) throws Exception {

List players = new Vector(3);

players.add(new Player(01, 99, "Wayne"));
players.add(new Player(03, 07, "Tim"));
players.add(new Player(02, 88, "Mario"));

for (Player p : players) System.out.print( p.name + " ");

}

}


class Player extends Object implements Comparable, Comparator {

int id, number; String name;

Player(int id, int number, String name) {
this.id = id; this.number=number; this.name=name;
}

public int compareTo(Player p) {
return this.id - p.id;
}

public int compare(Player p1, Player p2) {
return p2.number - p1.number;
}

}

a) The code would not compile
b) The code would compile but not run
c) The code would print out Tim Mario Wayne
d) The code would print out Wayne Mario Tim
e) The code would print out Mario Tim Wayne
f) The code would print out Wayne Tim Mario

Option f) is correct.

While the Player class implements the Comparable interface, and provides a compareTo method that would sort on the id of the player, the fact is, the List or Vector was never actually sorted, and as such, no sorting was performed, so the elements placed into the vector will be sorted in the exact same order in which elements were added, which produces an output of Wayne Tim Mario

####################################################


What line of code, placed immediately before the enhanced for:each loop, would generate the output of Wayne Tim Mario?

import java.util.*;
public class BeyondCompare {
public static void main (String args[]) throws Exception {
List players = new Vector(3);

players.add(new Player(01, 99, "Wayne"));
players.add(new Player(03, 07, "Tim"));
players.add(new Player(02, 88, "Mario"));


/* Place Code Here */

for (Player p : players) System.out.print( p.name + " ");

}

}


class Player extends Object implements Comparable, Comparator {

int id, number; String name;

Player(int id, int number, String name) {
this.id = id; this.number=number; this.name=name;
}

public int compareTo(Player p) {
return p.id - this.id;
}

public int compare(Player p1, Player p2) {
return p2.number - p1.number;
}

}


a) players.sort();
b) Arrays.sort(players);
c) Vector.sort(players);
d) Collections.sort(players);

Option d) is correct.

The player class does not define or inherit any sort method, so this options is just plain wrong.

The java.util.Arrays class does define a sort method, but it requires an array as a parameter, not a Vector or a List, as we have in this example.

"Arrays:
static void
sort(Object[] a)
Sorts the specified array of objects into ascending order, according to the natural ordering
of its elements."
- sort method of java.util.Arrays class

Vector does not have a static sort method, so option c) is incorrect.

The Collections class does indeed have a sort method, and when passed any class that implements the List interface, it will sort those classes according to their "natural order." For a class such as the Player class, or any class that implements the Comparable interface, the natural order is determined by the ordering results of the compareTo method.

With the Player class, the compareTo method orders players according to their jersey number, from lowest to highest, making the output Tim Mario Wayne, whose jersey numbers are 7, 88 and 99 respectively.



What would be the result of attempting to compile and run the following code?

import java.util.*;
public class BeyondCompare {
public static void main (String args[]) throws Exception {
List players = new Vector(3);

players.add(new Player(01, 99, "Wayne"));
players.add(new Player(03, 07, "Tim"));
players.add(new Player(02, 88, "Mario"));


Collections.sort(players);

for (Player p : players) System.out.print( p.name + " ");

}

}


class Player extends Object implements Comparator {

int id, number; String name;

Player(int id, int number, String name) {
this.id = id; this.number=number; this.name=name;
}

public int compareTo(Player p) {
return p.id - this.id;
}

public int compare(Player p1, Player p2) {
return p2.number - p1.number;
}

}


a) The code would not compile
b) The code would compile but not run
c) The code would print out Tim Mario Wayne
d) The code would print out Wayne Mario Tim
e) The code would print out Mario Tim Wayne
f) The code would print out Wayne Tim Mario

Option a) is correct.

In this case, the Player class is not implementing the Comparable interface, so when the compiler sees the call to Collections.sort(players), it realizes that the Vector of players cannot have its various elements compared, and as such, the compiler chokes and a compiled class file cannot be generated.

Note that the Player class does contain the compareTo method, as required by the Comparable interface. However, if the class does not explicitly state that it implements the Comparable interface, it cannot be used by any methods that require an instance of type Comparable, as is the case with the Collections and Arrays sort methods.



What would be the result of attempting to compile and run the following code?

import java.util.*;
public class BeyondCompare {
public static void main (String args[]) throws Exception {
List players = new Vector(3);

players.add(new Player(01, 99, "Wayne"));
players.add(new Player(03, 07, "Tim"));
players.add(new Player(02, 88, "Mario"));


Collections.sort(players, new Player());

for (Player p : players) System.out.print( p.name + " ");

}

}


class Player extends Object implements Comparator {

int id, number; String name;


Player(int id, int number, String name) {
this.id = id; this.number=number; this.name=name;
}

public int compareTo(Player p) {
return p.id - this.id;
}

public int compare(Player p1, Player p2) {
return p2.number - p1.number;
}

}


a) The code would not compile
b) The code would compile but not run
c) The code would print out Tim Mario Wayne
d) The code would print out Wayne Mario Tim
e) The code would print out Mario Tim Wayne
f) The code would print out Wayne Tim Mario

Option a) is correct.

This is clearly a bit of misdirection, getting you to concentrate on the comparison aspect of this code, but tat is not what's wrong with the code. The line of code Collections.sort(players, new Player()); fails to compile due to the fact that the default constructor of the Player class is not available. Every class that extends Object has an implicit, default, constructor. But, if a non-defualt exists in a class, as it does in the Player class, the default constructor is no longer implicitly available. So, the call to new Player() causes a compile error.

Exam Objectives
Section 1: Declarations, Initialization and Scoping

Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class. - SCJP Exam Objectives


Which line of code, placed immediately before the enhanced for:each loop in the main method, would generate the output of Wayne Mario Tim?

import java.util.*;
public class BeyondCompare {
public static void main (String args[]) throws Exception {
List players = new Vector(3);

players.add(new Player(01, 99, "Wayne"));
players.add(new Player(03, 07, "Tim"));
players.add(new Player(02, 88, "Mario"));


/* Place Code Here */

for (Player p : players) System.out.print( p.name + " ");

}

}


class Player extends Object implements Comparable, Comparator {

int id, number; String name;


Player(int id, int number, String name) {
this.id = id; this.number=number; this.name=name;
}

public int compareTo(Player p) {
return p.id - this.id;
}

public int compare(Player p1, Player p2) {
return p2.number - p1.number;
}

}


a) Collections.sort(players, new Player());
b) Collections.sort(players);
c) Collections.sort(players, new Player(01, 01, 01));
d) Collections.sort(players, new Player(0, 0, null));

Option d) is correct.

Option a) will not compile, as the default constructor, Player(), is not available in the Player class.

Option b) will allow the code to compile, but the sorting will occur according to the natural ordering of the class, which is produced by ordering the elements of the list according to the compareTo method, which is required by any class implementing the Comparable interface. However, the Comparable interface would sort the list of Players according to their ids, generating output of Wayne Mario Tim.

Option c) would not compile, as there is no constructor for the Player class that takes three integer types as parameters.

Option d) will not only compile, but will also sort the Players according to their jersey numbers, generating an output of Tim Mario Wayne.

#########################################################

What code snippet, placed immediately before the enhanced for:each loop in the main method, would sort the Player names alphabetically?

a)
Collections.sort(players,
new Comparator() {
public int compare (Player p1, Player p2)
{ return p1.name.compareTo(p2.name) ;}
}
);

b)

Collections.sort(players, new String());

c)
Collections.sort(players,
new Comparator() {
public int compare (Player p1, Player p2)
{ return p1.name.compareTo(p2.name) ;}
}
);

d)
Collections.sort(
Collections.sort(players, new Player(0, 0, new String()));

Option c) is correct.

##################################################

What would be the result of attempting to compile and run the following code?

import java.util.*;

public class SCJPSorts {

public static void main (String args[]) {

int first = 5; char second = '8';
byte third = 2; short fourth = 3;

Object[] araise = {first, second, third, fourth};

for (int i=0;i lt; araise.length; i++)
System.out.print(araise[i] + " ");
}
}

a) The code would not compile
b) The code would compile but not run
c) The code would print out 0 1 2 3
d) The code would print out 3 2 1 0
e) The code would print out 2 3 5 8
f) The code would print out 8 5 3 2
g) The code would print out 5 8 2 3
h) The code would print out 3 2 8 5


Option a) is correct.

This code looks good, but the loop invokes the size() method of the array. The number of elements in an array is determined by the length property, not the size() method. Collection classes such as a List or a Vector support a call to size(), but an array does not, so this code will fail at the compilation stage.

If the length property of the array was used, the values would be printed out in the same order in which they were added to the array, which would be 5 8 2 3

#############################################################

What would be the result of attempting to compile and run the following code?

import java.util.*;

public class SCJPSorts {

public static void main (String args[]) {

int first = 5; char second = '8';
byte third = 2; short fourth = 3;

Object[] araise = {first, second, third, fourth};

Arrays.sort(araise);

for (int i=0;i<araise.length; i++)
System.out.print(araise[i] + " ");
}
}



a) The code would not compile
b) The code would compile but not run
c) The code would print out 0 1 2 3
d) The code would print out 3 2 1 0
e) The code would print out 2 3 5 8
f) The code would print out 8 5 3 2
g) The code would print out 5 8 2 3
h) The code would print out 3 2 8 5

Option b) is correct. This code will compile, but it will not run.

When objects are sorted using the Collections.sort() or the Arrays.sort() method call, elements in the collection are sorted in their natural order. However, all of the elements of the array must be comparable to one another. In this case, the second element, a Character, is not sortable against the first element, an Integer, and the following ClassCastException occurs:

Exception in thread "main" java.lang.ClassCastException: java.lang.Character can
not be cast to java.lang.Integer
at java.lang.Integer.compareTo(Integer.java:35)
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.sort(Arrays.java:1079)
at SCJPSorts.main(SCJPSorts.java:14)



##########################################################

What would be the result of attempting to compile and run the following code?

import java.util.*;

public class SCJPSorts {

public static void main (String args[]) {

int first = 5; int second = 8;
int third = 2; int fourth = 3;

Object[] araise = {first, second, third, fourth};

Arrays.sort(araise);

for (int i=0;i@lt;araise.length; i++)
System.out.print(araise[i] + " ");
}
}

a) The code would not compile
b) The code would compile but not run
c) The code would print out 0 1 2 3
d) The code would print out 3 2 1 0
e) The code would print out 2 3 5 8
f) The code would print out 8 5 3 2
g) The code would print out 5 8 2 3
h) The code would print out 3 2 8 5


Option e) is correct.

When this code runs, the array is sorted using the call to the java.util.Arrays' sort method. This sorts the elements in the array in their natural order, which for Integer types would be from lowest to highest, producing an output of 2 3 5 8.

######################################################

Which of the following classes implement the Comparable interface?

a) String
b) Integer
c) Float
d) Character
e) java.util.Date
f) java.io.File
g) Object

Options a) b) c) d) e) and f) are correct.

The only class here that does not explicitly implement the Comparable interface is the java.lang.Object.

Remember though, just because classes implement the Comparable interface, doesn't mean those objects can necessarily be compated to oneanother. A Character and a File both implement the Comparable interface, but attempting to compare the two different types together would result in a ClassCastException.


Runtime vs. Compile Time Errors in Java: Mock SCJP 6 Certification Exam Questions

1. What is the result of attempting to compile and run the following public class?

public class ErrorTester{
   public static void main(string args[]) throws Throwable{ System.out.println("Hello World");}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but with no output
d) The class will compile and run with the expected output



####################################################

2. What is the result of attempting to compile and run the following public class?
public class ErrorTester{
static public void main(String args[]) throws Throwable {
System.out.println("Hello World");
throw new NoSuchMethodException();
}
}
a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run and print out Hello World
d) The class will compile and run and print out Hello World and throw an Exception



#########################################################

3. What is the result of attempting to compile and run the following public class?

public class ErrorTester{
public static void main(String args[]) throws Throwable {
throw new NoSuchMethodException();
System.out.println("Hello World");
}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run and print out Hello World
d) The class will compile and run and print out Hello World and throw an Exception



#########################################

4. What is the result of attempting to compile and run the following public class?


public class ErrorTester{
public void static main(String args[]) throws Throwable {
System.out.println("Hello World");
}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run and print out Hello World
d) The class will compile and run and print out Hello World and throw an Exception



####################################################



5. What is the result of attempting to compile and run the following class?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
int x;
for (int i = 0; i<10; i++) {
if (i<5) x = i;
else x=0;
System.out.print(x);
}
}
}



a) The class will not compile.
b) The class will compile but not run
d) The class will compile and run and print 0000056789
e) The class will compile and run and print 0000006789
f) The class will compile and run and print 00000678910




###############################################

6. What is the result of attempting to compile and run the following class?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
int x;
for (int i = 0; i<10; i++) {
if (i<5) x = i;
else i=10;
System.out.print(x);
}
}
}



a) The class will not compile.
b) The class will compile but not run
d) The class will compile and run and print 01234
e) The class will compile and run and print 12345
f) The class will compile and run and print 4


################################################################################


7. What is the result of attempting to compile and run the following class?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
int x;
for (int i = 0; i<10; i++) {
if (i<5) x = i;
else {i=10; x = 0;}
System.out.print(x);
}
}
}


a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run and print 123450
d) The class will compile and run and print 012340
e) The class will compile and run and print 5
f) The class will compile and run and print 0



########################################################

8. What is the result of attempting to compile and run the following class?

public class ErrorTester{
public static void main(String args[]) throws Throwable {
String input = (new java.util.Scanner( System.in )).nextLine();
double timesTwo = 2 x new Double(input);
System.out.println(input);
}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but print out nothing
d) The class will compile and run and throw an Exception
e) The class will compile and run and might throw a RuntimeException


###################################################################


9. What is the result of attempting to compile and run the following class?

public class ErrorTester{
public static void main(String args[]) throws Throwable {
String input = (new java.util.Scanner( System.in )).nextLine();
double timesTwo = 2 * new Double(input);
System.out.println(input);
}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but print out nothing
d) The class will compile and run and throw an Exception
e) The class will compile and run and might throw a RuntimeException



#####################################################################

10. What is the result of attempting to compile and run the following class with the input of 123?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
String input = (new java.util.Scanner( System.in )).nextLine();
double timesTwo = 2 * new Double(input);
System.out.println(input);
}
}


a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but print out nothing
d) The class will compile and run but print out 123
e) The class will compile and run but print out 246



##################################################################################


11. What is the result of attempting to compile and run the following class?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
int x = 10;
int y = 5;
int z = (long)x*y;
System.out.println(z);
}
}


a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but throw a casting Exception at runtime
d) The class will compile and run but print 50


#####################################################

12. What is the result of attempting to compile and run the following class?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
int x = 10;
char y = 5;
long z = x*y;
System.out.println(z);
}
}


a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but throw a casting Exception at runtime
d) The class will compile and run but print 50

13. What is the result of attempting to compile and run the following public class?

public class ErrorTester throws Throwable{
   public static void main(String args[]) { System.out.println("Hello World");}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but with no output
d) The class will compile and run with the expected output


#########################################
#########################################
***************************************************
#########################################
#########################################

1. What is the result of attempting to compile and run the following public class?

public class ErrorTester throws Throwable{
   public static void main(string args[]) { System.out.println("Hello World");}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but with no output
d) The class will compile and run with the expected output


Option a) is correct.

The main method spells the word String incorrectly, and as a result, the code simply will not compile. This class will not even make it to the running stage, as no compiled, ErrorTester.class file will be generated, and there would be no class file to run. If the main method spelled string as String, the code would compile and output Hello World to the console.


####################################################

2. What is the result of attempting to compile and run the following public class?
public class ErrorTester{
static public void main(String args[]) throws Throwable {
System.out.println("Hello World");
throw new NoSuchMethodException();
}
}
a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run and print out Hello World
d) The class will compile and run and print out Hello World and throw an Exception

In this case, option d) is correct. The code will indeed compile, as the syntax is solid. The main method is properly structured, so the class will indeed run. Notice that the words static and public are transposed? That's not typical, but it is legal, as the keywords that decorate the method, before defining the return type, need not go in any particular order.

The class will indeed run, and the text Hello World will indeed go to the console. But after the text is printed out, an Exception will be thrown, the program will terminate, and administrators will be going through the logs and trying to figure out why your application keeps printing out:

Hello World
Exception in thread "main" java.lang.NoSuchMethodException
at ErrorTester.main(ErrorTester.java:4)

#########################################################

3. What is the result of attempting to compile and run the following public class?

public class ErrorTester{
public static void main(String args[]) throws Throwable {
throw new NoSuchMethodException();
System.out.println("Hello World");
}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run and print out Hello World
d) The class will compile and run and print out Hello World and throw an Exception

Option a) is correct. This code will cause a compile error.

In this example, the compiler recognizes that the programmer codes an instruction after an exception is positively thrown. Since the exception is thrown, not code following the exception will be executed if there is no try-catch block in existence. As a result, the compiler coughs up, indicating:

C:\_jdk1.6\bin>javac ErrorTester.java
ErrorTester.java:4: unreachable statement
System.out.println("Hello World");
^
1 error


#########################################

4. What is the result of attempting to compile and run the following public class?


public class ErrorTester{
public void static main(String args[]) throws Throwable {
System.out.println("Hello World");
}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run and print out Hello World
d) The class will compile and run and print out Hello World and throw an Exception

Option a) is correct.

This code places a method decorator after the return type of the main method. Placing anything before the method name other than a return type is not allowed by the compiler, so this code would not make it past the compiler, and no Java class file would ever be generated.

Note that placing a decorator after the return type is not just invalid for the main method. This particular questions completely messes up the runnable main method, but making such a mistake for any method, not just the runnable main, would generate a compile error.

####################################################



5. What is the result of attempting to compile and run the following class?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
int x;
for (int i = 0; i<10; i++) {
if (i<5) x = i;
else x=0;
System.out.print(x);
}
}
}



a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run and print 0123400000
d) The class will compile and run and print 1234567890
e) The class will compile and run and print 012340000
f) The class will compile and run and print 123456789

In this case, option c) is correct.

There are not trick in this question, other than understanding application flow and Java syntax. Leaving the braces, {}, off the if and else block is nasty, and it is a very bad programming practice, but it is valid. When braces are missing after an if or else keyword, the first line after the if or else is considered to be the complete body of the code block, making this code completely valid.

When run, the output is: 0123400000


###############################################

6. What is the result of attempting to compile and run the following class?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
int x;
for (int i = 0; i<10; i++) {
if (i<5) x = i;
else i=10;
System.out.print(x);
}
}
}



a) The class will not compile.
b) The class will compile but not run
d) The class will compile and run and print 01234
e) The class will compile and run and print 12345
f) The class will compile and run and print 4

Option a) is correct.

In this case, the compiler does not know whether x ever gets initialized. All variables must be initialized before being used, and since the variable x is initialized in the if block, the compiler worries that the if block is never executed, the variable x will never be initialized, and subsequently, the System.out.println(x); statement will be printing out an uninitialized variable, which is not allowed.

################################################################################


7. What is the result of attempting to compile and run the following class?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
int x;
for (int i = 0; i<10; i++) {
if (i<5) x = i;
else {i=10; x = 0;}
System.out.print(x);
}
}
}


a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run and print 123450
d) The class will compile and run and print 012340
e) The class will compile and run and print 5
f) The class will compile and run and print 0

In this case, option d) is correct.

Although the missing brackets around the code in the if block is unconventional, it is valid, so long as there is only one statement that makes up the body of the block. Since the code is valid and compiles, this questions just gets down to following the execution of the method, which results in the value 012340 being printed out to the console.

########################################################

8. What is the result of attempting to compile and run the following class?

public class ErrorTester{
public static void main(String args[]) throws Throwable {
String input = (new java.util.Scanner( System.in )).nextLine();
double timesTwo = 2 x new Double(input);
System.out.println(input);
}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but print out nothing
d) The class will compile and run and throw an Exception
e) The class will compile and run and might throw a RuntimeException

In this case, option a) is correct.

The program clearly tries to multiply two number together, but the operator for multiplication is a star, *, not an x. As a result, this code will not compile, and not get past the compilation stage.

###################################################################


9. What is the result of attempting to compile and run the following class?

public class ErrorTester{
public static void main(String args[]) throws Throwable {
String input = (new java.util.Scanner( System.in )).nextLine();
double timesTwo = 2 * new Double(input);
System.out.println(input);
}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but print out nothing
d) The class will compile and run and throw an Exception
e) The class will compile and run and might throw a RuntimeException

Option e) is correct.

This program takes input from the user, and multiplies that input by two. However, if the input is not numeric, the creation of the Double, new Double(input), will fail, triggering the following runtime Exception message:

C:\_jdk1.6\bin>java ErrorTester
a
Exception in thread "main" java.lang.NumberFormatException: For input string: "a
"at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:12
24)at java.lang.Double.valueOf(Double.java:475)at java.lang.Double.(Double.java:567)at ErrorTester.main(ErrorTester.java:6)


#####################################################################

10. What is the result of attempting to compile and run the following class with the input of 123?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
String input = (new java.util.Scanner( System.in )).nextLine();
double timesTwo = 2 * new Double(input);
System.out.println(input);
}
}


a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but print out nothing
d) The class will compile and run but print out 123
e) The class will compile and run but print out 246

In this case, option d) is correct.

While is appears that the program wants to print out twice the value entered by the user, the fact is, the original input, with the variable name input, is printed to the console. As such, if the user entered 123 into the console, this program would print 123 back out to the console, making option d) correct.

##################################################################################


11. What is the result of attempting to compile and run the following class?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
int x = 10;
int y = 5;
int z = (long)x*y;
System.out.println(z);
}
}


a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but throw a casting Exception at runtime
d) The class will compile and run but print 50

Option a) is correct.

The compiler recgonizes that the return of x*y is an int, and it is being cast into a long, so the compiler does not allow this, generating the following error message:

C:\_jdk1.6\bin>javac ErrorTester.java
ErrorTester.java:6: possible loss of precision
found : long
required: int
int z = (long)x*y;
^
1 error



#####################################################

12. What is the result of attempting to compile and run the following class?


public class ErrorTester{
public static void main(String args[]) throws Throwable {
int x = 10;
char y = 5;
long z = x*y;
System.out.println(z);
}
}


a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but throw a casting Exception at runtime
d) The class will compile and run but print 50

Option d) is correct.

In this case, the code is completely valid, and the class will both compile and run, generating an output of 50.

A common misconception is that a char is purely a character type. In fact, the char can take on numeric values just as easily as it can take on character data. In this case, the char holds the value of 5, and when multiplied by 10, a value of 50 is returned and subsequently printed to the console.


#####################################

13. What is the result of attempting to compile and run the following public class?

public class ErrorTester throws Throwable{
   public static void main(String args[]) { System.out.println("Hello World");}
}

a) The class will not compile.
b) The class will compile but not run
c) The class will compile and run but with no output
d) The class will compile and run with the expected output


Option a) is correct.

The problem with this code is the fact that the throws clause is on the class, not the main method. Only methods can declare that they throw an exception, not a class. As a result, this method does not compile, and generates the following, very clear and precise, error message:

C:\_jdk1.6\bin>javac ErrorTester.java
ErrorTester.java:1: '{' expected
public class ErrorTester throws Throwable{
^
1 error


This is a pretty blatant coding error, but sometimes, when you really get deep into the SCJP questions, an obvious coding error can be difficult to spot, so be careful!

Wednesday, July 16, 2008

SCJP 6.0 Imports and Static Exam Objectives Enums as well

Given the following class named TestCode, in a package named com.mcnz.tests, which of the provided options do NOT successfully reference the final variable named CFRB? (i.e, which of the following will not compile?)

package com.mcnz.tests;
public class TestCode {
public final long CFRB = 1010;
}


a)
package com.mcnz;
public class DetestableCode extends com.mcnz.tests.TestCode {
static{
DetestableCode dc = new DetestableCode();
System.out.println(dc.CFRB);
}
}

b)
package com.mcnz;
import com.mcnz.tests.*;
public class DetestedCode {
static{
System.out.println(TestCode.CFRB);
}
}


c)
package com.mcnz.tests;
public class TestedCode {
public void radio() {
{System.out.println(TestCode.CFRB);}
}
}


d)
package com.mcnz.tests;
public class TesterCode {
static {System.out.println(TestCode.CFRB);}
}

Only option a) will compile, making b) c) and d) the correct answer. This means b) c) and d) will not compile.

Constants in Java are typically decorated with the final and static keywords together. However, if the keyword static is missing from a final variable, the final variable must be referenced through an instance. Only variables decorated with the static keyword can be accessed by only using the class name, such as CFRB. Options b) c) and d) all use static notation to reference the non-static, final variable, making them all fail in compilation, and thus making them the correct answers to this quiz question.


###########################################

Given the following class named TestCode, in a package named com.mcnz.tests, which of the provided options will successfully reference the final variable named CFRB?

package com.mcnz.tests;
public class TestCode {
public static final long CFRB = 1010;
}


a)

package com.mcnz;
import com.mcnz.tests.TestCode.*;
public class DetestedCode {
static{
System.out.println(CFRB);
}
}
b)
package com.mcnz;

public class DetestableCode extends com.mcnz.tests.TestCode {
static{
System.out.println(CFRB);
}
}

c)
package com.mcnz.tests;
import com.mcnz.tests.TestCode;
public class TestedCode {
public void radio() {
{System.out.println(CFRB);}
}
}


d)
package com.mcnz.tests;
import static com.mcnz.tests.TestCode.*;
public class TesterCode {
static {System.out.println(CFRB);}
}


Options b) and d) will successfully compile.

Option a) appears to be attempting to perform a static import, but the static keyword is missing after the import keyword, and as such, this option will not compile, with a compile error indicating that CFRB cannot be resolved.

Option b) will indeed compile. Referencing the static final variable without the name of the class preceeding the name CFRB, along with the lack of a static import statement for com.mcnz.tests.TestCode.*, would lead one to believe that the code might not compile. However, a subclass always inherits all of the properties of the parent class, be it static, non-static or even final variables. As such, the DetestableCode class, which extends TestCode, can indeed reference the constant variable CFRB directly.

Option c) will also generate a message indicating the "CFRB cannot be resolved." Simply importing the class that contains the static final property is not enough - to directly reference the property named CFRB, TestCode would either need to properly perform a static import of the TestCode class, or use the actual name TestCode when referencing the CFRB variable, such as TestCode.CFRB.

Option d) uses the correct syntax for performing a static import, and as such, the static final property named CFRB can be referenced directly, by name only, without the name of the class preceeding the name of the property.

######################################

Which of the following enum declarations would compile?


a)
public enum JavaCerts {
SCJA, SCJP, SCWCD, SCBCD, SCMAD, SCDJWS, SCEA
}
b)
public enum JavaCerts {
SCJA, SCJP, SCWCD, SCBCD, SCMAD, SCDJWS, SCEA;
}
c)

public enum JavaCerts {
{SCJA, SCJP, SCWCD, SCBCD, SCMAD, SCDJWS, SCEA}
}

d)

public enum JavaCerts {
{SCJA, SCJP, SCWCD, SCBCD, SCMAD, SCDJWS, SCEA;}
}

Options a) and b) are correct.

Options c) and d) incorrectly places parenthesis around the elements of the enum, causing the compiler to choke up a message such as: "Unexpected end of file. Initializer expected before this token."

The elements of the enum must be declared, and the enum initialized, directly inside the body of the enum, and not within and sub-blocks. Options a) and b) both follow this pattern, making them both correct.


#############################################################################

If possible, hich of the following lines of code placed on //line 4 would allow the code to compile successfully?


package net.mcnz;
public class Goals {
public static void main(String args[]){
//line 4
System.out.println(myCert);
}
}

interface Certs{
enum SunCert {
SCJA, SCJP, SCWCD, SCBCD, SCMAD, SCDJWS, SCEA
}
}


a) SunCert myCert = new Certs.SunCert(SCJP);
b) Certs.SunCert myCert = new Certs.SunCert(SCJP);
c) Certs.SunCert myCert = Certs.SunCert.SCJP;
d) An enum cannot be defined within an interface, so nothing on line 4 would allow this code to compile.

Option c) is correct.

When referencing an enum, the new keyword simply does not come into play. As a result, a) and b) are incorrect.

An enum can indeed be defined within an interface, although it certainly seems strange. Nevertheless, it can be done, so d) is incorrect.

Option c) is correct. The enum is within an interface, so the syntax would be the name of the interface followed by the name of the enum when the type is declared, Certs.SunCert. When the enum is initialized, the syntax would be the name of the interface, the name of the enum and then the property of the enum, all referenced using dot notation, Certs.SunCert.SCJP.



#######################################################

Which line of code, placed within the brackets of the viewEar method call in the main method, would cause the literal String true to be printed to the console?

package net.mcnz;
public class Inner {
public static void main(String args[]){
Inner.viewEar(/* Code Goes here */);
}
public static void viewEar(Ear e) {
System.out.println(e.isWaxy());
}
}

interface Ear { public abstract boolean isWaxy(); }


a) implements Ear {public boolean isWaxy(){return true;}}
b) implements Ear() {public boolean isWaxy(){return true;}}
c) new Ear {public boolean isWaxy(){return true;}}
d) new Ear() {public boolean isWaxy(){return true;}}
e) new class Ear {public boolean isWaxy(){return true;}}
f) new class Ear() {public boolean isWaxy(){return true;}}

Option d) is correct.

To implement an inner class that provides an implementation for an interface, the new keyword preceeds the name of the interface, with the name of the interface having open and closed brackets following it, as though we were calling a constructor for a class, new Ear(). From there, parenthesis surround the normal, concrete implementation of any of the abstract methods defined in the interface.

new Ear() {public boolean isWaxy(){return true;}}

When this inner class implementation of the Ear interface is provided, the program returns the literal String true to the console.


Java is an object oriented programming language. So, when we work in Java, we work with objects.

In the line of code:

System.out.println("Hello World");

we see a special object called the System.

Now, objects are made up of all sorts of fabulous things, including properties, methods, and sometimes, other objects. In the case of the System, it contains a special object that can print out to the console, and quite appropriately, this object that can print to the console is named out.

Furthermore, the object named out has a method called print() and another method called println, to which we can pass text and have that text printed out to the console.

So, System is an object, out is an object contained by the system, and print or println are methods that can be called on the System's object named out.

Now, when we refer to objects, and then any objects they may have, and then any methods or properties that we are allowed to call, we use a dot (.) notation. So, when we call the System object, ask for the object named out, and then call the print method on the out object, the code looks like this:

System.out.print("Hello World");