Download Question 1

Document related concepts
no text concepts found
Transcript
1
Question 1)
Which of the following are legal
statements?
1)
2)
3)
4)
float f=1/3;
int i=1/3;
float f=1.01;
double d=999d;
Question 2)
Which of the following are Java
keywords?
1)
2)
3)
4)
NULL
new
instanceOf
wend
Question 3)
Which of the following are valid
statements?
1)
2)
3)
4)
System.out.println(1+1);
int i=2+'2';
String s="on"+'one';
byte b=255;
Question 4)
Which of the following
statements are true?
1) The garbage collection
algorithm in Java is vendor
implemented
2) The size of primitives is
platform dependent
3) The default type for a
numerical literal with decimal
component is a float.
4) You can modify the value in
an Instance of the Integer class
with the setValue method
Question 5)
Which of the following are true
statements?
1) I/O in Java can only be
performed using the Listener
classes
2) The RandomAccessFile class
allows you to move directly to
any point a file.
3) The creation of a named
instance of the File class creates
a matching file in the underlying
operating system only when the
close method is called.
4) The characteristics of an
instance of the
File class such as
the directory separator, depend on
the current underlying operating
system
Question 10)
Question 6).
1) A byte can represent
between -128 to 127
2) A byte can represent
between -127 to 128
3) A byte can represent
between -256 to 256
4) A char can represent
between -2x2 pow 16 2 x2 pow
16 - 1
Which of the following statements
are true?
1) The instanceof operator can be
used to determine if a reference is an
instance of a class, but not an
interface.
2) The instanceof operator can be
used to determine if a reference is an
instance of a particular primitive
wrapper class
3) The instanceof operator will only
determine if a reference is an
instance of a class immediately
above in the hierarchy but no further
up the inheritance chain
4) The instanceof operator can be
used to determine if one reference is
of the same class as another
reference thus
Question 7)
Which of the following statements
are true?
1) An interface can only contain
method and not variables
2) Interfaces cannot have
constructors
3) A class may extend only one other
class and implement only one
interface
4) Interfaces are the Java approach
to addressing its lack of multiple
inheritance, but require
implementing classes to create the
functionality of the Interfaces.
Which of the following
statements are true?
Question 11)
What will happen when you
attempt to compile and run the
following code
class Base{
public void Base(){
System.out.println("
Base");
}
}
public class In extends Base{
public static void
main(String argv[]){
In i=new In();
}
}
1) Compile time error Base is a
keyword
2) Compilation and no output
at runtime
3) Output of Base
4) Runtime error Base has no
valid constructor
Question 12)
Question 8)
You have a public class called
myclass with the main method
defined as follows
Which of the following are valid
statements
public static void main(String
parm[]){
1) public class MyCalc extends Math
2) Math.max(s);
3) Math.round(9.99,1);
4)Math.mod(4,10);
System.out.println(parm[0]);
}
Question 9)
Which of the following are methods
of the Runnable interface
If you attempt to compile the
class and run the program as
follows
java myclass hello
What will happen?
1)
2)
3)
4)
run
start
yield
stop
1) Compile time error, main is
not correctly defined
2) Run time error, main is not
2
correctly defined
3) Compilation and output of
java
4) Compilation and output of
hello
Question 13)
Which of the following
statements are true?
1) If a class has any abstract
methods it must be declared
abstract itself.
2) All methods in an abstract
class must be declared as
abstract
3) When applied to a class, the
final modifier means it cannot be
sub-classed
4) transient and volatile are Java
modifiers
Question 14)
Which of the following are valid
methods?
1) public static native void
amethod(){}
2) public static void amethod(){}
3) private protected void
amethod(){}
4) static native void amethod();
public static void main(String
argv[]){
Severn s = new Severn();
}
void Severn(){
System.out.println("Severn");
}
}
1) Compilation and output of the
string "Severn" at runtime
2) Compile time error
3) Compilation and no output at
runtime
4) Compilation and output of the
string "Base"
1) A component may have only
one event listener attached at
a time
2) An event listener may be
removed from a component
3) The ActionListener interface
has no corresponding Adapter
class
4) The processing of an event
listener requires a try/catch
block
Question 20)
Which of the following are Java
keywords?
Question 17)
Which of the following statements
are true?
1) static methods do not have access
to the implicit variable called this
2) A static method may be called
without creating an instance of its
class
3) A static method may not be
overriden to be non-static
4) A static method may not be
overloaded
1)
2)
3)
4)
sizeof
main
transient
volatile
Question 21)
Which of the following
statements are true?
Which of the following will compile
without error?
1) The default constructor has
a return type of void
2) The default constructor
takes a parameter of void
3) The default constructor
takes no parameters
4) The default constructor is
not created if the class has any
constructors of its own.
1)
Question 22)
char c='1';
System.out.println(c>>1);
Which of the following
statements are true?
2)
1) All of the variables in an
interface are implicitly static
2) All of the variables in an
interface are implicitly final
3) All of the methods in an
interface are implicitly abstract
4) A method in an interface
can access class level variables
Question 18)
Question 15)
Which of the following
statements are true?
1) Constructors cannot have a
visibility modifier
2) Constructors can be marked
public and protected, but not
private
3) Constructors can only have a
primitive return type
4) Constructors are not inherited
Question 16)
What will happen when you
attempt to compile and run the
following class?
class Base{
Base(int i){
System.out.println("Base");
}
}
class Severn extends Base{
Integer i=Integer("1");
System.out.println(i>>1);
3)
int i=1;
System.out.println(i<<<1);
4)
int i=1;
System.out.println(i<<1);
Question 19)
Which of the following are true?
Question 23)
Which of the following
statements are true?
1) The String class is
implemented as a char array,
elements are addressed using
the stringname[] convention
2) The + operator is
overloaded for concatenation
3
for the String class
3) Strings are a primitive type in
Java and the StringBuffer is used
as the matching wrapper type
4) The size of a string can be
retrieved using the length
property
public static void main(String
argv[]){
boolean b1 = true;
if((b1 ==true) || place(true)){
System.out.println("Hello
Crowle");
}
}
Question 24)
Which of the following
statements are true?
1) A method in an interface must
not have a body
2) A class may extend one other
class plus at most one interface
3) A class may extends at most
one other class plus implement
many interfaces
4) An class accesses an interface
via the keyword uses
Question 25)
Which of the following
statements are true?
1) The following statement will
produce a result of 1.
System.out.println( -1 >>>2);
2) Performing an unsigned left
shift (<<<) on a negative
number will always produce a
negative number result
3) The following statement will
produce a result of zero,
System.out.println(1 >>1);
4) All the Java integral types are
signed numbers
Question 26)
Which of the following
statements are true?
1) The elements in a Java array
can only be of primitive types,
not objects
2) Arrays elements are initialized
to default values wherever they
are created using the keword
new
3) An array may be dynamically
resized using the setSize method
4) You can find out the size of an
array using the size method
Question 27)
Given the following class
public class Ombersley{
public static boolean
place(boolean location){
if(location==true){
System.out.println("Borcetshire");
}
System.out.println("Powick");
return true;
}
}
What will happen when you attempt
to compile and run it?
1) Compile time error
2) Output of "Hello Crowle"
3) Output of Borcetshire and Powick
followed by "Hello Crowle"
4) No output
Question 28)
You are given a class hierarchy with
an instance of the class Dog. The
class Dog is a child of mammal and
the class Mammal is a child of the
class Vertebrate. The class
Vertebrate has a method called move
which prints out the string "move".
The class mammal overrides this
method and prints out the string
"walks". The class Dog overrides this
method and prints out the string
"walks on paws". Given an instance
of the class Dog,. how can you
access the ancestor method move in
Vertebrate so it prints out the string
"move";
1)
2)
3)
4)
d.super().super().move();
d.parent().parent().move();
d.move();
none of the above;
Question 29)
Which of the following most closely
describes the process of overriding?
1) A class with the same name
replaces the functionality of a class
defined earlier in the hierarchy
2) A method with the same name
completely replaces the functionality
of a method earlier in the hierarchy
3) A method with the same name but
different parameters gives
multiple uses for the same
method name
4) A class is prevented from
accessing methods in its
immediate ancestor
Question 30)
Which of the following
statements are true?
1) The % is used to calculate a
percentage thus: 10 % 20=50
2) The / operator is used to
divide one value by another
3) The # symbol may not be
used as the first character of a
variable
4) The $ symbol may not be
used as the first character of a
variable
Question 31)
Which of the following
statements are true?
1) The default layout manager
for an Applet is FlowLayout
2) The default layout manager
for a Frame is FlowLayout
3) A layout manager must be
assigned to an Applet before
the setSize method is called
4) The FlowLayout manager
attempts to honor the
preferred size of any
components
Question 32)
Which of the following
statements are true about a
variable created with the static
modifier?
1) Once assigned the value of
a static variable may not be
altered
2) A static variable created in a
method will keep the same
value between calls
3) Only one instance of a static
variable will exist for any
amount of class instances
4) The static modifier can only
be applied to a primitive value
Question 33)
Which of the following
statements are true?
4
1) Java uses a system called UTF
for I/O to support international
character sets
2) The RandomAccessFile is the
most suitable class for
supporting international
character sets
3) An instance of
FileInputStream may not be
chained to an instance of
FileOutputStream
4) File I/O activities requires use
of Exception handling
Question 34)
What will happen when you
attempt to compile and run the
following code?
import java.io.*;
class ExBase{
abstract public void
martley(){
}
}
public class MyEx extends
ExBase{
public static void main(String
argv[]){
DataInputStream fi = new
DataInputStream(System.in);
try{
fi.readChar();
}catch(IOException e){
System.exit(0);
}
finally
{System.out.println("Doing
finally");}
}
}
1) Compile time error
2) It will run, wait for a key press
and then exit
3) It will run, wait for a
keypress, print "Doing finally"
then exit
4) At run and immediately exit
Question 35)
What will happen when you
attempt to compile and run the
following code
public class Borley extends
Thread{
public static void main(String
argv[]){
Borley b = new Borley();
b.start();
}
public void
run(){
System.out.println("Running");
}
makes extensive use of the the
GridBagConstraints class.
}
Question 39)
1) Compilation and run but no output
2) Compilation and run with the
output "Running"
3) Compile time error with complaint
of no Thread target
4) Compile time error with complaint
of no access to Thread package
Given the following class
definition
Question 36)
Assuming any exception handling has
been set up, which of the following
will create an instance of the
RandomAccessFile class
1) RandomAccessFile raf=new
RandomAccessFile("myfile.txt","rw");
2) RandomAccessFile raf=new
RandomAccessFile( new
DataInputStream());
3) RandomAccessFile raf=new
RandomAccessFile("myfile.txt");
4) RandomAccessFile raf=new
RandomAccessFile( new
File("myfile.txt"));
Question 37)
Given the following class definition
public class Upton{
public static void main(String
argv[]){
}
public void amethod(int i){}
//Here
}
Which of the following would be legal
to place after the comment //Here ?
1) public int amethod(int z){}
2) public int amethod(int i,int
j){return 99;}
3) protected void amethod(long l){ }
4) private void anothermethod(){}
Question 38)
Which of the following statements
are true?
1) Code must be written if the
programmer wants a frame to close
on selecting the system close menu
2) The default layout for a Frame is
the BorderLayout Manager
3) The layout manager for a Frame
cannot be changed once it has been
assigned
4) The GridBagLayout manager
public class Droitwich{
class one{
private class two{
public void
main(){
System.out.println("two");
}
}
}
}
Which of the following
statements are true
1) The code will not compile
because the classes are nested
to more than one level
2) The code will not compile
because class two is marked as
private
3) The code will compile and
output the string two at
runtime
4) The code will compile
without error
Question 40)
Given the following code
class Base{
static int oak=99;
}
public class Doverdale extends
Base{
public static void main(String
argv[]){
Doverdale d = new
Doverdale();
d.amethod();
}
public void amethod(){
//Here
}
}
Which of the following if placed
after the comment //Here, will
compile and modify the value
of the variable oak?
1)
2)
3)
4)
super.oak=1;
oak=33;
Base.oak=22;
oak=50.1;
5
Question 41)
You are creating an application
that has a form with a text entry
field used to enter a persons age.
Which of the following is
appropriate for capturing this
information.
1) Use the Text field of a
TextField and parse the result
using Integer
2) Use the getInteger method of
the TextField
3) Use the getText method of a
TextBox and parse the result
using the getInt method of
Integer class
4) Use the getText method of a
TextField and use the parseInt
method of the Integer class
Question 42)
Given the following declaration
Integer i=new Integer(99);
How can you now set the value
of i to 10?
1)
2)
3)
4)
i=10;
i.setValue(10);
i.parseInt(10);
none of the above
Question 43)
Which of the following
statements are true
1) constructors cannot be
overloaded
2) constructors cannot be
overridden
3) a constructor can return a
primitive or an object reference
4) constructor code executes
from the current class up the
hierarchy to the ancestor class
Question 44)
Given a reference called
to a class which extends Thread,
which of the following will cause it to
give up cycles to allow another
thread to execute.
1) t.yield();
2) Thread.yield();
3) yield(100); //Or some other
suitable amount in milliseconds
4) yield(t);
Question 45)
What will happen when you attempt
to compile and run the following
code?
public class Sandys{
private int court;
public static void main(String
argv[]){
Sandys s = new Sandys(99);
System.out.println(s.court);
}
Sandys(int ballcount){
court=ballcount;
}
}
System.out.println("Base");
}
}
public class Checket extends
Base{
public static void main(String
argv[]){
Checket c = new
Checket();
super();
}
Checket(){
System.out.println("Checket");
}
}
1)
2)
3)
4)
Compile time error
Checket followed by Base
Base followed by Checket
runtime error
Question 48)
Which of the following
statements are true?
1) Compile time error, the variable
court is defined as private
2) Compile time error, s is not
initialized when the System.out
method is called
3) Compilation and execution with no
output
4) Compilation and run with an
output of 99
1) Static methods cannot be
overriden to be non static
2) Static methods cannot be
declared as private
3) Private methods cannot be
overloaded
4) An overloaded method
cannot throw exceptions not
checked in the base class
Question 46)
Question 49)
Which of the following statements
are true?
Which of the following
statements are true?
1) A method cannot be overloaded to
be less public in a child class
2) To be overridden a method only
needs the same name and parameter
types
3) To be overridden a method must
have the same name, parameter and
return types
4) An overridden method must have
the same name, parameter names
and parameter types
1) The automatic garbage
collection of the JVM prevents
programs from ever running
out of memory
2) A program can suggest that
garbage collection be
performed but not force it
3) Garbage collection is
platform independent
4) An object becomes eligible
for garbage collection when all
references denoting it are set
to null.
Question 47)
What will happen when you attempt
to compile and run the following
code?
t
class Base{
Base(){
Question 50)
Given the following code
public class Sytch{
int x=2000;
6
public static void main(String
argv[]){
System.out.println("Ms
"+argv[1]+"Please pay $"+x);
}
}
What will happen if you attempt
to compile and run this code with
the command line
java Sytch Jones Diggle
1) Compilation and output of Ms
Diggle Please pay $2000
2) Compile time error
3) Compilation and output of Ms
Jones Please pay $2000
4) Compilation but runtime error
Question 51)
What will happen when you
attempt to compile and run the
following code
class Base{
protected int i = 99;
}
public class Ab{
private int i=1;
public static void main(String
argv[]){
Ab a = new Ab();
a.hallow();
}
abstract void hallow(){
System.out.println("Claines
"+i);
}
}
1) Compile time error
2) Compilation and output of
Claines 99
3) Compilation and output of
Claines 1
4) Compilation and not output at
runtime
Question 52)
You have been asked to create a
scheduling system for a hotel
and catering organsiation.
You have been given the
following information and asked
to create a set of classes to
represent it.
On the catering side of the
organsiation they have
Head Chefs
Chefs
Apprentice Chefs
The system needs to store an
employeeid, salary and the holiday
entitlement
}
1)
2)
3)
4)
Compile time error
Output of 2
Output of 1
Output of 0
How would you best represent this
information in Javae been given the
following information and asked to
create a set of classes to represent
it.
Question 55)
How would you best represent this
information in Java
public class Agg{
static public long i=10;
public static void main(String
argv[]){
switch(i){
default:
1) Create classes for Head Chef,
Chef, Apprentice Chef and store the
other values in fields
2) Create an employee class and
derive sub classes for Head Chef,
Chef, Apprentice Chef and store the
other values in fields.
3) Create and employee class with
fields for Job title and fields for the
other values.
4) Create classes for all of the items
mentioned and create a container
class to represent employees
Question 53)
You need to read in the lines of a
large text file containing tens of
megabytes of data. Which of the
following would be most suitable for
reading in such a file
1) new FileInputStream("file.name")
2) new InputStreamReader(new
FileInputStream("file.name"))
3) new BufferedReader(new
InputStreamReader(new
FileInputStream("file.name")));
4) new RandomAccessFile raf=new
RandomAccessFile("myfile.txt","+rw"
);
Question 54)
What will happen when you attempt
to compile and run the following
code?
public class Inc{
public static void main(String
argv[]){
Inc inc = new Inc();
int i =0;
inc.fermin(i);
i = i++;
System.out.println(i);
}
void fermin(int i){
i++;
}
What will happen when you
attempt to compile and run the
following code?
System.out.println("no value
given");
case 1:
System.out.println("one");
case 10:
System.out.println("ten");
case 5:
System.out.println("five");
}
}
}
1) Compile time error
2) Output of "ten" followed by
"five"
3) Output of "ten"
4) Compilation and run time
error because of location of
default
Question 56)
Given the following class
public class ZeroPrint{
public static void main(String
argv[]){
int i =0;
//Here
}
}
Which of the following lines if
placed after the comment
//Here will print out 0.
1)
2)
3)
4)
System.out.println(i++);
System.out.println(i+'0');
System.out.println(i);
System.out.println(i--);
Question 57)
7
Given the following code
class Base {}
class Agg extends Base{
public String getFields(){
String name = "Agg";
return name;
}
}
public class Avf{
public static void main(String
argv[]){
Base a = new Agg();
//Here
}
}
What code placed after the
comment //Here will result in
calling the getFields method
resulting in the output of the
string "Agg"?
1)
System.out.println(a.getFields())
;
2) System.out.println(a.name);
3) System.out.println((Base)
a.getFields());
4) System.out.println( ((Agg)
a).getFields());
Question 58)
What will happen when you
attempt to compile and run the
following code.
public class Pvf{
static boolean Paddy;
public static void main(String
argv[]){
System.out.println(Paddy);
}
}
1) Compile time error
2) compilation and output of
false
3) compilation and output of true
4) compilation and output of null
Question 59)
Which of the following
statements are true?
1) The x,y coordinates of an
instance of MouseEvent can be
obtained using the getX() and
getY() methods
2) The x,y
coordinates of an
instance of MouseEvent can be
obtained using the X and Y integer
fields
3) The time of a MouseEvent can be
extracted using the getTime()
method
4) The time of a MouseEvent can be
extracted using the getWhen method
The fact that option 3 does not
compile may be a surprise. The
problem is because the default
type for a number with a
decimal component is a double
and not a float. The additional
trailing d in the option with 999
doesn't help, but it doesn't
harm.
Question 60)
Answer to Question 2)
Given the following code
Objective 4.3)
import java.io.*;
2) new
public class Ppvg{
public static void main(String
argv[]){
Ppvg p = new Ppvg();
p.fliton();
}
public int fliton(){
try{
FileInputStream din =
new FileInputStream("Ppvg.java");
din.read();
}catch(IOException ioe){
System.out.println("flytwic
k");
return 99;
}finally{
System.out.println("fliton")
;
}
return -1;
}
}
Assuming the file Ppvg.java is
available to be read which of the
following statements are true if you
try to compile and run the program?
The option NULL (note the
upper case letter) is definitely
not a keyword. There is some
discussion as to i. There is
some discussion as to if null is
a keyword but for the purpose
of the exam you should
probably assume it is a
keyword.
The option instanceOf is a bit
of a misleading option that
would probably not occur on
the exam. The real keyword is
instanceof (note that the of has
no capital letter O). I had the
incorrect version in an earlier
version of this tutorial as it
looks more likely to my eyes.
The instanceof keyword looks
like a method, but it is actually
an operator.
The option wend is probably
valid in some other language
to indicate the end of a while
loop, but Java has no such
keyword.
Answer to Question 3)
1) The program will run and output
only "flytwick"
2) The program will run and output
only "fliton"
3) The program will run and output
both "fliton" and "flytwick"
4) An error will occur at compile time
because the method fliton attempts
to return two values
Answers
Answer to Question 1)
Objective 4.5)
1) float f=1/3;
2) int i=1/3;
4) double d=999d;
Objective 4.5)
1) System.out.println(1+1);
2) int i=2+'2';
Option 3 is not valid because
single quotes are used to
indicate a character constant
and not a string. Several
people have emailed me to say
that option 3 will compile.
When they eventually compiled
the exact code they have
agreed, it will not compile. Let
me re-state that
String s="on"+'one';
Will NOT compile.
8
Option 4 will not compile because
255 is out of the range of a byte
Answer to Question 4)
Objective 7.1)
1) The garbage collection
algorithm in Java is vendor
implemented
Threading and garbage collection
are two of the few areas that are
platform dependent. This is one
of the
reasons why Java is not suitable
for realtime programming. It is
not a good idea use it to control
your
plane or nuclear power station.
Once an instance of the Integer
class has a value it cannot be
changed.
Answer to Question 5)
Objective 10.1)
(Not on the official sub objectives
but this topic does come up on
the exam)
2) The RandomAccessFile class
allows you to move directly to
any point a file.
4) The characteristics of an
instance of the File class such as
the directory separator, depend
on the current underlying
operating system
The File class can be considered
to represent information about a
file rather than a real file object.
You can create a file in the
underlying operating system by
passing an instance of a file to a
stream such as
FileOutputStream. The file will be
created when you call the close
method of the stream.
Answer to Question 6)
Objective 5.1)
2) The instanceof operator can
be used to determine if a
reference is an instance of a
particular primitive wrapper class
Java1.1 added
the isInstance
method to the class Class to allow
you to dynamically determine a class
type. The exam does not test you on
isInstance.
Answer to Question 7)
Objective 4.1)
2) Interfaces cannot have
constructors
If you try to create a constructor for
an Interface the compiler will give
you an error message something like
The char type is the only
unsigned type in Java and thus
cannot represent a negative
number.
For more information on this
topic go to
Answer to Question 11)
Objective 1.2)
2) Compilation and no output
at runtime
"interface can't have constructors".
4) Interfaces are the Java approach
to addressing the single inheritance
model, but require implementing
classes to create the functionality of
the Interfaces.
An interface may contain variables as
well as methods. However any
variables are final by default and
must be assigned values on creation.
A class can only extend one other
class (single inheritance) but may
implement as many interfaces as you
like (or is sensible).
Answer to Question 8)
Objective 9.1)
None of these are valid statements.
The Math class is final and cannot be
extended. The max method takes
two parameters, round only takes
one parameter and there is no mod
parameter. You may get questions in
the exam that have no apparently
correct answer. If you are absolutely
sure this is the case, do not check
any of the options.
Because the method in Base
called Base has a return type it
is not a constructor and there
for does not get called on
creation of an instance of its
child class In
For more information on this
topic go to
Answer to Question 12)
Objective 4.2)
4) Compilation and output of
hello
This type of question is
particularly calculated to catch
out C/C++ programmers who
might expect parameter zero
to be the name of the
compiler.
For more information on this
topic go to
Answer to Question 13)
Objective 1.2)
Answer to Question 9)
Objective 7.1)
1) The Runnable interface has only
one method run that needs to be
created in any class that implements
it. The start method is used to
actually call and start the run
method executing.
Answer to Question 10)
The instanceof operator can only
be used to make a static
comparison with a class type.
1) A byte can represent
between -128 to 127
Objective 4.5)
1) If a class has any abstract
methods it must be declared
abstract itself.
3) The final modifier means
that a class cannot be subclassed
4) transient and volatile are
Java modifiers
An abstract class may have
non abstract methods. Any
class that descends from an
abstract class must implement
the abstract methods of the
9
base class or declare them as
abstract itself.
For more information on this
topic go to
Answer to Question 14)
Objective 1.2)
2) public static void amethod(){}
4) static native void amethod();
Option 1 is not valid because it
has braces and the native
modifier means that the method
can have no body. This is
because the body must be
implemented in some other
language (often C/C++). Option
3 is not valid because private
and protected contradict
themselves.
For more information on this
topic go to
1) static
methods do not
have access to the implicit variable
called this
2) A static method may be called
without creating an instance of its
class
3) a static may not be overriden to
be non-static
The implicit variable this refers to the
current instance of a class and thus
and by its nature a static method
cannot have access to it.
For more information on this topic go
to
Answer to Question 18)
Objective 5.1)
1)
char c='1';
System.out.println(c>>1);
4)
Answer to Question 15)
Objective 6.2)
int i=1;
System.out.println(i<<1);
4) Constructors are not inherited
Constructors can be marked
public, private or protected.
Constructors do not have a
return type.
For more information on this
topic go to
Answer to Question 16)
Be aware that Integer (not the upper
case I) is a wrapper class and thus
cannot be treated like a primitive.
The fact that option 1 will compile
may be a surprise, but although the
char type is normally used to store
character types, it is actually an
unsigned integer type. The reason
option 3 does not compile is that
Java has a >>> operator but not a
<<< operator. ;>> operator but not
a <<< operator.
Objective 1.3)
For more information on this topic go
to
2) Compile time error
Answer to Question 19)
An error occurs when the class
Severn attempts to call the zero
parameter constructor in the
class Base Because the Base
class has an integer constructor
Java does not provide the
"behind the scenes" zero
parameter constructor.
For more information on this
topic go to
Answer to Question 17)
Objective 1.2)
Objective 4.6)
2) An event listener may be removed
from a component
3) The ActionListener interface has
no corresponding Adapter class
method, the idea of the
Adapter classes is to eliminate
the need to create blank
methods.
For more information on this
topic go to
Answer to Question 20)
Objective 4.3)
3) transient
4) volatile
Option 1, sizeof is designed to
catch out the C/C++
programmers. Java does not
have a sizeof keyword as the
size of primitives should be
consistent on all Java
implementations. Although a
program needs a main method
with the standard signature to
start up it is not a keyword.
The real keywords are less
commonly used and therefore
might not be so familiar to you.
For more information on this
topic go to
Answer to Question 21)
Objective 1.3)
3) The default constructor
takes no parameters
4) The default constructor is
not created if the class has any
constructors of its own.
Option 1 is fairly obviously
wrong as constructors never
have a return type. Option 2 is
very dubious as well as Java
does not offer void as a type
for a method or constructor.
For more information on this
topic go to
Answer to Question 22)
Objective 4.1)
A component may have multiple
event listeners attached. Thus a field
may need to respond to both the
mouse and the keyboard, requiring
multiple event handlers. The
ActionListener has not matching
Adapter class because it has only one
1) All of the variables in an
interface are implicitly static
2) All of the variables in an
interface are implicitly final
3) All of the methods in an
interface are implictly abstract
10
All the variables in an interface
are implicitly static and final. Any
methods in an interface have no
body, so may not access any
type of variable
primitive is
actually an
unsigned integer type.
Answer to Question 23)
Answer to Question 26)
Objective 4.5)
Objective 4.4)
2) The + operator is overloaded
for concatenation for the String
class
2) Arrays elements are initialized to
default values wherever they are
created using the keyword new.
In Java Strings are implemented
as a class within the Java.lang
package with the special
distinction that the + operator is
overloaded. If you thought that
the String class is implemented
as a char array, you may have a
head full of C/++ that needs
emptying. There is not "wrapper
class" for String as wrappers are
only for primitive types.
If you are surprised that option 4
is not a correct answer it is
because length is a method for
the String class, but a property
for and array and it is easy to get
the two confused.
Answer to Question 24)
Objective 6.1)
1) A method in an interface must
not have a body
3) A class may extends one other
class plus many interfaces
A class accesses an interface
using the implements keyword
(not uses)
Answer to Question 25)
Objective 5.1)
3) The following statement will
produce a result of zero,
System.out.println(1 >>1);
Although you might not know the
exact result of the operation -1
>>> 2 a knowledge of the way
the bits will be shifted will tell
you that the result is not plus 1.
(The result is more like
1073741823 ) There is no such
Java operator as the unsigned
left shift. Although it is normally
used for storing characters rather
than numbers the char Java
And for information on the size of
primitives see
of the difference between
overloading and overriding in
that an overriden method is
like something overriden in the
road, it is squashed, flat no
longer used and replaced by
something else. An overloaded
method has been given extra
work to do (it is loaded up with
work), but it is still being used
in its original format. This is
just my little mind trick and
doesn't match to anything that
Java is doing.
Answer to Question 30)
You can find the size of an array
using the length field. The method
length is used to return the number
of characters in a String. An array
can contain elements of any type but
they must all be of the same type.
The size of an array is fixed at
creation. If you want to change its
size you can of course create a new
array and assign the old one to it. A
more flexible approach can be to use
a collection class such as Vector.
Answer to Question 27)
Objective 5.3)
2) Output of "Hello Crowle"
This code is an example of a short
circuited operator. Because the first
operand of the || (or) operator
returns true Java sees no reason to
evaluate the second. Whatever the
value of the second the overall result
will always be true. Thus the method
called place is never called.
Answer to Question 28)
Objective 6.2)
4) none of the above;
You may access methods of a direct
parent class through the use of super
but classes further up the hierarchy
are not visible.
Answer to Question 29)
Objective 6.1)
2) A method with the same name
completly replaces the functionality
of a method earlier in the hierarchy
Option 3 is more like a description of
overloading. I like to remind myself
Objective 1.2)
2) The / operator is used to
divide one value by another
3) The # symbol may not be
used as the first character of a
variable
The % is the modulo operator
and returns the remainder
after a division. Thus 10 %
3=1
The $ symbol may be used as
the first character of a
variable, but I would suggest
that it is generally not a good
idea. The # symbol cannot be
used anywhere in the name of
a variable. Knowing if a
variable can start with the # or
$ characters may seem like
arbitrary and non essential
knowlege but questions like
this do come up on the exam.
Answer to Question 31)
Objective 8.1)
1) The default layout manager
for an Applet is FlowLayout
4) The FlowLayout manager
attempts to honor the
preferred size of any
components
The default layout manager
fror an Application is
BorderLayout. An applet will
use the default of FlowLayout if
one is not specifically applied.
Answer to Question 32)
Objective 1.2)
11
3) Only one instance of a static
variable will exist for any amount
of class instances
4) The code will compile
without error
Option 1) is more a description
of a final variable. Option 2 is
designed to fool Visual Basic
programmers like me as this is
how you can use the keyword
static in VB. The modifier static
can be applied to a class (only an
innner class) , method or
variable.
This is perfectly
legitimate if
useless sample of creating an
instnace of a Thread and causing its
run method to execute via a call to
the start method. The Thread class is
part of the core java.lang package
and does not need any explicit
import statement. The reference to a
Thread target is an attempt to
mislead with a reference to the
method of using the Runnable
interface instead of simply inheriting
from the Thread super class.
Answer to Question 33)
Answer to Question 36)
Answer to Question 40)
Objective 11.1)
Objective 11.1)
Objective 1.2)
1) Java uses a system called UTF
for I/O to support international
character sets
3) An instance of
FileInputStream may not be
chained to an instance of
FileOutputStream
4) File I/O activities requires use
of Exception handling
1) RandomAccessFile raf=new
RandomAccessFile("myfile.txt","rw");
1) super.oak=1;
2) oak=33;
3) Base.oak=22;
Internally Java uses Unicode
which are 16 bit characters. For
I/O Java uses UTF which may be
more thatn 16 bits per chamore
thatn 16 bits per character.
Generally InputStreams can only
be chained to other
InputStreams and
OutputStreams can only be
chained to other OutputStreams.
The piped streams are an
exception to this.
Objective 6.2)
Answer to Question 34)
Objective 1.2)
1) Compile time error
It wil produce an error like
"Abstract and native method
can't have a body. This is typical
of the more misleading question
where you might think it is
asking you about the
circumstances under which the
finally clause runs, but actually it
is about something else.
Answer to Question 35)
Objective 7.1)
2) Compilation and run with the
output "Running"
The RandomAccessFile is an anomaly
in the Java I/O architecture. It
descends directly from Object and is
not part of the Streams architecture.
Answer to Question 37)
2) public int amethod(int i, int j)
{return 99;}
3) protected void amethod (long l){}
4) private void anothermethod(){}
Option 1 will not compile on two
counts. One is the obvious one that it
claims to return an integer. The
other is that it is effectivly an
attempt to redefine a method within
the same class. The change of name
of the parameter from i to z has no
effect and a method cannot be
overriden within the same class.
Answer to Question 38)
Objective 8.1)
1) Code must be written to cause a
frame to close on selecting the
system close menu
2) The default layout for a Frame is
the BorderLayout Manager
4) The GridBagLayout manager
makes extensive use of the the
GridBagConstraints class.
There are no restrictions on the
level of nesting for
inner/nested classes. Inner
classes may be marked
private. The main method is
not declared as public static
void main, and assuming that
the commandline was java
Droitwich it would not be
invoked anyway.
Because the variable oak is
declared as static only one
copy of it will exist. Thus it can
be changed either through the
name of its class or through
the name of any instance of
that class. Because it is created
as an integer it canot be
assigned a fractional
component without a cast.
Answer to Question 41)
Obje Question 41)
Objective 4.6)
4) Use the getText method of a
Textfield and use the parseInt
method of the Integer class
Here is an example of how you
might do this
Integer.parseInt(txtInputValue.
getText());
I'm not sure that a question on
this actually will come up in the
exam but it is a very useful
thing to know in the real world.
Answer to Question 42)
You can change the layout manager
for a Frame or any other container
whenever you like.
Objective 4.6)
Answer to Question 39)
The wrapper classes are
immutable. Once the value has
been set it cannot be changed.
A common use of the wrapper
Objective 1.2)
4) none of the above
12
classes is to take advantage of
their static methods such as
Integer.parseInt(String s) that
will returns an integer if the the
value has been set it cannot be
changed. A common use of the
wrapper classes is to take
advantage of their static
methods such as
Integer.parseInt(String s) that
will returns an integer if the
String contains one.
Answer to Question 43)
Objective 6.2)
3) To be overriden a method must
have the same name, parameter and
return types
Option 1 is a sneaky one in that it
should read overriden not
overloaded. An overriden method
must also have the same return
type. Parameter names are purely a
programmer convenience and are not
a factor in either overloading and
overriding. Parameter order is a
factor however.
Objective 6.2)
Answer to Question 47)
2) constructors cannot be
overriden
Overloading constructors is a key
technique to allow multiple ways
of initialising classes. By
definition, constructors have
have no return values so option
3 makes no sense. Option 4 is
the inverse of what happens as
constructor code will execute
starting from the oldest ancestor
class downwards. You can test
this by writing a class that
inherits from a base class and
getting the constructor to print
out a message. When you create
the child class you will see the
order of constructor calling.
Answer to Question 44)
Objective 7.1)
yield is a static method and
causes whatever thread is
currently executing to yield its
cycles.
1) t.yield();
2) Thread.yield()
(Thanks Roseanne )
Answer to Question 45)
Objective 6.2)
4) Compilation and run with an
output of 99
The fact that the variable court is
declared as private does not stop
the constructor from being able
to initialise it.
Answer to Question 46)
Objective 6.2)
garbage collection when it is
assigned to null
If a program keeps creating
new references without any
being discarded it may run out
of memory. Unlike most
aspects of Java garbage
collection is platform
dependent.
Answer to Question 50)
Objective 1.2)
2) Compile time error
The main method is static and
cannot access the non static
variable x
1) Compile time error
With the sun JDK it will produce the
following error
Answer to Question 51)
Objective 1.2)
1) Compile time error
"Only constructors can invoke
constructors".
If you took out the call to super that
causes this error the program would
compile and at runtime it would
output Base and then Checket as
constructors are called from the
oldest ancestor class downwards.
Answer to Question 48)
Objective 1.2)
1) Static methods cannot be
overriden to be non static
The JDK1.1 compiler will issue an
error message "static methods
cannot be overriden" if you atempt to
do thiuot; if you atempt to do this.
There is no logic or atempt to do
this. There is no logic or reason why
private methods should not be
overloaded or that static methods
should not be declared private.
Option 4 is a jumbled up version of
the limitations of exceptions for
overriden methods
Answer to Question 49)
Objective 3.1)
2) A program can suggest that
garbage collection be performed but
not force it
4) A reference becomes eligable for
When compiled with JDK 1.1
the following error is produced.
Abstract and native methods
can't have a body: void
hallow() abstract void hallow()
Answer to Question 52)
Objective 6.1)
3) Create and employee class
with fields for Job title and
fields for the other values.
These questions can appear
tricky as the whole business of
designing class structures is
more art than science. It is
asking you to decide if an item
of data is best represented by
the "Is a" or "Has a"
relationship. Thus in this case
any of the job titles mentioned
will always refer to something
that "Is a" employee. However
the employee "has a" job title
that might change.
One of the important points is
to ask yourself when creating a
class "Could this change into
another class at some point in
the future". Thus in this
example an apprentice chef
would hope one day to turn
into a chef and if she is very
good will one day be head
chef. Few other mock exams
seem to have this type of
13
questions but they di come up in
the real exam.
Answer to
Question 56)
Objective 5.1)
Answer to Question 53)
Objective 11.1)
3) new BufferedReader(new
InputStreamReader(new
FileInputStream("file.name")));
The key to this question is that it
asks about tens of megabytes of
data, implying that performance
is an issue. A Buffered Reader
will optimise the performance of
accessing a file. Although the
objectives do not specifically
mention it questions on I/O do
come up on the exam.
Answer to Question 54)
Objective 5.4)
4) Output of 0
The method fermin only receives
a copy of the variable i and any
modifications to it are not
reflected in the version in the
calling method. The post
increment operator ++ effectivly
modifes the value of i after the
initial value has been assiged to
the left hand side of the equals
operator. This can be a very
tricky conept to understand
Answer to Question 55)
Objective 2.1)
1) Compile time error
This might be considered a
"gocha" or deliberate attempt to
mislead you because i has been
given the data type of long and
the parameter must be of long
and the parameter must be
either a byte, char, short or int.
If you attempt to compile this
code with JDK 1.2 you will get an
error that says something like
"Incompatible type for switch,
Explicit cast needed to convert
long to int". Answering with
option 2 would have been
reasonable because if the
parameter had been an integer
type the lack of break
statements would have caused
this output. If you gave either of
the answers you should probably
revise the subject.
1) System.out.println(i++);
3) System.out.println(i);
4) System.out.println(i==);
The options for this question might
look suspiciously easy if you are not
aware of the effects of the postincrement operators. The ++ and ==
operations for examples 1 and 4 only
come into effect after the output
operations, ie after whatever else is
done to them on that line of code.
Option 2 should be fairly obvious as
you should know that the single
quote characters indicate a char
value, ie storing the character rather
than the numberical value for 0.
If you chose option 4, referring
to the mythical getTime
method you have made a
reasonable guess based on the
normal conventions of Java.
However the conventions do
not always hold true. If you
chose option 3 perhaps you are
not as aware of the
conventions as you should be.
Answer to Question 60)
Objective 2.3
2) The program will run and
output only "fliton"
This question tests your
knowledge of the principle that
the finally clause will almost
always run.
Answer to Question 57)
Objective 6.2)
4) System.out.println( ((Agg)
a).getFields());
The Base type reference to the
instance of the class Agg needs to be
cast from Base to Agg to get access
to its methods.The method invoked
depends on the object itself, not on
the declared type. So, a.getField()
tries to invoke a getField method in
Base which does not exist. But the
call to ((Agg)a).getField() will invoke
the getField() in the Agg class. You
will be unlucky to get a question as
complex as this on the exam. If you
think option 1 is valid, have a go at
compiling the code.
Answer to Question 58)
Objective 4.4)
Breakdown of Questions by
Topic
30)Objective
48)Objective
39)Objective
40)Objective
50)Objective
51)Objective
17)Objective
32)Objective
14)Objective
11)Objective
13)Objective
34)Objective
1.2)
1.2)
1.2)
1.2)
1.2)
1.2)
1.2)
1.2)
1.2)
1.2)
1.2)
1.2)
55)Objective 2.2)
60)Objective 3.4)
16)Objective 1.3)
21)Objective 1.3)
49)Objective 3.1)
26)Objective 4.4)
2) compilation and output of false
A variable defined at class level will
always be given a default value and
the default value for the primitive
type boolean is false
Answer to Question 59)
Objective 4.6)
1) The x,y coordinates of an instance
of MouseEvent can be obtained using
the getX() and getY() methods
4) The time of a MouseEvent can be
extracted using the getWhen method
1)Objective 4.5)
3)Objective 4.5)
10)Objective 4.5)
22)Objective 4.1)
7) Objective 4.1)
12)Objective 4.2)
2) Objective 4.3)
23)Objective 4.5)
42)Objective 4.6)
41)Objective 4.6)
19)Objective 4.6)
20)Objective 4.3)
48)Objective 4.4)
59)Objective 4.6)
14
5.
6) Objective 5.1)
25)Objective 5.1)
18)Objective 5.1)
27)Objective 5.3)
54)Objective 5.4)
56)Objective 5.1)
24)Objective 6.1)
29)Objective 6.1)
52)Objective 6.1)
45)Objective
46)Objective
47)Objective
43)Objective
37)Objective
28)Objective
15)Objective
6.2)
6.2)
6.2)
6.2)
6.2)
6.2)
6.2)
4)Objective 7.1)
9)Objective 7.1)
35)Objective 7.1)
44)Objective 7.1)
31)Objective 8.1)
38)Objective 8.1)
8)Objective 9.1)
5)Objective 10.1)
33)Objective 11.1)
36)Objective 11.1)
53)Objective 11.1)
End of document
- Sample test 1
1. Which of the following
are correct definitions of
method main of a class.
Select all correct
answeres.
A. public static int
main(char
args[]);
B. public static void
main(String
args[]);
C. public static void
MAIN(String
args[]);
D. public static void
main(String
args);
E. public static void
main(char
args[]);
2. What all gets printed
when the following code
is compiled and run ?
Select all correct
answers.
3.
4.
public class xyz {
public
static void main(String
args[]) {
6.
for(int i = 0; i < 2;
i++) {
7.
for(int j = 2; j>= 0;
j•) {
8.
if(i == j) break;
9.
System.out.println("i=" + i +
" j="+j);
10.
}
11.
}
12.
}
13. }
14.
A. i=0 j=0
B. i=0 j=1
C. i=0 j=2
D. i=1 j=0
E. i=1 j=1
F. i=1 j=2
G. i=2 j=0
H. i=2 j=1
I. i=2 j=2
15. What gets printed when the
following code is compiled
and run with the following
arguments java test 2
Select the one correct
answer.
16.
17. public class test {
18.
public static void
main(String args[]) {
19.
Integer intObj =
Integer.valueOf(args[args.le
ngth - 1]);
20.
int i =
intObj.intValue();
21.
22.
if(args.length > 1)
23.
System.out.println(i);
24.
if(args.length > 0)
25.
System.out.println(i
- 1);
26.
else
27.
System.out.println(i
- 2);
28.
}
29. }
30.
31.
A. test
B. test -1
C. 0
D. 1
E. 2
32. In Java what expression can
be used to represent number
of elements in an array
named arr ?
33. How would the number 5 be
represented in hex using
upto four characters.
34. Which of the following
is a Java keyword.
Select all correct
answers.
A. extern
B. synchronized
C. volatile
D. friend
E. friendly
F. transient
G. this
H. then
35. Is the following
statement true or false.
The constructor of a
class must not have a
return type.
A. true
B. false
36. What is the number of
bytes used by Java
primitive long. Select
the one correct
answer.
A. The number of
bytes is
compiler
dependent.
B. 2
C. 4
D. 8
E. 64
37. What is the result of
invoking the method
substring(2, 4) on the
string "example"?
Include the answer in
quotes as the result is
of type String.
38. Which of the following
is correct ? Select all
correct answers.
A. The native
keyword
indicates that
the method is
implemented in
another
language like
C/C++.
B. The only
statements
that can appear
before an
import
statement in a
Java file are
comments.
C. The method
definitions
inside
interfaces are
public and
abstract. They
cannot be
private or
protected.
15
39.
40.
41.
42.
D. A class
constructor may
have public or
protected keyord
before them,
nothing else.
What is the result of
evaluating the expression
14 ^ 23. Select the one
correct answer.
A. 25
B. 37
C. 6
D. 31
E. 17
F. 9
G. 24
Which of the following
are true. Select all
correct answers.
A. && operator is
used for shortcircuited logical
AND.
B. ~ operator is the
bit-wise XOR
operator.
C. | operator is used
to perform
bitwise OR and
also shortcircuited logical
OR.
D. The unsigned
right shift
operator in Java
is >>.
Name the access
modifier which when
used with a method,
makes it available to all
the classes in the same
package and to all the
subclasses of the class.
Which of the following is
true. Select all correct
answers.
A. A class that is
abstract may not
be instantiated.
B. The final keyword
indicates that the
body of a method
is to be found
elsewhere. The
code is written in
non-Java
language,
typicaly in
C/C++.
C. A static variable
indicates there is
only one copy of
that variable.
D. A method defined
as private
indicates that it
is accessible to
all
other classes in the
same package.
43. What all gets printed when
the following program is
compiled and run. Select all
correct answers.
44.
45. public class test {
46.
public static void
main(String args[]) {
47.
int i, j=1;
48.
i = (j>1)?2:1;
49.
switch(i) {
50.
case 0:
System.out.println(0);
break;
51.
case 1:
System.out.println(1);
52.
case 2:
System.out.println(2);
break;
53.
case 3:
System.out.println(3);
break;
54.
}
55.
}
56. }
57.
58.
A. 0
B. 1
C. 2
D. 3
59. What all gets printed when
the following program is
compiled and run. Select all
correct answers.
60.
61. public class test {
62.
public static void
main(String args[]) {
63.
int i=0, j=2;
64.
do {
65.
i=++i;
66.
j•;
67.
} while(j>0);
68.
System.out.println(i);
69.
}
70. }
71.
72.
A. 0
B. 1
C. 2
D. The program does
not compile because
of statement
"i=++i;"
73. What all gets printed when
the following gets compiled
and run. Select all correct
answers.
74.
75. public class test {
76.
public static void
main(String args[]) {
77.
int i=1, j=1;
78.
79.
80.
81.
82.
83.
84.
try {
i++;
j•;
if(i/j > 1)
i++;
}
catch(ArithemticExcepti
on e) {
85.
86.
87.
System.out.println(0);
}
catch(ArrayIndexOutOf
BoundsException e) {
88.
89.
90.
System.out.println(1);
}
catch(Exception
e) {
91.
92.
93.
94.
95.
96.
System.out.println(2);
}
finally {
System.out.println(3);
}
System.out.println(4);
97.
}
98. }
99.
100.
A. 0
B. 1
C. 2
D. 3
E. 4
101.
What all gets
printed when the
following gets compiled
and run. Select all
correct answer.
102.
103. public class test {
104.
public static void
main(String args[]) {
105.
int i=1, j=1;
106.
try {
107.
i++;
108.
j•;
109.
if(i == j)
110.
i++;
111.
}
112.
catch(ArithmeticExcepti
on e) {
113.
System.out.println(0);
114.
}
115.
catch(ArrayIndexOutOf
BoundsException e) {
116.
System.out.println(1);
117.
}
118.
catch(Exception
e) {
16
119.
System.out.println(2);
120.
}
121.
finally {
122.
System.out.println(3);
123.
}
124.
System.out.println(4);
125.
}
126. }
127.
128.
A. 0
B. 1
C. 2
D. 3
E. 4
129.
What all gets
printed when the
following gets compiled
and run. Select all
correct answer.
130.
131. public class test {
132.
public static void
main(String args[]) {
133.
String s1 = "abc";
134.
String s2 = "abc";
135.
if(s1 == s2)
136.
System.out.println(1);
137.
else
138.
System.out.println(2);
139.
if(s1.equals(s2))
140.
System.out.println(3);
141.
else
142.
System.out.println(4);
143.
}
144. }
145.
146.
A. 1
B. 2
C. 3
D. 4
147.
What all gets
printed when the
following gets compiled
and run. Select all
correct answer.
148.
149. public class test {
150.
public static void
main(String args[]) {
151.
String s1 = "abc";
152.
String s2 = new
String("abc");
153.
154.
if(s1 == s2)
155.
System.out.println(1);
156.
else
157.
System.out.println(2);
158.
if(s1.equals(s2))
159.
System.out.println(3);
160.
else
161.
System.out.println(4);
162.
}
163. }
164.
165.
A. 1
B. 2
C. 3
D. 4
166.
The default layout
manager for a Frame is ...
A. FlowLayout
B. BorderLayout
C. GridLayout
D. GridBagLayout
E. CardLayout
167.
Which of the
following are valid adapter
classes in Java. Select all
correct answers.
A. ComponentAdapter
B. ActionAdapter
C. AdjustmentAdapter
D. ItemAdapter
E. FocusAdapter
168.
Which of the
following are legal array
declarations. Select all
correct answers.
A. int i[5][];
B. int i[][];
C. int []i[];
D. int i[5][5];
E. int[][] a;
169.
What is the range of
values that can be specified
for an int. Select the one
correct answer.
A. The range of values
is compiler
dependent.
B. -231 to 231 - 1
C. -231-1 to 231
D. -215 to 215 - 1
E. -215-1 to 215
170.
How can you ensure
that the memory allocated by
an object is freed. Select the
one correct answer.
A. By invoking the free
method on the
object.
B. By calling
system.gc() method.
C. By setting all
references to the
object to new values
(say null).
D. Garbage collection
cannot be forced. The
programmer cannot
force the compiler to
free the
memory used
by an object.
171.
What gets
printed when the
following code is
compiled. Select the
one correct answer.
172.
173. public class test {
174.
public static void
main(String args[]) {
175.
int i = 1;
176.
do {
177.
i•;
178.
} while (i > 2);
179.
System.out.println(i);
180.
}
181. }
182.
183.
A. 0
B. 1
C. 2
D. -1
184.
Which of these
is a legal definition of a
method named m
assuming it throws
IOException, and
returns void. Also
assume that the
method does not take
any arguments. Select
all correct answers.
A. void m()
throws
IOException{}
B. void m() throw
IOException{}
C. void m(void)
throws
IOException{}
D. m() throws
IOException{}
E. void m()
throws
IOException
F. void m() {}
throws
IOException
185.
Which of the
following are legal
identifier names in
Java. Select all correct
answers.
A. %abcd
B. $abcd
C. 1abcd
D. package
E. _a_long_name
186.
At what stage
in the following method
does the string "abc"
becomes available for
garbage collection.
17
Select the one correct
answer.
187.
188. void method X() {
189.
String r = new
String("abc");
190.
String s = "abc";
191.
r = r+1; //1
192.
r = null; //2
193.
s = s + r; //3
194. } //4
195.
196.
A. Before statement
labelled 1
B. Before statement
labelled 2
C. Before statement
labelled 3
D. Before statement
labelled 4
E. Never.
197.
String s = new
String("xyz");
Assuming the above
declaration, which of the
following statements
would compile. Select all
correct answers.
A. s = 2 * s;
B. int i = s[0];
C. s = s + s;
D. s = s >> 2;
E. None of the
above.
198.
Which of the
following statements
related to Garbage
Collection are correct.
Select all correct
answers.
A. It is posible for a
program to free
memory at a
given time.
B. Garbage
Collection feature
of Java ensures
that the program
never runs out of
memory.
C. It is possible for
a program to
make an object
available for
Garbage
Collection.
D. The finalize
method of an
object is invoked
before garbage
collection is
performed on the
object.
199.
If a base class
has a method defined as
void method() { }
Which of the following
are
legal
prototypes in a derived class
of this class. Select all
correct answers.
A. void method() { }
B. int method() { return
0;}
C. void method(int i) {
}
D. private void
method() { }
200.
In which all cases
does an exception gets
generated. Select all correct
answers.
int i = 0, j = 1;
A. if((i == 0) || (j/i ==
1))
B. if((i == 0) | (j/i ==
1))
C. if((i != 0) && (j/i ==
1))
D. if((i != 0) & (j/i ==
1))
201.
Which method
defined in the EventObject
class returns the Object that
generated an event. The
method should be given in
the format - return_type
method_name();
202.
Which of the
following object receives
ActionEvent. Select all the
correct answers.
A. List
B. Button
C. Choice
D. CheckBox
E. TextField
F. MenuItem
203.
Name the class that
may be used to create
submenus in pull-down
menus.
204.
Which of the
following statements are
true. Select all correct
answers.
A. The wait method
defined in the Thread
class, can be used to
convert a thread
from Running state
to Waiting state.
B. The wait(), notify(),
notifyAll() must be
executed in
sybchronized code.
C. The notify() method
can be used to signal
and move waiting
threads to ready-torun state.
D. The Thread class is
an abstract class.
205.
In which class
is the wait() method
defined. Select the one
correct answer.
A. Applet
B. Runnable
C. Thread
D. Object
206.
Which keyword
when applied on a
method indicates that
only one thread should
execute the method at
a time. Select the one
correct answer.
A. transient
B. volatile
C. synchronized
D. native
E. static
F. final
207.
What is the
name of the Collection
interface used to
represent elements in a
sequence (in a
particular order).
Select the one correct
answer.
A. Collection
B. Set
C. List
D. Map
208.
Which of these
classes implement the
Collection interface
SortedMap. Select all
correct answers.
A. HashMap
B. HashTable
C. TreeMap
D. HashSet
E. TreeSet
F. Vector
209.
Which is the
only layout manager
which always honours
the size of a
component. Select the
one correct answers.
A. FlowLayout
B. GridLayout
C. BorderLayout
D. CardLayout
E. GridBagLayout
210.
Which of the
following are true
about interfaces. Select
all correct answers.
A. Methods
declared in
interfaces are
implicitly
private.
B. Variables
declared in
interfaces are
implicitly
18
public, static, and
final.
C. An interface can
extend any
number of
interfaces.
D. The keyword
implements
indicate that an
interface inherits
from another.
211.
Assume that
class A extends class B,
which extends class C.
Also all the three classes
implement the method
test(). How can a method
in class A invoke the
test() method defined in
class C. Select the one
correct answers.
A. test();
B. super.test();
C. super.super.test(
);
D. ::test();
E. C.test();
F. It is not possible
to invoke test()
method defined
in C from a
method in A.
212.
What is the
return type of method
round(double d) defined
in Math class.
213.
What gets
written on the screen
when the following
program is compiled and
run. Select the one right
answer.
214.
215. public class test {
216.
public static void
main(String args[]) {
217.
int i;
218.
float f = 2.3f;
219.
double d = 2.7;
220.
i = ((int)Math.ceil(f))
* ((int)Math.round(d));
221.
222.
System.out.println(i);
223.
}
224. }
225.
A. 4
B. 5
C. 6
D. 6.1
E. 9
226.
Is the following
statement true or false.
As the toString method is
defined in the Object
class, System.out.println
can be
used to
print any object.
A. true
B. false
227.
Which of these
classes defined in java.io and
used for file-handling are
abstract. Select all correct
answers.
A. InputStream
B. PrintStream
C. Reader
D. FileInputStream
E. FileWriter
228.
Which of these are
valid Event Listener
interfaces. Select all correct
answer.
A. MouseMotionListener
B. WindowListener
C. DialogListener
D. PaintListener
229.
Name the collection
interface used to represent
collections that maintain
unique elements.
230.
What is the result of
compiling and running the
following program.
231.
232. public class test {
233.
public static void
main(String args[]) {
234.
String str1="abc";
235.
String str2="def";
236.
String
str3=str1.concat(str2);
237.
238.
str1.concat(str2);
239.
System.out.println(str1);
240.
}
241. }
242.
A. abc
B. def
C. abcabc
D. abcdef
E. defabc
F. abcdefdef
243.
Select the one
correct answer. The number
of characters in an object of
a class String is given by
A. The member variable
called size
B. The member variable
called length
C. The method size()
returns the number
of characters.
D. The method length()
returns the number
of characters.
244.
Select the one
correct answer. Which
method defined in Integer
class can be used to convert
an Integer object to
primitive int type.
A. valueOf
B. intValue
C. getInt
D. getInteger
245.
Name the
return type of method
hashCode() defined in
Object class, which is
used to get the unique
hash value of an
Object.
246.
Which of the
following are correct.
Select all correct
answers.
A. An import
statement, if
defined, must
be the first
statement of
the file.
B. private
members are
accessible to all
classes in the
same package.
C. An abstract
class can be
declared as
final.
D. Local variables
cannot be
declared as
static.
247.
Name the
keyword which makes
a variable belong to a
class, rather than being
defined for each
instance of the class.
Select the one correct
answer.
A. static
B. final
C. abstract
D. native
E. volatile
F. transient
248.
Which of these
are core interfaces in
the collection
framework. Select all
correct answers.
A. Tree
B. Stack
C. Queue
D. Array
E. LinkedList
F. Map
249.
Which abstract
class is the superclass
of all menu-related
classes.
250.
Which of these
statements are true.
19
Select all correct
answers.
A. For each try
block there must
be at least one
catch block
defined.
B. A try block may
be followed by
any number of
finally blocks.
C. A try block must
be followed by at
least one finally
or catch block.
D. If both catch and
finally blocks are
defined, catch
block must
precede the
finally block.
Answers to Sample Test 1
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
b
b, c, f
d
arr.length
Any of these is correct 0x5, 0x05, 0X05, 0X5
b, c, f, g
a
d
"am"
a, c. b is not correct. A
package statement may
appear before an import
statement.
a
a
protected
a, c
b, c
c
a, d, e
d, e
a, c
b, c
b
a, e
b, c, e
b
d
a
a
b, e
d
c
c, d
a, c
b, d
Object getSource();
a, b, e, f
Menu
b, c
d
c
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
c
c
a
b, c
f
long
e
a
a, c
a, b
Set
a
d
b
int
d
a
f
MenuComponent
c, d
Q 1. What is the output of the
following
StringBuffer sb1 = new
StringBuffer("Amit");
StringBuffer sb2= new
StringBuffer("Amit");
String ss1 = "Amit";
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss1));
System.out.println("Poddar".substrin
g(3));
Ans:
a) false
false
false
dar
b) false
true
false
Poddar
c) Compiler Error
d) true
true
false
dar
Correct Answer is a)
***** Look carefully at code and
answer the following questions ( Q2
to Q8)
1
import java.applet.Applet;
2 import java.awt.*;
3 import java.awt.event.*;
4
public class hello4 extends
Applet {
5
public void init(){
6
add(new myButton("BBB"));
7
}
8
public void paint(Graphics
screen) {
9 }
10
class myButton extends
Button{
11
myButton(String
label){
12
super(label);
13
}
14
public String
paramString(){
15
return
super.paramString();
16
}
17
}
18 public static void
main(String[] args){
19
Frame myFrame = new
Frame(
20
"Copyright Amit");
21
myFrame.setSize(300,100);
22
Applet myApplet = new
hello4();
23
Button b = new
Button("My Button");
24
myApplet.add(b);
25
b.setLabel(b.getLabel()+"New"
);
26 // myButton b1 =(new
hello4()).new
myButton("PARAMBUTTON");
27
System.out.println(b1.paramSt
ring());
28
myFrame.add(myApplet);
29
myFrame.setVisible(true);
30
myFrame.addWindowListener(
new WindowAdapter(){
31
public void
windowClosing(WindowEvent
e){
32
System.exit(0);}});
33 }
34 } //End hello4 class.
Q2. If you run the above
program via appletviewer (
defining a HTML file), You see
on screen.
a) Two buttons
b) One button with label as
"BBB"
c) One button with label as "My
ButtonNew"
d) One button with label as
"My Button"
Correct answer is b)
Q3. In the above code if line
26 is uncommented and
program runs as standalone
application
20
a) Compile Error
b) Run time error
c) It will print the the label as
PARAMBUTTON for button b1
Correct answer is c)
Q4 In the code if you compile as
"javac hello4.java" following files
will be generated.
a) hello4.class,
myButton.class,hello41.class
b)hello4.class,
hello4$myButton.class,hello4$1.c
lass
c)hello4.clas,hello4$myButton.cl
ass
Correct answer is b)
Q5. If above program is run as a
standalone application. How
many buttons will be displayed
a) Two buttons
b) One button with label as
"BBB"
c) One button with label as "My
ButtonNew"
d) One button with label as "My
Button"
Q8.If line no 26 is replaced with
Button b1 = new
Button("PARAMBUTTON").(Hint
:paramString() method in
java.awt.Button is a protected
method.(Assume line 26 is
uncommented)
a) Code will not compile.
b) Code will compile but will give a
run time error.
c) Code will compile and no run time
error.
Correct answer is a) Because
protected variables and methods can
not be accssed in another package
directly. They can only be accessed if
the class is subclassed and instance
of subclass is used.
Q9. What is the output of following if
the return value is "the value 0 if the
argument string is equal to this
string; a value less than 0 if this
string is lexicographically less than
the string argument; and a value
greater than 0 if this string is
lexicographically greater than the
string argument" (Assuming written
inside main)
correct answer is C)
Q6. If from line no 14 keyword
"public" is removed, what will
happen.( Hint :paramString()
method in java.awt.Button is a
protected method. (Assume line
26 is uncommented)
a) Code will not compile.
b) Code will compile but will give
a run time error.
c) Code will compile and no run
time error.
Correct answer is a). As you can
not override a method with
weaker access privileges
Q7. If from line no 14 keyword
"public" is replaced with
"protected", what will
happen.(Hint :paramString()
method in java.awt.Button is a
protected method.(Assume line
26 is uncommented)
a) Code will not compile.
b) Code will compile but will give
a run time error.
c) Code will compile and no run
time error.
Correct answer is c) . As you can
access a protected variable in the
same package.
String s5 = "AMIT";
String s6 = "amit";
System.out.println(s5.compareTo(s6)
);
System.out.println(s6.compareTo(s5)
);
System.out.println(s6.compareTo(s6)
);
Ans
a> -32
32
0
b> 32
32
0
c> 32
-32
0
d> 0
0
0
Correct Answer is a)
Q 10) What is the output (Assuming
written inside main)
String s1 = new String("amit");
String s2 = s1.replace('m','i');
s1.concat("Poddar");
System.out.println(s1);
System.out.println((s1+s2).charAt(5
));
a) Compile error
b) amitPoddar
o
c) amitPoddar
i
d) amit
i
Correct answer is d)As String is
imutable.so s1 is always
"amit". and s2 is "aiit".
Q 11) What is the output
(Assuming written inside
main)
String s1 = new
String("amit");
System.out.println(s1.replace('
m','r'));
System.out.println(s1);
String s3="arit";
String s4="arit";
String s2 =
s1.replace('m','r');
System.out.println(s2==s3);
System.out.println(s3==s4);
a) arit
amit
false
true
b) arit
arit
false
true
c) amit
amit
false
true
d) arit
amit
true
true
Correct answer is a) s3==s4
is true because java points
both s3 and s4 to same
memory location in string pool
Q12) Which one does not
extend java.lang.Number
1)Integer
2)Boolean
3)Character
4)Long
5)Short
Correct answer is 2) and 3)
Q13) Which one does not have
a valueOf(String) method
1)Integer
2)Boolean
3)Character
4)Long
5)Short
21
Correct answer is 3)
Q.14) What is the output of
following (Assuming written
inside main)
String s1 = "Amit";
String s2 = "Amit";
String s3 = new
String("abcd");
String s4 = new
String("abcd");
System.out.println(s1.equals(s2)
);
System.out.println((s1==s2));
System.out.println(s3.equals(s4)
);
System.out.println((s3==s4));
a) true
true
true
false
b) true
true
true
true
c) true
false
true
false
Correct answer is a)
Q15. Which checkbox will be
selected in the following code (
Assume with main and added to
a Frame)
Frame myFrame = new
Frame("Test");
CheckboxGroup cbg = new
CheckboxGroup();
Checkbox cb1 = new
Checkbox("First",true,cbg);
Checkbox cb2 = new
Checkbox("Scond",true,cbg);
Checkbox cb3 = new
Checkbox("THird",false,cbg);
cbg.setSelectedCheckbox(cb3);
myFrame.add(cb1);
myFrame.add(cb2);
myFrame.add(cb3);
a)
cb1
b)
cb2,cb1
c)
cb1,cb2,cb3
d)
cb3
Correct Answer is d) As in a
CheckboxGroup only one can be
selected
Q16) Which checkbox will be
selected in the following code (
Assume with main and added to
a Frame)
Frame
myFrame = new
Frame("Test");
CheckboxGroup cbg = new
CheckboxGroup();
Checkbox cb1 = new
Checkbox("First",true,cbg);
Checkbox cb2 = new
Checkbox("Scond",true,cbg);
Checkbox cb3 = new
Checkbox("THird",true,cbg);
myFrame.add(cb1);
myFrame.add(cb2);
myFrame.add(cb3);
a)
cb1
b)
cb2,cb1
c)
cb1,cb2,cb3
d)
cb3
c) No error and line 6 will
print 1000
d) No error and line 6 will
print 4
Correct Answer is d) As in a
CheckboxGroup only one can be
selected
Q21) What is default layout
manager for panels and
applets?
a) Flowlayout
b) Gridlayout
c) BorderLayout
Q17) What will be the output of line
5
1 Choice c1 = new Choice();
2 c1.add("First");
3 c1.addItem("Second");
4 c1.add("Third");
5
System.out.println(c1.getItemCount(
));
a) 1
b) 2
c) 3
d) None of the above
Correct Answer is c)
Q18) What will be the order of four
items added
Choice c1 = new Choice();
c1.add("First");
c1.addItem("Second");
c1.add("Third");
c1.insert("Lastadded",2);
System.out.println(c1.getItemCount(
));
a) First,Second,Third,Fourth
b) First,Second,Lastadded,Third
c) Lastadded,First,Second,Third
Correct ANswer is d)
Q20) Which one of the
following does not extends
java.awt.Component
a) CheckBox
b) Canvas
c) CheckbocGroup
d) Label
Correct answer is c)
Correct answer is a)
Q22) For awt components
which of the following
statements are true?
a) If a component is not
explicitly assigned a font, it
usese the same font that it
container uses.
b) If a component is not
explicitly assigned a
foreground color , it usese the
same foreground color that it
container uses.
c) If a component is not
explicitly assigned a backround
color , it usese the same
background color that it
container uses.
d) If a component is not
explicitly assigned a layout
manager , it usese the same
layout manager that it
container uses.
correct answer is a),b),c)
Correct ANswer is b)
Q19) Answer based on following code
1 Choice c1 = new Choice();
2 c1.add("First");
3 c1.addItem("Second");
4 c1.add("Third");
5 c1.insert("Lastadded",1000);
6
System.out.println(c1.getItemCount(
));
a)
b)
Compile time error
Run time error at line 5
Q23)java.awt.Component class
method getLocation() returns
Point (containg x and y
cordinate).What does this x
and y specify
a) Specify the postion of
components lower-left
component in the coordinate
space of the component's
parent.
b) Specify the postion of
components upper-left
component in the coordinate
22
space of the component's parent.
c) Specify the postion of
components upper-left
component in the coordinate
space of the screen.
correct answer is b)
Q24. Q. What will be the output
of follwing
{
double d1 = -0.5d;
System.out.println("Ceil for d1 "
+ Math.ceil(d1));
System.out.println("Floor for d1 "
+Math.floor(d1));
}
Answers:
a) Ceil for d1 0
Floor for d1 -1;
b) Ceil for d1 0
Floor for d1 -1.0;
c) Ceil for d1 0.0
Floor for d1 -1.0;
d) Ceil for d1 -0.0
Floor for d1 -1.0;
correct answer is d) as 0.0 is
treated differently from -0.0
Q25. What is the output of
following
{
float f4 = -5.5f;
float f5 = 5.5f;
float f6 = -5.49f;
float f7 = 5.49f;
System.out.println("Round
+ Math.round(f4));
System.out.println("Round
+ Math.round(f5));
System.out.println("Round
+ Math.round(f6));
System.out.println("Round
+ Math.round(f7));
}
a)Round f4 is -6
Round f5 is 6
Round f6 is -5
Round f7 is 5
f4 is "
f5 is "
f6 is "
a)Round f4 is -2147483648
Round f5 is 2147483647
Round f7 is -2147483648
b)Round f4 is -2147483648
Round f5 is 2147483647
Round f7 is -2147483655
correct answer is a)
//Reason If the argument is negative
infinity or any value less than or
equal to the value of
Integer.MIN_VALUE, the result is
equal to the value of
Integer.MIN_VALUE.
If the argument is positive infinity
or any value greater than or equal to
the value of Integer.MAX_VALUE, the
result is
equal to the value of
Integer.MAX_VALUE. // From JDK api
documentation
Q27)
1 Boolean b1 = new
Boolean("TRUE");
2 Boolean b2 = new
Boolean("true");
3 Boolean b3 = new
Boolean("JUNK");
4 System.out.println("" + b1 + b2
+ b3);
f7 is "
b)Round f4 is -5
Round f5 is 6
Round f6 is -5
Round f7 is 5
Correct answer is b)
Q26. Given Integer.MIN_VALUE
= -2147483648
Integer.MAX_VALUE =
2147483647
What is the output of following
{
float f4 =
Integer.MIN_VALUE;
float f5 = Integer.MAX_VALUE;
float f7 = -2147483655f;
System.out.println("Round f4 is " +
Math.round(f4));
System.out.println("Round f5 is " +
Math.round(f5));
System.out.println("Round f7 is " +
Math.round(f7));
}
a) Comiler error
b) RunTime error
c)truetruefalse
d)truetruetrue
Correct answer is c)
Q 28) In the above question if line 4
is changed to
System.out.println(b1+b2+b3);
The output is
a) Compile time error
b) Run time error
c) truetruefalse
d) truetruetrue
Correct answer is a) As there is no
method to support Boolean +
Boolean
Boolean b1 = new
Boolean("TRUE");
Think ----->System.out.println(b1);
// Is this valid or not?
Q 29. What is the output
{
Float f1 = new
Float("4.4e99f");
Float f2 = new Float("4.4e99f");
Double d1 = new
Double("4.4e99");
System.out.println(f1);
System.out.println(f2);
System.out.println(d1);
}
a) Runtime error
b) Infinity
-Infinity
4.4E99
c) Infinity
-Infinity
Infinity
d) 4.4E99
-4.4E99
4.4E99
Correct answer is b)
Q30 Q. Which of the following
wrapper classes can not
take a "String" in constructor
1)
2)
3)
4)
5)
6)
Boolean
Integer
Long
Character
Byte
Short
correct answer is 4)
Q31. What is the output of
following
Double d2 = new Double("5.5");
Double d3 = new Double("5.5");
System.out.println(d2==d3);
System.out.println(d2.equals(d
3));
a) true
true
b) false
false
c) true
false
d) false
true
Correct answer is d)
Q32) Which one of the
following always honors the
components's preferred size.
a) FlowLayout
23
b) GridLayout
c) BorderLayout
Correct answer is a)
Q33) Look at the following code
import java.awt.*;
public class visual extends
java.applet.Applet{
static Button b = new
Button("TEST");
public void init(){
add(b);
}
public static void main(String
args[]){
Frame f = new
Frame("Visual");
f.setSize(300,300);
f.add(b);
f.setVisible(true);
}
}
What will happen if above code is
run as a standalone application
a) Displays an empty frame
b) Displays a frame with a button
covering the entire frame
c) Displays a frame with a button
large enough to accomodate its
label.
Correct answer is b) ReasonFrame uses Border Layout which
places the button to CENTRE
(By default) and ignores
Button's preferred size.
Q34 If the code in Q33 is
compiled and run via
appletviewer what will happen
a) Displays an empty applet
b) Displays a applet with a
button covering the entire frame
c) Displays a applet with a
button large enough to
accomodate its label.
Correct answer is c) ReasonApplet uses FlowLayout which
honors Button's preferred size.
Q35. What is the output
public static void main(String
args[]){
Frame f = new
Frame("Visual");
f.setSize(300,300);
f.setVisible(true);
Point p = f.getLocation();
System.out.println("x is "
+ p.x);
System.out.println("y is "
+ p.y);
}
a) x is 300
y is 300
b) x is 0
y is 0
c) x is 0
y is 300
correct answer is b) Because postion
is always relative to parent container
and in this
case Frame f is the topemost
container
Q36) Which one of the following
always ignores the components's
preferred size.
a) FlowLayout
b) GridLayout
c) BorderLayout
Correct answer is b)
Q37) Consider a directory structure
like this (NT or 95)
C:\JAVA\12345.msg --FILE
\dir1\IO.class -- IO.class is
under dir1
references to the current user
directory have been completely
resolved.
WHERE AS
getAbsolutePath Returns the
absolute pathname of the file
represented by this object. If
this object represents an
absolute pathname, then
return the pathname.
Otherwise, return a pathname
that is a concatenation of the
current user directory, the
separator character, and the
pathname of this file object.
Q 38) Suppose we copy
IO.class from C:\java\dir1 to
c:\java
What will be the output of
running "java IO" from
C:\java.
a) C:\java\12345.msg
C:\java\..\12345.msg
b) C:\12345.msg
C:\java\..\12345.msg
Consider the following code
import java.io.*;
public class IO {
public static void main(String
args[]) {
File f = new
File("..\\12345.msg");
try{
System.out.println(f.getCanonicalPat
h());
System.out.println(f.getAbsolutePath
());
}catch(IOException e){
System.out.println(e);
}
}
}
What will be the output of running
"java IO" from C:\java\dir1
a) C:\java\12345.msg
C:\java\dir1\..\12345.msg
b) C:\java\dir1\12345.msg
C:\java\dir1\..\12345.msg
c) C:\java\dir1\..\12345.msg
C:\java\dir1\..\12345.msg
correct answer is a) as
getCanonicalPath Returns the
canonical form of this File object's
pathname. The precise definition of
canonical form is system-dependent,
but it usually
specifies an absolute pathname in
which all relative references and
c) C:\java\..\12345.msg
C:\java\\..\12345.msg
correct answer is b)
Q39) Which one of the
following methods of
java.io.File throws IOException
and why
a) getCanonicalPath and
getAbsolutePath both require
filesystem queries.
b) Only getCannonicalPath as it
require filesystem queries.
c) Only getAbsolutePath as it
require filesystem queries.
Correct answer is b)
Q40) What will be the output
if
Consider a directory
structure like this (NT or 95)
C:\JAVA\12345.msg -FILE
\dir1\IO.class -IO.class is under dir1
import java.io.*;
public class IO {
public static void
main(String args[]) {
File f = new
File("12345.msg");
String arr[] =
f.list();
System.out.println(arr.length);
24
}
correct answer
is d)
}
a) Compiler error as 12345.msg
is a file not a directory
b) java.lang.NullPointerException
at run time
c) No error , but nothing will be
printed on screen
Correct ansewer is b)
Q41) What will be the output
Consider a directory structure
like this (NT or 95)
C:\JAVA\12345.msg --FILE
import java.io.*;
public class IO {
public static void
main(String args[]) {
File f1 = new
File("\\12345.msg");
System.out.println(f1.getPath());
System.out.println(f1.getParent()
);
System.out.println(f1.isAbsolute(
));
System.out.println(f1.getName()
);
Q42) If in question no 41 the line
File f1 = new
File("\\12345.msg"); is replaced with
File f1 = new File("12345.msg");
What will be the output
a) 12345.msg
\
true
12345.msg
true
true
b) 12345.msg
null
true
12345.msg
true
true
c) 12345.msg
null
false
12345.msg
true
true
d) \12345.msg
\
true
12345.msg
false
false
System.out.println(f1.exists());
System.out.println(f1.isFile());
}
}
a) \12345.msg
\
true
12345.msg
true
true
b) \12345.msg
\
true
\12345.msg
false
false
c) 12345.msg
\
true
12345.msg
false
false
d) \12345.msg
\
true
12345.msg
false
false
Correct answer is c)
Q 1. What is the output of the
following
StringBuffer sb1 = new
StringBuffer("Amit");
StringBuffer sb2= new
StringBuffer("Amit");
String ss1 = "Amit";
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss1));
System.out.println("Poddar".substrin
g(3));
Ans:
a) false
false
false
dar
b) false
true
false
Poddar
c) Compiler Error
d) true
true
false
dar
Correct Answer is a)
***** Look carefully at code
and answer the following
questions ( Q2 to Q8)
1
import java.applet.Applet;
2 import java.awt.*;
3 import java.awt.event.*;
4
public class hello4 extends
Applet {
5
public void init(){
6
add(new
myButton("BBB"));
7
}
8
public void
paint(Graphics screen) {
9 }
10
class myButton extends
Button{
11
myButton(String
label){
12
super(label);
13
}
14
public String
paramString(){
15
return
super.paramString();
16
}
17
}
18 public static void
main(String[] args){
19
Frame myFrame = new
Frame(
20
"Copyright Amit");
21
myFrame.setSize(300,100);
22
Applet myApplet = new
hello4();
23
Button b = new
Button("My Button");
24
myApplet.add(b);
25
b.setLabel(b.getLabel()+"New"
);
26 // myButton b1 =(new
hello4()).new
myButton("PARAMBUTTON");
27
System.out.println(b1.paramSt
ring());
28
myFrame.add(myApplet);
29
myFrame.setVisible(true);
30
myFrame.addWindowListener(
new WindowAdapter(){
31
public void
windowClosing(WindowEvent
e){
32
System.exit(0);}});
33 }
25
34 } //End hello4 class.
Q2. If you run the above
program via appletviewer (
defining a HTML file), You see on
screen.
a) Two buttons
b) One button with label as
"BBB"
c) One button with label as "My
ButtonNew"
d) One button with label as "My
Button"
Correct answer is b)
Q3. In the above code if line 26
is uncommented and program
runs as standalone application
a) Compile Error
b) Run time error
c) It will print the the label as
PARAMBUTTON for button b1
Correct answer is c)
Q4 In the code if you compile as
"javac hello4.java" following files
will be generated.
a) hello4.class,
myButton.class,hello41.class
b)hello4.class,
hello4$myButton.class,hello4$1.c
lass
c)hello4.clas,hello4$myButton.cl
ass
Correct answer is b)
Q5. If above program is run as a
standalone application. How
many buttons will be displayed
a) Two buttons
b) One button with label as
"BBB"
c) One button with label as "My
ButtonNew"
d) One button with label as "My
Button"
correct answer is C)
Q6. If from line no 14 keyword
"public" is removed, what will
happen.( Hint :paramString()
method in java.awt.Button is a
protected method. (Assume line
26 is uncommented)
a) Code will not compile.
b) Code will compile but will give
a run time error.
c) Code will compile and no run
time error.
Correct answer
is a). As you can
not override a method with weaker
access privileges
Q7. If from line no 14 keyword
"public" is replaced with "protected",
what will happen.(Hint
:paramString() method in
java.awt.Button is a protected
method.(Assume line 26 is
uncommented)
a) Code will not compile.
b) Code will compile but will give a
run time error.
c) Code will compile and no run time
error.
Correct answer is c) . As you can
access a protected variable in the
same package.
Q8.If line no 26 is replaced with
Button b1 = new
Button("PARAMBUTTON").(Hint
:paramString() method in
java.awt.Button is a protected
method.(Assume line 26 is
uncommented)
a) Code will not compile.
b) Code will compile but will give a
run time error.
c) Code will compile and no run time
error.
Correct answer is a) Because
protected variables and methods can
not be accssed in another package
directly. They can only be accessed if
the class is subclassed and instance
of subclass is used.
Q9. What is the output of following if
the return value is "the value 0 if the
argument string is equal to this
string; a value less than 0 if this
string is lexicographically less than
the string argument; and a value
greater than 0 if this string is
lexicographically greater than the
string argument" (Assuming written
inside main)
String s5 = "AMIT";
String s6 = "amit";
System.out.println(s5.compareTo(s6)
);
System.out.println(s6.compareTo(s5)
);
System.out.println(s6.compareTo(s6)
);
Ans
a> -32
32
0
b> 32
32
0
c> 32
-32
0
d> 0
0
0
Correct Answer is a)
Q 10) What is the output
(Assuming written inside
main)
String s1 = new
String("amit");
String s2 =
s1.replace('m','i');
s1.concat("Poddar");
System.out.println(s1);
System.out.println((s1+s2).ch
arAt(5));
a) Compile error
b) amitPoddar
o
c) amitPoddar
i
d) amit
i
Correct answer is d)As String is
imutable.so s1 is always
"amit". and s2 is "aiit".
Q 11) What is the output
(Assuming written inside
main)
String s1 = new
String("amit");
System.out.println(s1.replace('
m','r'));
System.out.println(s1);
String s3="arit";
String s4="arit";
String s2 =
s1.replace('m','r');
System.out.println(s2==s3);
System.out.println(s3==s4);
a) arit
amit
false
true
b) arit
arit
false
true
c) amit
amit
false
true
d) arit
amit
26
true
true
Correct answer is a) s3==s4 is
true because java points both s3
and s4 to same memory location
in string pool
Q12) Which one does not extend
java.lang.Number
1)Integer
2)Boolean
3)Character
4)Long
5)Short
Correct answer is 2) and 3)
Q13) Which one does not have a
valueOf(String) method
1)Integer
2)Boolean
3)Character
4)Long
5)Short
Correct answer is 3)
Q.14) What is the output of
following (Assuming written
inside main)
String s1 = "Amit";
String s2 = "Amit";
String s3 = new
String("abcd");
String s4 = new
String("abcd");
System.out.println(s1.equals(s2)
);
Checkbox
cb1 = new
Checkbox("First",true,cbg);
Checkbox cb2 = new
Checkbox("Scond",true,cbg);
Checkbox cb3 = new
Checkbox("THird",false,cbg);
cbg.setSelectedCheckbox(cb3);
myFrame.add(cb1);
myFrame.add(cb2);
myFrame.add(cb3);
a)
cb1
b)
cb2,cb1
c)
cb1,cb2,cb3
d)
cb3
Correct Answer is d) As in a
CheckboxGroup only one can be
selected
Q16) Which checkbox will be selected
in the following code ( Assume with
main and added to a Frame)
Frame myFrame = new
Frame("Test");
CheckboxGroup cbg = new
CheckboxGroup();
Checkbox cb1 = new
Checkbox("First",true,cbg);
Checkbox cb2 = new
Checkbox("Scond",true,cbg);
Checkbox cb3 = new
Checkbox("THird",true,cbg);
myFrame.add(cb1);
myFrame.add(cb2);
myFrame.add(cb3);
a)
cb1
b)
cb2,cb1
c)
cb1,cb2,cb3
d)
cb3
System.out.println((s1==s2));
System.out.println(s3.equals(s4)
);
System.out.println((s3==s4));
a) true
true
true
false
b) true
true
true
true
c) true
false
true
false
Correct answer is a)
Correct Answer is d) As in a
CheckboxGroup only one can be
selected
Q17) What will be the output of line
5
1 Choice c1 = new Choice();
2 c1.add("First");
3 c1.addItem("Second");
4 c1.add("Third");
5
System.out.println(c1.getItemCount(
));
a) 1
b) 2
c) 3
d) None of the above
Correct Answer is c)
Q15. Which checkbox will be
selected in the following code (
Assume with main and added to
a Frame)
Frame myFrame = new
Frame("Test");
CheckboxGroup cbg = new
CheckboxGroup();
Q18) What will be the order of four
items added
Choice c1 = new Choice();
c1.add("First");
c1.addItem("Second");
c1.add("Third");
c1.insert("Lastadded",2);
System.out.println(c1.getItem
Count());
a) First,Second,Third,Fourth
b)
First,Second,Lastadded,Third
c)
Lastadded,First,Second,Third
Correct ANswer is b)
Q19) Answer based on
following code
1 Choice c1 = new Choice();
2 c1.add("First");
3 c1.addItem("Second");
4 c1.add("Third");
5
c1.insert("Lastadded",1000);
6
System.out.println(c1.getItem
Count());
a) Compile time error
b) Run time error at line 5
c) No error and line 6 will
print 1000
d) No error and line 6 will
print 4
Correct ANswer is d)
Q20) Which one of the
following does not extends
java.awt.Component
a) CheckBox
b) Canvas
c) CheckbocGroup
d) Label
Correct answer is c)
Q21) What is default layout
manager for panels and
applets?
a) Flowlayout
b) Gridlayout
c) BorderLayout
Correct answer is a)
Q22) For awt components
which of the following
statements are true?
a) If a component is not
explicitly assigned a font, it
usese the same font that it
container uses.
b) If a component is not
explicitly assigned a
foreground color , it usese the
same foreground color that it
container uses.
c) If a component is not
explicitly assigned a backround
27
color , it usese the same
background color that it
container uses.
d) If a component is not
explicitly assigned a layout
manager , it usese the same
layout manager that it container
uses.
correct answer is a),b),c)
Q23)java.awt.Component class
method getLocation() returns
Point (containg x and y
cordinate).What does this x and
y specify
a) Specify the postion of
components lower-left
component in the coordinate
space of the component's parent.
b) Specify the postion of
components upper-left
component in the coordinate
space of the component's parent.
c) Specify the postion of
components upper-left
component in the coordinate
space of the screen.
correct answer is b)
Q24. Q. What will be the output
of follwing
{
double d1 = -0.5d;
System.out.println("Ceil for d1 "
+ Math.ceil(d1));
System.out.println("Floor for d1 "
+Math.floor(d1));
}
Answers:
a) Ceil for d1 0
Floor for d1 -1;
b) Ceil for d1 0
Floor for d1 -1.0;
c) Ceil for d1 0.0
Floor for d1 -1.0;
d) Ceil for d1 -0.0
Floor for d1 -1.0;
correct answer is d) as 0.0 is
treated differently from -0.0
Q25. What is the output of
following
{
float f4 = -5.5f;
float f5 = 5.5f;
float f6 = -5.49f;
float f7 = 5.49f;
System.out.println("Round f4 is "
+ Math.round(f4));
System.out.println("Round f5 is "
+ Math.round(f5));
System.out.println("Round f6 is "
+ Math.round(f6));
System.out.println("Round f7 is " +
Math.round(f7));
}
a)Round f4 is -6
Round f5 is 6
Round f6 is -5
Round f7 is 5
b)Round f4 is -5
Round f5 is 6
Round f6 is -5
Round f7 is 5
Correct answer is b)
Q26. Given Integer.MIN_VALUE = 2147483648
Integer.MAX_VALUE =
2147483647
What is the output of following
{
float f4 = Integer.MIN_VALUE;
float f5 = Integer.MAX_VALUE;
float f7 = -2147483655f;
System.out.println("Round f4 is " +
Math.round(f4));
System.out.println("Round f5 is " +
Math.round(f5));
System.out.println("Round f7 is " +
Math.round(f7));
}
a)Round f4 is -2147483648
Round f5 is 2147483647
Round f7 is -2147483648
b)Round f4 is -2147483648
Round f5 is 2147483647
Round f7 is -2147483655
correct answer is a)
//Reason If the argument is negative
infinity or any value less than or
equal to the value of
Integer.MIN_VALUE, the result is
equal to the value of
Integer.MIN_VALUE.
If the argument is positive infinity
or any value greater than or equal to
the value of Integer.MAX_VALUE, the
result is
equal to the value of
Integer.MAX_VALUE. // From JDK api
documentation
Q27)
1 Boolean b1 = new
Boolean("TRUE");
2 Boolean b2 = new
Boolean("true");
3 Boolean b3 = new
Boolean("JUNK");
4 System.out.println("" + b1 + b2
+ b3);
a) Comiler error
b) RunTime error
c)truetruefalse
d)truetruetrue
Correct answer is c)
Q 28) In the above question if
line 4 is changed to
System.out.println(b1+b2+b3)
; The output is
a) Compile time error
b) Run time error
c) truetruefalse
d) truetruetrue
Correct answer is a) As there is
no method to support Boolean
+ Boolean
Boolean b1 = new
Boolean("TRUE");
Think ---->System.out.println(b1); // Is
this valid or not?
Q 29. What is the output
{
Float f1 = new
Float("4.4e99f");
Float f2 = new Float("4.4e99f");
Double d1 = new
Double("4.4e99");
System.out.println(f1);
System.out.println(f2);
System.out.println(d1);
}
a) Runtime error
b) Infinity
-Infinity
4.4E99
c) Infinity
-Infinity
Infinity
d) 4.4E99
-4.4E99
4.4E99
Correct answer is b)
Q30 Q. Which of the following
wrapper classes can not
take a "String" in constructor
1)
2)
3)
4)
5)
6)
Boolean
Integer
Long
Character
Byte
Short
correct answer is 4)
28
Q31. What is the output of
following
Double d2 = new Double("5.5");
Double d3 = new Double("5.5");
System.out.println(d2==d3);
System.out.println(d2.equals(d3)
);
a) true
true
b) false
false
c) true
false
d) false
true
Correct answer is d)
Q32) Which one of the following
always honors the components's
preferred size.
a) FlowLayout
b) GridLayout
c) BorderLayout
Correct answer is a)
Q33) Look at the following code
import java.awt.*;
public class visual extends
java.applet.Applet{
static Button b = new
Button("TEST");
public void init(){
add(b);
}
public static void main(String
args[]){
Frame f = new
Frame("Visual");
f.setSize(300,300);
f.add(b);
f.setVisible(true);
}
}
What will happen if above code is
run as a standalone application
a) Displays an empty frame
b) Displays a frame with a button
covering the entire frame
c) Displays a frame with a button
large enough to accomodate its
label.
Correct answer is b) ReasonFrame uses Border Layout which
places the button to CENTRE
(By default) and ignores
Button's preferred size.
Q34 If the code in Q33 is compiled
and run via appletviewer what will
happen
a) Displays an empty applet
b) Displays a applet with a button
covering the entire frame
c) Displays a applet with a button
large enough to accomodate its label.
Correct answer is c) Reason- Applet
uses FlowLayout which honors
Button's preferred size.
Q35. What is the output
public static void main(String
args[]){
Frame f = new Frame("Visual");
f.setSize(300,300);
f.setVisible(true);
Point p = f.getLocation();
System.out.println("x is " +
p.x);
System.out.println("y is " +
p.y);
}
a) x is 300
y is 300
b) x is 0
y is 0
c) x is 0
y is 300
correct answer is b) Because postion
is always relative to parent container
and in this
case Frame f is the topemost
container
Q36) Which one of the following
always ignores the components's
preferred size.
a) FlowLayout
b) GridLayout
c) BorderLayout
Correct answer is b)
Q37) Consider a directory structure
like this (NT or 95)
C:\JAVA\12345.msg --FILE
\dir1\IO.class -- IO.class is
under dir1
Consider the following code
import java.io.*;
public class IO {
public static void main(String
args[]) {
File f = new
File("..\\12345.msg");
try{
System.out.println(f.getCanonicalPat
h());
System.out.println(f.getAbsolut
ePath());
}catch(IOException
e){
System.out.println(e);
}
}
}
What will be the output of
running "java IO" from
C:\java\dir1
a) C:\java\12345.msg
C:\java\dir1\..\12345.msg
b) C:\java\dir1\12345.msg
C:\java\dir1\..\12345.msg
c) C:\java\dir1\..\12345.msg
C:\java\dir1\..\12345.msg
correct answer is a) as
getCanonicalPath Returns the
canonical form of this File
object's pathname. The precise
definition of canonical form is
system-dependent, but it
usually
specifies an absolute pathname
in which all relative references
and references to the current
user directory have been
completely resolved.
WHERE AS
getAbsolutePath Returns the
absolute pathname of the file
represented by this object. If
this object represents an
absolute pathname, then
return the pathname.
Otherwise, return a pathname
that is a concatenation of the
current user directory, the
separator character, and the
pathname of this file object.
Q 38) Suppose we copy
IO.class from C:\java\dir1 to
c:\java
What will be the output of
running "java IO" from
C:\java.
a) C:\java\12345.msg
C:\java\..\12345.msg
b) C:\12345.msg
C:\java\..\12345.msg
c) C:\java\..\12345.msg
C:\java\\..\12345.msg
correct answer is b)
Q39) Which one of the
following methods of
29
java.io.File throws IOException
and why
a) getCanonicalPath and
getAbsolutePath both require
filesystem queries.
b) Only getCannonicalPath as it
require filesystem queries.
c) Only getAbsolutePath as it
require filesystem queries.
Correct answer is b)
Q40) What will be the output if
Consider a directory structure
like this (NT or 95)
C:\JAVA\12345.msg --FILE
\dir1\IO.class -- IO.class
is under dir1
import java.io.*;
public class IO {
public static void
main(String args[]) {
File f = new
File("12345.msg");
String arr[] =
f.list();
System.out.println(arr.length);
}
}
a) Compiler error as 12345.msg
is a file not a directory
b) java.lang.NullPointerException
at run time
c) No error , but nothing will be
printed on screen
Correct ansewer is b)
Q41) What will be the output
Consider a directory structure
like this (NT or 95)
C:\JAVA\12345.msg --FILE
import java.io.*;
public class IO {
public static void
main(String args[]) {
File f1 = new
File("\\12345.msg");
System.out.println(f1.getPath());
System.out.println(f1.getParent()
);
System.out.println(f1.isAbsolute(
));
System.out.println(f1.getName()
);
}
}
a) \12345.msg
\
true
12345.msg
true
true
b) \12345.msg
\
true
\12345.msg
false
false
c) 12345.msg
\
true
12345.msg
false
false
d) \12345.msg
\
true
12345.msg
false
false
correct answer is d)
Q42) If in question no 41 the line
File f1 = new
File("\\12345.msg"); is replaced with
File f1 = new File("12345.msg");
What will be the output
a) 12345.msg
\
true
12345.msg
true
true
b) 12345.msg
null
true
12345.msg
true
true
c) 12345.msg
null
false
12345.msg
true
true
d) \12345.msg
\
true
12345.msg
false
false
System.out.println(f1.exists());
Correct answer is c)
System.out.println(f1.isFile());
Location: ... > Declarations
and Access Control > Objective
1.1 > Item 1
-----------------------------------------------------------------------------Click the Exhibit button.
Which two lines of code will
compile correctly? (Choose
two.)
1. class CharArray2 {
2. public static void main(
String [] args) {
3.
char b = 'b';
4.
char c = 'C';
5.
char [] c1 = {'a', 'b',
'c'};
6.
char [] c2 = {'a', b , 'c'};
7.
char [] c3 = ('a', 'b', 'c');
8.
char [] c4 = [3];
9.
char [] c5 = [3] {'a', 'b',
'c'};
10.
char [] c6 = [] {'a', 'b',
c};
11. }
12. }
A line 5
B line 6
C line 7
D line 8
E line 9
F line 10
Answer:
Options A and B are the correct
answers. This question
explores a Java syntax
shortcut. A and B represent
acceptable syntax to declare,
construct, and initialize an
array in a single line of code.
Location: ... > Declarations
and Access Control > Objective
1.1 > Item 2
-----------------------------------------------------------------------------Click the Exhibit button.
1. class Test{
2. public static void main(
String [] args) {
3.
int [] y;
4.
int [] z = new int [] {1,
2, 3};
5.
y = z;
6.
z[1] = 7;
7.
for (int x= 0;x<3; x++)
{
8.
System.out.print("
y[" + x + "] = " + y[x]);
9.
}
10. }
11. }
What is the result?
A y[0] = 0 y[1] = 1 y[2] =
2
30
B y[0] = 7 y[1] = 2 y[2] = 3
C y[0] = 1 y[1] = 7 y[2] = 3
D y[0] = 1 y[1] = 2 y[2] = 3
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option C is the correct answer. y
and z are reference variables.
Line 5 assigns y to refer to the
same array as z, there is still
only one array (however there
are two array references). When
line 6 executes, it changes a
value in the only array there is,
(the one both y and z refer to).
Therefore when the array is
accessed via y, the updated
value is displayed.
ocation: ... > Declarations and
Access Control > Objective 1.2 >
Item 1
-------------------------------------Which declaration ensures that a
class cannot be subclassed?
A abstract class MyClass { }
B final public class MyClass { }
C final abstract class MyClass {
}
D static private class MyClass {
}
E static protected class MyClass
{}
Answer:
Option B is the correct answer.
The final modifier insures that a
class can not be subclassed.
Q31. class XXX {
2. long doStuff (int input) {
3.
static long x = 7;
4.
return (long) input / x;
5. }
6.
7. public static void main(String
[] args) {
8.
XXX xxx = new XXX();
9.
System.out.println(xxx.doStuff(4
2));
10. }
11. }
What will be the result?
A 6
B 7
C 42
D Compilation fails
E An exception is thrown at
runtime
Answer:
Option D is the correct answer.
The compiler will notice that in
Line 3 the code is declaring a
static variable, but it's in a local
method, which is not legal. If
several instances of XXX were
instantiated it would be
impossible to
know which
instance the static should belong to.
Location: ... > Declarations and
Access Control > Objective 1.3 >
Item 1
-------------------------------------------Click the Exhibit button.
1. class Foo {
2. Foo(String s) { }
3. }
4. class Bar extends Foo { }
Which statement is true?
A Class Bar will not compile
B Class Bar has a public constructor
C Class Bar's constructor invokes
super()
D Class Foo's constructor does not
invoke super()
answer:
Option A is the correct answer. The
compiler attempts to create a default
constructor for class Bar, because
Bar has not defined any constructors.
The class Bar constructor will include
a call to super(). Since class Foo
does not have a no-arg constructor,
class Bar will not compile because
the default constructor the compiler
is attempting to build includes a call
to super(), and there is no matching
no-arg constructor in class Foo.
Location: ... > Declarations and
Access Control > Objective 1.3 >
Item 2
------------------------------------------------------------------------------Given:
1. class Pizza { }
Which of these represents the
functionality of the default
constructor for Pizza?
A Pizza()
B Pizza() {super();}
C public void Pizza()
D public Pizza() {super();}
E There is no default constructor for
Pizza
Answer:
Option B is the correct answer. The
compiler creates a default
constructor for Pizza, with default
access (matching the access of the
class), and a no-arg call to super().
Location: ... > Declarations and
Access Control > Objective 1.4 >
Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. class XL {
2. public long doMath() {
3.
return 343L;
4. }
5. }
6.
7. class L extends XL {
8.
9. }
Which two methods inserted at
line 8, will not compile?
(Choose two.)
a public void doMath() { }
B public void doMath(int i) {
}
C public int doMath() { return
343 }
D public long doMath(int i) {
return 343 }
answer:
Options A and C are the correct
answers. A and C represent an
illegal override of the class XL
doMath() method. Because the
arguments have not changed,
the return type cannot change.
Location: ... > Declarations
and Access Control > Objective
1.4 > Item 2
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. class Test {
2. public short doStuff(int i)
{ return 27; }
3. }
4.
5. public class SubTest extends
Test {
6. public int doStuff(int x) {
return 30; }
7.
8. public static void
main(String [] args) {
9.
Test t = new Test();
10.
SubTest s = new
SubTest();
11. int t1 = t.doStuff(30);
12. int s1 = s.doStuff(27);
13. System.out.println( t1 +
" " + s1);
14. }
15. }
What is the result?
A 27 30
B 30 27
C 27 27
D 30 30
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option E is the correct answer.
Line 6 is an illegal override of
the doStuff() method in class
Test.
31
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.1 > Item
1
-------------------------------------------Click the Exhibit button to view
the code.
1. for (int x = 3; x > = 0; x--) {
2. switch (x - 1) {
3.
case 0:
System.out.print("foo ");
4.
case 1:
System.out.print("bar ");
5.
case 2:
System.out.print("baz ");
6.
case 3:
System.out.print("foo ");
7. }
8. }
What is the result?
A baz bar foo
B foo baz bar foo
C baz bar foo bar foo foo
D baz foo bar baz foo foo bar
baz foo
E Compilation fails
F An exception is thrown at
runtime
answer:
Option D is the correct answer.
As the switch expression iterates
from 2 to -1 the cases start at 2,
1, and 0 and fall through.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.1 > Item
2
--------------------------------------Click the Exhibit button to view
the code.
1. for (int toggle = 0, y = 0; y <
6; y++ ) {
2. toggle = y % 2;
3. if (toggle) {
4.
System.out.print("true ");
5. }
6. else {
7.
System.out.print("false ");
8. }
9. }
What is the result?
A true true true true true true
B true false true false true false
C false true false true false true
D false false false false false
false
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option E is the correct answer.
Line three is illegal, it should
probably read if (toggle == 1) {.
Location: ... > Flow Control,
Assertions, and Exception Handling >
Objective 2.2 > Item 1
--------------------------------------Click the Exhibit button to view the
code.
7. int x,y;
8. next: for(x = 5, y = 1 ; ; ) {
9. --x;
10. for ( ; x > -1 ; y++) {
11.
if ( x < y ) {
12.
break next;
13.
}
14. }
15. }
16. System.out.println(x + " " + y);
What is the result?
A 23
B 34
C 45
D 56
E Compilation fails
F An exception is thrown at runtime
nswer:
Option C is the correct answer. The
variable x is decremented once, in
line 9, then the program loops
through the inner for loop,
incrementing y until x < y, at which
point y equals 5 and the break is
executed.
Location: ... > Flow Control,
Assertions, and Exception Handling >
Objective 2.2 > Item 2
-------------------------------------------Click the Exhibit button to view the
code.
13. long x = 20, y = 30;
14. while ( ++x < = y ) {
15.
--y;
16.
if ( x > y ) {
17.
break;
18.
}
19. }
20. System.out.print(x + " " + y);
What is the result?
A 26 25
B 25 25
C 25 24
D 25 26
E 26 26
Answer:
Option A is the correct answer. The
while statement on line 14
increments x before doing the
comparison test. The break
statement is never reached.
Location: ... > Flow Control,
Assertions, and Exception Handling >
Objective 2.3 > Item 1
-------------------------------------------Which two statements are true?
(Choose two.)
A catch(Foo f) can catch Foo
or any of its superclasses
B If you throw an Error, it
does not need to be enclosed
in a try block
C Any statement that can
throw an Exception must be
enclosed in a try block
D An overriding method must
declare any Exceptions
declared by the overridden
method
E An overriding method can
throw a superclass of the
Exception declared by the
overridden method
F An overriding method is
permitted to throw a
RuntimeException, even if it
has not been declared by the
overridden method.
Answer:
Options B and F are the correct
answers. Overriding methods
are not allowed to throw new
or broader checked exceptions.
A checked exception is any
exception extending from class
Exception, but not extending
from RuntimeException. Errors
do not need to be enclosed in
try blocks.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.4 >
Item 1
--------------------------------------Click the Exhibit button to
view the code.
1. public class Test243 {
2. public static void main
(String [] args) {
3.
try {
4.
String s = "two";
5.
int i =
Integer.parseInt(s);
6.
System.out.print("i =
" + i);
7.
} catch (Exception ex) {
8.
System.out.print("
Exception ");
9.
}
catch(NumberFormatException
exc) {
10.
System.out.print("
NumberFormatException ");
11.
} finally {
12.
System.out.print("
finally ");
13.
}
14.
System.out.print("
done ");
15. }
16. }
What is the result?
A Exception finally
32
B i = two finally done
C Exception finally done
D NumberFormatException
finally
E NumberFormatException
finally done
F Compilation fails
Answer:
Option F is the correct answer.
The NumberFormatException will
be caught by the Exception
catch. The compiler recognizes
that the second catch can never
be reached. You must always put
the catch blocks in order going
from most specific to broadest. If
the exceptions are siblings (i.e.
one does not extend from the
other), then the order does not
matter.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.4 > Item
2
-------------------------------------------- Click the Exhibit button
to view the code.
1. public class Test244 {
2. public static void main (String
[] args) {
3.
try {
4.
foo();
5.
System.out.print(" one
");
6.
} catch(Exception e) {
7.
System.out.print(" two
");
8.
} finally {
9.
System.out.print(" three
");
10.
}
11.
System.out.print(" four ");
12. }
13.
14. public static void foo() {
15.
throw new
RuntimeException();
16. }
17. }
What is the result? (Choose one)
A three
B two three
C three four
D two three four
E one two three four
F Compilation fails
Answer:
Option D is the correct answer.
Method foo() throws a
RuntimeException, which does
not need to be declared. When
the exception is thrown, the
catch and finally blocks run, and
then the main() method runs to
completion
the end).
(printing four at
Location: ... > Flow Control,
Assertions, and Exception Handling >
Objective 2.5 > Item 1
--------------------------------------------
Which two fragments are examples
of inappropriate uses of assertions?
(Choose two.)
A assert (!(foo == null));
foo.go();
B public void method(boolean b) {
assert (b);
C if (x > y) {
z = x;
} else {
assert (x < 4);
}
D private void test(int z) {
assert (f.setSize(z) > 5);
}
E public int methodA(int x) {
assert (s > 3);
}
Answer:
Options B and D are the correct
answers. B's violation is checking an
argument of a public method. D's
violation is to allow the assert to
have side effects, in this case by
calling a setter method on a
reference. E is an appropriate use of
an assertion because it is not
checking the argument of a public
method.
References:
http://java.sun.com/j2se/1.4/docs/g
uide/lang/assert.html#usageconditions
Location: ... > Flow Control,
Assertions, and Exception Handling >
Objective 2.6 > Item 1
-------------------------------------------------------------------------Which two statements are true?
(Choose two.)
A The -ae flag tells the VM to
enable assertions
B The -ea flag tells the compiler to
enable assertions
C The -assert flag tells the VM to
enable assertions
D The -esa flag tells the VM to
enable some assertions
E The -assertions flag tells the
compiler to enable assertions
F The -enableassertions flag tells
the VM to enable assertions
Answer:
Options D and F are the correct
answers. The -esa flag means
enable system assertions.
ocation: ... > Garbage
Collection > Objective 3.1 >
Item 1
-------------------------------------which two statements are true
about the garbage collection
system? (Choose two.)
A Calling Runtime.gc() will
reclaim memory.
B It guarantees that
programs will not have
memory leaks
C Objects will never be
collected as long as they are
accessible from live threads.
D Objects that have finalize()
methods always have their
finalize() methods called before
the program ends.
E If object 'A' has at least one
other object with a reference
to it, then object 'A' will not be
garbage collected.
F Objects instantiated within
a method and referenced only
by a local variable are created
in the garbage collectible heap.
nswer:
Options C and F are the correct
answers. C is correct because
an object accessible from a live
thread may yet be called by
the JVM. F is correct because
all objects are created in the
garbage collectible heap.
Location: ... > Garbage
Collection > Objective 3.2 >
Item 1
-------------------------------------------Click the Exhibit button to
view the code.
1. class Test {
2. public static void
main(String [] args) {
3.
Test2 t2 = new Test2();
4.
Test2 t3;
5.
t3 = t2.m1();
6.
t2 = t2.linker(t2,t3);
7.
t2 = null;
8.
t3 = null;
9. }
10. }
11.
12. class Test2 {
13.
Test2 link;
14.
Test2 m1() {
15.
Test2 x = new Test2();
33
16.
return x;
17.
}
18.
Test2 linker(Test2 z1,
Test2 z2) {
19.
z1.link = z2;
20.
z2.link = z1;
21.
return z1;
22. }
23. }
Which statement is true?
A After line 8 no objects can be
garbage collected.
B After line 7 one object can be
garbage collected.
C After line 7 no objects can be
garbage collected.
D After line 6 at least one
object has more than two
references
E The z1 and z2 references
must be nulled to make any
objects eligible for garbage
collection.
Answer:
Option C is the correct answer.
After line 7 the t3 reference is
still valid and because of the link
variables both of the Test2
objects are still accessible.
4. int x = 5;
5. Object getDuplicate(Object key)
{
6.
return null;
7. }
8. }
9.
10. private class NewWeakHash
extends WeakHash {
11. public NewWeakHash() {
12.
int x = 7;
13. }
14.
15. public static void main(String
args [] ) {
16.
WeakHash wh = new
WeakHash();
17. }
18. }
What is the result?
A Compilation succeeds
B Compilation fails because of an
error on line 6
C Compilation fails because of an
error on line 10
D Compilation fails because of an
error on line 16
E An exception is thrown at runtime
Answer:
Option C is the correct answer.
Classes cannot be declared private.
Location: ... > Garbage
Collection > Objective 3.3 >
Item 1
--------------------------------------Click the Exhibit button to view
the code.
7. Dog [] da = new Dog[2];
8. Dog clover = new Dog();
9. da[1] = clover;
10. clover = null;
11. Dog fido = new Dog();
12. Dog spot = new Dog();
When is the clover object
eligible for garbage collection?
A after line 9
B after line 10
C after line 11
D never in this code
Answer:
Option D is the correct answer.
The last reference to clover
(da[1]), is never nulled.
1. package com.abc.package1;
2. import java.util.*;
3. public class WeakHash extends
WeakHashMap {
4. int x = 5;
5. Object getDuplicate(Object key)
{
6.
return null;
7. }
8. }
9.
10. private class NewWeakHash
extends WeakHash {
11. public NewWeakHash() {
12.
int x = 7;
13. }
14.
15. public static void main(String
args [] ) {
16.
WeakHash wh = new
WeakHash();
17. }
18. }
Location: ... > Language
Fundamentals > Objective 4.1 >
Item 1
-------------------------------------Click the Exhibit button to view
the code.
1. package com.abc.package1;
2. import java.util.*;
3. public class WeakHash
extends WeakHashMap {
Location: ... > Language
Fundamentals > Objective 4.1 >
Item 2
-------------------------------------------Click the Exhibit button to view the
code.
1.
2. public class NewCollections {
3. public static void main(String []
args) {
4.
java.util.WeakHashMap
hm = new
java.util.WeakHashMap();
5.
Object o1 = null;
6.
o1 = hm.put(o1, o1);
7. }
8. }
Which statement must be
added at line 1 to allow this
code to compile?
A import java.util.*;
B no statement is required
C import
java.util.WeakHashMap;
D include
java.util.WeakHashMap;
nswer:
Option B is the correct answer.
When a fully qualified name is
used, you don't have to import
the classes or packages.
Location: ... > Language
Fundamentals > Objective 4.2
> Item 1
--------------------------------------Which two are valid method
signatures in an interface?
(Choose two.)
A short doShort();
B static char doChar();
C protected byte doByte();
D public boolean
doBoolean(int x);
E final public String
doString(int x);
Answer:
Options A and D are the
correct answers. A is correct
because interface methods are
implicitly public. D is correct
because interface can be
declared public even though
they are so implicitly.
Location: ... > Language
Fundamentals > Objective 4.3
> Item 1
--------------------------------------Click the Exhibit button to
view the code.
1. public class ABC {
2. public static void
main(String [] args ) {
3.
String a = args[3];
4.
String b = args[2];
5.
String c = args[1];
6.
System.out.println("c = "
+ c);
7.
}
8. }
And the command line
invocation:
34
java ABC A B C
What is the result?
a c=
B c=A
C c=B
D c=C
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option F is the correct answer.
Line 3 will fail; args[3] is out of
bounds.
Location: ... > Language
Fundamentals > Objective 4.4 >
Item 1
-------------------------------------Click the Exhibit button to view
the code.
1. class Test {
2. public static void
main(String [] args) {
3.
construct Test(int i) {
4.
for (int y=0; y<i; y++)
5.
System.out.print(" " +
y);
6.
}
7. }
8. }
And command line invocation:
java Test 6
What is the result?
a 12345
B 012345
C Compilation fails
D An exception is thrown at
runtime
Answer:
Option C is the correct answer.
The word 'construct' is not a
valid modifier keyword in the
Java language. Constructors are
identified by having the same
name as the class, but having no
return type.
Location: ... > Language
Fundamentals > Objective 4.4 >
Item 2
-------------------------------------------Which two are keywords?
(Choose two.)
A super
B Boolean
C unsigned
D interface
E anonymous
Answer:
Options A and D are the correct
answers. 'interface' and 'super'
are both valid keywords. C is
wrong because
'unsigned' is a
keyword in C, C++, but not Java. E
is wrong because 'anonymous' is a
Java concept but not a keyword. B
'Boolean' is a class. The Java
primitive keyword is 'boolean'.
Location: ... > Language
Fundamentals > Objective 4.5 >
Item 1
---------------------------------------Click the Exhibit button to view the
code.
1. class IvarLocal {
2. static int x;
3. public static void main(String
args []) {
4.
int y;
5.
System.out.println("x = " + x +
" y = " + y);
6. }
7. }
What is the result?
A x=y=
B x=y=0
C x=0y=
D x=0y=0
E Compilation fails
F An exception is thrown at runtime
Answer:
Option E is the correct answer. The
compiler will be concerned about
whether y has been initialized.
Location: ... > Language
Fundamentals > Objective 4.5 >
Item 2
---------------------------------------Click the Exhibit button to view the
code.
7. short x = 1;
8. int [] y = new int[4];
9. y[0] = x;
10. y[1] = x+1;
11. for(int z= 0;z<4; z++) {
12.
System.out.println(" " +
y[z]);
13. }
What is the result?
A 0123
B 1223
C 1200
D 1 2 null null
E Compilation fails
F An exception is thrown at runtime
Answer:
Option C is the correct answer. The
elements in array y are implicitly
initialized to zeros, and then
elements 0 and 1 are updated.
Location: ... > Language
Fundamentals > Objective 4.6
> Item 1
-------------------------------------Which one is valid?
A boolean b2 = 1;
B boolean b3 = null;
C boolean b1 = FALSE;
D boolean b4 = "false";
E boolean b5 = (4 < 1);
answer:
Option E is the correct answer.
The expression (4 < 1)
resolves to false.
Location: ... > Language
Fundamentals > Objective 4.6
> Item 2
-------------------------------------Which three are valid?
(Choose three.)
A float f1 = 0x123.45;
B float f2 = 3.14f;
C float f3 = (double) 1.8;
D float f4 = 1.0;
E float f5 = (float) '\'';
F float f6 = '\ubabe';
Answer:
Options B, E, and F are the
correct answers. B is explicitly
cast to a float. E casts a char
(which is an unsigned int) to a
float. F casts a Unicode char to
a float.
Location: ... > Operators and
Assignments > Objective 5.1 >
Item 2
-------------------------------------------Given:
10. int x = -1, y = -2;
11. System.out.println( (x<0)
^ (y<0) ) ;
What is the result?
A true
B false
C Compilation fails
D The code runs with no
output
E An exception is thrown at
runtime
Answer:
Option B is the correct answer.
Both equality tests resolve to
true - true XOR true is false.
Location: ... > Operators and
Assignments > Objective 5.2 >
Item 1
--------------------------------------------
35
click the Exhibit button to view
the code.
10. int[] arr1 = new int[2];
11. int[] arr2 =
(int[])arr1.clone();
12. System.out.println( "Array 1
equals array 2 - " + arr1.equals(
arr2 ) );
What is the result?
A Array 1 equals array 2 B Array 1 equals array 2 - true
C Array 1 equals array 2 - null
D Array 1 equals array 2 - false
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option D is the correct answer.
Arrays inherit the default
Object.equals implementation
which compares references not
equivalence of content therefore
comparing two distinct arrays will
always yield false even if the
compared arrays are clones.
Location: ... > Operators and
Assignments > Objective 5.3 >
Item 1
--------------------------------------Click the Exhibit button to view
the code.
10. boolean flag1 = true;
11. boolean flag2 = false;
12. System.out.println( ( flag2 &
flag1 ) & ( flag1 & flag2 ) );
Which two are true? (Choose
two.)
A The code outputs the value
false
B The output may vary if the
ordering is changed
C flag1 and flag2 are both
evaluated exactly once
D The output is always true
regardless of the ordering
E The output is always false
regardless of the ordering
Answer:
Options A and E are the correct
answers. The entire logical
statement is composed of non
shortcutting and therefore ALL
boolean expressions will be
evaluated regardless of the
outcome of a preceding
evaluation. As there are booleans
that resolve to false in all three
composite boolean expressions
the outcome must be false.
Location: ... >
Operators and
Assignments > Objective 5.3 > Item
2
--------------------------------------Click the Exhibit button to view the
code.
10. public boolean t1() { return
"hello".equals("HELLO"); }
11. public boolean t2() { return
!t1(); }
12.
13. public void op () {
14. System.out.println( (t1() &&
t2()) | t2() );
15. }
Which four are true? (Choose four.)
A Compilation fails
B Calling op() means t2() is always
called once
C Calling op() means t1() is always
called once
D The output from op() is always
the value true
E Calling op() means t2() is always
called twice
F Calling op() means t1() is always
called twice
G Reversing the first expression to
(t2() && t1()) does not affect the
output
Answer:
Options B, D, F, and G are the
correct answers.
t1() resolves to false t2() resolves to
not t1() - true reordering the first
expression does not affect the
outcome because it is a double &&
The first call to t1() returns false and
will shortcut the && expression to
false and the non shortcut | to the
second t2() returns true resulting in
overall true. Due to shortcut t2() is
only ever called once t1() is called
once in the expression and a second
time from t2(), therefore is called
twice
Location: ... > Operators and
Assignments > Objective 5.4 > Item
1
------------------------------------------------------------------------------click the Exhibit button to view the
code.
10. public void op3( boolean[] flags )
{
11. flags = new boolean[3];
12. for ( int i=0; i<flags.length;
i++ ) {
13.
flags[i] = ((i%2)==0);
14. }
15. }
16. public void arrayTest () {
17. boolean[] initial = null;
18. op3( initial );
19. System.out.println( initial[0] );
20. }
What is the result if method
arrayTest() is called?
A true
B null
C false
D Compilation fails
E The code runs with no
output
F An exception is thrown at
runtime
Answer:
Option F is the correct answer.
An exception is thrown at
runtime. Defining and
initializing the array in op3()
has no effect on the callers
reference which remains null.
Therefore the access on
initial[0] causes a
java.lang.NullPointerException
Location: ... > Operators and
Assignments > Objective 5.4 >
Item 2
--------------------------------------Click the Exhibit button to
view the code.
10. public StringBuffer op4(
StringBuffer sb ) {
11. sb.append("-widgets");
12. return sb;
13. }
14. public void roundRobinTest
() {
15. StringBuffer sb = new
StringBuffer();
16. sb.append("acme");
17. op4(sb);
18. sb.append("-andnuggets");
19. System.out.println(
sb.toString() );
20. }
What is the result if method
roundRobinTest() is called?
A
B
C
D
E
F
acme
acme-widgets
-and-nuggets
acme-and-nuggets
-widgets-and-nuggets
acme-widgets-and-nuggets
Answer:
Option F is the correct answer.
sb is created in roundRobinTest
and its reference passed by
value into op4 where the
shared object is modified. The
same sb is then returned to the
caller, but the caller never
36
assigns or re-assigns its local sb
reference and it appears that
modifications in op4 are lost, but
as this is a shared object by
reference all modifications
remain, so the output is acmewidgets-and-nuggets
Location: ... > Objective 6.1 >
Item 1
-------------------------------------Click the Exhibit button to view
the code.
1. class A {
2. private static class B {
3.
private static String msg
= "ok" ;
4. }
5. public static String access()
{
6.
return B.msg;
7. }
8. }
9. class X {
10. public static void main(
String[] args ) {
11.
System.out.println(
A.access() );
12. }
13. }
Which two are true? (Choose
two.)
A Compilation fails
B The code outputs the value
ok
C An exception is thrown at
runtime
D Any private members of B
can be accessed from class A
only through accessor methods
E The private modifier on msg
must be weakened to default or
public for this code to work
correctly
Answer:
Options B and D are the correct
answers. Access to an nested
classes private methods and
variables is granted to the
encapsulating classes methods.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 3: Extending Classes -ISBN: 0-201-70433-1
Location: ... > Objective 6.1 >
Item 2
-------------------------------------------- Click the Exhibit button
to view the code.
1. interface D {}
2. class E implements D {}
3. class F extends E {
4.
F() {}
5. }
6. class G extends F implements D
{}
7. class X {
8.
public static void main( String[]
args ) {
9.
E e = new F();
10.
D d = new G();
11. }
12. }
Which three are true? (Choose
three.)
A The declaration of G is illegal
B E is said to be a superclass of F
C G is said to be a superclass of E
D The assignment at line 10 is legal
E A variable can be declared using
an interface type
F Compilation fails
answer:
B, D, and E. B is correct because
class F extends class E, making E a
superclass of F. D and E are correct
because the code compiles
successfully, the declaration of G
reimplementing D is legal, as is the
declaration of d using an interface D
as its type.
Location: ... > Objective 6.2 > Item
1
---------------------------------------Click the Exhibit button to view the
code.
10. class P {
11. P( String s ){}
12. P( short s ){}
13. }
14. class Q extends P {
15. protected Q() {
super((short)3); }
16. public Q( int i ) { super( new
Integer(i).toString() ); }
17. Q( boolean b ) { super(""); }
18. Q( short s ) { super( s ); }
19. }
If the following new statements are
invoked in a separate class in the
same package as classes P and Q,
which three are true? (Choose
three.)
A Compilation fails for code - new
Q();
B Compilation fails for code - new
P();
C Compilation fails for code - new
Q("");
D Compilation fails for code - new
P('a');
E Compilation fails for code - new
Q((short)1);
F Compilation fails for code - new
Q( new Q(3) instanceof P );
Answer:
Options B, C, and D are the
correct answers. The
relationship and declaration of
P & Q are sound. This question
is quite simple couched in
seemingly complex code.
Simply test the argument
passed in the new call with a
constructor in the target class,
if a match is found it compiles.
The last three options here do
not have matching
constructors.
Location: ... > Objective 6.2
> Item 2
-------------------------------------Click the Exhibit button to view
the code.
10. abstract class X {
11. public final void op(){}
12. abstract final void op();
13. void op( String s ){}
14. abstract synchronized
void op(int i) throws Exception;
15. abstract private void op(
String a, int i );
16. }
Which three are true? (Choose
three.)
A Line 10 is uncompilable
B Line 11 is uncompilable
C Line 12 is uncompilable
D Line 13 is uncompilable
E Line 14 is uncompilable
F Line 15 is uncompilable
Answer:
Options C, E, and F are the
correct answers.
line 10 ok, the class must be
declared abstract
line 11 ok, the initial method
declaration signature
line 12 fails, cannot combine
abstract and final, conflict of
intentions
line 13 ok, the first successful
overload of op(), but with
differing access privileges
line 14 fails, cannot combine
abstract with implementation
details like synchronized
line 15 fails, cannot combine
abstract and private, no way to
implement in subclass
Location: ... > Objective 6.3
> Item 1
-------------------------------------------Click the Exhibit button to view
the code.
1. interface XX {}
37
2. interface YY extends XX {}
3. abstract class ZZ implements
XX {}
4. class AA extends ZZ
implements YY {
5. private class BB{}
6. }
7. class Main extends AA {
8. public static void main(
String[] args ) {
9.
XX xx1 = new XX ();
10.
XX xx2 = new AA ();
11.
ZZ zz1 = new Main ();
12.
Main m = new AA();
13. }
14. }
Which two are true? (Choose
two.)
A Line 5 is uncompilable
B Line 9 is uncompilable
C Line 10 is uncompilable
D Line 11 is uncompilable
E Line 12 is uncompilable
F Compilation succeeds
Answer:
Options B and E are the correct
answers. Line 9 attempts to
instantiate an interface. Line 12
is an incompatible assignment;
you can't assign a superclass
object to a subclass reference
type.
Location: ... > Objective 6.3 >
Item 1
Click the Exhibit button to view
the code.
1. interface XX {}
2. interface YY extends XX {}
3. abstract class ZZ implements
XX {}
4. class AA extends ZZ
implements YY {
5. private class BB{}
6. }
7. class Main extends AA {
8. public static void main(
String[] args ) {
9.
XX xx1 = new XX ();
10.
XX xx2 = new AA ();
11.
ZZ zz1 = new Main ();
12.
Main m = new AA();
13. }
14. }
Which two are true? (Choose
two.)
A Line 5 is uncompilable
B Line 9 is uncompilable
C Line 10 is uncompilable
D Line 11 is uncompilable
E Line 12 is uncompilable
F Compilation succeeds
Answer:
Options B and E
are the correct
answers. Line 9 attempts to
instantiate an interface. Line 12 is an
incompatible assignment; you can't
assign a superclass object to a
subclass reference type.
Location: ... > Objective 6.3 >
Item 2
Click the Exhibit button to view
the code.
1. class Outer {
2. class Inner {}
3. }
4. class ExtendedOuter extends
Outer {
5. class ExtendedInner extends
Inner {}
6. }
7. class Main extends Outer.Inner {
8. Main( Outer ref ) {
9. ref.super();
10. }
11. public static void main( String[]
args ) {
12. new Main( new
ExtendedOuter() );
13. }
14. }
What is the result?
A Compilation fails
B An exception is thrown at runtime
C The code runs with no output
Answer:
Option C is the correct answer. An
inner class can extend another,
unrelated, inner class provided an
appropriate enclosing instance is
supplied to the superclass. The
resulting inner class then has two
enclosing instances, one for the
extended class and one for the
superclass. Therefore this code
cleanly compiles and outputs
nothing.
Location: ... > Threads > Objective
7.1 > Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. public static void main( String[]
args ) {
2. class Widget extends
java.lang.Thread {
3.
Widget(boolean daemon) {
4.
this.setDaemon(daemon);
5.
this.start();
6.
}
7. }
8.
9. for ( int i= 0;i<10; i++ ) {
10. new Widget(((i%2)==0));
11. }
12. }
Which two statements are
true? (Choose two.)
A Compilation fails.
B Only five threads are
created.
C An exception is thrown at
runtime.
D Ten independent threads
are created.
E Ten threads are created but
only five execute.
F The program terminates
after the tenth thread is
created.
Answer:
Options D and F are the correct
answers. The program creates
precisely 10 threads, every
other of which is marked as
daemon thread. Each thread
executes on the default run()
method so all will terminate
and therefore the program
terminates.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
location: ... > Threads >
Objective 7.1 > Item 2
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
11. public static void main(
String[] args ) {
12. class Widget extends
java.lang.Thread {
13.
Widget() {
14.
this.start();
15.
}
16. }
17.
18. Widget w = new
Widget();
19. w.setDaemon(true);
20. }
Which statement is true?
A Compilation fails.
B The program never
terminates.
C One daemon thread is
created.
D An exception is thrown at
runtime.
E The program terminates
after the thread is created.
Answer:
Option D is the correct answer.
An exception is thrown at
runtime va.lang.IllegalThreadStateExce
38
ption setdaemon(true) can not
be invoked on an active thread.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.2 > Item 1
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
1. class Worker extends
java.lang.Thread {
2. public void run() {
3.
while ( true ) {}
4. }
5.
6. public static void main(
String[] args ) {
7.
for (int i=0;
i<MAX_PRIORITY; i++ ){
8.
Worker w = new
Worker();
9.
w.setPriortity(
MIN_PRIORITY+i );
10.
w.setDaemon(true);
11.
w.start();
12. }
13. }
14. }
Which two statements are true?
(Choose two.)
A Compilation fails.
B An exception is thrown at
runtime.
C All threads are guaranteed to
execute.
D Some of the threads may
never execute.
E The program runs forever
with no output.
F The program terminates when
the main() method completes.
Answer:
Options D and F are the correct
answers. As all threads are
marked as Daemon threads, the
program contains no user
threads once main terminates, so
the program as a whole
terminates. A number of the
daemon threads may never
execute due to the early
termination of the program and
the priority levels assigned.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads > Objective
7.2 > Item 2
Click the Exhibit button to view the
code.
1. class Worker extends
java.lang.Thread {
2. public void run() {
3. while ( true ) {
4.
synchronized( this ) {
5.
try {
6.
wait();
7.
} catch (Exception e) {}
8.
}
9.
System.out.println("ok");
10. }
11. }
12. public static void main( String[]
args ) {
13. new Worker().start();
14. }
15. }
Which two statements are true?
(Choose two.)
A Compilation fails.
B The program never terminates.
C The program runs with no output.
D The value ok is repeatedly
output.
E The program terminates and
outputs ok precisely once.
F The Worker thread never blocks
inside the wait method because there
are no other threads executing.
answer:
Options B and C are the correct
answers. This program simply
launches a single user thread that
immediately blocks inside the wait()
method The thread is never
unblocked because no other thread is
executing to call the notify on the
lock.
Reference:
The Java Programming Language,
Third Edition, by Arnold, Gosling &
Holmes, Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads > Objective
7.3 > Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
10. class X {
11. synchronized void iTest() {
12.
while(true) {
13.
Thread.yield();
14.
}
15. }
16. synchronized static void sTest()
{}
17. public void op() {}
18. }
And, given a single instance of
X, and two or more concurrent
threads, which statement is
true?
A Multiple threads can
execute iTest() concurrently.
B Any thread calling iTest()
will be blocked pending a call
to notify.
C While a thread is executing
iTest(), any call on sTest() will
block pending lock access.
D While a thread is executing
iTest(), no other threads may
execute any methods declared
in X.
E While a thread is executing
iTest(), op() may be
concurrently executed inside
the same instance of X.
Answer:
Option E is the correct answer.
Static methods synchronize on
the class object, not on an
instance object, so concurrent
calls to iTest() and sTest() will
not block each other. op() is
not synchronized so may be
called concurrently with
anything else.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.3 > Item 2
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. class WorkerT extends
java.lang.Thread {
2. private static StringBuffer
sb = new StringBuffer();
3. public void run() {
4.
notify();
5.
try {
6.
wait();
7.
} catch (Exception e) {}
8. }
9. public static void main(
String[] args ) {
10.
for (int i= 0;i<10; i++)
{
11.
new
WorkerT().start();
12.
}
13. }
14. }
Which statement is true?
A Compilation fails.
B All 10 threads block.
39
C An exception is thrown at
runtime.
D All 10 threads execute to
completion.
E Each thread is unlocked by
the following thread until only
the final thread remains blocked.
Answer:
Option C is the correct answer.
An exception is thrown
java.lang.IllegalMonitorStateExce
ption: current thread not owner.
The caller of wait(), notify(), or
notifyAll() must own the monitor
lock that is, they must be
executing inside a synchronized
method or section to be able to
successfully call any of these
methods.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.4 > Item 1
-----------------------------------------------------------------------------Which three statements are
true? (Choose three.)
A The Object class defines a
wait() method.
B
The Thread class overrides
a wait() method.
C
The Runnable interface
defines a wait() method.
D
wait() can be called at any
time by an executing thread.
E
The wait() method used in
thread communication releases
an object lock.
F
The wait() method is
overloaded and also has the
following signature public final
void wait(long timeout).
answer:
Options A, E, and F are the
correct answers.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.4 > Item 2
--------------------------------------- which two statements are
correct? (Choose two.)
A To call notify() a thread must
own the monitor lock.
B
The notify() and notifyAll()
methods are defined in the
Thread class.
C
The
notify() and
notifyAll() methods are defined in the
Object class.
D
A thread can only call notify() if
another thread has previously called
wait().
E
The notify() and notifyAll()
methods are defined in the Runnable
interface.
Answer:
Options A and C are the correct
answers.
Reference:
The Java Programming Language,
Third Edition, by Arnold, Gosling &
Holmes, Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Fundamental Classes
in the java.lang package > Objective
8.1 > Item 1
--------------------------------------Click the Exhibit button to view the
code.
1. public class Test813 {
2. public static void main(String []
args) {
3.
double a = Math.round(5.5);
4.
double b = Math.round(5.2);
5.
double c = Math.round(-5.0);
6.
double d = Math.round(-5.4);
7.
double e = Math.round(-5.5);
8.
System.out.print( "Results: " +
a+""+b+""+c+""+d+""
+ e);
9.
}
10. }
What is the result?
A Results: 6.0 5.0 -5.0 -5.0 -5.0
B Results: 6.0 5.0 -5.0 -5.0 -6.0
C Results: 5.0 5.0 -5.0 -5.0 -5.0
D Results: 6.0 5.0 -5.0 -4.0 -5.0
E Results: 6.0 5.0 5.0 5.0 6.0
F Compilation fails.
nswer:
Option A is the correct answer. Both
positive and negative numbers are
rounded up to the larger number. For
a positive number such as 5.5, the
greater number is 6, but for -5.5 the
greater number is -5.0.
Location: ... > Fundamental
Classes in the java.lang package >
Objective 8.2 > Item 1
-------------------------------------------- Click the Exhibit button to view
the code.
1. public class Test823 {
2. public static void main(String []
args) {
3.
String a = "freddy";
4.
String b = a.substring(0,3);
5.
b.toUpperCase();
6.
System.out.println(a += b);
7. }
8. }
What is the result?
A freddyFRE
B freddyfre
C freddyFRED
D freddyfred
E Compilation fails.
Answer:
Option B is the correct answer.
The a String reference is never
modified, and the
toUpperCase() call is not
assigned to b so b's original
object does not change.
Location: ... > Fundamental
Classes in the java.lang
package > Objective 8.2 >
Item 2
--------------------------------------Click the Exhibit button to
view the code.
1. public class Test825 {
2. public static void
main(String [] args) {
3.
String a = "big";
4.
String b = a;
5.
a = a + "bird";
6.
a = b;
7.
b = "bird";
8.
System.out.println(a =
a+b);
9. }
10. }
What is the result?
A bigbird
B birdbird
C bigbigbird
D bigbirdbird
E Compilation fails.
Answer:
Option A is the correct answer.
In line 4, b is set to refer to the
String literal "big". The String
referenced by b is not changed
by the change to a in line 5,
because Strings are
immutable. In line 5, a new
String object "bigbird" is
created, and assigned to a. At
this point (line 5) b is still
referring to "big" and a is now
referring to "bigbird". In line
6,then, a is set to refer to the
String literal "big" referenced
by b, so both a and b refer to
the String literal "big". In line
7, b is set to reference a String
literal "bird", while a is left
unchanged and still refers to
"big". Finally, a + b is printed
out, producing "bigbird".
Location: ... > Fundamental
Classes in the java.lang
40
package > Objective 8.3 > Item
1
-------------------------------------- Which creates a new
Character object?
A Character a = new
Character("c");
B
Character a =
Character.getCharacter('s');
C
Character a = new
Character(new char[]{'s'});
D
Character a =
Character.valueOf("c".toChar());
E Character a = new
Character((new char[]{'s'})[0]);
Answer:
Option E is the correct answer.
The Character class has only one
constructor, and it takes a char
primitive. Answer "E" constructs
an anonymous char array holding
a single char, then accesses the
array element at index 0, thus
returning a char to the Character
constructor.
Location: ... > Fundamental
Classes in the java.lang package
> Objective 8.3 > Item 2
--------------------------------------Click the Exhibit button to view
the code.
1. public class Test834 {
2. public static void main(String
[] args) {
3.
try {
4.
Double d = new
Double(new
Byte(6).doubleValue());
5.
String s = d.toString();
6.
System.out.println(Integer.parse
Int(s));
7.
}
catch(NumberFormatException
ex) {
8.
System.out.println("failed");
9.
}
10. }
11. }
What is the result?
A 6
B 6.0
C null
D failed
E Compilation fails.
F An uncaught exception is
thrown at runtime.
Answer:
Option E is the correct answer.
Byte does not have a constructor
that takes an int. The Byte
constructor must be passed a
previously declared byte
variable, or explicitly cast an int
value.
Location: ... > The Collections
Framework > Objective 9.1 > Item 1
-------------------------------------------- Which two statements are true
of class java.util.HashMap? (Choose
two.)
A Its methods are thread-safe.
B It allows null references to be
stored.
C It provides fast, bi-directional
iteration.
D It implements java.util.Hashable.
E It tracks when its elements were
last accessed.
F Its elements can be accesssed
using a unique key.
Answer:
Options B and F are the correct
answers. HashMap implements
java.util.Map, which allows elements
to be accessed using a unique key.
Whereas HashTable does not permit
null references to be stored,
HashMap allows both keys and
elements to be null.
Location: ... > The Collections
Framework > Objective 9.1 > Item 2
--------------------------------Click the Exhibit button to view the
code.
1. TreeSet s = new TreeSet();
2. s.add("Fred");
3. s.add("Mike");
4. s.add("Zeus");
5. s.add("Fred");
6. s.add("Amy");
7. Iterator i = s.iterator();
8. while(i.hasNext()) {
9.
System.out.print(i.next() + ",
");
10. }
What is the result?
A Fred, Mike, Zeus, Amy,
B Amy, Fred, Mike, Zeus,
C Fred, Mike, Zeus, Fred, Amy,
D Amy, Fred, Fred, Mike, Zeus,
E Five elements will be printed, but
the order is not guaranteed.
F Four elements will be printed, but
the order is not guaranteed.
Answer:
Option B is the correct answer. A
TreeSet is a Set, which eliminates
duplicates, so Fred only goes in once.
A TreeSet is sorted so the Strings
come out in alphabetical order
Location: ... > The Collections
Framework > Objective 9.2 > Item 1
--------------------------------------- If
class X implements hashcode() and
equals() correctly, and given two
instances (o1 and o2) of class X,
which two are true? (Choose two.)
A if o1.hashcode() and
o2.hashcode() are not the
same, then o1 and o2 must not
be equal
B o1.hashcode() and
o2.hashcode() might be the
same if o1 and o2 are
considered equal
C o1.hashcode() and
o2.hashcode() must be the
same if o1 and o2 are
considered equal
D if o1 and o2 are not equal,
then o1.hashcode() and
o2.hashcode() must not be the
same
Answer:
Options A and C are the correct
answers. Hashcode suggests
the likelihood of equality, while
equality requires that
hashcodes must be the same.
The rules for correct
implementation of hashcode
and equals require that if two
objects are equal, their
hashcodes MUST be the same.
If two objects are unequal,
however, they may still have
the same hashcode. So, object
equivalency guarantees
hashcode equivalency, but
hashcode equivalency does not
guarantee object equivalency.
Java Programmer
Certification Mock
Question 1)
What will happen when you
attempt to compile and run
this code?
abstract class Base{
abstract public void
myfunc();
public void another(){
System.out.println("Another
method");
}
}
public class Abs extends Base{
public static void
main(String argv[]){
Abs a = new Abs();
a.amethod();
}
public void myfunc(){
System.out.println("My Func");
}
public void amethod(){
myfunc();
41
}
}
1) The code will compile and run,
printing out the words "My Func"
2) The compiler will complain
that the Base class has non
abstract methods
3) The code will compile but
complain at run time that the
Base class has non abstract
methods
4) The compiler will complain
that the method myfunc in the
base class has no body, nobody
at all to looove it
System.out.println("Another
method");
}
}
public class Abs extends Base{
public static void main(String
argv[]){
Abs a = new Abs();
a.amethod();
}
public void myfunc(){
System.out.println("My
func");
}
Question 2)
What will happen when you
attempt to compile and run this
code?
public class MyMain{
public static void main(String
argv){
System.out.println("Hello
cruel world");
}
}
1) The compiler will complain
that main is a reserved word and
cannot be used for a class
2) The code will compile and
when run will print out "Hello
cruel world"
3) The code will compile but will
complain at run time that no
constructor is defined
4) The code will compile but will
complain at run time that main is
not correctly defined
Question 3)
Which of the following are Java
modifiers?
1)
2)
3)
4)
5)
public
private
friendly
transient
vagrant
Question 4)
What will happen when you
attempt to compile and run this
code?
class Base{
abstract public void
myfunc();
public void another(){
public void amethod(){
myfunc();
}
}
1) The code will compile and run,
printing out the words "My Func"
2) The compiler will complain that
the Base class is not declared as
abstract.
3) The code will compile but
complain at run time that the Base
class has non abstract methods
4) The compiler will complain that
the method myfunc in the base class
has no body, nobody at all to looove
it
Question 5)
Why might you define a method as
native?
1) To get to access hardware that
Java does not know about
2) To define a new data type such as
an unsigned integer
3) To write optimised code for
performance in a language such as
C/C++
4) To overcome the limitation of the
private scope of a method
Question 6)
What will happen when you attempt
to compile and run this code?
class Base{
public final void amethod(){
System.out.println("amethod");
}
}
public class Fin extends Base{
public static void main(String
argv[]){
Base b = new Base();
b.amethod();
}
}
1) Compile time error
indicating that a class with any
final methods must be declared
final itself
2) Compile time error
indicating that you cannot
inherit from a class with final
methods
3) Run time error indicating
that Base is not defined as final
4) Success in compilation and
output of "amethod" at run
time.
Question 7)
What will happen when you
attempt to compile and run
this code?
public class Mod{
public static void main(String
argv[]){
}
public static native void
amethod();
}
1) Error at compilation: native
method cannot be static
2) Error at compilation native
method must return value
3) Compilation but error at run
time unless you have made
code containing native
amethod available
4) Compilation and execution
without error
Question 8)
What will happen when you
attempt to compile and run
this code?
private class Base{}
public class Vis{
transient int iVal;
public static void
main(String elephant[]){
}
}
1)Compile time error: Base
cannot be private
2)Compile time error indicating
that an integer cannot be
transient
3)Compile time error transient
not a data type
42
4)Compile time error malformed
main method
Question 9)
What happens when you attempt
to compile and run these two
files in the same directory?
//File P1.java
package MyPackage;
class P1{
void afancymethod(){
System.out.println("What a
fancy method");
}
}
//File P2.java
public class P2 extends P1{
public static void main(String
argv[]){
P2 p2 = new P2();
p2.afancymethod();
}
}
1) Both compile and P2 outputs
"What a fancy method" when run
2) Neither will compile
3) Both compile but P2 has an
error at run time
4) P1 compiles cleanly but P2 has
an error at compile time
Question 10)
You want to find out the value of
the last element of an array. You
write the following code. What
will happen when you compile
and run it.?
public class MyAr{
public static void main(String
argv[]){
int[] i = new int[5];
System.out.println(i[5]);
}
}
1)
2)
3)
4)
An error at compile time
An error at run time
The value 0 will be output
The string "null" will be output
Question 11)
You want to loop through an
array and stop when you come
to the last element. Being a good
java programmer and forgetting
everything you ever knew about
C/C++ you know that arrays
contain information about their
size. Which of the following can
you use?
1)myarray.length();
2)myarray.length;
3)myarray.size
4)myarray.size();
component
3) Use the setLayoutManager
method
4) Use the updateLayout
method
Question 12)
Question 15)
What best describes the appearance
of an application with the following
code?
Which of the following are
fields of the
GridBagConstraints class?
import java.awt.*;
public class FlowAp extends Frame{
public static void main(String
argv[]){
FlowAp fa=new FlowAp();
fa.setSize(400,300);
fa.setVisible(true);
1)
2)
3)
4)
}
FlowAp(){
add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
}//End of constructor
}//End of Application
1) A Frame with buttons marked One
to Four placed on each edge.
2) A Frame with buutons marked
One to four running from the top to
bottom
3) A Frame with one large button
marked Four in the Centre
4) An Error at run time indicating you
have not set a LayoutManager
Question 13)
How do you indicate where a
component will be positioned using
Flowlayout?
1) North, South,East,West
2) Assign a row/column grid
reference
3) Pass a X/Y percentage parameter
to the add method
4) Do nothing, the FlowLayout will
position the component
ipadx
fill
insets
width
Question 16)
What most closely matches the
appearance when this code
runs?
import java.awt.*;
public class CompLay extends
Frame{
public static void main(String
argv[]){
CompLay cl = new
CompLay();
}
CompLay(){
Panel p = new Panel();
p.setBackground(Color.pink);
p.add(new Button("One"));
p.add(new Button("Two"));
p.add(new
Button("Three"));
add("South",p);
setLayout(new
FlowLayout());
setSize(300,300);
setVisible(true);
}
}
1) The buttons will run from
left to right along the bottom
of the Frame
2) The buttons will run from
left to right along the top of
the frame
3) The buttons will not be
displayed
4) Only button three will show
occupying all of the frame
Question 14)
Question 17)
How do you change the current
layout manager for a container
1) Use the setLayout method
2) Once created you cannot change
the current layout manager of a
Which statements are correct
about the anchor field?
1) It is a field of the
GridBagLayout manager for
43
controlling component placement
2) It is a field of the
GridBagConstraints class for
controlling component placement
3) A valid setting for the anchor
field is
GridBagConstraints.NORTH
4) The anchor field controls the
height of components added to a
container
Question 18)
What will happen when you
attempt to compile and run the
following code?
public class Bground extends
Thread{
public static void main(String
argv[]){
Bground b = new
Bground();
b.run();
}
public void start(){
for (int i = 0; i <10;
i++){
System.out.println("Value of i =
" + i);
}
}
}
1) A compile time error
indicating that no run method is
defined for the Thread class
2) A run time error indicating
that no run method is defined for
the Thread class
3) Clean compile and at run time
the values 0 to 9 are printed out
4) Clean compile but no output
at runtime
Question 19)
Is the following statement true
or false?
When using the GridBagLayout
manager, each new component
requires a new instance of the
GridBagConstraints class.
1) true
2) false
Question 20)
Which most closely matches a
description of a Java Map?
1) A vector of arrays for a 2D
geographic representation
2) A class for containing unique
array elements
3) A class for
containing unique vector elements
4) An interface that ensures that
implementing classes cannot contain
duplicate keys
3) To allow a thread of higher
priority to run
4) To call from the currently
running thread with a
parameter designating which
thread should be allowed to
run
Question 21)
Question 25)
How does the set collection deal with
duplicate elements?
What will happen when you
attempt to compile and run the
following code
1) An exception is thrown if you
attempt to add an element with a
duplicate value
2) The add method returns false if
you attempt to add an element with
a duplicate value
3) A set may contain elements that
return duplicate values from a call to
the equals method
4) Duplicate values will cause an
error at compile time
Question 22)
What can cause a thread to stop
executing?
public class Hope{
public static void
main(String argv[]){
Hope h = new
Hope();
}
protected Hope(){
for(int i =0; i <10; i
++){
System.out.println(i);
}
}
}
1) The program exits via a call to
System.exit(0);
2) Another thread is given a higher
priority
3) A call to the thread's stop method.
4) A call to the halt method of the
Thread class?
1) Compilation error:
Constructors cannot be
declared protected
2) Run time error:
Constructors cannot be
declared protected
3) Compilation and running
with output 0 to 10
4) Compilation and running
with output 0 to 9
Question 23)
Question 26)
For a class defined inside a method,
what rule governs access to the
variables of the enclosing method?
What will happen when you
attempt to compile and run the
following code
1) The class can access any variable
2) The class can only access static
variables
3) The class can only access
transient variables
4) The class can only access final
variables
public class MySwitch{
public static void main(String
argv[]){
MySwitch ms= new
MySwitch();
ms.amethod();
}
Question 24)
Under what circumstances might you
use the yield method of the Thread
class
public void amethod(){
int k=10;
switch(k){
default: //Put the default
at the bottom, not here
1) To call from the currently running
thread to allow another thread of the
same or higher priority to run
2) To call on a waiting thread to
allow it to run
System.out.println("This is the
default output");
break;
case 10:
44
Question 29)
System.out.println("ten");
case 20:
System.out.println("twenty");
break;
}
}
}
1) None of these options
2) Compile time error target of
switch must be an integral type
3) Compile and run with output
"This is the default output"
4) Compile and run with output
of the single line "ten"
What will happen when you attempt
to compile and run the following code
with the command line "hello there"
public class Arg{
String[] MyArg;
public static void main(String
argv[]){
MyArg=argv;
}
public void amethod(){
}
public class ExcepDemo
extends Base{
public static void
main(String argv[]){
ExcepDemo e = new
ExcepDemo();
}
public void amethod(){}
protected ExcepDemo(){
try{
DataInputStream
din = new
DataInputStream(System.in);
Question 27)
System.out.println(argv[1]);
}
}
System.out.println("Pausing");
din.readByte();
Which of the following is the
correct syntax for suggesting
that the JVM performs garbage
collection
1)
2)
3)
4)
System.out.println("Continuing
");
this.amethod();
}catch(IOException
ioe) {}
1) System.free();
2)
System.setGarbageCollection();
3) System.out.gc();
4) System.gc();
Question 30)
Question 28)
What will happen when you
attempt to compile and run the
following code
public class As{
int i = 10;
int j;
char z= 1;
boolean b;
public static void main(String
argv[]){
As a = new As();
a.amethod();
}
public void amethod(){
System.out.println(j);
System.out.println(b);
}
}
1) Compilation succeeds and at
run time an output of 0 and false
2) Compilation succeeds and at
run time an output of 0 and true
3) Compile time error b is not
initialised
4) Compile time error z must be
assigned a char value
Compile time error
Compilation and output of "hello"
Compilation and output of "there"
None of the above
What will happen when you attempt
to compile and run the following code
public class StrEq{
public static void main(String
argv[]){
StrEq s = new StrEq();
}
private StrEq(){
String s = "Marcus";
String s2 = new
String("Marcus");
if(s == s2){
System.out.println("we have a
match");
}else{
System.out.println("Not equal");
}
}
}
1) Compile time error caused by
private constructor
2) Output of "we have a match"
3) Output of "Not equal"
4) Compile time error by attempting
to compare strings using ==
Question 31)
What will happen when you attempt
to compile and run the following code
import java.io.*;
class Base{
public void amethod()throws
FileNotFoundException{}
}
}
1) Compile time error caused
by protected constructor
2) Compile time error caused
by amethod not declaring
Exception
3) Runtime error caused by
amethod not declaring
Exception
4) Compile and run with output
of "Pausing" and "Continuing"
after a key is hit
Question 32)
What will happen when you
attempt to compile and run
this program
public class Outer{
public String name = "Outer";
public static void main(String
argv[]){
Inner i = new Inner();
i.showName();
}//End of main
private class Inner{
String name =new
String("Inner");
void showName(){
System.out.println(name);
}
}//End of Inner class
}
1) Compile and run with output
of "Outer"
45
2) Compile and run with output
of "Inner"
3) Compile time error because
Inner is declared as private
4) Compile time error because of
the line creating the instance of
Inner
Question 33)
What will happen when you
attempt to compile and run this
code
//Demonstration of event
handling
import java.awt.*;
import java.awt.event.*;
public class MyWc extends Frame
implements WindowListener{
public static void main(String
argv[]){
MyWc mwc = new MyWc();
}
public void
windowClosing(WindowEvent
we){
System.exit(0);
}//End of
windowClosing
public void MyWc(){
setSize(300,300);
setVisible(true);
}
}//End of class
1) Error at compile time
2) Visible Frame created that
that can be closed
3) Compilation but no output at
run time
4) Error at compile time because
of comment before import
statements
Question 34)
Which option most fully describes
will happen when you attempt to
compile and run the following
code
public class MyAr{
public static void main(String
argv[]) {
MyAr m = new MyAr();
m.amethod();
}
public void amethod(){
static int i;
System.out.println(i);
}
}
1) Compilation and output of the
value 0
2) Compile time
error because i
has not been initialized
3) Compilation and output of null
4) Compile time error
Question 35)
Which of the following will compile
correctly
1) short myshort = 99S;
2) String name = 'Excellent tutorial
Mr Green';
3) char c = 17c;
4)int z = 015;
1) At the root of the collection
hierarchy is a class called
Collection
2) The collection interface
contains a method called
enumerator
3) The interator method
returns an instance of the
Vector class
4) The Set interface is
designed for unique elements
Question 40)
Which of the following
statements are correct?
Question 36)
What will be output by the following
line?
1) If multiple listeners are
added to a component only
events for the last listener
added will be processed
2) If multiple listeners are
added to a component the
events will be processed for all
but with no guarantee in the
order
3) Adding multiple listeners to
a comnponent will cause a
compile time error
4) You may remove as well add
listeners to a component.
System.out.println(Math.floor(-2.1));
Question 41)
1)
2)
3)
4)
Given the following code
Which of the following are Java key
words
1)double
2)Switch
3)then
4)instanceof
Question 37)
-2
2.0
-3
-3.0
Question 38)
Given the following main method in a
class called Cycle and a command
line of
java Cycle one two
what will be output?
public static void main(String
bicycle[]){
System.out.println(bicycle[0]);
}
1)
2)
3)
4)
None of these options
cycle
one
two
Question 39)
Which of the following statements
are true?
class Base{}
public class MyCast extends
Base{
static boolean b1=false;
static int i = -1;
static double d = 10.1;
public static void
main(String argv[]){
MyCast m = new
MyCast();
Base b = new Base();
//Here
}
}
Which of the following, if
inserted at the comment
//Here will allow the code to
compile and run without error
1)
2)
3)
4)
b=m;
m=b;
d =i;
b1 =i;
46
Question 42)
Which of the following
statements about threading are
true
1) You can only obtain a
mutually exclusive lock on
methods in a class that extends
Thread or implements runnable
2) You can obtain a mutually
exclusive lock on any object
3) A thread can obtain a
mutually exclusive lock on an
object by calling a synchronized
method on that object.
4) Thread scheduling algorithms
are platform dependent
Question 43)
Your chief Software designer has
shown you a sketch of the new
Computer parts system she is
about to create. At the top of the
hierarchy is a Class called
Computer and under this are two
child classes. One is called
LinuxPC and one is called
WindowsPC.
The main difference between the
two is that one runs the Linux
operating System and the other
runs the Windows System (of
course another difference is that
one needs constant re-booting
and the other runs reliably).
Under the WindowsPC are two
Sub classes one called Server
and one Called Workstation. How
might you appraise your
designers work?
1) Give the goahead for further
design using the current scheme
2) Ask for a re-design of the
hierarchy with changing the
Operating System to a field
rather than Class type
3) Ask for the option of
WindowsPC to be removed as it
will soon be obsolete
4) Change the hierarchy to
remove the need for the
superfluous Computer Class.
Question 44)
Which of the following
statements are true
1) An inner class may be defined
as static
2) There are NO circumstances
where an inner
class may be
defined as private
3) A programmer may only provide
one constructor for an anonymous
class
4) An inner class may extend
another class
Question 48)
Given the following variables
Question 45)
char c = 'c';
int i = 10;
double d = 10;
long l = 1;
String s = "Hello";
What will happen when you attempt
to compile and run the following code
Which of the following will
compile without error?
int Output=10;
boolean b1 = false;
if((b1==true) &&
((Output+=10)==20)){
System.out.println("We are equal
"+Output);
}else
{
System.out.println("Not equal!
"+Output);
}
1)c=c+i;
2)s+=i;
3)i+=s;
4)c+=s;
Question 49)
Which of the following will
compile without error?
1) Compile error, attempting to
peform binary comparison on logical
data type
2) Compilation and output of "We are
equal 10"
3) Compilation and output of "Not
equal! 20"
4) Compilation and output of "Not
equal! 10"
1) File f = new
File("/","autoexec.bat");
2) DataInputStream d = new
DataInputStream(System.in);
3) OutputStreamWriter o =
new
OutputStreamWriter(System.o
ut);
4) RandomAccessFile r = new
RandomAccessFile("OutFile");
Question 46)
Question 50)
Given the following variables which
of the following lines will compile
without error?
Given the folowing classes
which of the following will
compile without error?
String s = "Hello";
long l = 99;
double d = 1.11;
int i = 1;
int j = 0;
1) j= i <<s;
interface IFace{}
class CFace implements
IFace{}
class Base{}
public class ObRef extends
Base{
public static void
main(String argv[]){
ObRef ob = new ObRef();
Base b = new Base();
Object o1 = new
Object();
IFace o2 = new CFace();
}
}
1)o1=o2;
2)b=ob;
3)ob=b;
4)o1=b;
2) j= i<<j;
3) j=i<<d;
4)j=i<<l;
Question 47)
What will be output by the following
line of code?
System.out.println(010|4);
Question 51)
1)
2)
3)
4)
14
0
6
12
Given the following code what
will be the output?
47
class ValHold{
public int i = 10;
}
can be legally
comment line
//Here ?
public class ObParm{
public static void main(String
argv[]){
ObParm o = new
ObParm();
o.amethod();
}
public void amethod(){
int i = 99;
ValHold v = new
ValHold();
v.i=30;
another(v,i);
System.out.print( v.i
);
}//End of amethod
class Base{
public Base(int i){}
}
public void another(ValHold
v, int i){
i=0;
v.i = 20;
ValHold vh = new
ValHold();
v = vh;
System.out.print(v.i);
System.out.print(i);
}//End of another
placed after the
public class MyOver extends Base{
public static void main(String arg[]){
MyOver m = new
MyOver(10);
}
MyOver(int i){
super(i);
}
MyOver(String s, int i){
this(i);
//Here
}
}
1)MyOver m = new MyOver();
2)super();
3)this("Hello",10);
4)Base b = new Base(10);
Question 54)
}
1)
2)
3)
4)
10030
20030
209930
10020
Given the following class definition,
which of the following statements
would be legal after the comment
//Here
class InOut{
Question 52)
Given the following class
definition, which of the following
methods could be legally placed
after the comment
//Here
public class Rid{
public void amethod(int i,
String s){}
//Here
}
1)public void amethod(String s,
int i){}
2)public int amethod(int i, String
s){}
3)public void amethod(int i,
String mystring){}
4) public void Amethod(int i,
String s) {}
String s= new String("Between");
public void amethod(final int
iArgs){
int iam;
class Bicycle{
public void
sayHello(){
//Here
}
}//End of bicycle class
}//End of amethod
public void another(){
int iOther;
}
yield()
sleep(long msec)
go()
stop()
Question 56)
Which of the following methods
are members of the Vector
class and allow you to input a
new element
1)
2)
3)
4)
addElement
insert
append
addItem
Question 57)
Which of the following
statements are true?
1) Adding more classes via
import statements will cause a
performance overhead, only
import classes you actually
use.
2) Under no circumstances can
a class be defined with the
private modifier
3) A inner class may under
some circumstances be defined
with the protected modifier
4) An interface cannot be
instantiated
Question 58)
Which of the following are
correct event handling
methods
1) mousePressed(MouseEvent
e){}
2) MousePressed(MouseClick
e){}
3) functionKey(KeyPress k){}
4)
componentAdded(ContainerEve
nt e){}
Question 59)
}
1)
2)
3)
4)
1)
2)
3)
4)
System.out.println(s);
System.out.println(iOther);
System.out.println(iam);
System.out.println(iArgs);
Question 53)
Question 55)
Given the following class
definition which of the following
Which of the following are methods
of the Thread class?
Which of the following are
methods of the Collection
interface?
1) iterator
2) isEmpty
3) toArray
4) setText
48
Question 60)
Objective 1.2)
Which of the following best
describes the use of the
synchronized keyword?
2) The compiler will complain that
the Base class is not declared as
abstract.
1) Allows two process to run in
paralell but to communicate with
each other
2) Ensures only one thread at a
time may access a method or
object
3) Ensures that two or more
processes will start and end at
the same time
4) Ensures that two or more
Threads will start and end at the
same time
If a class contains abstract methods
it must itself be declared as abstract
Answers
Answer 1)
Objective 1.2)
1) The code will compile and run,
printing out the words "My Func"
A class that contains an abstract
method must be declared
abstract itself, but may contain
non abstract methods.
Answer 2)
Objective 4.1)
4) The code will compile but will
complain at run time that main is
not correctly defined
In this example the parameter is
a string not a string array as
needed for the correct main
method
Answer 10)
Objective 4.2)
2) An error at run time
Answer 5)
Objective 1.2)
1) To get to access hardware that
Java does not know about
3) To write optimised code for
performance in a language such as
C/C++
Answer 6)
Objective 1.2)
4) Success in compilation and output
of "amethod" at run time.
A final method cannot be ovverriden
in a sub class, but apart from that it
does not cause any other
restrictions.
Answer 7)
Objective 1.2)
4) Compilation and execution without
error
It would cause a run time error if you
had a call to amethod though.
Answer 8)
Objective 1.2)
1)Compile time error: Base cannot
be private
Answer 3)
Objective 4.3)
compile P2 an error occurs
indicating that superclass P1
cannot be found.
A top leve (non nested) class cannot
be private.
This code will compile, but at
run-time you will get an
ArrayIndexOutOfBounds
exception. This becuase
counting in Java starts from 0
and so the 5th element of this
array would be i[4].
Remember that arrays will
always be initialized to default
values wherever they are
created.
Answer 11)
Objective 1.1)
2)myarray.length;
The String class has a length()
method to return the number
of characters. I have
sometimes become confused
between the two.
Answer 12)
Objective 8.2)
3) A Frame with one large
button marked Four in the
Centre
The default layout manager for
a Frame is the BorderLayout
manager. This Layout manager
defaults to placing components
in the centre if no constraint is
passed with the call to the add
method.
Answer 13)
1) public
2) private
4) transient
Answer 9)
The keyword transient is easy to
forget as is not frequently used.
Although a method may be
considered to be friendly like in
C++ it is not a Java keyword.
4) P1 compiles cleanly but P2 has an
error at compile time
nswer 4)
Objective 8.2)
Objective 1.2)
4) Do nothing, the FlowLayout
will position the component
Answer 14)
The package statement in P1.java is
the equivalent of placing the file in a
different directory to the file P2.java
and thus when the compiler tries to
Objective 8.2)
1) Use the setLayout method
49
Answer 15)
Objective 10.1)
nswer 25)
Objective 8.2)
4) An interface that ensures that
implementing classes cannot contain
duplicates
Objective 6.2)
1) ipadx
2) fill
3) insets
Answer 21)
4) Compilation and running
with output 0 to 9
Answer 16)
Objective 10.1)
Answer 26)
Objective 8.2)
2) The add method returns false if
you attempt to add an element with
a duplicate value
Objective 2.1)
I find it a surprise that you do not
get an exception.
Because of the lack of a break
statement after the break 10;
statement the actual output
will be
2) The buttons will run from left
to right along the top of the
frame
The call to the setLayout(new
FlowLayout()) resets the Layout
manager for the entire frame and
so the buttons end up at the top
rather than the bottom.
wer 17)
Objective 8.2)
2) It is a field of the
GridBagConstraints class for
controlling component placement
3) A valid settting for the anchor
field is
GridBagconstraints.NORTH
nswer 18)
Objective 7.1)
4) Clean compile but no output
at runtime
This is a bit of a sneaky one as I
have swapped around the names
of the methods you need to
define and call when running a
thread. If the for loop were
defined in a method called public
void run() and the call in the
main method had been to
b.start() The list of values from 0
to 9 would have been output.
Answer 22)
Objective 7.1)
1) The program exits via a call to
exit(0);
2) The priority of another thread is
increased
3) A call to the stop method of the
Thread class
Answer 20)
Answer 27)
Objective 3.1)
4) System.gc();
Note that this question asks what
can cause a thread to stop executing,
not what will cause a thread to stop
executing. Java threads are
somewhat platform dependent and
you should be carefull when making
assumptions about Thread priorities.
On some platforms you may find that
a Thread with higher priorities gets
to "hog" the processor. You can read
up on this in more detail at
Objective 4.4)
Answer 23)
Objective 1.2)
Objective 4.1)
1) Compile time error
4) The class can only access final
variables
You will get an error saying
something like "Cant make a
static reference to a non static
variable". Note that the main
method is static. Even if main
was not static the array argv is
local to the main method and
would thus not be visible within
amethod.
Answer 24)
Objective 7.1)
1) To call from the currently running
thread to allow another thread of the
same or higher priority to run
2) false
You can re-use the same
instance of the
GridBagConstraints when added
successive components.
"ten" followed by "twenty"
Answer 28)
Answer 19)
Objective 8.2)
1) None of these options
Option 3 looks plausible but there is
no guarantee that the thread that
grabs the cpu time will be of a higher
priority. It will depend on the
threading algorithm of the Java
Virtual Machine and the underlying
operating system
1) Compilation succeeds and at
run time an output of 0 and
false
The default value for a boolean
declared at class level is false,
and integer is 0;
Answer 29)
Answer 30)
Objective 5.2)
3) Output of "Not equal"
Despite the actual character
strings matching, using the ==
operator will simply compare
50
memory location. Because the
one string was created with the
new operator it will be in a
different location in memory to
the other string.
but not produce
output is ment to
mislead on the basis that what looks
like a constructor is actually an
ordinary method as it has a return
type.
nswer 31)
Answer 34)
Objective 2.3)
Objective 1.2)
4) Compile and run with output
of "Pausing" and "Continuing"
after a key is hit
4) Compile time error
An overriden method in a sub
class must not throw Exceptions
not thrown in the base class. In
the case of the method amethod
it throws no exceptions and will
thus compile without complain.
There is no reason that a
constructor cannot be protected.
An error will be caused by attempting
to define an integer as static within a
method. The lifetime of a field within
a method is the duration of the
running of the method. A static field
exists once only for the class. An
approach like this does work with
Visual Basic.
Objective 10.1)
4) The Set is designed for
unique elements.
Collection is an interface, not a
class. The Collection interface
includes a method called
iterator. This returns an
instance of the Iterator class
which has some similarities
with Enumerators.
The name set should give away
the purpose of the Set
interface as it is analogous to
the Set concept in relational
databases which implies
uniquness.
Answer 40)
Answer 35)
Objective 8.1)
Answer 32)
Objective 4.5)
Objective 6.3)
4)int z = 015;
4) Compile time error because of
the line creating the instance of
Inner
The letters c and s do not exist as
literal indicators and a String must
be enclosed with double quotes, not
single as in this case.
2) If multiple listeners are
added to a component the
events will be processed for all
but with no guarantee in the
order
4) You may remove as well add
listeners to a component.
This looks like a question about
inner classes but it is also a
reference to the fact that the
main method is static and thus
you cannot directly access a non
static method. The line causing
the error could be fixed by
changing it to say
Inner i = new Outer().new
Inner();
Then the code would compile and
run producing the output "Inner"
Answer 33)
Objective 4.6)
1) Error at compile time
If you implement an interface
you must create bodies for all
methods in that interface. This
code will produce an error saying
that MyWc must be declared
abstract because it does not
define all of the methods in
WindowListener. Option 4 is
nonsense as comments can
appear anywhere. Option 3
suggesting that it might compile
Answer 36)
Objective 4.3)
1)double
4)instanceof
Note the upper case S on switch
means it is not a keyword and the
word then is part of Visual Basic but
not Java. Also, instanceof looks like a
method but is actually a keyword,
It ought to be fairly intuitive
that a component ought to be
able to have multiple listeners.
After all, a text field might
want to respond to both the
mouse and keyboard
nswer 41)
Objective 5.1)
1) b=m;
3) d =i;
4) -3.0
You can assign up the
inheritance tree from a child to
a parent but not the other way
without an explicit casting. A
boolean can only ever be
assigned a boolean value.
nswer 38)
Answer 42)
Objective 4.2)
Objective 7.3)
3) one
2) You can obtain a mutually
exclusive lock on any object
3) A thread can obtain a
mutually exclusive lock on an
object by calling a
synchronized method on that
object.
4) Thread scheduling
Answer 37)
Objective 9.1)
Command line parameters start from
0 and from the first parameter after
the name of the compile (normally
Java)
nswer 39)
51
algorithms are platform
dependent
Yes that says dependent and not
independent.
Answer 43)
Objective 6.1)
2) Ask for a re-design of the
hierarchy with changing the
Operating System to a field
rather than Class type
This question is about the
requirement to understand the
difference between the "is-a" and
the "has-a" relationship. Where a
class is inherited you have to ask
if it represents the "is-a"
relationship. As the difference
between the root and the two
children are the operating
system you need to ask are
Linux and Windows types of
computers.The answer is no,
they are both types of Operating
Systems. So option two
represents the best of the
options. You might consider
having operating system as an
interface instead but that is
another story.
Of course there are as many
ways to design an object
hierarchy as ways to pronounce
Bjarne Strousjoup, but this is the
sort of answer that Sun will
proabably be looking for in the
exam. Questions have been
asked in discussion forums if this
type of question really comes up
in the exam. I think this is
because some other mock exams
do not contain any questions like
this. I assure you that this type
of question can come up in the
exam. These types of question
are testing your understanding of
the difference between the is-a
and has-a relationship in class
design.
nested class.
There is some
debate if such a class should be
called an inner class. I tend to think
it should be on the basis that it is
created inside the opening braces of
another class. How could a
programmer provide a constructor
for an anonymous class?. Remember
a constructor is a method with no
return type and the same name as
the class. Inner classes may be
defined as private
Answer 45)
Objective 5.3)
4) Compilation and output of "Not
equal! 10"
The output will be "Not equal 10".
This illustrates that the Output +=10
calculation was never performed
because processing stopped after the
first operand was evaluated to be
false. If you change the value of b1
to true processing occurs as you
would expect and the output is "We
are equal 20";.
Answer 46)
Objective 5.1)
2)j= i<<j;
4)j=i<<l;
Answer 47)
Objective 5.3)
4) 12
As well as the binary OR objective
this questions requires you to
understand the octal notation which
means that the leading letter zero
(not the letter O)) means that the
first 1 indicates the number contains
one eight and nothing else. Thus this
calculation in decimal mean
1100
---Which is 12 in decimal
The | bitwise operator means
that for each position where
there is a 1, results in a 1 in
the same position in the
answer.
Answer 48)
Objective 5.1)
2)s+=i;
Only a String acts as if the +
operator were overloaded
Answer 49)
Objective 10.1)
Although the objectives do not
specifically mention the need
to understand the I/O Classes,
feedback from people who
have taken the exam indicate
that you will get questions on
this topic. As you will probably
need to know this in the real
world of Java programming,
get familiar with the basics. I
have assigned these questions
to Objective 10.1 as that is a
fairly vague objective.
1) File f = new
File("/","autoexec.bat");
2) DataInputStream d = new
DataInputStream(System.in);
3) OutputStreamWriter o =
new
OutputStreamWriter(System.o
ut);
nswer 44)
8|4
Option 4, with the
RandomAccess file will not
compile because the
constructor must also be
passed a mode parameter
which must be either "r" or
"rw"
Objective 4.1)
To convert this to binary means
Answer 50)
1) An inner class may be defined
as static
4) An inner class may extend
another class
1000
Objective 5.1)
0100
1)o1=o2;
----
2)b=ob;
A static inner class is also
sometimes known as a top level
52
Objective 7.2)
4)o1=b;
Answer 51)
Objective 5.4)
4) 10020
In the call
another(v,i);
A reference to v is passed and
thus any changes will be intact
after this call.
nswer 52)
Objective 6.2)
1) public void amethod(String s,
int i){}
4) public void Amethod(int i,
String s) {}
Overloaded methods are
differentiated only on the
number, type and order of
parameters, not on the return
type of the method or the names
of the parameters.
Answer 53)
1) yield()
2) sleep
4) stop()
Note, the methods stop and suspend
have been deprecated with the Java2
release, and you may get questions
on the exam that expect you to know
this. Check out the Java2 Docs for an
explanation
Any call to this or super must be
the first line in a constructor. As
the method already has a call to
this, no more can be inserted.
Objective 4.1)
1) System.out.println(s);
4) System.out.println(iArgs);
A class within a method can only
see final variables of the
enclosing method. However it the
normal visibility rules apply for
variables outside the enclosing
method.
Answer 55)
class A {
protected int i;
A(int i) {
Answer 56)
Objective 10.1)
1) addElement
}
}
Answer 57)
Which of the following would
be a valid inner class for this
class?
Objective 4.1)
Select all valid answers.
The import statement allows you to
use a class directly instead of fully
qualifying it with the full package
name, adding more classess with the
import statement does not cause a
runtime performance overhad. I
assure you this is true. An inner class
can be defined with the protected
modifier, though I am not certain
why you would want to do it. An
inner class can be defined with the
private modifier, try compiling some
sample code before emailing me to
ask about this.
a)
3)A inner class may under some
circumstances be defined with the
protected modifier
4) An interface cannot be
instantiated
class B {
class B {
}
b)
class B extends A {
}
c)
B() {
System.out.println("i = " +
i);
Answer 58)
}
Objective 4.6)
nswer 54)
Question 1: Given the
following class definition:
this.i = i;
Objective 6.2)
4)Base b = new Base(10);
2) Ensures only one thread at
a time may access a method or
object
1) mousePressed(MouseEvent e){}
4) componentAdded(ContainerEvent
e){}
}
d)
class B {
Answer 59)
class A {
Objective 10.1)
1) iterator
2) isEmpty
3) toArray
Answer 60)
Objective 7.3)
}
}
e)
class A {
}
53
Question 2: What statements
are true concerning the
method notify() that is used
in conjunction with wait()?
e) 0
public void run() {
for (int i = startHere; i <=
endHere; i++) {
Select all valid answers.
System.out.println(i);
a) if there is more than one
thread waiting on a condition,
only the thread that has been
waiting the longest is notified
b) if there is more than one
thread waiting on a
condition,there is no way to
predict which thread will be
notifed
}
};
public static void
main(String[] args) {
t.start();
}
b)
c) notify() is defined in the
Thread class
public void run() {
for (int i = startHere; i <=
endHere; i++) {
System.out.println(i);
e) notify() should only be
invoked from within a while loop
Question 3: Given the
following class:
class Counter {
Thread t = new
Thread(new
CounterBehavior());
}
a implements Runnable {
d) it is not strictly necessary to
own the lock for the object you
invoke notify() for
Question 5: Given the
following class:
}
}
Which of the following is a
valid definition of
CounterBehavior that would
make Counter’s main() method
count from 1 to 100, counting
once per second?
Select the one right answer.
}
a)This class is an inner class to
Counter:
};
class Counter {
public int startHere = 1;
public int endHere = 100;
public static void main(String[]
args) {
new Counter().go();
class CounterBehavior {
c)
Thread a = new Thread() {
for (int i = 1; i <= 100;
i++);
public void run() {
try {
for (int i = startHere; i <=
endHere; i++) {
}
System.out.println(i);
Thread.sleep(1000);
System.out.println(i);
void go() {
// A
Thread t = new Thread(a);
t.start();
}
}
}
};
Question 4: What is written to
the standard output given the
following statement:
}
System.out.println(4 | 7);
What block of code can you
replace at line A above so that
this program will count from
startHere to endHere?
Select the one right answer.
Select all valid answers.
a)
Runnable a = new Runnable() {
} catch
(InterruptedException x) {}
}
}
b) This class is an inner class
to Counter:
a) 4
class CounterBehavior
implements Runnable {
b) 5
public void run() {
c) 6
d) 7
for (int i = 1; i <= 100;
i++);
try {
54
BufferedReader buffer = new
BufferedReader(reader);
System.out.println(i);
Thread.sleep(1000);
class D extends A {
} catch
(InterruptedException x) {}
public float z;
}
}
What can method2() access directly,
without a reference to another
instance?
public void run() {
try {
for (int i = 1; i <= 100;
i++) {
System.out.println(i);
Thread.sleep(1000);
}
} catch
(InterruptedException x) {}
Select all valid answers.
d)
a) the variable x defined in A
InputStreamReader reader =
new
InputStreamReader(myfile);
b) the variable y defined in A
c) method1 defined in B
BufferedReader buffer = new
BufferedReader(reader);
d) the variable z defined in D
s = buffer.readLine();
Question 7: You have an 8-bit file
using the character set defined
by ISO 8859-8. You are writing
an application to display this file
in a TextArea. The local encoding
is already set to 8859-8. How can
you write a chunk of code to read
the first line from this file?
e)
}

Question 6: Given the
following class definition:

class A {

public int x;
private int y;
class B {
protected void method1() {
}
myfile is the name of the file
you want to read
stream is an InputStream
object associated with this
file
s is a String object
Select all valid answers.
a)
Question 8: How can you
write a line of code for an
applet’s init() method that
determines how wide the
applet is?
Select all valid answers.
a) int width = this.getY();
b) int width = this.getSize().w;
c) int width = getSize();
d) int width = getSize().w;
private void method2() {
BufferedReader buffer = new
BufferedReader(reader);
}
s = buffer.readLine();
Question 9: For a variable
width font, how "wide" is a
TextField created using the
expression:
class C {
}
BufferedReader buffer = new
BufferedReader(reader);
InputStreamReader reader = new
InputStreamReader(stream, "88598");
}
}
FileReader reader = new
FileReader(myfile);
s = buffer.readLine();
You have three variables accessible
to you:
}
BufferedReader buffer = new
BufferedReader(reader);
s = buffer.readLine();
c) This class is a top-level class:
static class CounterBehavior
implements Runnable {
c)
InputStreamReader reader =
new
InputStreamReader(myfile,
"8859-8");
}
}
s = buffer.readLine();
b)
InputStreamReader reader = new
InputStreamReader(stream);
e) int width = getWidth();
new TextField(20)
Select the one right answer.
55
a) 20 times the average of all the
characters in the font used for
this TextField object
b) 20 times the width of the
letter M
c) 20 times the width of the
letter a
d) 20 inches
e) 20 picas
Question 10: Given this
interface definition:
interface A {
int method1(int i);
int method2(int j);
}
which of the following classes
implement this interface and is
not abstract?
Select all valid answers.
a)
class B implements A {
int method1() { }
import
java.awt.event.*;
public class MyApplet extends
java.applet.Applet {
public void init() {
Button b = new
Button("Button1");
b.addMouseListener(new
ClickHandler());
add(b);
}
class ClickHandler extends
MouseAdapter {
public void
mouseClicked(MouseEvent evt) {
// A
}
}
}
What line of code at A writes the
mouse’s horizontal location to the
standard output at the time of the
event?
Fill in the blank.
Question 12: Given the same
code as in question 10, how can
you write a line of code at A that
will place the Button object into a
variable named mybutton that is
already defined to be a reference
to a Button object?
Fill in the blank.
int method2() { }
}
b)
class B {
int method1(int i) { }
int method2(int j) { }
}
c)
class B implements A {
int method1(int i) { }
int method2(int j) { }
}
d)
class B extends A {
int method1(int i) { }
int method2(int j) { }
}
e)
class B implements A {
int method2(int j) { }
int method1(int i) { }
}
Question 11: Given the
following code:
import java.awt.*;
Question 13: Which Listener
interface can you implement to
be able to respond to the user
hitting the enter key after typing
into a TextField object?
Question 14: What is written to
the standard output as the result
of executing the following
statements?
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean(true);
if (b1 == b2)
if (b1.equals(b2))
System.out.println("a");
else
System.out.println("b");
else
if (b1.equals(b2))
System.out.println("c");
else
System.out.println("d");
)a
b) b
c) c
d) d
Question 15: Which Listener
interfaces can you add to a
TextArea object?
a) TextListener
b) ActionListener
c) MouseMotionListener
d) MouseListener
e) ComponentListener
Question 16: What appears
in the standard output if the
method named problem() in
the code below throws an
instance of class Exception
when the method named
trythis() is invoked?
public void trythis() {
try {
System.out.println("1");
problem();
} catch (RuntimeException
x) {
System.out.println("2");
return;
} catch (Exception x) {
System.out.println("3");
return;
} finally {
System.out.println("4");
}
System.out.println("5");
}
elect all valid answers.
a) "1"
b) "2"
c) "3"
d) "4"
e) "5"
56
Question 17: What is the type
of the Event object passed to
the mouseDragged() method
defined in a class that
implements
java.awt.event.MouseMotionL
istener (that is, what is the
class name for the
argument)?
estion 18: Examine the
following switch block:
char mychar = 'c';
switch (mychar) {
default:
case 'a':
System.out.println("a"); break;
case 'b':
System.out.println("b"); break;
}
a) This line of
code is illegal.
b) s is a two-dimensional array
containing 10 rows and 10 columns
e) static void main(String[]
args)
c) s is an array of 10 arrays.
Question 23: Which of the
following identifiers are
ILLEGAL?
d) Each element in s is set to ""
e) Each element in s is uninitialized
and must be initialized before it is
referenced.
uestion 21: What will happen if
you try to compile and run the
following class?
class Test {
static int myArg = 1;
public static void main(String[]
args) {
int myArg;
Which of the following questions
are definitely true?
}
a) This switch block is illegal,
because only integers can be
used in the switch statement.
}
b) This switch block is fine.
a) This code compiles and displays 0
in the standard output when run.
d) When this code runs, nothing
is written to the standard output.
e) When this code runs, the
letter "a" is written to the
standard output.
uestion 19: What keyword
must appear in a method
declaration (followed by the
name of the exception) when
that method might cause an
exception to be thrown and
that method does not handle
the exception?
Question 20: Which
statements accurately
describe the following line of
code?
Select all valid answers.
String[][] s = new String[10][];
Select all valid answers.
a) #_pound
b) _underscore
c) 5Interstate
d) Interstate5
Question 24: If the user
invokes a stand-alone
application by typing:
java YourApp 1 2 3
and the main() method defines
its String[] parameter as args,
how can you access the
number 2 using args?
System.out.println(myArg);
Select all valid answers.
c) This switch block is illegal,
because the default statement
must come last.
d) static public int
main(String[] args)
Select the one right answer.
b) This code compiles and displays 1
in the standard output when run.
Fill in the blank.
Question 25: Which interface
implementations can you add
as listeners for a TextField
object?
Select all valid answers.
a) ActionListener
b) FocusListener
c) This code does not compile
because you cannot define a local
variable named the same as a static
variable.
c) MouseMotionListener
d) This code does not compile
because the local variable is used
before it is initialized.
e) ContainerListener
Question 22: Which declarations
for the main() method in a standalone program are NOT valid?
Select all valid answers.
a) public static void main()
b) public static void main(String[]
string)
d) WindowListener
Question 26: What must be
true for the RunHandler
class so that instances of
RunHandler can be used as
written in the code below:
class Test {
public static void
main(String[] args) {
Thread t = new
Thread(new RunHandler());
t.start();
c) public static void main(String
args)
}
}
57
Select all valid answers.
double k = 3.2;
a) RunHandler must implement
the java.lang.Runnable interface.
if (i < k)
if (i == j)
b) RunHandler must extend the
Thread class.
c) RunHandler must provide a
run() method declared as public
and returning void.
System.out.println(i);
else
System.out.println(j);
import java.awt.*;
public class MyApplet extends
Applet {
Button b1, b2;
public void init() {
ActionListener a = new
ActionListener() {
public void
actionPerformed(ActionEvent
evt) {
if (evt.getSource() ==
b1) {
else
d) RunHandler must provide an
init() method.
Question 27: To determine if
you can invoke
addContainerListener() for a
component referenced using
a variable named c, which
expression(s) can you
evaluate that will give you a
true or false answer to this
questions?
System.out.println(k);
Select the one right answer.
a) 3
b) 0
c) 3.2
d) none of these
Select all valid answers.
a) c == Container
b) c.equals(Class.Container)
c) c instanceof Container
d) c instanceof Component
e) c implements Container
Question 28: Write a
statement for a constructor
that invokes the no-args,
default constructor in its
superclass.
Question 29: What is written
to the standard output given
the following statement:
System.out.println(4 & 7);
Select the one right answer.
a) 4
b) 5
c) 6
d) 7
e) 0
Question 30: What will the
following block of code write
to the standard output when
it is executed?
Question 31: How can you use
the String method indexOf() to
determine which position the
letter 'C' is in given this String:
String s = "ABCDE";
Write a complete statement in your
answer, but you do not have to
assign the letter you retrieve to
another variable.
Question 32: Given that the
variable g references a valid
Graphics object, what does the
following statement do?
g.fillRect(2, 3, 10, 20);
Select all valid answers.
a) draw the outline of a rectangle in
the current background color
b) draw the outline of a rectangle in
the current foreground color
b1.setEnabled(false);
b2.setEnabled(true);
} else {
b1.setEnabled(true);
b2.setEnabled(false);
}
}
};
b1 = new Button("1");
b1.addActionListener(a);
add(b1);
b2 = new Button("2");
b2.addActionListener(a);
add(b2);
}
}
lect all valid answers.
a) Nothing appears in the
applet
b) One button appears in the
applet but does nothing
c) Two buttons appear in the
applet
d) When the user clicks a
button, nothing happens
e) When the user clicks a
button, it becomes disabled
f) When a user clicks a button,
the other button becomes
enabled
c) fill in a rectangle using the current
background color
Question 34: The method
setBackground() defined
for the Graphics class:
d) fill in a rectangle using the current
foreground color
Select all valid answers.
e) fill in a rectangle in black
int i = 3;
Question 33: Describe the
following applet.
int j = 0;
import java.applet.Applet;
import java.awt.event.*;
a) takes an integer value
b) takes an instance of class
Color
c) takes an instance of a
Component subclass
58
d) sets the drawing mode for the
associated Component object
e) sets the drawing color for the
associated Component object
f) changes the background color
for the associated Component
object
Question 35: What does the
following program do when it
is run with the command:
java Mystery Mighty Mouse
class Mystery {
public static void main(String[]
args) {
Changer c = new Changer();
c.method(args);
System.out.println(args[0] +
" " + args[1]);
}
static class Changer {
void method(String[] s) {
String temp = s[0];
s[0] = s[1];
s[1] = temp;
}
}
}
elect the one
right answer.
a) this code will not compile
b) this code compiles but throws an
exception at runtime
c) this code runs but nothing appears
in the standard output
d) this code runs and "constructor" in
the standard output
e) this code runs and writes "null" in
the standard output
Question 37: What can you write
at the comment //A in the code
below so that this program
writes the word "running" to the
standard output?
class RunTest implements Runnable
{
Question 38: What order
can you place the following
pieces of a source file in so
that the source file will
compile without errors or
warnings?
//A
import java.applet.*;
//B
class Helper {
}
//C
package myclasses;
//D
public class MyApplet extends
java.applet.Applet {
}
Select all valid answers.
a) A, B, C, D
public static void main(String[]
args) {
b) A, C, B, D
RunTest rt = new RunTest();
c) C, A, B, D
Thread t =new Thread(rt);
elect the one right answer.
//A
a) This program causes an
ArrayIndexOutOfBoundsExceptio
n to be thrown
d) C, A, D, B
e) C, B, A, D
}
public void run() {
b) This program runs but does
not write anything to the
standard output
System.out.println("running");
}
c) This program writes "Mighty
Mouse" to the standard output
void go() {
d) This program writes "Mouse
Mighty" to the standard output
Question 39: Analyze these
two consequetive lines of
code:
float f = 3.2;
int i = f;
start(1);
Select all valid answers.
a) this code would not compile
}
void start(int i) {
Question 36: What happens
when you try to compile and
run the following program?
class Mystery {
String s;
public static void main(String[]
args) {
Mystery m = new Mystery();
m.go();
}
void Mystery() {
s = "constructor";
}
void go() {
System.out.println(s);
}
d) rt.start(1);
}
}
Select all valid answers.
a) System.out.println("running");
b) rt.start();
c) rt.go();
b) this code would compile and
i would be set to 3
c) the second line could
compile if it were written
instead as:
int i = (byte)f;
d) the first line could compile if
it were written instead as:
float f = 3.2F;
Question 40: Construct an
array of 3 String objects
containing the strings "a",
"b", and "c" using the { }
59
notation. Call the String by
the variable name s.
Question 41: What is the final
value of temp in this
sequence?
long temp = (int)3.9;
setLayout(new
BorderLayout());
add("East", new Button("hello"));
}
Question 47: Analyze the
following code:
class WhatHappens
implements Runnable {
public static void
main(String[] args) {
Select the one right answer.
temp %= 2;
a) Nothing will appear in the applet
Thread t = new
Thread(this);
a) 0
b) 1
c) 2
d) 3
Select the one right answer.
e) A button will fill the entire applet
Question 42: Analyze this line
of code:
Question 45: Choose all true
statements about the paint()
method defined in the
Component class:
a) this line of code will not
compile
b) this code will compile but
nothing will appear in the
standard output
public void run() {
System.out.println("hi");
e) 4
Select the one right answer.
}
c) A button will appear on the left
side of the applet
d) A button will appear on the right
side of the applet
if (5 & 7 > 0 && 5 | 2)
System.out.println("true");
t.start();
b) A button will appear in the applet
set in the exact center
Select all valid answers.
a) it is protected
b) it takes an instance of class
Graphics
c) it is static
c) this code will compile and
write the word "true" in the
standard output
d) it is invoked automatically
whenever you minimize and then
maximize a component, such as a
window
Question 43: Create a List
object that allows multiple
selections and displays 5
rows at a time.
e) there is also a version that takes
an int
}
}
Select the one right answer.
a) This program does not
compile
b) This program compiles but
nothing appears in the
standard output
c) This program compiles and
the word "hi" appears in the
standard output, once
d) This program compiles and
the word "hi" appears
continuously in the standard
output until the user hits
control-c to stop the program
Question 48: What is wrong
with the following code?
final class First {
Question 46: Given this
ActionListener:
private int a = 1;
int b = 2;
Start by writing:
class HandleClick implements
ActionListener {
List l =
public void
actionPerformed(ActionEvent evt) {
in your answer.
// A
public void init() {
class Second extends First {
}
fill in the blank.
Question 44: What will the
user interface look like in an
applet given the following
init() method?
}
public void method() {
}
What line of code can you write at A
that will make a component
referenced by c disappear from the
display?
System.out.println(a + b);
}
}
Select all valid answers.
ill in the blank.
60
a) You cannot invoke println()
without passing it a String
System.out.println(x);
}
b) Since a is private, no classes
other than First can access it
c) Second cannot extend First
d) final is not a valid keyword for
a class
Question 49: Analyze the
following two classes.
class First {
static int a = 3;
}
Question 52: What appears
in the standard output
when the method named
testing is invoked?
}
}
void testing() {
Select the one right answer.
one:
a) Class B tries to access a private
variable defined in its ouer class.
two:
for (int i = 0; i < 3; i++) {
b) Class A attempts to create an
instance of B when there is no
current instance of class A.
c) Class B’s constructor must be
public.
final class Second extends First {
void method() {
question 51: Analyze the
following code.
three:
for (int j = 10; j < 30;
j+=10) {
System.out.println(i +
j);
if (i > 2)
void looper() {
System.out.println(a);
}
h) the number 10 to the
standard output
continue one;
int x = 0;
}
one:
}
}
while (x < 10) {
Select the one right answer.
System.out.println(++x);
a) Class First compiles, but class
Second does not
if (x > 3)
b) Class Second compiles, but
class First does not
break two;
}
c) Neither class compiles
d) Both classes compile, and if
method() is invoked, it writes 3
to the standard output
e) Both classes compile, but if
method() is invoked, it throws an
exception
Question 50: Why won’t the
following class compile?
class A {
private int x;
public static void main(String[]
args) {
new B();
}
two:
Select all valid answers.
a) 10 and 20
b) 11 and 21
c) 12 and 22
}
d) 13 and 23
Select all valid answers.
e) 30, 31, 32, 33
a) This code compiles
Question 53: What will the
result be for the following
block of code when it is
executed?
b) This code does not compile
c) This method writes the number 0
to the standard output
int i = 3;
int j = 0;
d) the numbers 1 and 2 to the
standard output
e) the number 3 to the standard
output
f) the number 4 to the standard
output
}
float k = 3.2F;
long m = -3;
if (Math.ceil(i) < Math.floor(k))
if (Math.abs(i) == m)
System.out.println(i);
class B {
B() {
g) the numbers 5 through 9 to the
standard output
else
System.out.println(j);
61
else
System.out.println("b");
b) arr[0] == 1
else
System.out.println(Math.abs(m)
+ 1);
if (obj1.equals(obj2))
c) arr[1] == 1
System.out.println("c");
else
Select the one right answer.
d) arr[2] == 0
System.out.println("d");
a) 3
Select the one right answer.
b) 0
c) -3
d) 4
e) none of these
Question 54: The ISO code for
the language you are
interested in is 8859-5.
Assume you have a stream in
a variable named mystream
that’s associated with a file
generated in this 8-bit
character set. If the default
conversion to Unicode in your
environment is for the
encoding 8859-1, how can
you create a new instance of
InputStreamReader that will
perform the conversion from
ISO 8859-5 to Unicode,
automatically? (Start by
writing the keyword new and
do not add a semicolon at the
end.)
ill in the blank.
Question 55: What is written
to the standard output as the
result of executing the
following statements?
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean(true);
Object obj1 = (Object)b1;
Object obj2 = (Object)b2;
a) a
b) b
Question 58: What will
happen if you try to compile
and execute B’s main()
method?
c) c
class A {
d) d
int i;
Question 56: What will the user
interface look like in an applet
given the following init()
method?
A(int i) {
if (obj1.equals(obj2))
System.out.println("a");
else
this.i = i * 2;
}
public void init() {
setLayout(new BorderLayout());
}
add(new Button("hello"));
class B extends A {
}
Select the one right answer.
public static void
main(String[] args) {
B b = new B(2);
a) Nothing will appear in the applet
}
b) A button will appear in the applet
set in the exact center
B(int i) {
c) A button will appear in the applet
along the top and centered
horizontally
d) A button will appear in the top left
corner
e) A button will fill the entire applet
Question 57: What expressions
are true concerning the following
lines of code?
int[] arr = {1, 2, 3};
if (obj1 == obj2)
e) arr[3] == 0
for (int i=0; i < 2; i++)
arr[i] = 0;
Select all valid answers.
a) arr[0] == 0
System.out.println(i);
}
}
Select the one right answer.
a) The instance variable i is set
to 4
b) The instance variable i is set
to 2
c) The instance variable i is set
to 0
d) This code will not compile
Question 59: Which best
describes the user interface
62
of an applet given the
following init() method:
e) None of
these are true
public void init() {
setLayout(new
BorderLayout());
add("North", new
TextField(10));
add("Center", new
Button("help"));
}
Select all valid answers.
a) The TextField object will be
placed at the top of the applet
and will be 10 columns wide
b) The Button object will be
centered in the applet and will be
just large enough to contain the
text "help"
c) The Button object will be
centered in the applet and will
start at the left edge of the
applet, fit just under the
TextField object above it, and
extend to the right and bottom
edge of the applet
d) The TextField object will be
placed along the top of the
applet and will stretch from the
left edge to the right edge
e) The placement of the Button
object and the TextField object
depends on the overall size of
the applet.
Question 60: Which of the
following statements about
try, catch, and finally are
true?
Select all valid answers.
a) A try block must always be
followed by a catch block
b) A try block can be followed
either by a catch block or a
finally block, or both
c) A catch block must always be
associated with a try block
d) A finally can never stand on
its own (that is, without being
associated with try block)
"The value of b2[1] =
null".
Question 21
What will happen if you
compile/run the following code?
1:
public class Q21
2: {
3:
int maxElements;
4:
5:
void Q21()
6:
{
7:
maxElements =
100;
8:
System.out.println(maxElements);
9:
}
10:
11:
Q21(int i)
12:
{
13:
maxElements = i;
14:
System.out.println(maxElements);
15:
}
16:
17:
public static void
main(String[] args)
18:
{
19:
Q21 a = new Q21();
20:
Q21 b = new Q21(999);
21:
}
22: }
A) Prints 100 and 999.
B) Prints 999 and 100.
C) Compilation error at line 3,
variable maxElements was not
initialized.
D) Compillation error at line 19.
Answer
Question 22
What will happen if run the
following code?
1:
Boolean[] b1 = new
Boolean[10];
2:
3:
boolean[] b2 = new
boolean[10];
4:
6:
System.out.println("The
value of b1[1] = " +b1[1]);
7:
System.out.println("The
value of b2[1] = " +b2[1]);
A) Prints "The value of b1[1] =
false"
"The value of b2[1] =
false".
B) Prints "The value of b1[1] =
null"
C) Prints "The value of b1[1]
= null"
"The value of b2[1] =
false".
D) Prints "The value of
b1[1] = false"
"The value of b2[1] =
null".
Answer
Question 23
Which of the following are
valid array
declarations/definitions?
1: int
2: int
3: int
int[10];
4: int
int[10];
5: int
int[10];
6: int
int[];
7: int
iArray1[10];
iArray2[];
iArray3[] = new
iArray4[10] = new
[]iArray5
= new
iArray6[]
= new
iArray7[]
= null;
A) 1.
B) 2.
C) 3.
D) 4.
E) 5.
F) 6.
G) 7.
Answer
Question 24
What is the output for the
following lines of code?
1: System.out.println(" "
+2 + 3);
2: System.out.println(2 +
3);
3: System.out.println(2 + 3
+"");
4: System.out.println(2 +
"" +3);
A) Compilation error at line
3
B) Prints 23, 5, 5 and 23.
C) Prints 5, 5, 5 and 23.
D) Prints 23, 5, 23 and 23.
Answer
Question 25
The following declaration(as
a member variable) is legal.
63
static final transient int
maxElements = 100;
A) True.
B) False.
Answer
A) prints -0.0, +0.0 and false.
B) prints -0.0, +0.0 and true.
C) prints 0.0, 0.0 and false.
D) prints 0.0, 0.0 and true.
so A and D are invalid. In
line 6 the array dimension is
missing(right hand side) so F is
invalid.
You can intialize an array
with null. so G is valid.
Answer
Back to Question 23
Question 26
What will happen if you
compile/run the following lines of
code?
1: int[] iArray = new int[10];
2:
3: iArray.length = 15;
4:
5:
System.out.println(iArray.length)
;
A) Prints 10.
B) Prints 15.
C) Compilation error, you
can't change the length of an
array.
D) Runtime exception at line
3.
Answer
Question 27
What will happen if you
compile/run the folowing lines of
code?
1: Vector a = new Vector();
2:
3: a.addElement(10);
4:
5:
System.out.println(a.elementAt(
0));
A) Prints 10.
B) Prints 11.
C) Compilation error at line 3.
D) Prints some garbage.
Answer
Question 28
What will happen if you invoke
the following method?
1: public void check()
2: {
3:
System.out.println(Math.min(0.0,+0.0));
4:
System.out.println(Math.max(0.0,+0.0));
5:
System.out.println(Math.min(0.0,+0.0) ==
Math.max(0.0,+0.0));
6: }
Question 29
What will happen if you
compile/run this code?
1:
2:
3:
4:
5:
6:
7:
8:
int
int
int
int
i = 012;
j = 034;
k = 056;
l = 078;
System.out.println(i);
System.out.println(j);
System.out.println(k);
A) Prints 12,34 and 56.
B) Prints 24,68 and 112.
C) Prints 10, 28 and 46.
D) Compilation error.
Answer
Question 30
When executed the following line
of code will print
Question No 24
B.
Back to Question 24
Question No 25
A.
Back to Question 25
Question No 26
C. Once array is created
then it is not possible to
change the length of the array.
Back to Question 26
Question No 27
C. You can't add primitives
to Vector. Here 10 is int type
primitive.
Back to Question 27
System.out.println(-1 *
Double.NEGATIVE_INFINITY);
A) -Infinity
B) Infinity
C) NaN
D) -NaN
Question No 28
B. The order of
floating/double values is
-Infinity --> Negative
Numbers/Fractions --> -0.0 -> +0.0 --> Positive
Numbers/Fractions --> Infinity.
Answer
Back to Question 28
Question No 21
D. Constructors should not return
any value. Java won't allow to
indicate with void.
In this case void Q21() is an
ordinary method which has the same
name of the Class.
Question No 29
D. Here integers are
assinged by octal values. Octal
numbers will contain digits
from 0 to 7.
8 is illegal digit for an
octal value, so you get
compilation error.
Back to Question 21
Back to Question 29
Question No 22
C. By default objects will be
initialized to null and primitives to
their corresponding default vaulues.
The same rule applies to array
of objects and primitves.
Back to Question 22
Question No 23
B,C,E and G. You can't specify the
array dimension in type
specification(left hand side),
Question No 30
B. Compile and see the
result.
Question 11
What will happen if you
compile/run the following
code?
1: public class Q11
2: {
3:
static String str1 =
"main method with String[]
args";
64
4:
static String str2 =
"main method with int[] args";
5:
6:
public static void
main(String[] args)
7:
{
8:
System.out.println(str1);
9:
}
10:
11:
public static void
main(int[] args)
12:
{
13:
System.out.println(str2);
14:
}
15: }
A) Duplicate method main(),
compilation error at line 6.
B) Duplicate method main(),
compilation error at line 11.
C) Prints "main method with
main String[] args".
D) Prints "main method with
main int[] args".
Answer
Question 12
What is the output of the
following code?
1: class Test
2: {
3:
Test(int i)
4:
{
5:
System.out.println("Test(" +i
+")");
6:
}
7: }
8:
9: public class Q12
10: {
11:
static Test t1 = new
Test(1);
12:
13:
Test
t2 = new
Test(2);
14:
15:
static Test t3 = new
Test(3);
16:
17:
public static void
main(String[] args)
18:
{
19:
Q12 Q = new
Q12();
20:
}
21: }
A) Test(1)
Test(2)
Test(3)
B) Test(3)
Test(2)
Test(1)
C) Test(2)
Test(1)
Test(3)
D) Test(1)
Test(3)
Test(2)
Answer
Question 13
What is the output of the following
code?
1: int i = 16;
2: int j = 17;
3:
4: System.out.println("i >> 1 =
" + (i >> 1));
5: System.out.println("j >> 1
= " + (j >> 1));
A) Prints "i >> 1 = 8"
"j >> 1 = 8"
B) Prints "i >> 1 = 7"
"j >> 1 = 7"
C) Prints "i >> 1 = 8"
"j >> 1 = 9"
D) Prints "i >> 1 = 7"
"j >> 1 = 8"
Q 1. What is the output of
the following
StringBuffer sb1 = new
StringBuffer("Amit");
StringBuffer sb2= new
StringBuffer("Amit");
String ss1 = "Amit";
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss1));
System.out.println("Poddar".substrin
g(3));
Ans:
a) false
false
false
dar
b) false
true
false
Poddar
c) Compiler Error
d) true
true
false
dar
Correct Answer is a)
***** Look carefully at code
and answer the following
questions ( Q2 to Q8)
1
import java.applet.Applet;
2 import java.awt.*;
3 import java.awt.event.*;
4
public class hello4 extends
Applet {
5
public void init(){
6
add(new
myButton("BBB"));
7
}
8
public void
paint(Graphics screen) {
9 }
10
class myButton extends
Button{
11
myButton(String
label){
12
super(label);
13
}
14
public String
paramString(){
15
return
super.paramString();
16
}
17
}
18 public static void
main(String[] args){
19
Frame myFrame = new
Frame(
20
"Copyright Amit");
21
myFrame.setSize(300,100);
22
Applet myApplet = new
hello4();
23
Button b = new
Button("My Button");
24
myApplet.add(b);
25
b.setLabel(b.getLabel()+"New"
);
26 // myButton b1 =(new
hello4()).new
myButton("PARAMBUTTON");
27
System.out.println(b1.paramSt
ring());
28
myFrame.add(myApplet);
29
myFrame.setVisible(true);
30
myFrame.addWindowListener(
new WindowAdapter(){
31
public void
windowClosing(WindowEvent
e){
32
System.exit(0);}});
33 }
34 } //End hello4 class.
Q2. If you run the above
program via appletviewer (
defining a HTML file), You see
on screen.
65
a) Two buttons
b) One button with label as
"BBB"
c) One button with label as "My
ButtonNew"
d) One button with label as "My
Button"
Correct answer is b)
Q3. In the above code if line 26
is uncommented and program
runs as standalone application
a) Compile Error
b) Run time error
c) It will print the the label as
PARAMBUTTON for button b1
Correct answer is c)
Q4 In the code if you compile as
"javac hello4.java" following files
will be generated.
a) hello4.class,
myButton.class,hello41.class
b)hello4.class,
hello4$myButton.class,hello4$1.c
lass
c)hello4.clas,hello4$myButton.cl
ass
Correct answer is b)
Q5. If above program is run as a
standalone application. How
many buttons will be displayed
a) Two buttons
b) One button with label as
"BBB"
c) One button with label as "My
ButtonNew"
d) One button with label as "My
Button"
happen.(Hint
:paramString()
method in java.awt.Button is a
protected method.(Assume line 26 is
uncommented)
a) Code will not compile.
b) Code will compile but will give a
run time error.
c) Code will compile and no run time
error.
Correct answer is c) . As you can
access a protected variable in the
same package.
Q8.If line no 26 is replaced with
Button b1 = new
Button("PARAMBUTTON").(Hint
:paramString() method in
java.awt.Button is a protected
method.(Assume line 26 is
uncommented)
a) Code will not compile.
b) Code will compile but will give a
run time error.
c) Code will compile and no run time
error.
Correct answer is a) Because
protected variables and methods can
not be accssed in another package
directly. They can only be accessed if
the class is subclassed and instance
of subclass is used.
Q9. What is the output of following if
the return value is "the value 0 if the
argument string is equal to this
string; a value less than 0 if this
string is lexicographically less than
the string argument; and a value
greater than 0 if this string is
lexicographically greater than the
string argument" (Assuming written
inside main)
0
Correct Answer is a)
Q 10) What is the output
(Assuming written inside
main)
String s1 = new
String("amit");
String s2 =
s1.replace('m','i');
s1.concat("Poddar");
System.out.println(s1);
System.out.println((s1+s2).ch
arAt(5));
a) Compile error
b) amitPoddar
o
c) amitPoddar
i
d) amit
i
Correct answer is d)As String is
imutable.so s1 is always
"amit". and s2 is "aiit".
Q 11) What is the output
(Assuming written inside
main)
String s1 = new
String("amit");
System.out.println(s1.replace('
m','r'));
System.out.println(s1);
String s3="arit";
String s4="arit";
String s2 =
s1.replace('m','r');
System.out.println(s2==s3);
System.out.println(s3==s4);
correct answer is C)
Q6. If from line no 14 keyword
"public" is removed, what will
happen.( Hint :paramString()
method in java.awt.Button is a
protected method. (Assume line
26 is uncommented)
a) Code will not compile.
b) Code will compile but will give
a run time error.
c) Code will compile and no run
time error.
Correct answer is a). As you can
not override a method with
weaker access privileges
Q7. If from line no 14 keyword
"public" is replaced with
"protected", what will
String s5 = "AMIT";
String s6 = "amit";
System.out.println(s5.compareTo(s6)
);
System.out.println(s6.compareTo(s5)
);
System.out.println(s6.compareTo(s6)
);
Ans
a> -32
32
0
b> 32
32
0
c> 32
-32
0
d> 0
0
a) arit
amit
false
true
b) arit
arit
false
true
c) amit
amit
false
true
d) arit
amit
true
true
Correct answer is a) s3==s4
is true because java points
both s3 and s4 to same
memory location in string pool
66
Q12) Which one does not extend
java.lang.Number
1)Integer
2)Boolean
3)Character
4)Long
5)Short
Correct ANswer is b)
myFrame.add(cb1);
myFrame.add(cb2);
myFrame.add(cb3);
a)
cb1
b)
cb2,cb1
c)
cb1,cb2,cb3
d)
cb3
Correct answer is 2) and 3)
Q13) Which one does not have a
valueOf(String) method
1)Integer
2)Boolean
3)Character
4)Long
5)Short
Correct answer is 3)
Q.14) What is the output of
following (Assuming written
inside main)
String s1 = "Amit";
String s2 = "Amit";
String s3 = new
String("abcd");
String s4 = new
String("abcd");
System.out.println(s1.equals(s2)
);
System.out.println((s1==s2));
Correct Answer is d) As in a
CheckboxGroup only one can be
selected
Q16) Which checkbox will be selected
in the following code ( Assume with
main and added to a Frame)
Frame myFrame = new
Frame("Test");
CheckboxGroup cbg = new
CheckboxGroup();
Checkbox cb1 = new
Checkbox("First",true,cbg);
Checkbox cb2 = new
Checkbox("Scond",true,cbg);
Checkbox cb3 = new
Checkbox("THird",true,cbg);
myFrame.add(cb1);
myFrame.add(cb2);
myFrame.add(cb3);
a)
cb1
b)
cb2,cb1
c)
cb1,cb2,cb3
d)
cb3
Q19) Answer based on
following code
1 Choice c1 = new Choice();
2 c1.add("First");
3 c1.addItem("Second");
4 c1.add("Third");
5
c1.insert("Lastadded",1000);
6
System.out.println(c1.getItem
Count());
a) Compile time error
b) Run time error at line 5
c) No error and line 6 will
print 1000
d) No error and line 6 will
print 4
Correct ANswer is d)
Q20) Which one of the
following does not extends
java.awt.Component
a) CheckBox
b) Canvas
c) CheckbocGroup
d) Label
Correct answer is c)
System.out.println(s3.equals(s4)
);
System.out.println((s3==s4));
a) true
true
true
false
b) true
true
true
true
c) true
false
true
false
Correct answer is a)
Q15. Which checkbox will be
selected in the following code (
Assume with main and added to
a Frame)
Frame myFrame = new
Frame("Test");
CheckboxGroup cbg = new
CheckboxGroup();
Checkbox cb1 = new
Checkbox("First",true,cbg);
Checkbox cb2 = new
Checkbox("Scond",true,cbg);
Checkbox cb3 = new
Checkbox("THird",false,cbg);
cbg.setSelectedCheckbox(cb3);
Correct Answer is d) As in a
CheckboxGroup only one can be
selected
Q17) What will be the output of line
5
1 Choice c1 = new Choice();
2 c1.add("First");
3 c1.addItem("Second");
4 c1.add("Third");
5
System.out.println(c1.getItemCount(
));
a) 1
b) 2
c) 3
d) None of the above
Correct Answer is c)
Q18) What will be the order of four
items added
Choice c1 = new Choice();
c1.add("First");
c1.addItem("Second");
c1.add("Third");
c1.insert("Lastadded",2);
System.out.println(c1.getItemCount(
));
a) First,Second,Third,Fourth
b) First,Second,Lastadded,Third
c) Lastadded,First,Second,Third
Q21) What is default layout
manager for panels and
applets?
a) Flowlayout
b) Gridlayout
c) BorderLayout
Correct answer is a)
Q22) For awt components
which of the following
statements are true?
a) If a component is not
explicitly assigned a font, it
usese the same font that it
container uses.
b) If a component is not
explicitly assigned a
foreground color , it usese the
same foreground color that it
container uses.
c) If a component is not
explicitly assigned a backround
color , it usese the same
background color that it
container uses.
d) If a component is not
explicitly assigned a layout
manager , it usese the same
layout manager that it
container uses.
67
correct answer is a),b),c)
Q23)java.awt.Component class
method getLocation() returns
Point (containg x and y
cordinate).What does this x and
y specify
a) Specify the postion of
components lower-left
component in the coordinate
space of the component's parent.
b) Specify the postion of
components upper-left
component in the coordinate
space of the component's parent.
c) Specify the postion of
components upper-left
component in the coordinate
space of the screen.
correct answer is b)
Q24. Q. What will be the output
of follwing
{
double d1 = -0.5d;
System.out.println("Ceil for d1 "
+ Math.ceil(d1));
System.out.println("Floor for d1 "
+Math.floor(d1));
}
Answers:
a) Ceil for d1 0
Floor for d1 -1;
b) Ceil for d1 0
Floor for d1 -1.0;
c) Ceil for d1 0.0
Floor for d1 -1.0;
d) Ceil for d1 -0.0
Floor for d1 -1.0;
correct answer is d) as 0.0 is
treated differently from -0.0
Q25. What is the output of
following
{
float f4 = -5.5f;
float f5 = 5.5f;
float f6 = -5.49f;
float f7 = 5.49f;
System.out.println("Round
+ Math.round(f4));
System.out.println("Round
+ Math.round(f5));
System.out.println("Round
+ Math.round(f6));
System.out.println("Round
+ Math.round(f7));
}
a)Round f4 is -6
Round f5 is 6
Round f6 is -5
Round f7 is 5
b)Round f4 is -5
f4 is "
f5 is "
f6 is "
f7 is "
Round f5 is 6
Round f6 is -5
Round f7 is 5
Correct answer is b)
Q26. Given Integer.MIN_VALUE = 2147483648
Integer.MAX_VALUE =
2147483647
What is the output of following
{
float f4 = Integer.MIN_VALUE;
float f5 = Integer.MAX_VALUE;
float f7 = -2147483655f;
System.out.println("Round f4 is " +
Math.round(f4));
System.out.println("Round f5 is " +
Math.round(f5));
System.out.println("Round f7 is " +
Math.round(f7));
}
a)Round f4 is -2147483648
Round f5 is 2147483647
Round f7 is -2147483648
b)Round f4 is -2147483648
Round f5 is 2147483647
Round f7 is -2147483655
correct answer is a)
//Reason If the argument is negative
infinity or any value less than or
equal to the value of
Integer.MIN_VALUE, the result is
equal to the value of
Integer.MIN_VALUE.
If the argument is positive infinity
or any value greater than or equal to
the value of Integer.MAX_VALUE, the
result is
equal to the value of
Integer.MAX_VALUE. // From JDK api
documentation
Q27)
1 Boolean b1 = new
Boolean("TRUE");
2 Boolean b2 = new
Boolean("true");
3 Boolean b3 = new
Boolean("JUNK");
4 System.out.println("" + b1 + b2
+ b3);
System.out.println(b1+b2+b3)
; The output is
a) Compile time error
b) Run time error
c) truetruefalse
d) truetruetrue
Correct answer is a) As there is
no method to support Boolean
+ Boolean
Boolean b1 = new
Boolean("TRUE");
Think ---->System.out.println(b1); // Is
this valid or not?
Q 29. What is the output
{
Float f1 = new
Float("4.4e99f");
Float f2 = new Float("4.4e99f");
Double d1 = new
Double("4.4e99");
System.out.println(f1);
System.out.println(f2);
System.out.println(d1);
}
a) Runtime error
b) Infinity
-Infinity
4.4E99
c) Infinity
-Infinity
Infinity
d) 4.4E99
-4.4E99
4.4E99
Correct answer is b)
Q30 Q. Which of the following
wrapper classes can not
take a "String" in constructor
1)
2)
3)
4)
5)
6)
Boolean
Integer
Long
Character
Byte
Short
correct answer is 4)
a) Comiler error
b) RunTime error
c)truetruefalse
d)truetruetrue
Q31. What is the output of
following
Double d2 = new Double("5.5");
Double d3 = new Double("5.5");
Correct answer is c)
System.out.println(d2==d3);
Q 28) In the above question if line 4
is changed to
System.out.println(d2.equals(d
3));
68
a) true
true
b) false
false
c) true
false
d) false
true
Correct answer is d)
Q32) Which one of the following
always honors the components's
preferred size.
a) FlowLayout
b) GridLayout
c) BorderLayout
Correct answer is a)
Q33) Look at the following code
import java.awt.*;
public class visual extends
java.applet.Applet{
static Button b = new
Button("TEST");
public void init(){
add(b);
}
public static void main(String
args[]){
Frame f = new
Frame("Visual");
f.setSize(300,300);
f.add(b);
f.setVisible(true);
}
}
What will happen if above code is
run as a standalone application
a) Displays an empty frame
b) Displays a frame with a button
covering the entire frame
c) Displays a frame with a button
large enough to accomodate its
label.
Correct answer is b) ReasonFrame uses Border Layout which
places the button to CENTRE
(By default) and ignores
Button's preferred size.
Q34 If the code in Q33 is
compiled and run via
appletviewer what will happen
a) Displays an empty applet
b) Displays a applet with a
button covering the entire frame
c) Displays a applet with a
button large enough to
accomodate its label.
Correct answer
is c) ReasonApplet uses FlowLayout which honors
Button's preferred size.
Q35. What is the output
public static void main(String
args[]){
Frame f = new Frame("Visual");
f.setSize(300,300);
f.setVisible(true);
Point p = f.getLocation();
System.out.println("x is " +
p.x);
System.out.println("y is " +
p.y);
}
a) x is 300
y is 300
b) x is 0
y is 0
c) x is 0
y is 300
correct answer is b) Because postion
is always relative to parent container
and in this
case Frame f is the topemost
container
Q36) Which one of the following
always ignores the components's
preferred size.
a) FlowLayout
b) GridLayout
c) BorderLayout
Correct answer is b)
Q37) Consider a directory structure
like this (NT or 95)
C:\JAVA\12345.msg --FILE
\dir1\IO.class -- IO.class is
under dir1
Consider the following code
import java.io.*;
public class IO {
public static void main(String
args[]) {
File f = new
File("..\\12345.msg");
try{
System.out.println(f.getCanonicalPat
h());
System.out.println(f.getAbsolutePath
());
}catch(IOException e){
System.out.println(e);
}
}
}
a) C:\java\12345.msg
C:\java\dir1\..\12345.msg
b) C:\java\dir1\12345.msg
C:\java\dir1\..\12345.msg
c) C:\java\dir1\..\12345.msg
C:\java\dir1\..\12345.msg
correct answer is a) as
getCanonicalPath Returns the
canonical form of this File
object's pathname. The precise
definition of canonical form is
system-dependent, but it
usually
specifies an absolute pathname
in which all relative references
and references to the current
user directory have been
completely resolved.
WHERE AS
getAbsolutePath Returns the
absolute pathname of the file
represented by this object. If
this object represents an
absolute pathname, then
return the pathname.
Otherwise, return a pathname
that is a concatenation of the
current user directory, the
separator character, and the
pathname of this file object.
Q 38) Suppose we copy
IO.class from C:\java\dir1 to
c:\java
What will be the output of
running "java IO" from
C:\java.
a) C:\java\12345.msg
C:\java\..\12345.msg
b) C:\12345.msg
C:\java\..\12345.msg
c) C:\java\..\12345.msg
C:\java\\..\12345.msg
correct answer is b)
Q39) Which one of the
following methods of
java.io.File throws IOException
and why
a) getCanonicalPath and
getAbsolutePath both require
filesystem queries.
b) Only getCannonicalPath as it
require filesystem queries.
c) Only getAbsolutePath as it
require filesystem queries.
Correct answer is b)
What will be the output of running
"java IO" from C:\java\dir1
69
Q40) What will be the output if
Consider a directory structure
like this (NT or 95)
C:\JAVA\12345.msg --FILE
\dir1\IO.class -- IO.class
is under dir1
import java.io.*;
public class IO {
public static void
main(String args[]) {
File f = new
File("12345.msg");
String arr[] =
f.list();
System.out.println(arr.length);
}
}
a) Compiler error as 12345.msg
is a file not a directory
b) java.lang.NullPointerException
at run time
c) No error , but nothing will be
printed on screen
Correct ansewer is b)
Q41) What will be the output
Consider a directory structure
like this (NT or 95)
C:\JAVA\12345.msg --FILE
import java.io.*;
public class IO {
public static void
main(String args[]) {
File f1 = new
File("\\12345.msg");
System.out.println(f1.getPath());
System.out.println(f1.getParent()
);
System.out.println(f1.isAbsolute(
));
System.out.println(f1.getName()
);
System.out.println(f1.exists());
System.out.println(f1.isFile());
}
}
a) \12345.msg
\
true
12345.msg
true
true
b) \12345.msg
\
true
\12345.msg
false
false
c) 12345.msg
\
true
12345.msg
false
false
d) \12345.msg
\
true
12345.msg
false
false
correct answer is d)
Q42) If in question no 41 the line
File f1 = new
File("\\12345.msg"); is replaced with
File f1 = new File("12345.msg");
What will be the output
c) 12345.msg
null
false
12345.msg
true
true
Correct answer is c)
Location: ... > Declarations and
Access Control > Objective 1.1 >
Item 1
---------------------------------------Click the Exhibit button.
Which two lines of code will compile
correctly? (Choose two.)
1. class CharArray2 {
2. public static void main( String []
args) {
3.
char b = 'b';
4.
char c = 'C';
5.
char [] c1 = {'a', 'b', 'c'};
6.
char [] c2 = {'a', b , 'c'};
7.
char [] c3 = ('a', 'b', 'c');
8.
char [] c4 = [3];
9.
char [] c5 = [3] {'a', 'b', 'c'};
10.
char [] c6 = [] {'a', 'b', c};
11. }
12. }
A line 5
B line 6
C line 7
D line 8
E line 9
F line 10
Answer:
Options A and B are the correct
answers. This question explores a
Java syntax shortcut. A and B
represent acceptable syntax to
declare, construct, and
initialize an array in a single
line of code.
Location: ... > Declarations
and Access Control > Objective
1.1 > Item 2
--------------------------------------Click the Exhibit button.
1. class Test{
2. public static void main(
String [] args) {
3.
int [] y;
4.
int [] z = new int [] {1,
2, 3};
5.
y = z;
6.
z[1] = 7;
7.
for (int x= 0;x<3; x++)
{
8.
System.out.print("
y[" + x + "] = " + y[x]);
9.
}
10. }
11. }
What is the result?
A y[0] = 0 y[1] = 1 y[2] =
2
B y[0] = 7 y[1] = 2 y[2] =
3
C y[0] = 1 y[1] = 7 y[2] =
3
D y[0] = 1 y[1] = 2 y[2] =
3
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option C is the correct answer.
y and z are reference
variables. Line 5 assigns y to
refer to the same array as z,
there is still only one array
(however there are two array
references). When line 6
executes, it changes a value in
the only array there is, (the
one both y and z refer to).
Therefore when the array is
accessed via y, the updated
value is displayed.
ocation: ... > Declarations
and Access Control > Objective
1.2 > Item 1
--------------------------------------------Which declaration
ensures that a class cannot be
subclassed?
A abstract class MyClass { }
B final public class MyClass {
}
C final abstract class MyClass
{}
D static private class MyClass
{}
E static protected class
MyClass { }
Answer:
70
Option B is the correct answer.
The final modifier insures that a
class can not be subclassed.
Q31. class XXX {
2. long doStuff (int input) {
3.
static long x = 7;
4.
return (long) input / x;
5. }
6.
7. public static void main(String
[] args) {
8.
XXX xxx = new XXX();
9.
System.out.println(xxx.doStuff(4
2));
10. }
11. }
What will be the result?
A 6
B 7
C 42
D Compilation fails
E An exception is thrown at
runtime
Answer:
Option D is the correct answer.
The compiler will notice that in
Line 3 the code is declaring a
static variable, but it's in a local
method, which is not legal. If
several instances of XXX were
instantiated it would be
impossible to know which
instance the static should belong
to.
Location: ... > Declarations and
Access Control > Objective 1.3 >
Item 1
--------------------------------------Click the Exhibit button.
1. class Foo {
2. Foo(String s) { }
3. }
4. class Bar extends Foo { }
Which statement is true?
A Class Bar will not compile
B Class Bar has a public
constructor
C Class Bar's constructor
invokes super()
D Class Foo's constructor does
not invoke super()
answer:
Option A is the correct answer.
The compiler attempts to create
a default constructor for class
Bar, because Bar has not defined
any constructors. The class Bar
constructor will include a call to
super(). Since class Foo does not
have a no-arg constructor, class
Bar will not compile because the
default constructor the compiler
is attempting to
build includes a
call to super(), and there is no
matching no-arg constructor in class
Foo.
Location: ... > Declarations and
Access Control > Objective 1.3 >
Item 2
--------------------------------------Given:
1. class Pizza { }
Which of these represents the
functionality of the default
constructor for Pizza?
A Pizza()
B Pizza() {super();}
C public void Pizza()
D public Pizza() {super();}
E There is no default constructor for
Pizza
Answer:
Option B is the correct answer. The
compiler creates a default
constructor for Pizza, with default
access (matching the access of the
class), and a no-arg call to super().
Location: ... > Declarations and
Access Control > Objective 1.4 >
Item 1
---------------------------------------Click the Exhibit button to view the
code.
1. class XL {
2. public long doMath() {
3.
return 343L;
4. }
5. }
6.
7. class L extends XL {
8.
9. }
Which two methods inserted at line
8, will not compile? (Choose two.)
a public void doMath() { }
B public void doMath(int i) { }
C public int doMath() { return 343
}
D public long doMath(int i) { return
343 }
answer:
Options A and C are the correct
answers. A and C represent an illegal
override of the class XL doMath()
method. Because the arguments
have not changed, the return type
cannot change.
Location: ... > Declarations and
Access Control > Objective 1.4 >
Item 2
-------------------------------------------- Click the Exhibit button to view
the code.
1. class Test {
2. public short doStuff(int i) {
return 27; }
3. }
4.
5. public class SubTest extends
Test {
6. public int doStuff(int x) {
return 30; }
7.
8. public static void
main(String [] args) {
9.
Test t = new Test();
10.
SubTest s = new
SubTest();
11. int t1 = t.doStuff(30);
12. int s1 = s.doStuff(27);
13. System.out.println( t1 +
" " + s1);
14. }
15. }
What is the result?
A 27 30
B 30 27
C 27 27
D 30 30
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option E is the correct answer.
Line 6 is an illegal override of
the doStuff() method in class
Test.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.1 >
Item 1
--------------------------------------Click the Exhibit button to
view the code.
1. for (int x = 3; x > = 0; x--)
{
2. switch (x - 1) {
3.
case 0:
System.out.print("foo ");
4.
case 1:
System.out.print("bar ");
5.
case 2:
System.out.print("baz ");
6.
case 3:
System.out.print("foo ");
7. }
8. }
What is the result?
A baz bar foo
B foo baz bar foo
C baz bar foo bar foo foo
D baz foo bar baz foo foo bar
baz foo
E Compilation fails
F An exception is thrown at
runtime
answer:
Option D is the correct answer.
As the switch expression
iterates from 2 to -1 the cases
71
start at 2, 1, and 0 and fall
through.
which point y
equals 5 and the
break is executed.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.1 > Item
2
-------------------------------------Click the Exhibit button to view
the code.
1. for (int toggle = 0, y = 0; y <
6; y++ ) {
2. toggle = y % 2;
3. if (toggle) {
4.
System.out.print("true ");
5. }
6. else {
7.
System.out.print("false ");
8. }
9. }
Location: ... > Flow Control,
Assertions, and Exception Handling >
Objective 2.2 > Item 2
-------------------------------------------- Click the Exhibit button to view
the code.
13. long x = 20, y = 30;
14. while ( ++x < = y ) {
15.
--y;
16.
if ( x > y ) {
17.
break;
18.
}
19. }
20. System.out.print(x + " " + y);
What is the result?
A 26 25
B 25 25
C 25 24
D 25 26
E 26 26
Answer:
Option A is the correct answer. The
while statement on line 14
increments x before doing the
comparison test. The break
statement is never reached.
What is the result?
A true true true true true true
B true false true false true false
C false true false true false true
D false false false false false
false
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option E is the correct answer.
Line three is illegal, it should
probably read if (toggle == 1) {.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.2 > Item
1
----------------------------------Click the Exhibit button to view
the code.
7. int x,y;
8. next: for(x = 5, y = 1 ; ; ) {
9. --x;
10. for ( ; x > -1 ; y++) {
11.
if ( x < y ) {
12.
break next;
13.
}
14. }
15. }
16. System.out.println(x + " " +
y);
What is the result?
A 23
B 34
C 45
D 56
E Compilation fails
F An exception is thrown at
runtime
nswer:
Option C is the correct answer.
The variable x is decremented
once, in line 9, then the program
loops through the inner for loop,
incrementing y until x < y, at
Location: ... > Flow Control,
Assertions, and Exception Handling >
Objective 2.3 > Item 1
---------------------------------------Which two statements are true?
(Choose two.)
A catch(Foo f) can catch Foo or any
of its superclasses
B If you throw an Error, it does not
need to be enclosed in a try block
C Any statement that can throw an
Exception must be enclosed in a try
block
D An overriding method must
declare any Exceptions declared by
the overridden method
E An overriding method can throw a
superclass of the Exception declared
by the overridden method
F An overriding method is permitted
to throw a RuntimeException, even if
it has not been declared by the
overridden method.
Answer:
Options B and F are the correct
answers. Overriding methods are not
allowed to throw new or broader
checked exceptions. A checked
exception is any exception extending
from class Exception, but not
extending from RuntimeException.
Errors do not need to be enclosed in
try blocks.
Location: ... > Flow Control,
Assertions, and Exception Handling >
Objective 2.4 > Item 1
----------------------------------------
Click the Exhibit button to
view the code.
1. public class Test243 {
2. public static void main
(String [] args) {
3.
try {
4.
String s = "two";
5.
int i =
Integer.parseInt(s);
6.
System.out.print("i =
" + i);
7.
} catch (Exception ex) {
8.
System.out.print("
Exception ");
9.
}
catch(NumberFormatException
exc) {
10.
System.out.print("
NumberFormatException ");
11.
} finally {
12.
System.out.print("
finally ");
13.
}
14.
System.out.print("
done ");
15. }
16. }
What is the result?
A Exception finally
B i = two finally done
C Exception finally done
D NumberFormatException
finally
E NumberFormatException
finally done
F Compilation fails
Answer:
Option F is the correct answer.
The NumberFormatException
will be caught by the Exception
catch. The compiler recognizes
that the second catch can
never be reached. You must
always put the catch blocks in
order going from most specific
to broadest. If the exceptions
are siblings (i.e. one does not
extend from the other), then
the order does not matter.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.4 >
Item 2
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. public class Test244 {
2. public static void main
(String [] args) {
3.
try {
4.
foo();
5.
System.out.print("
one ");
6.
} catch(Exception e) {
72
7.
System.out.print(" two
");
8.
} finally {
9.
System.out.print(" three
");
10.
}
11.
System.out.print(" four ");
12. }
13.
14. public static void foo() {
15.
throw new
RuntimeException();
16. }
17. }
What is the result? (Choose one)
A three
B two three
C three four
D two three four
E one two three four
F Compilation fails
Answer:
Option D is the correct answer.
Method foo() throws a
RuntimeException, which does
not need to be declared. When
the exception is thrown, the
catch and finally blocks run, and
then the main() method runs to
completion (printing four at the
end).
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.5 > Item
1
--------------------------------------Which two fragments are
examples of inappropriate uses
of assertions? (Choose two.)
A assert (!(foo == null));
foo.go();
B public void method(boolean
b) {
assert (b);
C if (x > y) {
z = x;
} else {
assert (x < 4);
}
D private void test(int z) {
assert (f.setSize(z) > 5);
}
E public int methodA(int x) {
assert (s > 3);
}
Answer:
Options B and D are the correct
answers. B's violation is checking
an argument of a public method.
D's violation is to allow the
assert to have side effects, in
this case by calling a setter
method on a reference. E is an
appropriate use
of an assertion
because it is not checking the
argument of a public method.
correct because all objects are
created in the garbage
collectible heap.
References:
http://java.sun.com/j2se/1.4/docs/g
uide/lang/assert.html#usageconditions
Location: ... > Garbage
Collection > Objective 3.2 >
Item 1
Location: ... > Flow Control,
Assertions, and Exception Handling >
Objective 2.6 > Item 1
-----------------------------------Which two statements are true?
(Choose two.)
A The -ae flag tells the VM to
enable assertions
B The -ea flag tells the compiler to
enable assertions
C The -assert flag tells the VM to
enable assertions
D The -esa flag tells the VM to
enable some assertions
E The -assertions flag tells the
compiler to enable assertions
F The -enableassertions flag tells
the VM to enable assertions
Answer:
Options D and F are the correct
answers. The -esa flag means enable
system assertions.
ocation: ... > Garbage Collection >
Objective 3.1 > Item 1
-------------------------------------------which two statements are true about
the garbage collection system?
(Choose two.)
A Calling Runtime.gc() will reclaim
memory.
B It guarantees that programs will
not have memory leaks
C Objects will never be collected as
long as they are accessible from live
threads.
D Objects that have finalize()
methods always have their finalize()
methods called before the program
ends.
E If object 'A' has at least one other
object with a reference to it, then
object 'A' will not be garbage
collected.
F Objects instantiated within a
method and referenced only by a
local variable are created in the
garbage collectible heap.
nswer:
Options C and F are the correct
answers. C is correct because an
object accessible from a live thread
may yet be called by the JVM. F is
--------------------------------------Click the Exhibit button to
view the code.
1. class Test {
2. public static void
main(String [] args) {
3.
Test2 t2 = new Test2();
4.
Test2 t3;
5.
t3 = t2.m1();
6.
t2 = t2.linker(t2,t3);
7.
t2 = null;
8.
t3 = null;
9. }
10. }
11.
12. class Test2 {
13.
Test2 link;
14.
Test2 m1() {
15.
Test2 x = new Test2();
16.
return x;
17.
}
18.
Test2 linker(Test2 z1,
Test2 z2) {
19.
z1.link = z2;
20.
z2.link = z1;
21.
return z1;
22. }
23. }
Which statement is true?
A After line 8 no objects can
be garbage collected.
B After line 7 one object can
be garbage collected.
C After line 7 no objects can
be garbage collected.
D After line 6 at least one
object has more than two
references
E The z1 and z2 references
must be nulled to make any
objects eligible for garbage
collection.
Answer:
Option C is the correct answer.
After line 7 the t3 reference is
still valid and because of the
link variables both of the Test2
objects are still accessible.
Location: ... > Garbage
Collection > Objective 3.3 >
Item 1
---------------------------------------Click the Exhibit button to
view the code.
73
7. Dog [] da = new Dog[2];
8. Dog clover = new Dog();
9. da[1] = clover;
10. clover = null;
11. Dog fido = new Dog();
12. Dog spot = new Dog();
When is the clover object
eligible for garbage collection?
A after line 9
B after line 10
C after line 11
D never in this code
Answer:
Option D is the correct answer.
The last reference to clover
(da[1]), is never nulled.
Location: ... > Language
Fundamentals > Objective 4.1 >
Item 1
---------------------------------------Click the Exhibit button to view
the code.
1. package com.abc.package1;
2. import java.util.*;
3. public class WeakHash
extends WeakHashMap {
4. int x = 5;
5. Object getDuplicate(Object
key) {
6.
return null;
7. }
8. }
9.
10. private class NewWeakHash
extends WeakHash {
11. public NewWeakHash() {
12.
int x = 7;
13. }
14.
15. public static void
main(String args [] ) {
16.
WeakHash wh = new
WeakHash();
17. }
18. }
What is the result?
A Compilation succeeds
B Compilation fails because of
an error on line 6
C Compilation fails because of
an error on line 10
D Compilation fails because of
an error on line 16
E An exception is thrown at
runtime
Answer:
Option C is the correct answer.
Classes cannot be declared
private.
1. package com.abc.package1;
2. import java.util.*;
3. public class WeakHash
extends WeakHashMap {
4. int x = 5;
5. Object
getDuplicate(Object key) {
6.
return null;
7. }
8. }
9.
10. private class NewWeakHash
extends WeakHash {
11. public NewWeakHash() {
12.
int x = 7;
13. }
14.
15. public static void main(String
args [] ) {
16.
WeakHash wh = new
WeakHash();
17. }
18. }
Location: ... > Language
Fundamentals > Objective 4.1 >
Item 2
---------------------------------------Click the Exhibit button to view the
code.
1.
2. public class NewCollections {
3. public static void main(String []
args) {
4.
java.util.WeakHashMap hm =
new java.util.WeakHashMap();
5.
Object o1 = null;
6.
o1 = hm.put(o1, o1);
7. }
8. }
Which statement must be added at
line 1 to allow this code to compile?
A import java.util.*;
B no statement is required
C import java.util.WeakHashMap;
D include java.util.WeakHashMap;
nswer:
Option B is the correct answer. When
a fully qualified name is used, you
don't have to import the classes or
packages.
Location: ... > Language
Fundamentals > Objective 4.2 >
Item 1
----------------------------------------Which two are valid method
signatures in an interface? (Choose
two.)
A short doShort();
B static char doChar();
C protected byte doByte();
D public boolean doBoolean(int x);
E final public String doString(int x);
Answer:
Options A and D are the correct
answers. A is correct because
interface methods are implicitly
public. D is correct because interface
can be declared public even
though they are so implicitly.
Location: ... > Language
Fundamentals > Objective 4.3
> Item 1
---------------------------------------Click the Exhibit button to
view the code.
1. public class ABC {
2. public static void
main(String [] args ) {
3.
String a = args[3];
4.
String b = args[2];
5.
String c = args[1];
6.
System.out.println("c = "
+ c);
7.
}
8. }
And the command line
invocation:
java ABC A B C
What is the result?
a c=
B c=A
C c=B
D c=C
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option F is the correct answer.
Line 3 will fail; args[3] is out of
bounds.
Location: ... > Language
Fundamentals > Objective 4.4
> Item 1
----------------------------------Click the Exhibit button to
view the code.
1. class Test {
2. public static void
main(String [] args) {
3.
construct Test(int i) {
4.
for (int y=0; y<i;
y++)
5.
System.out.print(" "
+ y);
6.
}
7. }
8. }
And command line invocation:
java Test 6
What is the result?
a 12345
B 012345
C Compilation fails
D An exception is thrown at
runtime
Answer:
Option C is the correct answer.
The word 'construct' is not a
74
valid modifier keyword in the
Java language. Constructors are
identified by having the same
name as the class, but having no
return type.
Location: ... > Language
Fundamentals > Objective 4.4 >
Item 2
--------------------------------------Which two are keywords?
(Choose two.)
A super
B Boolean
C unsigned
D interface
E anonymous
Answer:
Options A and D are the correct
answers. 'interface' and 'super'
are both valid keywords. C is
wrong because 'unsigned' is a
keyword in C, C++, but not Java.
E is wrong because 'anonymous'
is a Java concept but not a
keyword. B 'Boolean' is a class.
The Java primitive keyword is
'boolean'.
Location: ... > Language
Fundamentals > Objective 4.5 >
Item 1
--------------------------------------Click the Exhibit button to view
the code.
1. class IvarLocal {
2. static int x;
3. public static void main(String
args []) {
4.
int y;
5.
System.out.println("x = " +
x + " y = " + y);
6. }
7. }
What is the result?
A x=y=
B x=y=0
C x=0y=
D x=0y=0
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option E is the correct answer.
The compiler will be concerned
about whether y has been
initialized.
Location: ... > Language
Fundamentals > Objective 4.5 >
Item 2
--------------------------------------Click the Exhibit button to view the
code.
7. short x = 1;
8. int [] y = new int[4];
9. y[0] = x;
10. y[1] = x+1;
11. for(int z= 0;z<4; z++) {
12.
System.out.println(" " +
y[z]);
13. }
What is the result?
A 0123
B 1223
C 1200
D 1 2 null null
E Compilation fails
F An exception is thrown at runtime
Answer:
Option C is the correct answer. The
elements in array y are implicitly
initialized to zeros, and then
elements 0 and 1 are updated.
Location: ... > Language
Fundamentals > Objective 4.6 >
Item 1
----------------------------------Which one is valid?
A boolean b2 = 1;
B boolean b3 = null;
C boolean b1 = FALSE;
D boolean b4 = "false";
E boolean b5 = (4 < 1);
answer:
Option E is the correct answer. The
expression (4 < 1) resolves to false.
Location: ... > Language
Fundamentals > Objective 4.6 >
Item 2
----------------------------------Which three are valid? (Choose
three.)
A float f1 = 0x123.45;
B float f2 = 3.14f;
C float f3 = (double) 1.8;
D float f4 = 1.0;
E float f5 = (float) '\'';
F float f6 = '\ubabe';
Answer:
Options B, E, and F are the correct
answers. B is explicitly cast to a
float. E casts a char (which is an
unsigned int) to a float. F casts a
Unicode char to a float.
Location: ... > Operators and
Assignments > Objective 5.1 > Item
2
----------------------------------Given:
10. int x = -1, y = -2;
11. System.out.println( (x<0)
^ (y<0) ) ;
What is the result?
A true
B false
C Compilation fails
D The code runs with no
output
E An exception is thrown at
runtime
Answer:
Option B is the correct answer.
Both equality tests resolve to
true - true XOR true is false.
Location: ... > Operators and
Assignments > Objective 5.2 >
Item 1
-----------------------------------------------------------------------------click the Exhibit button to view
the code.
10. int[] arr1 = new int[2];
11. int[] arr2 =
(int[])arr1.clone();
12. System.out.println( "Array
1 equals array 2 - " +
arr1.equals( arr2 ) );
What is the result?
A Array 1 equals array 2 B Array 1 equals array 2 true
C Array 1 equals array 2 null
D Array 1 equals array 2 false
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option D is the correct answer.
Arrays inherit the default
Object.equals implementation
which compares references not
equivalence of content
therefore comparing two
distinct arrays will always yield
false even if the compared
arrays are clones.
Location: ... > Operators and
Assignments > Objective 5.3 >
Item 1
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
10. boolean flag1 = true;
11. boolean flag2 = false;
75
12. System.out.println( ( flag2 &
flag1 ) & ( flag1 & flag2 ) );
Which two are true? (Choose
two.)
A The code outputs the value
false
B The output may vary if the
ordering is changed
C flag1 and flag2 are both
evaluated exactly once
D The output is always true
regardless of the ordering
E The output is always false
regardless of the ordering
Answer:
Options A and E are the correct
answers. The entire logical
statement is composed of non
shortcutting and therefore ALL
boolean expressions will be
evaluated regardless of the
outcome of a preceding
evaluation. As there are booleans
that resolve to false in all three
composite boolean expressions
the outcome must be false.
Location: ... > Operators and
Assignments > Objective 5.3 >
Item 2
----------------------------------Click the Exhibit button to view
the code.
10. public boolean t1() { return
"hello".equals("HELLO"); }
11. public boolean t2() { return
!t1(); }
12.
13. public void op () {
14. System.out.println( (t1()
&& t2()) | t2() );
15. }
Which four are true? (Choose
four.)
A Compilation fails
B Calling op() means t2() is
always called once
C Calling op() means t1() is
always called once
D The output from op() is
always the value true
E Calling op() means t2() is
always called twice
F Calling op() means t1() is
always called twice
G Reversing the first expression
to (t2() && t1()) does not affect
the output
Answer:
Options B, D, F, and G are the
correct answers.
t1() resolves to false t2()
resolves to not t1() - true
reordering the
first expression
does not affect the outcome because
it is a double && The first call to t1()
returns false and will shortcut the &&
expression to false and the non
shortcut | to the second t2() returns
true resulting in overall true. Due to
shortcut t2() is only ever called once
t1() is called once in the expression
and a second time from t2(),
therefore is called twice
Location: ... > Operators and
Assignments > Objective 5.4 > Item
1
------------------------------------------------------------------------------click the Exhibit button to view the
code.
10. public void op3( boolean[] flags )
{
11. flags = new boolean[3];
12. for ( int i=0; i<flags.length;
i++ ) {
13.
flags[i] = ((i%2)==0);
14. }
15. }
16. public void arrayTest () {
17. boolean[] initial = null;
18. op3( initial );
19. System.out.println( initial[0] );
20. }
What is the result if method
arrayTest() is called?
A
B
C
D
E
F
true
null
false
Compilation fails
The code runs with no output
An exception is thrown at runtime
Answer:
Option F is the correct answer. An
exception is thrown at runtime.
Defining and initializing the array in
op3() has no effect on the callers
reference which remains null.
Therefore the access on initial[0]
causes a
java.lang.NullPointerException
Location: ... > Operators and
Assignments > Objective 5.4 > Item
2
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
10. public StringBuffer op4(
StringBuffer sb ) {
11. sb.append("-widgets");
12. return sb;
13. }
14. public void roundRobinTest () {
15. StringBuffer sb = new
StringBuffer();
16. sb.append("acme");
17. op4(sb);
18. sb.append("-andnuggets");
19. System.out.println(
sb.toString() );
20. }
What is the result if method
roundRobinTest() is called?
A
B
C
D
E
F
acme
acme-widgets
-and-nuggets
acme-and-nuggets
-widgets-and-nuggets
acme-widgets-and-nuggets
Answer:
Option F is the correct answer.
sb is created in roundRobinTest
and its reference passed by
value into op4 where the
shared object is modified. The
same sb is then returned to the
caller, but the caller never
assigns or re-assigns its local
sb reference and it appears
that modifications in op4 are
lost, but as this is a shared
object by reference all
modifications remain, so the
output is acme-widgets-andnuggets
Location: ... > Objective 6.1
> Item 1
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. class A {
2. private static class B {
3.
private static String
msg = "ok" ;
4. }
5. public static String
access() {
6.
return B.msg;
7. }
8. }
9. class X {
10. public static void main(
String[] args ) {
11.
System.out.println(
A.access() );
12. }
13. }
Which two are true? (Choose
two.)
A Compilation fails
B The code outputs the value
ok
76
C An exception is thrown at
runtime
D Any private members of B
can be accessed from class A
only through accessor methods
E The private modifier on msg
must be weakened to default or
public for this code to work
correctly
Answer:
Options B and D are the correct
answers. Access to an nested
classes private methods and
variables is granted to the
encapsulating classes methods.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 3: Extending Classes -ISBN: 0-201-70433-1
Location: ... > Objective 6.1 >
Item 2
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
1. interface D {}
2. class E implements D {}
3. class F extends E {
4.
F() {}
5. }
6. class G extends F
implements D {}
7. class X {
8.
public static void main(
String[] args ) {
9.
E e = new F();
10.
D d = new G();
11. }
12. }
Which three are true? (Choose
three.)
A The declaration of G is illegal
B E is said to be a superclass of
F
C G is said to be a superclass of
E
D The assignment at line 10 is
legal
E A variable can be declared
using an interface type
F Compilation fails
answer:
B, D, and E. B is correct because
class F extends class E, making E
a superclass of F. D and E are
correct because the code
compiles successfully, the
declaration of G reimplementing
D is legal, as is the declaration of
d using an interface D as its
type.
Location: ... > Objective 6.2 > Item
1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
10. class P {
11. P( String s ){}
12. P( short s ){}
13. }
14. class Q extends P {
15. protected Q() {
super((short)3); }
16. public Q( int i ) { super( new
Integer(i).toString() ); }
17. Q( boolean b ) { super(""); }
18. Q( short s ) { super( s ); }
19. }
If the following new statements are
invoked in a separate class in the
same package as classes P and Q,
which three are true? (Choose
three.)
A Compilation fails for code - new
Q();
B Compilation fails for code - new
P();
C Compilation fails for code - new
Q("");
D Compilation fails for code - new
P('a');
E Compilation fails for code - new
Q((short)1);
F Compilation fails for code - new
Q( new Q(3) instanceof P );
Answer:
Options B, C, and D are the correct
answers. The relationship and
declaration of P & Q are sound. This
question is quite simple couched in
seemingly complex code. Simply test
the argument passed in the new call
with a constructor in the target class,
if a match is found it compiles. The
last three options here do not have
matching constructors.
Location: ... > Objective 6.2 > Item
2
----------------------------------Click the Exhibit button to view the
code.
10. abstract class X {
11. public final void op(){}
12. abstract final void op();
13. void op( String s ){}
14. abstract synchronized void
op(int i) throws Exception;
15. abstract private void op( String
a, int i );
16. }
Which three are true? (Choose
three.)
A Line 10 is uncompilable
B Line 11 is uncompilable
C Line 12 is uncompilable
D Line 13 is uncompilable
E Line 14 is uncompilable
F Line 15 is uncompilable
Answer:
Options C, E, and F are the
correct answers.
line 10 ok, the class must be
declared abstract
line 11 ok, the initial method
declaration signature
line 12 fails, cannot combine
abstract and final, conflict of
intentions
line 13 ok, the first successful
overload of op(), but with
differing access privileges
line 14 fails, cannot combine
abstract with implementation
details like synchronized
line 15 fails, cannot combine
abstract and private, no way to
implement in subclass
Location: ... > Objective 6.3
> Item 1
--------------------------------------------------------------------------Click the Exhibit button to view
the code.
1. interface XX {}
2. interface YY extends XX {}
3. abstract class ZZ
implements XX {}
4. class AA extends ZZ
implements YY {
5. private class BB{}
6. }
7. class Main extends AA {
8. public static void main(
String[] args ) {
9.
XX xx1 = new XX ();
10.
XX xx2 = new AA ();
11.
ZZ zz1 = new Main ();
12.
Main m = new AA();
13. }
14. }
Which two are true? (Choose
two.)
A Line 5 is uncompilable
B Line 9 is uncompilable
C Line 10 is uncompilable
D Line 11 is uncompilable
E Line 12 is uncompilable
F Compilation succeeds
Answer:
Options B and E are the correct
answers. Line 9 attempts to
instantiate an interface. Line
12 is an incompatible
assignment; you can't assign a
77
superclass object to a subclass
reference type.
Location: ... > Objective 6.3 >
Item 1
Click the Exhibit button to view
the code.
1. interface XX {}
2. interface YY extends XX {}
3. abstract class ZZ implements
XX {}
4. class AA extends ZZ
implements YY {
5. private class BB{}
6. }
7. class Main extends AA {
8. public static void main(
String[] args ) {
9.
XX xx1 = new XX ();
10.
XX xx2 = new AA ();
11.
ZZ zz1 = new Main ();
12.
Main m = new AA();
13. }
14. }
Which two are true? (Choose
two.)
A Line 5 is uncompilable
B Line 9 is uncompilable
C Line 10 is uncompilable
D Line 11 is uncompilable
E Line 12 is uncompilable
F Compilation succeeds
Answer:
Options B and E are the correct
answers. Line 9 attempts to
instantiate an interface. Line 12
is an incompatible assignment;
you can't assign a superclass
object to a subclass reference
type.
Location: ... > Objective 6.3 >
Item 2
Click the Exhibit button to
view the code.
1. class Outer {
2. class Inner {}
3. }
4. class ExtendedOuter extends
Outer {
5. class ExtendedInner extends
Inner {}
6. }
7. class Main extends
Outer.Inner {
8. Main( Outer ref ) {
9. ref.super();
10. }
11. public static void main(
String[] args ) {
12. new Main( new
ExtendedOuter() );
13. }
14. }
What is the result?
A Compilation
fails
B An exception is thrown at runtime
C The code runs with no output
Answer:
Option C is the correct answer. An
inner class can extend another,
unrelated, inner class provided an
appropriate enclosing instance is
supplied to the superclass. The
resulting inner class then has two
enclosing instances, one for the
extended class and one for the
superclass. Therefore this code
cleanly compiles and outputs
nothing.
Location: ... > Threads > Objective
7.1 > Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. public static void main( String[]
args ) {
2. class Widget extends
java.lang.Thread {
3.
Widget(boolean daemon) {
4.
this.setDaemon(daemon);
5.
this.start();
6.
}
7. }
8.
9. for ( int i= 0;i<10; i++ ) {
10. new Widget(((i%2)==0));
11. }
12. }
Which two statements are true?
(Choose two.)
A Compilation fails.
B Only five threads are created.
C An exception is thrown at
runtime.
D Ten independent threads are
created.
E Ten threads are created but only
five execute.
F The program terminates after the
tenth thread is created.
Answer:
Options D and F are the correct
answers. The program creates
precisely 10 threads, every other of
which is marked as daemon thread.
Each thread executes on the default
run() method so all will terminate
and therefore the program
terminates.
Reference:
The Java Programming Language,
Third Edition, by Arnold, Gosling &
Holmes, Chapter 10: Threads
ISBN: 0-201-70433-1
location: ... > Threads >
Objective 7.1 > Item 2
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
11. public static void main(
String[] args ) {
12. class Widget extends
java.lang.Thread {
13.
Widget() {
14.
this.start();
15.
}
16. }
17.
18. Widget w = new
Widget();
19. w.setDaemon(true);
20. }
Which statement is true?
A Compilation fails.
B The program never
terminates.
C One daemon thread is
created.
D An exception is thrown at
runtime.
E The program terminates
after the thread is created.
Answer:
Option D is the correct answer.
An exception is thrown at
runtime va.lang.IllegalThreadStateExce
ption setdaemon(true) can not
be invoked on an active
thread.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.2 > Item 1
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. class Worker extends
java.lang.Thread {
2. public void run() {
3.
while ( true ) {}
4. }
5.
6. public static void main(
String[] args ) {
7.
for (int i=0;
i<MAX_PRIORITY; i++ ){
8.
Worker w = new
Worker();
9.
w.setPriortity(
MIN_PRIORITY+i );
10.
w.setDaemon(true);
11.
w.start();
12. }
78
13. }
14. }
Which two statements are true?
(Choose two.)
A Compilation fails.
B An exception is thrown at
runtime.
C All threads are guaranteed to
execute.
D Some of the threads may
never execute.
E The program runs forever
with no output.
F The program terminates when
the main() method completes.
Answer:
Options D and F are the correct
answers. As all threads are
marked as Daemon threads, the
program contains no user
threads once main terminates, so
the program as a whole
terminates. A number of the
daemon threads may never
execute due to the early
termination of the program and
the priority levels assigned.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.2 > Item 2
Click the Exhibit button to view
the code.
1. class Worker extends
java.lang.Thread {
2. public void run() {
3. while ( true ) {
4.
synchronized( this ) {
5.
try {
6.
wait();
7.
} catch (Exception e) {}
8.
}
9.
System.out.println("ok");
10. }
11. }
12. public static void main(
String[] args ) {
13. new Worker().start();
14. }
15. }
Which two statements are true?
(Choose two.)
A Compilation fails.
B The program never
terminates.
C The program runs with no
output.
D The value ok is repeatedly
output.
E The program
terminates and
outputs ok precisely once.
F The Worker thread never blocks
inside the wait method because there
are no other threads executing.
answer:
Options B and C are the correct
answers. This program simply
launches a single user thread that
immediately blocks inside the wait()
method The thread is never
unblocked because no other thread is
executing to call the notify on the
lock.
Reference:
The Java Programming Language,
Third Edition, by Arnold, Gosling &
Holmes, Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads > Objective
7.3 > Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
10. class X {
11. synchronized void iTest() {
12.
while(true) {
13.
Thread.yield();
14.
}
15. }
16. synchronized static void sTest()
{}
17. public void op() {}
18. }
And, given a single instance of X,
and two or more concurrent threads,
which statement is true?
A Multiple threads can execute
iTest() concurrently.
B Any thread calling iTest() will be
blocked pending a call to notify.
C While a thread is executing
iTest(), any call on sTest() will block
pending lock access.
D While a thread is executing
iTest(), no other threads may
execute any methods declared in X.
E While a thread is executing
iTest(), op() may be concurrently
executed inside the same instance of
X.
Answer:
Option E is the correct answer. Static
methods synchronize on the class
object, not on an instance object, so
concurrent calls to iTest() and
sTest() will not block each other.
op() is not synchronized so may be
called concurrently with anything
else.
Reference:
The Java Programming Language,
Third Edition, by Arnold, Gosling &
Holmes, Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.3 > Item 2
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. class WorkerT extends
java.lang.Thread {
2. private static StringBuffer
sb = new StringBuffer();
3. public void run() {
4.
notify();
5.
try {
6.
wait();
7.
} catch (Exception e) {}
8. }
9. public static void main(
String[] args ) {
10.
for (int i= 0;i<10; i++)
{
11.
new
WorkerT().start();
12.
}
13. }
14. }
Which statement is true?
A Compilation fails.
B All 10 threads block.
C An exception is thrown at
runtime.
D All 10 threads execute to
completion.
E Each thread is unlocked by
the following thread until only
the final thread remains
blocked.
Answer:
Option C is the correct answer.
An exception is thrown
java.lang.IllegalMonitorStateEx
ception: current thread not
owner. The caller of wait(),
notify(), or notifyAll() must
own the monitor lock that is,
they must be executing inside
a synchronized method or
section to be able to
successfully call any of these
methods.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.4 > Item 1
-----------------------------------------------------------------------------Which three statements are
true? (Choose three.)
A The Object class defines a
wait() method.
79
B
The Thread class overrides
a wait() method.
C
The Runnable interface
defines a wait() method.
D
wait() can be called at any
time by an executing thread.
E
The wait() method used in
thread communication releases
an object lock.
F
The wait() method is
overloaded and also has the
following signature public final
void wait(long timeout).
answer:
Options A, E, and F are the
correct answers.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.4 > Item 2
-----------------------------------------------------------------------------which two statements are
correct? (Choose two.)
A To call notify() a thread must
own the monitor lock.
B
The notify() and notifyAll()
methods are defined in the
Thread class.
C
The notify() and notifyAll()
methods are defined in the
Object class.
D
A thread can only call
notify() if another thread has
previously called wait().
E
The notify() and notifyAll()
methods are defined in the
Runnable interface.
Answer:
Options A and C are the correct
answers.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Fundamental
Classes in the java.lang package
> Objective 8.1 > Item 1
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
1. public class Test813 {
2. public static void main(String
[] args) {
3.
double a =
Math.round(5.5);
4.
double b = Math.round(5.2);
5.
double c = Math.round(-5.0);
6.
double d = Math.round(-5.4);
7.
double e = Math.round(-5.5);
8.
System.out.print( "Results: " +
a+""+b+""+c+""+d+""
+ e);
9.
}
10. }
What is the result?
A Results: 6.0 5.0 -5.0 -5.0 -5.0
B Results: 6.0 5.0 -5.0 -5.0 -6.0
C Results: 5.0 5.0 -5.0 -5.0 -5.0
D Results: 6.0 5.0 -5.0 -4.0 -5.0
E Results: 6.0 5.0 5.0 5.0 6.0
F Compilation fails.
nswer:
Option A is the correct answer. Both
positive and negative numbers are
rounded up to the larger number. For
a positive number such as 5.5, the
greater number is 6, but for -5.5 the
greater number is -5.0.
Location: ... > Fundamental
Classes in the java.lang package >
Objective 8.2 > Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. public class Test823 {
2. public static void main(String []
args) {
3.
String a = "freddy";
4.
String b = a.substring(0,3);
5.
b.toUpperCase();
6.
System.out.println(a += b);
7. }
8. }
What is the result?
A freddyFRE
B freddyfre
C freddyFRED
D freddyfred
E Compilation fails.
Answer:
Option B is the correct answer. The a
String reference is never modified,
and the toUpperCase() call is not
assigned to b so b's original object
does not change.
Location: ... > Fundamental Classes
in the java.lang package > Objective
8.2 > Item 2
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. public class Test825 {
2. public static void main(String []
args) {
3.
String a = "big";
4.
String b = a;
5.
a = a + "bird";
6.
a = b;
7.
b = "bird";
8.
System.out.println(a =
a+b);
9. }
10. }
What is the result?
A bigbird
B birdbird
C bigbigbird
D bigbirdbird
E Compilation fails.
Answer:
Option A is the correct answer.
In line 4, b is set to refer to the
String literal "big". The String
referenced by b is not changed
by the change to a in line 5,
because Strings are
immutable. In line 5, a new
String object "bigbird" is
created, and assigned to a. At
this point (line 5) b is still
referring to "big" and a is now
referring to "bigbird". In line
6,then, a is set to refer to the
String literal "big" referenced
by b, so both a and b refer to
the String literal "big". In line
7, b is set to reference a String
literal "bird", while a is left
unchanged and still refers to
"big". Finally, a + b is printed
out, producing "bigbird".
Location: ... > Fundamental
Classes in the java.lang
package > Objective 8.3 >
Item 1
--------------------------------------------------------------------------Which creates a new
Character object?
A Character a = new
Character("c");
B
Character a =
Character.getCharacter('s');
C
Character a = new
Character(new char[]{'s'});
D
Character a =
Character.valueOf("c".toChar()
);
E Character a = new
Character((new
char[]{'s'})[0]);
Answer:
Option E is the correct answer.
The Character class has only
one constructor, and it takes a
char primitive. Answer "E"
constructs an anonymous char
array holding a single char,
then accesses the array
element at index 0, thus
returning a char to the
Character constructor.
80
Location: ... > Fundamental
Classes in the java.lang package
> Objective 8.3 > Item 2
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
1. public class Test834 {
2. public static void main(String
[] args) {
3.
try {
4.
Double d = new
Double(new
Byte(6).doubleValue());
5.
String s = d.toString();
6.
System.out.println(Integer.parse
Int(s));
7.
}
catch(NumberFormatException
ex) {
8.
System.out.println("failed");
9.
}
10. }
11. }
What is the result?
A 6
B 6.0
C null
D failed
E Compilation fails.
F An uncaught exception is
thrown at runtime.
Answer:
Option E is the correct answer.
Byte does not have a constructor
that takes an int. The Byte
constructor must be passed a
previously declared byte
variable, or explicitly cast an int
value.
Location: ... > The Collections
Framework > Objective 9.1 >
Item 1
-----------------------------------------------------------------------------Which two statements are true
of class java.util.HashMap?
(Choose two.)
A Its methods are thread-safe.
B It allows null references to be
stored.
C It provides fast, bi-directional
iteration.
D It implements
java.util.Hashable.
E It tracks when its elements
were last accessed.
F Its elements can be accesssed
using a unique key.
Answer:
Options B and F are the correct
answers. HashMap implements
java.util.Map,
which allows
elements to be accessed using a
unique key. Whereas HashTable does
not permit null references to be
stored, HashMap allows both keys
and elements to be null.
Location: ... > The Collections
Framework > Objective 9.1 > Item 2
---------------------------------------Click the Exhibit button to view the
code.
1. TreeSet s = new TreeSet();
2. s.add("Fred");
3. s.add("Mike");
4. s.add("Zeus");
5. s.add("Fred");
6. s.add("Amy");
7. Iterator i = s.iterator();
8. while(i.hasNext()) {
9.
System.out.print(i.next() + ",
");
10. }
What is the result?
A Fred, Mike, Zeus, Amy,
B Amy, Fred, Mike, Zeus,
C Fred, Mike, Zeus, Fred, Amy,
D Amy, Fred, Fred, Mike, Zeus,
E Five elements will be printed, but
the order is not guaranteed.
F Four elements will be printed, but
the order is not guaranteed.
Answer:
Option B is the correct answer. A
TreeSet is a Set, which eliminates
duplicates, so Fred only goes in once.
A TreeSet is sorted so the Strings
come out in alphabetical order
Location: ... > The Collections
Framework > Objective 9.2 > Item 1
-If class X implements hashcode()
and equals() correctly, and given two
instances (o1 and o2) of class X,
which two are true? (Choose two.)
A if o1.hashcode() and
o2.hashcode() are not the same,
then o1 and o2 must not be equal
B o1.hashcode() and o2.hashcode()
might be the same if o1 and o2 are
considered equal
C o1.hashcode() and o2.hashcode()
must be the same if o1 and o2 are
considered equal
D if o1 and o2 are not equal, then
o1.hashcode() and o2.hashcode()
must not be the same
Answer:
Options A and C are the correct
answers. Hashcode suggests the
likelihood of equality, while equality
requires that hashcodes must be the
same. The rules for correct
implementation of hashcode and
equals require that if two objects are
equal, their hashcodes MUST
be the same. If two objects are
unequal, however, they may
still have the same hashcode.
So, object equivalency
guarantees hashcode
equivalency, but hashcode
equivalency does not
guarantee object equivalency.
---------Question 1
-------What will happen if you
compile/run this code?
1: public class Q1 extends
Thread
2: {
3: public void run()
4: {
5:
System.out.println("Before
start method");
6:
this.stop();
7:
System.out.println("After stop
method");
8: }
9:
10: public static void
main(String[] args)
11: {
12:
Q1 a = new Q1();
13:
a.start();
14: }
15: }
A) Compilation error at line 7.
B) Runtime exception at line 7.
C) Prints "Before start method"
and "After stop method".
D) Prints "Before start method"
only.
-------------Question 2
-------------What will happen if you
compile/run the following
code?
1: class Test
2: {
3:
static void show()
4:
{
5:
System.out.println("Show
method in Test class");
6:
}
7: }
8:
9: public class Q2 extends
Test
10: {
11:
static void show()
12:
{
13:
System.out.println("Show
method in Q2 class");
81
14:
}
15:
public static void
main(String[] args)
16:
{
17:
Test t = new Test();
18:
t.show();
19:
Q2 q = new Q2();
20:
q.show();
21:
22:
t = q;
23:
t.show();
24:
25:
q = t;
26:
q.show();
27:
}
28: }
A) prints "Show method in Test
class"
"Show method in Q2
class"
"Show method in Q2
class"
"Show method in Q2
class"
B) prints "Show method in Test
class"
"Show method in Q2
class"
"Show method in Test
class"
"Show method in Test
class"
C) prints "Show method in Test
class"
"Show method in Q2
class"
"Show method in Test
class"
"Show method in Q2
class"
D) Compilation error.
--------------Question 3
--------------The following code will give
1: class Test
2: {
3:
void show()
4:
{
5:
System.out.println("non-static
method in Test");
6:
}
7: }
8: public class Q3 extends Test
9: {
10:
static void show()
11:
{
12:
System.out.println("Overridden
non-static method in Q3");
13:
}
14:
15:
public static void
main(String[] args)
16:
{
17:
Q3 a = new Q3();
18:
}
19: }
A) Compilation error at line 3.
B) Compilation error at line 10.
C) No compilation error, but runtime
exception at line 3.
D) No compilation error, but runtime
exception at line 10.
--------Question 4
--------The following code will give
1: class Test
2: {
3:
static void show()
4:
{
5:
System.out.println("Static
method in Test");
6:
}
7: }
8: public class Q4 extends Test
9: {
10:
void show()
11:
{
12:
System.out.println("Overridden static
method in Q4");
13:
}
14:
public static void
main(String[] args)
15:
{
16:
}
17: }
A) Compilation error at line 3.
B) Compilation error at line 10.
C) No compilation error, but runtime
exception at line 3.
D) No compilation error, but runtime
exception at line 10.
-------------Question 5
-------------The following code will print
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
int i =
i <<=
i >>=
i >>=
1;
31;
31;
1;
int j = 1;
j >>= 31;
j >>= 31;
System.out.println("i = " +i );
System.out.println("j = " +j);
A) i = 1
j=1
B) i = -1
j=1
C) i = 1
j = -1
D) i = -1
j=0
--------------Question 6
--------------The following code will print
1: Double a = new
Double(Double.NaN);
2: Double b = new
Double(Double.NaN);
3:
4: if( Double.NaN ==
Double.NaN )
5:
System.out.println("True");
6: else
7:
System.out.println("False");
8:
9: if( a.equals(b) )
10:
System.out.println("True");
11: else
12:
System.out.println("False");
A) True
True
B) True
False
C) False
True
D) False
False
----------------------------------------------------Question 7
----------------------------------------------------The following code will print
1: if( new Boolean("true")
== new Boolean("true"))
2:
System.out.println("True");
3: else
4:
System.out.println("False");
A) Compilation error.
B) No compilation error, but
runtime exception.
C) Prints "True".
D) Prints "False".
--------Question 8
82
--------The following code will give
1: public class Q8
2: {
3:
int i = 20;
4:
static
5:
{
6:
int i = 10;
7:
8:
}
9:
public static void
main(String[] args)
10:
{
11:
Q8 a = new Q8();
12:
System.out.println(a.i);
13:
}
14: }
A) Compilation error, variable "i"
declared twice.
B) Compilation error, static
initializers for initialization
purpose only.
C) Prints 10.
D) Prints 20.
----------------------------------------------------Question 9
----------------------------------------------------The following code will give
1:
Byte b1 = new
Byte("127");
2:
3:
if(b1.toString() ==
b1.toString())
4:
System.out.println("True");
5:
else
6:
System.out.println("False");
A) Compilation error, toString()
is not avialable for Byte.
B) Prints "True".
C) Prints "False".
Question 10
----------------------------------------------------What will happen if you
compile/run this code?
1: public class Q10
2: {
3:
public static void
main(String[] args)
4:
{
5:
int i = 10;
6:
int j = 10;
7:
boolean b = false;
8:
9:
if( b = i == j)
10:
System.out.println("True");
11:
else
12:
System.out.println("False");
13:
}
14: }
A) Compilation error at line 9 .
B) Runtime error exception at line 9.
C) Prints "True".
D) Prints "False".
----------------------------------------------------Question 11
----------------------------------------------------What will happen if you compile/run
the following code?
1: public class Q11
2: {
3:
static String str1 = "main
method with String[] args";
4:
static String str2 = "main
method with int[] args";
5:
6:
public static void
main(String[] args)
7:
{
8:
System.out.println(str1);
9:
}
10:
11:
public static void main(int[]
args)
12:
{
13:
System.out.println(str2);
14:
}
15: }
A) Duplicate method main(),
compilation error at line 6.
B) Duplicate method main(),
compilation error at line 11.
C) Prints "main method with main
String[] args".
D) Prints "main method with main
int[] args".
----------------------------------------------------Question 12
----------------------------------------------------What is the output of the following
code?
1: class Test
2: {
3:
Test(int i)
4:
{
5:
System.out.println("Test("
+i +")");
6:
}
7: }
8:
9: public class Q12
10: {
11:
static Test t1 = new
Test(1);
12:
13:
Test
t2 = new
Test(2);
14:
15:
static Test t3 = new
Test(3);
16:
17:
public static void
main(String[] args)
18:
{
19:
Q12 Q = new
Q12();
20:
}
21: }
A) Test(1)
Test(2)
Test(3)
B) Test(3)
Test(2)
Test(1)
C) Test(2)
Test(1)
Test(3)
D) Test(1)
Test(3)
Test(2)
----------------------------------------------------Question 13
----------------------------------------------------What is the output of the
following code?
1:
2:
3:
4:
1 =
5:
1 =
int i = 16;
int j = 17;
System.out.println("i >>
" + (i >> 1));
System.out.println("j >>
" + (j >> 1));
A) Prints i >> 1 = 8
j >> 1 = 8
B) Prints i >> 1 = 7
j >> 1 = 7
C) Prints i >> 1 = 8
j >> 1 = 9
D) Prints i >> 1 = 7
j >> 1 = 8
----------------------------------------------------Question 14
-----------------------------------------------------
83
What is the output of the
following code?
1:
2:
3:
4:
int i = 45678;
int j = ~i;
System.out.println(j);
A) Compilation error at line 2. ~
operator applicable to boolean
values only.
B) Prints 45677.
C) Prints -45677.
D) Prints -45679.
----------------------------------------------------Question 15
----------------------------------------------------What will happen when you
invoke the following method?
1: void infiniteLoop()
2: {
3:
byte b = 1;
4:
5:
while ( ++b > 0 )
6:
;
7:
System.out.println("Welcome to
Java");
8: }
A) The loop never
ends(infiniteLoop).
B) Prints "Welcome to Java".
C) Compilation error at line 5.
++ operator should not be used
for byte type variables.
----------------------ANSWER-----------------------------------------------------Question No
: 1 2 3 4 5 6 7 8 9 10 11 12 13
14 15
Correct Answer
:
DDBBDCDDCCCDADB
Your Answer
A--------------
Location: ... > Declarations and
Access Control > Objective 1.1 >
Item 1
-----------------------------------------------------------------------------Click the Exhibit button.
Which two lines of code will
compile correctly? (Choose two.)
1. class CharArray2 {
2. public static void main(
String [] args) {
3.
char b = 'b';
4.
char c =
'C';
5.
char [] c1 = {'a', 'b', 'c'};
6.
char [] c2 = {'a', b , 'c'};
7.
char [] c3 = ('a', 'b', 'c');
8.
char [] c4 = [3];
9.
char [] c5 = [3] {'a', 'b', 'c'};
10.
char [] c6 = [] {'a', 'b', c};
11. }
12. }
A line 5
B line 6
C line 7
D line 8
E line 9
F line 10
Answer:
Options A and B are the correct
answers. This question explores a
Java syntax shortcut. A and B
represent acceptable syntax to
declare, construct, and initialize an
array in a single line of code.
Location: ... > Declarations and
Access Control > Objective 1.1 >
Item 2
------------------------------------------------------------------------------Click the Exhibit button.
1. class Test{
2. public static void main( String []
args) {
3.
int [] y;
4.
int [] z = new int [] {1, 2, 3};
5.
y = z;
6.
z[1] = 7;
7.
for (int x= 0;x<3; x++) {
8.
System.out.print(" y[" + x
+ "] = " + y[x]);
9.
}
10. }
11. }
What is the result?
A y[0] = 0 y[1] = 1 y[2] = 2
B y[0] = 7 y[1] = 2 y[2] = 3
C y[0] = 1 y[1] = 7 y[2] = 3
D y[0] = 1 y[1] = 2 y[2] = 3
E Compilation fails
F An exception is thrown at runtime
Answer:
Option C is the correct answer. y and
z are reference variables. Line 5
assigns y to refer to the same array
as z, there is still only one array
(however there are two array
references). When line 6 executes, it
changes a value in the only array
there is, (the one both y and z refer
to). Therefore when the array is
accessed via y, the updated value is
displayed.
ocation: ... > Declarations and
Access Control > Objective 1.2 >
Item 1
------------------------------------------------------------------------------Which declaration ensures that a
class cannot be subclassed?
A abstract class MyClass { }
B final public class MyClass {
}
C final abstract class MyClass
{}
D static private class MyClass
{}
E static protected class
MyClass { }
Answer:
Option B is the correct answer.
The final modifier insures that
a class can not be subclassed.
Q31. class XXX {
2. long doStuff (int input) {
3.
static long x = 7;
4.
return (long) input / x;
5. }
6.
7. public static void
main(String [] args) {
8.
XXX xxx = new XXX();
9.
System.out.println(xxx.doStuff
(42));
10. }
11. }
What will be the result?
A 6
B 7
C 42
D Compilation fails
E An exception is thrown at
runtime
Answer:
Option D is the correct answer.
The compiler will notice that in
Line 3 the code is declaring a
static variable, but it's in a
local method, which is not
legal. If several instances of
XXX were instantiated it would
be impossible to know which
instance the static should
belong to.
Location: ... > Declarations
and Access Control > Objective
1.3 > Item 1
-----------------------------------------------------------------------------Click the Exhibit button.
1. class Foo {
2. Foo(String s) { }
3. }
4. class Bar extends Foo { }
Which statement is true?
A Class Bar will not compile
B Class Bar has a public
constructor
C Class Bar's constructor
invokes super()
D Class Foo's constructor
does not invoke super()
84
answer:
Option A is the correct answer.
The compiler attempts to create
a default constructor for class
Bar, because Bar has not defined
any constructors. The class Bar
constructor will include a call to
super(). Since class Foo does not
have a no-arg constructor, class
Bar will not compile because the
default constructor the compiler
is attempting to build includes a
call to super(), and there is no
matching no-arg constructor in
class Foo.
Location: ... > Declarations and
Access Control > Objective 1.3 >
Item 2
-----------------------------------------------------------------------------Given:
1. class Pizza { }
Which of these represents the
functionality of the default
constructor for Pizza?
A Pizza()
B Pizza() {super();}
C public void Pizza()
D public Pizza() {super();}
E There is no default
constructor for Pizza
Answer:
Option B is the correct answer.
The compiler creates a default
constructor for Pizza, with default
access (matching the access of
the class), and a no-arg call to
super().
Location: ... > Declarations and
Access Control > Objective 1.4 >
Item 1
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
1. class XL {
2. public long doMath() {
3.
return 343L;
4. }
5. }
6.
7. class L extends XL {
8.
9. }
Which two methods inserted at
line 8, will not compile? (Choose
two.)
a public void doMath() { }
B public void doMath(int i) { }
C public int doMath() { return
343 }
D public long doMath(int i) {
return 343 }
answer:
Options A and C are the correct
answers. A and C represent an illegal
override of the class XL doMath()
method. Because the arguments
have not changed, the return type
cannot change.
Location: ... > Declarations and
Access Control > Objective 1.4 >
Item 2
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. class Test {
2. public short doStuff(int i) {
return 27; }
3. }
4.
5. public class SubTest extends Test
{
6. public int doStuff(int x) { return
30; }
7.
8. public static void main(String []
args) {
9.
Test t = new Test();
10.
SubTest s = new SubTest();
11. int t1 = t.doStuff(30);
12. int s1 = s.doStuff(27);
13. System.out.println( t1 + " " +
s1);
14. }
15. }
What is the result?
A 27 30
B 30 27
C 27 27
D 30 30
E Compilation fails
F An exception is thrown at runtime
Answer:
Option E is the correct answer. Line 6
is an illegal override of the doStuff()
method in class Test.
Location: ... > Flow Control,
Assertions, and Exception Handling >
Objective 2.1 > Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. for (int x = 3; x > = 0; x--) {
2. switch (x - 1) {
3.
case 0: System.out.print("foo
");
4.
case 1: System.out.print("bar
");
5.
case 2: System.out.print("baz
");
6.
case 3: System.out.print("foo
");
7. }
8. }
What is the result?
A baz bar foo
B foo baz bar foo
C baz bar foo bar foo foo
D baz foo bar baz foo foo bar
baz foo
E Compilation fails
F An exception is thrown at
runtime
answer:
Option D is the correct answer.
As the switch expression
iterates from 2 to -1 the cases
start at 2, 1, and 0 and fall
through.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.1 >
Item 2
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. for (int toggle = 0, y = 0; y
< 6; y++ ) {
2. toggle = y % 2;
3. if (toggle) {
4.
System.out.print("true ");
5. }
6. else {
7.
System.out.print("false
");
8. }
9. }
What is the result?
A true true true true true
true
B true false true false true
false
C false true false true false
true
D false false false false false
false
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option E is the correct answer.
Line three is illegal, it should
probably read if (toggle == 1)
{.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.2 >
Item 1
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
7. int x,y;
8. next: for(x = 5, y = 1 ; ; ) {
9. --x;
10. for ( ; x > -1 ; y++) {
11.
if ( x < y ) {
85
12.
break next;
13.
}
14. }
15. }
16. System.out.println(x + " " +
y);
What is the result?
A 23
B 34
C 45
D 56
E Compilation fails
F An exception is thrown at
runtime
nswer:
Option C is the correct answer.
The variable x is decremented
once, in line 9, then the program
loops through the inner for loop,
incrementing y until x < y, at
which point y equals 5 and the
break is executed.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.2 > Item
2
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
13. long x = 20, y = 30;
14. while ( ++x < = y ) {
15.
--y;
16.
if ( x > y ) {
17.
break;
18.
}
19. }
20. System.out.print(x + " " +
y);
What is the result?
A 26 25
B 25 25
C 25 24
D 25 26
E 26 26
Answer:
Option A is the correct answer.
The while statement on line 14
increments x before doing the
comparison test. The break
statement is never reached.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.3 > Item
1
-----------------------------------------------------------------------------Which two statements are true?
(Choose two.)
A catch(Foo f) can catch Foo or
any of its superclasses
B If you throw an Error, it does
not need to be enclosed in a try
block
C Any
statement that
can throw an Exception must be
enclosed in a try block
D An overriding method must
declare any Exceptions declared by
the overridden method
E An overriding method can throw a
superclass of the Exception declared
by the overridden method
F An overriding method is permitted
to throw a RuntimeException, even if
it has not been declared by the
overridden method.
Answer:
Options B and F are the correct
answers. Overriding methods are not
allowed to throw new or broader
checked exceptions. A checked
exception is any exception extending
from class Exception, but not
extending from RuntimeException.
Errors do not need to be enclosed in
try blocks.
Location: ... > Flow Control,
Assertions, and Exception Handling >
Objective 2.4 > Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. public class Test243 {
2. public static void main (String []
args) {
3.
try {
4.
String s = "two";
5.
int i = Integer.parseInt(s);
6.
System.out.print("i = " + i);
7.
} catch (Exception ex) {
8.
System.out.print("
Exception ");
9.
}
catch(NumberFormatException exc)
{
10.
System.out.print("
NumberFormatException ");
11.
} finally {
12.
System.out.print(" finally
");
13.
}
14.
System.out.print(" done ");
15. }
16. }
What is the result?
A Exception finally
B i = two finally done
C Exception finally done
D NumberFormatException finally
E NumberFormatException finally
done
F Compilation fails
Answer:
Option F is the correct answer. The
NumberFormatException will be
caught by the Exception catch. The
compiler recognizes that the second
catch can never be reached. You
must always put the catch
blocks in order going from
most specific to broadest. If
the exceptions are siblings (i.e.
one does not extend from the
other), then the order does not
matter.
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.4 >
Item 2
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. public class Test244 {
2. public static void main
(String [] args) {
3.
try {
4.
foo();
5.
System.out.print("
one ");
6.
} catch(Exception e) {
7.
System.out.print("
two ");
8.
} finally {
9.
System.out.print("
three ");
10.
}
11.
System.out.print(" four
");
12. }
13.
14. public static void foo() {
15.
throw new
RuntimeException();
16. }
17. }
What is the result? (Choose
one)
A three
B two three
C three four
D two three four
E one two three four
F Compilation fails
Answer:
Option D is the correct answer.
Method foo() throws a
RuntimeException, which does
not need to be declared. When
the exception is thrown, the
catch and finally blocks run,
and then the main() method
runs to completion (printing
four at the end).
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.5 >
Item 1
------------------------------------------------------------------------------
86
Which two fragments are
examples of inappropriate uses
of assertions? (Choose two.)
A assert (!(foo == null));
foo.go();
B public void method(boolean
b) {
assert (b);
C if (x > y) {
z = x;
} else {
assert (x < 4);
}
D private void test(int z) {
assert (f.setSize(z) > 5);
}
E public int methodA(int x) {
assert (s > 3);
}
Answer:
Options B and D are the correct
answers. B's violation is checking
an argument of a public method.
D's violation is to allow the
assert to have side effects, in
this case by calling a setter
method on a reference. E is an
appropriate use of an assertion
because it is not checking the
argument of a public method.
References:
http://java.sun.com/j2se/1.4/do
cs/guide/lang/assert.html#usage
-conditions
Location: ... > Flow Control,
Assertions, and Exception
Handling > Objective 2.6 > Item
1
------------------------------------------------------------------------Which two statements are true?
(Choose two.)
A The -ae flag tells the VM to
enable assertions
B The -ea flag tells the compiler
to enable assertions
C The -assert flag tells the VM
to enable assertions
D The -esa flag tells the VM to
enable some assertions
E The -assertions flag tells the
compiler to enable assertions
F The -enableassertions flag
tells the VM to enable assertions
Answer:
Options D and F are the correct
answers. The -esa flag means
enable system assertions.
ocation: ... >
Garbage
Collection > Objective 3.1 > Item 1
------------------------------------------------------------------------------which two statements are true about
the garbage collection system?
(Choose two.)
A Calling Runtime.gc() will reclaim
memory.
B It guarantees that programs will
not have memory leaks
C Objects will never be collected as
long as they are accessible from live
threads.
D Objects that have finalize()
methods always have their finalize()
methods called before the program
ends.
E If object 'A' has at least one other
object with a reference to it, then
object 'A' will not be garbage
collected.
F Objects instantiated within a
method and referenced only by a
local variable are created in the
garbage collectible heap.
nswer:
Options C and F are the correct
answers. C is correct because an
object accessible from a live thread
may yet be called by the JVM. F is
correct because all objects are
created in the garbage collectible
heap.
Location: ... > Garbage Collection >
Objective 3.2 > Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. class Test {
2. public static void main(String []
args) {
3.
Test2 t2 = new Test2();
4.
Test2 t3;
5.
t3 = t2.m1();
6.
t2 = t2.linker(t2,t3);
7.
t2 = null;
8.
t3 = null;
9. }
10. }
11.
12. class Test2 {
13.
Test2 link;
14.
Test2 m1() {
15.
Test2 x = new Test2();
16.
return x;
17.
}
18.
Test2 linker(Test2 z1, Test2
z2) {
19.
z1.link = z2;
20.
z2.link = z1;
21.
return z1;
22. }
23. }
Which statement is true?
A After line 8 no objects can
be garbage collected.
B After line 7 one object can
be garbage collected.
C After line 7 no objects can
be garbage collected.
D After line 6 at least one
object has more than two
references
E The z1 and z2 references
must be nulled to make any
objects eligible for garbage
collection.
Answer:
Option C is the correct answer.
After line 7 the t3 reference is
still valid and because of the
link variables both of the Test2
objects are still accessible.
Location: ... > Garbage
Collection > Objective 3.3 >
Item 1
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
7. Dog [] da = new Dog[2];
8. Dog clover = new Dog();
9. da[1] = clover;
10. clover = null;
11. Dog fido = new Dog();
12. Dog spot = new Dog();
When is the clover object
eligible for garbage collection?
A after line 9
B after line 10
C after line 11
D never in this code
Answer:
Option D is the correct answer.
The last reference to clover
(da[1]), is never nulled.
Location: ... > Language
Fundamentals > Objective 4.1
> Item 1
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. package com.abc.package1;
2. import java.util.*;
3. public class WeakHash
extends WeakHashMap {
4. int x = 5;
5. Object
getDuplicate(Object key) {
6.
return null;
7. }
87
8. }
9.
10. private class NewWeakHash
extends WeakHash {
11. public NewWeakHash() {
12.
int x = 7;
13. }
14.
15. public static void
main(String args [] ) {
16.
WeakHash wh = new
WeakHash();
17. }
18. }
What is the result?
A Compilation succeeds
B Compilation fails because of
an error on line 6
C Compilation fails because of
an error on line 10
D Compilation fails because of
an error on line 16
E An exception is thrown at
runtime
Answer:
Option C is the correct answer.
Classes cannot be declared
private.
1. package com.abc.package1;
2. import java.util.*;
3. public class WeakHash
extends WeakHashMap {
4. int x = 5;
5. Object getDuplicate(Object
key) {
6.
return null;
7. }
8. }
9.
10. private class NewWeakHash
extends WeakHash {
11. public NewWeakHash() {
12.
int x = 7;
13. }
14.
15. public static void
main(String args [] ) {
16.
WeakHash wh = new
WeakHash();
17. }
18. }
Location: ... > Language
Fundamentals > Objective 4.1 >
Item 2
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
1.
2. public class NewCollections {
3. public static void main(String
[] args) {
4.
java.util.WeakHashMap hm
= new java.util.WeakHashMap();
5.
Object o1
= null;
6.
o1 = hm.put(o1, o1);
7. }
8. }
Which statement must be added at
line 1 to allow this code to compile?
A import java.util.*;
B no statement is required
C import java.util.WeakHashMap;
D include java.util.WeakHashMap;
nswer:
Option B is the correct answer. When
a fully qualified name is used, you
don't have to import the classes or
packages.
Location: ... > Language
Fundamentals > Objective 4.2 >
Item 1
------------------------------------------------------------------------------Which two are valid method
signatures in an interface? (Choose
two.)
A short doShort();
B static char doChar();
C protected byte doByte();
D public boolean doBoolean(int x);
E final public String doString(int x);
Answer:
Options A and D are the correct
answers. A is correct because
interface methods are implicitly
public. D is correct because interface
can be declared public even though
they are so implicitly.
Location: ... > Language
Fundamentals > Objective 4.3 >
Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. public class ABC {
2. public static void main(String []
args ) {
3.
String a = args[3];
4.
String b = args[2];
5.
String c = args[1];
6.
System.out.println("c = " + c);
7.
}
8. }
And the command line invocation:
java ABC A B C
What is the result?
a c=
B c=A
C c=B
D c=C
E Compilation fails
F An exception is thrown at runtime
Answer:
Option F is the correct answer.
Line 3 will fail; args[3] is out of
bounds.
Location: ... > Language
Fundamentals > Objective 4.4
> Item 1
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. class Test {
2. public static void
main(String [] args) {
3.
construct Test(int i) {
4.
for (int y=0; y<i;
y++)
5.
System.out.print(" "
+ y);
6.
}
7. }
8. }
And command line invocation:
java Test 6
What is the result?
a 12345
B 012345
C Compilation fails
D An exception is thrown at
runtime
Answer:
Option C is the correct answer.
The word 'construct' is not a
valid modifier keyword in the
Java language. Constructors
are identified by having the
same name as the class, but
having no return type.
Location: ... > Language
Fundamentals > Objective 4.4
> Item 2
-----------------------------------------------------------------------------Which two are keywords?
(Choose two.)
A super
B Boolean
C unsigned
D interface
E anonymous
Answer:
Options A and D are the
correct answers. 'interface' and
'super' are both valid
keywords. C is wrong because
'unsigned' is a keyword in C,
C++, but not Java. E is wrong
because 'anonymous' is a Java
concept but not a keyword. B
'Boolean' is a class. The Java
primitive keyword is 'boolean'.
88
Location: ... > Language
Fundamentals > Objective 4.5 >
Item 1
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
1. class IvarLocal {
2. static int x;
3. public static void main(String
args []) {
4.
int y;
5.
System.out.println("x = " +
x + " y = " + y);
6. }
7. }
then elements 0
updated.
What is the result?
A x=y=
B x=y=0
C x=0y=
D x=0y=0
E Compilation fails
F An exception is thrown at
runtime
Location: ... > Language
Fundamentals > Objective 4.6 >
Item 2
------------------------------------------------------------------------------Which three are valid? (Choose
three.)
A float f1 = 0x123.45;
B float f2 = 3.14f;
C float f3 = (double) 1.8;
D float f4 = 1.0;
E float f5 = (float) '\'';
F float f6 = '\ubabe';
Answer:
Option E is the correct answer.
The compiler will be concerned
about whether y has been
initialized.
Location: ... > Language
Fundamentals > Objective 4.5 >
Item 2
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
7. short x = 1;
8. int [] y = new int[4];
9. y[0] = x;
10. y[1] = x+1;
11. for(int z= 0;z<4; z++) {
12.
System.out.println(" " +
y[z]);
13. }
What is the result?
A 0123
B 1223
C 1200
D 1 2 null null
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option C is the correct answer.
The elements in array y are
implicitly initialized to zeros, and
and 1 are
Location: ... > Language
Fundamentals > Objective 4.6 >
Item 1
------------------------------------------------------------------------------Which one is valid?
A boolean b2 = 1;
B boolean b3 = null;
C boolean b1 = FALSE;
D boolean b4 = "false";
E boolean b5 = (4 < 1);
answer:
Option E is the correct answer. The
expression (4 < 1) resolves to false.
Answer:
Options B, E, and F are the correct
answers. B is explicitly cast to a
float. E casts a char (which is an
unsigned int) to a float. F casts a
Unicode char to a float.
Location: ... > Operators and
Assignments > Objective 5.1 > Item
2
------------------------------------------------------------------------------Given:
10. int x = -1, y = -2;
11. System.out.println( (x<0) ^
(y<0) ) ;
What is the result?
A true
B false
C Compilation fails
D The code runs with no output
E An exception is thrown at runtime
Answer:
Option B is the correct answer. Both
equality tests resolve to true - true
XOR true is false.
Location: ... > Operators and
Assignments > Objective 5.2 > Item
1
-------------------------------------------------------------------------------
click the Exhibit button to view
the code.
10. int[] arr1 = new int[2];
11. int[] arr2 =
(int[])arr1.clone();
12. System.out.println( "Array
1 equals array 2 - " +
arr1.equals( arr2 ) );
What is the result?
A Array 1 equals array 2 B Array 1 equals array 2 true
C Array 1 equals array 2 null
D Array 1 equals array 2 false
E Compilation fails
F An exception is thrown at
runtime
Answer:
Option D is the correct answer.
Arrays inherit the default
Object.equals implementation
which compares references not
equivalence of content
therefore comparing two
distinct arrays will always yield
false even if the compared
arrays are clones.
Location: ... > Operators and
Assignments > Objective 5.3 >
Item 1
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
10. boolean flag1 = true;
11. boolean flag2 = false;
12. System.out.println( ( flag2
& flag1 ) & ( flag1 & flag2 ) );
Which two are true? (Choose
two.)
A The code outputs the value
false
B The output may vary if the
ordering is changed
C flag1 and flag2 are both
evaluated exactly once
D The output is always true
regardless of the ordering
E The output is always false
regardless of the ordering
Answer:
Options A and E are the correct
answers. The entire logical
statement is composed of non
shortcutting and therefore ALL
boolean expressions will be
evaluated regardless of the
outcome of a preceding
evaluation. As there are
89
booleans that resolve to false in
all three composite boolean
expressions the outcome must
be false.
Location: ... > Operators and
Assignments > Objective 5.3 >
Item 2
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
10. public boolean t1() { return
"hello".equals("HELLO"); }
11. public boolean t2() { return
!t1(); }
12.
13. public void op () {
14. System.out.println( (t1()
&& t2()) | t2() );
15. }
Which four are true? (Choose
four.)
A Compilation fails
B Calling op() means t2() is
always called once
C Calling op() means t1() is
always called once
D The output from op() is
always the value true
E Calling op() means t2() is
always called twice
F Calling op() means t1() is
always called twice
G Reversing the first expression
to (t2() && t1()) does not affect
the output
Answer:
Options B, D, F, and G are the
correct answers.
t1() resolves to false t2()
resolves to not t1() - true
reordering the first expression
does not affect the outcome
because it is a double && The
first call to t1() returns false and
will shortcut the && expression
to false and the non shortcut | to
the second t2() returns true
resulting in overall true. Due to
shortcut t2() is only ever called
once t1() is called once in the
expression and a second time
from t2(), therefore is called
twice
Location: ... > Operators and
Assignments > Objective 5.4 >
Item 1
-----------------------------------------------------------------------------click the Exhibit button to view
the code.
10. public void
op3( boolean[]
flags ) {
11. flags = new boolean[3];
12. for ( int i=0; i<flags.length;
i++ ) {
13.
flags[i] = ((i%2)==0);
14. }
15. }
16. public void arrayTest () {
17. boolean[] initial = null;
18. op3( initial );
19. System.out.println( initial[0] );
20. }
What is the result if method
arrayTest() is called?
A
B
C
D
E
F
true
null
false
Compilation fails
The code runs with no output
An exception is thrown at runtime
Answer:
Option F is the correct answer. An
exception is thrown at runtime.
Defining and initializing the array in
op3() has no effect on the callers
reference which remains null.
Therefore the access on initial[0]
causes a
java.lang.NullPointerException
Location: ... > Operators and
Assignments > Objective 5.4 > Item
2
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
10. public StringBuffer op4(
StringBuffer sb ) {
11. sb.append("-widgets");
12. return sb;
13. }
14. public void roundRobinTest () {
15. StringBuffer sb = new
StringBuffer();
16. sb.append("acme");
17. op4(sb);
18. sb.append("-and-nuggets");
19. System.out.println(
sb.toString() );
20. }
What is the result if method
roundRobinTest() is called?
A
B
C
D
E
F
acme
acme-widgets
-and-nuggets
acme-and-nuggets
-widgets-and-nuggets
acme-widgets-and-nuggets
Answer:
Option F is the correct answer.
sb is created in roundRobinTest
and its reference passed by
value into op4 where the
shared object is modified. The
same sb is then returned to the
caller, but the caller never
assigns or re-assigns its local
sb reference and it appears
that modifications in op4 are
lost, but as this is a shared
object by reference all
modifications remain, so the
output is acme-widgets-andnuggets
Location: ... > Objective 6.1
> Item 1
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. class A {
2. private static class B {
3.
private static String
msg = "ok" ;
4. }
5. public static String
access() {
6.
return B.msg;
7. }
8. }
9. class X {
10. public static void main(
String[] args ) {
11.
System.out.println(
A.access() );
12. }
13. }
Which two are true? (Choose
two.)
A Compilation fails
B The code outputs the value
ok
C An exception is thrown at
runtime
D Any private members of B
can be accessed from class A
only through accessor methods
E The private modifier on msg
must be weakened to default
or public for this code to work
correctly
Answer:
Options B and D are the
correct answers. Access to an
nested classes private methods
and variables is granted to the
encapsulating classes methods.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 3: Extending Classes - ISBN: 0-201-70433-1
90
Location: ... > Objective 6.1 >
Item 2
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
1. interface D {}
2. class E implements D {}
3. class F extends E {
4.
F() {}
5. }
6. class G extends F
implements D {}
7. class X {
8.
public static void main(
String[] args ) {
9.
E e = new F();
10.
D d = new G();
11. }
12. }
Which three are true? (Choose
three.)
A The declaration of G is illegal
B E is said to be a superclass of
F
C G is said to be a superclass of
E
D The assignment at line 10 is
legal
E A variable can be declared
using an interface type
F Compilation fails
answer:
B, D, and E. B is correct because
class F extends class E, making E
a superclass of F. D and E are
correct because the code
compiles successfully, the
declaration of G reimplementing
D is legal, as is the declaration of
d using an interface D as its
type.
Location: ... > Objective 6.2 >
Item 1
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
10. class P {
11. P( String s ){}
12. P( short s ){}
13. }
14. class Q extends P {
15. protected Q() {
super((short)3); }
16. public Q( int i ) { super(
new Integer(i).toString() ); }
17. Q( boolean b ) { super("");
}
18. Q( short s ) { super( s ); }
19. }
If the following
new statements
are invoked in a separate class in the
same package as classes P and Q,
which three are true? (Choose
three.)
A Compilation fails for code - new
Q();
B Compilation fails for code - new
P();
C Compilation fails for code - new
Q("");
D Compilation fails for code - new
P('a');
E Compilation fails for code - new
Q((short)1);
F Compilation fails for code - new
Q( new Q(3) instanceof P );
Answer:
Options B, C, and D are the correct
answers. The relationship and
declaration of P & Q are sound. This
question is quite simple couched in
seemingly complex code. Simply test
the argument passed in the new call
with a constructor in the target class,
if a match is found it compiles. The
last three options here do not have
matching constructors.
Location: ... > Objective 6.2 > Item
2
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
10. abstract class X {
11. public final void op(){}
12. abstract final void op();
13. void op( String s ){}
14. abstract synchronized void
op(int i) throws Exception;
15. abstract private void op( String
a, int i );
16. }
Which three are true? (Choose
three.)
A Line 10 is uncompilable
B Line 11 is uncompilable
C Line 12 is uncompilable
D Line 13 is uncompilable
E Line 14 is uncompilable
F Line 15 is uncompilable
Answer:
Options C, E, and F are the correct
answers.
line 10 ok, the class must be
declared abstract
line 11 ok, the initial method
declaration signature
line 12 fails, cannot combine abstract
and final, conflict of intentions
line 13 ok, the first successful
overload of op(), but with
differing access privileges
line 14 fails, cannot combine
abstract with implementation
details like synchronized
line 15 fails, cannot combine
abstract and private, no way to
implement in subclass
Location: ... > Objective 6.3
> Item 1
--------------------------------------------------------------------------Click the Exhibit button to view
the code.
1. interface XX {}
2. interface YY extends XX {}
3. abstract class ZZ
implements XX {}
4. class AA extends ZZ
implements YY {
5. private class BB{}
6. }
7. class Main extends AA {
8. public static void main(
String[] args ) {
9.
XX xx1 = new XX ();
10.
XX xx2 = new AA ();
11.
ZZ zz1 = new Main ();
12.
Main m = new AA();
13. }
14. }
Which two are true? (Choose
two.)
A Line 5 is uncompilable
B Line 9 is uncompilable
C Line 10 is uncompilable
D Line 11 is uncompilable
E Line 12 is uncompilable
F Compilation succeeds
Answer:
Options B and E are the correct
answers. Line 9 attempts to
instantiate an interface. Line
12 is an incompatible
assignment; you can't assign a
superclass object to a subclass
reference type.
Location: ... > Objective 6.3
> Item 1
Click the Exhibit button to
view the code.
1. interface XX {}
2. interface YY extends XX {}
3. abstract class ZZ
implements XX {}
4. class AA extends ZZ
implements YY {
5. private class BB{}
6. }
7. class Main extends AA {
8. public static void main(
String[] args ) {
9.
XX xx1 = new XX ();
91
10.
XX xx2 = new AA ();
11.
ZZ zz1 = new Main ();
12.
Main m = new AA();
13. }
14. }
Which two are true? (Choose
two.)
A Line 5 is uncompilable
B Line 9 is uncompilable
C Line 10 is uncompilable
D Line 11 is uncompilable
E Line 12 is uncompilable
F Compilation succeeds
Answer:
Options B and E are the correct
answers. Line 9 attempts to
instantiate an interface. Line 12
is an incompatible assignment;
you can't assign a superclass
object to a subclass reference
type.
Location: ... > Objective 6.3 >
Item 2
Click the Exhibit button to
view the code.
1. class Outer {
2. class Inner {}
3. }
4. class ExtendedOuter extends
Outer {
5. class ExtendedInner extends
Inner {}
6. }
7. class Main extends
Outer.Inner {
8. Main( Outer ref ) {
9. ref.super();
10. }
11. public static void main(
String[] args ) {
12. new Main( new
ExtendedOuter() );
13. }
14. }
What is the result?
A Compilation fails
B An exception is thrown at
runtime
C The code runs with no output
Answer:
Option C is the correct answer.
An inner class can extend
another, unrelated, inner class
provided an appropriate
enclosing instance is supplied to
the superclass. The resulting
inner class then has two
enclosing instances, one for the
extended class and one for the
superclass. Therefore this code
cleanly compiles and outputs
nothing.
Location: ... > Threads >
Objective 7.1 > Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. public static void main( String[]
args ) {
2. class Widget extends
java.lang.Thread {
3.
Widget(boolean daemon) {
4.
this.setDaemon(daemon);
5.
this.start();
6.
}
7. }
8.
9. for ( int i= 0;i<10; i++ ) {
10. new Widget(((i%2)==0));
11. }
12. }
Which two statements are true?
(Choose two.)
A Compilation fails.
B Only five threads are created.
C An exception is thrown at
runtime.
D Ten independent threads are
created.
E Ten threads are created but only
five execute.
F The program terminates after the
tenth thread is created.
Answer:
Options D and F are the correct
answers. The program creates
precisely 10 threads, every other of
which is marked as daemon thread.
Each thread executes on the default
run() method so all will terminate
and therefore the program
terminates.
Reference:
The Java Programming Language,
Third Edition, by Arnold, Gosling &
Holmes, Chapter 10: Threads
ISBN: 0-201-70433-1
location: ... > Threads >
Objective 7.1 > Item 2
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
11. public static void main( String[]
args ) {
12. class Widget extends
java.lang.Thread {
13.
Widget() {
14.
this.start();
15.
}
16. }
17.
18. Widget w = new Widget();
19. w.setDaemon(true);
20. }
Which statement is true?
A Compilation fails.
B The program never
terminates.
C One daemon thread is
created.
D An exception is thrown at
runtime.
E The program terminates
after the thread is created.
Answer:
Option D is the correct answer.
An exception is thrown at
runtime va.lang.IllegalThreadStateExce
ption setdaemon(true) can not
be invoked on an active
thread.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.2 > Item 1
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. class Worker extends
java.lang.Thread {
2. public void run() {
3.
while ( true ) {}
4. }
5.
6. public static void main(
String[] args ) {
7.
for (int i=0;
i<MAX_PRIORITY; i++ ){
8.
Worker w = new
Worker();
9.
w.setPriortity(
MIN_PRIORITY+i );
10.
w.setDaemon(true);
11.
w.start();
12. }
13. }
14. }
Which two statements are
true? (Choose two.)
A Compilation fails.
B An exception is thrown at
runtime.
C All threads are guaranteed
to execute.
D Some of the threads may
never execute.
E The program runs forever
with no output.
F The program terminates
when the main() method
completes.
Answer:
92
Options D and F are the correct
answers. As all threads are
marked as Daemon threads, the
program contains no user
threads once main terminates, so
the program as a whole
terminates. A number of the
daemon threads may never
execute due to the early
termination of the program and
the priority levels assigned.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.2 > Item 2
Click the Exhibit button to view
the code.
1. class Worker extends
java.lang.Thread {
2. public void run() {
3. while ( true ) {
4.
synchronized( this ) {
5.
try {
6.
wait();
7.
} catch (Exception e) {}
8.
}
9.
System.out.println("ok");
10. }
11. }
12. public static void main(
String[] args ) {
13. new Worker().start();
14. }
15. }
Which two statements are true?
(Choose two.)
A Compilation fails.
B The program never
terminates.
C The program runs with no
output.
D The value ok is repeatedly
output.
E The program terminates and
outputs ok precisely once.
F The Worker thread never
blocks inside the wait method
because there are no other
threads executing.
answer:
Options B and C are the correct
answers. This program simply
launches a single user thread
that immediately blocks inside
the wait() method The thread is
never unblocked because no
other thread is executing to call
the notify on the lock.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling
& Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads > Objective
7.3 > Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
10. class X {
11. synchronized void iTest() {
12.
while(true) {
13.
Thread.yield();
14.
}
15. }
16. synchronized static void sTest()
{}
17. public void op() {}
18. }
And, given a single instance of X,
and two or more concurrent threads,
which statement is true?
A Multiple threads can execute
iTest() concurrently.
B Any thread calling iTest() will be
blocked pending a call to notify.
C While a thread is executing
iTest(), any call on sTest() will block
pending lock access.
D While a thread is executing
iTest(), no other threads may
execute any methods declared in X.
E While a thread is executing
iTest(), op() may be concurrently
executed inside the same instance of
X.
Answer:
Option E is the correct answer. Static
methods synchronize on the class
object, not on an instance object, so
concurrent calls to iTest() and
sTest() will not block each other.
op() is not synchronized so may be
called concurrently with anything
else.
Reference:
The Java Programming Language,
Third Edition, by Arnold, Gosling &
Holmes, Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.3 > Item 2
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. class WorkerT extends
java.lang.Thread {
2. private static StringBuffer sb =
new StringBuffer();
3. public void run() {
4.
notify();
5.
try {
6.
wait();
7.
} catch (Exception e) {}
8. }
9. public static void main(
String[] args ) {
10.
for (int i= 0;i<10; i++)
{
11.
new
WorkerT().start();
12.
}
13. }
14. }
Which statement is true?
A Compilation fails.
B All 10 threads block.
C An exception is thrown at
runtime.
D All 10 threads execute to
completion.
E Each thread is unlocked by
the following thread until only
the final thread remains
blocked.
Answer:
Option C is the correct answer.
An exception is thrown
java.lang.IllegalMonitorStateEx
ception: current thread not
owner. The caller of wait(),
notify(), or notifyAll() must
own the monitor lock that is,
they must be executing inside
a synchronized method or
section to be able to
successfully call any of these
methods.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.4 > Item 1
-----------------------------------------------------------------------------Which three statements are
true? (Choose three.)
A The Object class defines a
wait() method.
B
The Thread class
overrides a wait() method.
C
The Runnable interface
defines a wait() method.
D
wait() can be called at
any time by an executing
thread.
E
The wait() method used
in thread communication
releases an object lock.
F
The wait() method is
overloaded and also has the
following signature public final
void wait(long timeout).
answer:
Options A, E, and F are the
correct answers.
93
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Threads >
Objective 7.4 > Item 2
-----------------------------------------------------------------------------which two statements are
correct? (Choose two.)
A To call notify() a thread must
own the monitor lock.
B
The notify() and notifyAll()
methods are defined in the
Thread class.
C
The notify() and notifyAll()
methods are defined in the
Object class.
D
A thread can only call
notify() if another thread has
previously called wait().
E
The notify() and notifyAll()
methods are defined in the
Runnable interface.
Answer:
Options A and C are the correct
answers.
Reference:
The Java Programming
Language, Third Edition, by
Arnold, Gosling & Holmes,
Chapter 10: Threads
ISBN: 0-201-70433-1
Location: ... > Fundamental
Classes in the java.lang package
> Objective 8.1 > Item 1
-----------------------------------------------------------------------------Click the Exhibit button to view
the code.
1. public class Test813 {
2. public static void main(String
[] args) {
3.
double a =
Math.round(5.5);
4.
double b =
Math.round(5.2);
5.
double c = Math.round(5.0);
6.
double d = Math.round(5.4);
7.
double e = Math.round(5.5);
8.
System.out.print( "Results:
"+a+""+b+""+c+""+
d + " " + e);
9.
}
10. }
What is the result?
A Results: 6.0 5.0 -5.0 -5.0 5.0
B
C
D
E
F
Results: 6.0
5.0 -5.0 -5.0 -6.0
Results: 5.0 5.0 -5.0 -5.0 -5.0
Results: 6.0 5.0 -5.0 -4.0 -5.0
Results: 6.0 5.0 5.0 5.0 6.0
Compilation fails.
nswer:
Option A is the correct answer. Both
positive and negative numbers are
rounded up to the larger number. For
a positive number such as 5.5, the
greater number is 6, but for -5.5 the
greater number is -5.0.
Location: ... > Fundamental
Classes in the java.lang package >
Objective 8.2 > Item 1
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. public class Test823 {
2. public static void main(String []
args) {
3.
String a = "freddy";
4.
String b = a.substring(0,3);
5.
b.toUpperCase();
6.
System.out.println(a += b);
7. }
8. }
What is the result?
A freddyFRE
B freddyfre
C freddyFRED
D freddyfred
E Compilation fails.
Answer:
Option B is the correct answer. The a
String reference is never modified,
and the toUpperCase() call is not
assigned to b so b's original object
does not change.
Location: ... > Fundamental Classes
in the java.lang package > Objective
8.2 > Item 2
------------------------------------------------------------------------------Click the Exhibit button to view the
code.
1. public class Test825 {
2. public static void main(String []
args) {
3.
String a = "big";
4.
String b = a;
5.
a = a + "bird";
6.
a = b;
7.
b = "bird";
8.
System.out.println(a = a+b);
9. }
10. }
What is the result?
A bigbird
B birdbird
C bigbigbird
D bigbirdbird
E Compilation fails.
Answer:
Option A is the correct answer.
In line 4, b is set to refer to the
String literal "big". The String
referenced by b is not changed
by the change to a in line 5,
because Strings are
immutable. In line 5, a new
String object "bigbird" is
created, and assigned to a. At
this point (line 5) b is still
referring to "big" and a is now
referring to "bigbird". In line
6,then, a is set to refer to the
String literal "big" referenced
by b, so both a and b refer to
the String literal "big". In line
7, b is set to reference a String
literal "bird", while a is left
unchanged and still refers to
"big". Finally, a + b is printed
out, producing "bigbird".
Location: ... > Fundamental
Classes in the java.lang
package > Objective 8.3 >
Item 1
--------------------------------------------------------------------------Which creates a new
Character object?
A Character a = new
Character("c");
B
Character a =
Character.getCharacter('s');
C
Character a = new
Character(new char[]{'s'});
D
Character a =
Character.valueOf("c".toChar()
);
E Character a = new
Character((new
char[]{'s'})[0]);
Answer:
Option E is the correct answer.
The Character class has only
one constructor, and it takes a
char primitive. Answer "E"
constructs an anonymous char
array holding a single char,
then accesses the array
element at index 0, thus
returning a char to the
Character constructor.
Location: ... > Fundamental
Classes in the java.lang
package > Objective 8.3 >
Item 2
-----------------------------------------------------------------------------Click the Exhibit button to
view the code.
1. public class Test834 {
2. public static void
main(String [] args) {
3.
try {
94
4.
Double d = new
Double(new
Byte(6).doubleValue());
5.
String s = d.toString();
6.
System.out.println(Integer.parse
Int(s));
7.
}
catch(NumberFormatException
ex) {
8.
System.out.println("failed");
9.
}
10. }
11. }
What is the result?
A 6
B 6.0
C null
D failed
E Compilation fails.
F An uncaught exception is
thrown at runtime.
Answer:
Option E is the correct answer.
Byte does not have a constructor
that takes an int. The Byte
constructor must be passed a
previously declared byte
variable, or explicitly cast an int
value.
Location: ... > The Collections
Framework > Objective 9.1 >
Item 1
-----------------------------------------------------------------------------Which two statements are true
of class java.util.HashMap?
(Choose two.)
A Its methods are thread-safe.
B It allows null references to be
stored.
C It provides fast, bi-directional
iteration.
D It implements
java.util.Hashable.
E It tracks when its elements
were last accessed.
F Its elements can be accesssed
using a unique key.
Answer:
Options B and F are the correct
answers. HashMap implements
java.util.Map, which allows
elements to be accessed using a
unique key. Whereas HashTable
does not permit null references
to be stored, HashMap allows
both keys and elements to be
null.
Location: ... > The Collections
Framework > Objective 9.1 >
Item 2 ------------------------------------------------------------------------------
Click the
Exhibit button to
view the code.
1. TreeSet s = new TreeSet();
2. s.add("Fred");
3. s.add("Mike");
4. s.add("Zeus");
5. s.add("Fred");
6. s.add("Amy");
7. Iterator i = s.iterator();
8. while(i.hasNext()) {
9.
System.out.print(i.next() + ",
");
10. }
What is the result?
A Fred, Mike, Zeus, Amy,
B Amy, Fred, Mike, Zeus,
C Fred, Mike, Zeus, Fred, Amy,
D Amy, Fred, Fred, Mike, Zeus,
E Five elements will be printed, but
the order is not guaranteed.
F Four elements will be printed, but
the order is not guaranteed.
Answer:
Option B is the correct answer. A
TreeSet is a Set, which eliminates
duplicates, so Fred only goes in once.
A TreeSet is sorted so the Strings
come out in alphabetical order
Location: ... > The Collections
Framework > Objective 9.2 > Item 1
------------------------------------------------------------------------------If class X implements hashcode()
and equals() correctly, and given two
instances (o1 and o2) of class X,
which two are true? (Choose two.)
A if o1.hashcode() and
o2.hashcode() are not the same,
then o1 and o2 must not be equal
B o1.hashcode() and o2.hashcode()
might be the same if o1 and o2 are
considered equal
C o1.hashcode() and o2.hashcode()
must be the same if o1 and o2 are
considered equal
D if o1 and o2 are not equal, then
o1.hashcode() and o2.hashcode()
must not be the same
Answer:
Options A and C are the correct
answers. Hashcode suggests the
likelihood of equality, while equality
requires that hashcodes must be the
same. The rules for correct
implementation of hashcode and
equals require that if two objects are
equal, their hashcodes MUST be the
same. If two objects are unequal,
however, they may still have the
same hashcode. So, object
equivalency guarantees hashcode
equivalency, but hashcode
equivalency does not guarantee
object equivalency.
Question 1: Given the
following class definition:
class A {
protected int i;
A(int i) {
this.i = i;
}
}
Which of the following would
be a valid inner class for this
class?
Select all valid answers.
a)
class B {
}
b)
class B extends A {
}
c)
class B {
B() {
System.out.println("i = " +
i);
}
}
d)
class B {
class A {
}
}
e)
class A {
}
95
Question 2: What statements
are true concerning the
method notify() that is used
in conjunction with wait()?
e) 0
public void run() {
for (int i = startHere; i <=
endHere; i++) {
Select all valid answers.
System.out.println(i);
a) if there is more than one
thread waiting on a condition,
only the thread that has been
waiting the longest is notified
b) if there is more than one
thread waiting on a
condition,there is no way to
predict which thread will be
notifed
}
};
public static void
main(String[] args) {
t.start();
}
b)
c) notify() is defined in the
Thread class
public void run() {
for (int i = startHere; i <=
endHere; i++) {
System.out.println(i);
e) notify() should only be
invoked from within a while loop
Question 3: Given the
following class:
class Counter {
Thread t = new
Thread(new
CounterBehavior());
}
a implements Runnable {
d) it is not strictly necessary to
own the lock for the object you
invoke notify() for
Question 5: Given the
following class:
}
}
Which of the following is a
valid definition of
CounterBehavior that would
make Counter’s main() method
count from 1 to 100, counting
once per second?
Select the one right answer.
}
a)This class is an inner class to
Counter:
};
class Counter {
public int startHere = 1;
public int endHere = 100;
public static void main(String[]
args) {
new Counter().go();
class CounterBehavior {
c)
Thread a = new Thread() {
for (int i = 1; i <= 100;
i++);
public void run() {
try {
for (int i = startHere; i <=
endHere; i++) {
}
System.out.println(i);
Thread.sleep(1000);
System.out.println(i);
void go() {
// A
Thread t = new Thread(a);
t.start();
}
}
}
};
Question 4: What is written to
the standard output given the
following statement:
}
System.out.println(4 | 7);
What block of code can you
replace at line A above so that
this program will count from
startHere to endHere?
Select the one right answer.
Select all valid answers.
a)
Runnable a = new Runnable() {
} catch
(InterruptedException x) {}
}
}
b) This class is an inner class
to Counter:
a) 4
class CounterBehavior
implements Runnable {
b) 5
public void run() {
c) 6
d) 7
for (int i = 1; i <= 100;
i++);
try {
96
InputStreamReader reader =
new
InputStreamReader(stream);
System.out.println(i);
Thread.sleep(1000);
class D extends A {
} catch
(InterruptedException x) {}
public float z;
}
BufferedReader buffer = new
BufferedReader(reader);
s = buffer.readLine();
}
c)
}
What can method2() access directly,
without a reference to another
instance?
}
c) This class is a top-level class:
Select all valid answers.
static class CounterBehavior
implements Runnable {
public void run() {
try {
for (int i = 1; i <= 100;
i++) {
a) the variable x defined in A
b) the variable y defined in A
c) method1 defined in B
d) the variable z defined in D
System.out.println(i);
Thread.sleep(1000);
}
} catch
(InterruptedException x) {}
}
Question 7: You have an 8-bit file
using the character set defined
by ISO 8859-8. You are writing
an application to display this file
in a TextArea. The local encoding
is already set to 8859-8. How can
you write a chunk of code to read
the first line from this file?
You have three variables accessible
to you:
}
Question 6: Given the
following class definition:

class A {

public int x;

private int y;
class B {
protected void method1() {
}
class C {
private void method2() {
}
}
}
}
myfile is the name of the file
you want to read
stream is an InputStream
object associated with this
file
s is a String object
Select all valid answers.
InputStreamReader reader =
new
InputStreamReader(myfile,
"8859-8");
BufferedReader buffer = new
BufferedReader(reader);
s = buffer.readLine();
d)
InputStreamReader reader =
new
InputStreamReader(myfile);
BufferedReader buffer = new
BufferedReader(reader);
s = buffer.readLine();
e)
FileReader reader = new
FileReader(myfile);
BufferedReader buffer = new
BufferedReader(reader);
s = buffer.readLine();
Question 8: How can you
write a line of code for an
applet’s init() method that
determines how wide the
applet is?
Select all valid answers.
a) int width = this.getY();
a)
b) int width = this.getSize().w;
InputStreamReader reader = new
InputStreamReader(stream, "88598");
c) int width = getSize();
BufferedReader buffer = new
BufferedReader(reader);
e) int width = getWidth();
s = buffer.readLine();
b)
d) int width = getSize().w;
Question 9: For a variable
width font, how "wide" is a
TextField created using the
expression:
new TextField(20)
97
Select the one right answer.
a) 20 times the average of all the
characters in the font used for
this TextField object
b) 20 times the width of the
letter M
c) 20 times the width of the
letter a
d) 20 inches
e) 20 picas
Question 10: Given this
interface definition:
interface A {
int method1(int i);
int method2(int j);
}
which of the following classes
implement this interface and is
not abstract?
Select all valid answers.
a)
class B implements A {
int method1() { }
int method2() { }
c) c
Question 11:
following code:
Given the
import java.awt.*;
import java.awt.event.*;
public class MyApplet extends
java.applet.Applet {
public void init() {
Button b = new
Button("Button1");
b.addMouseListener(new
ClickHandler());
add(b);
}
class ClickHandler extends
MouseAdapter {
public void
mouseClicked(MouseEvent evt) {
// A
}
}
}
What line of code at A writes the
mouse’s horizontal location to the
standard output at the time of the
event?
Fill in the blank.
Question 12: Given the same
code as in question 10, how can
you write a line of code at A that
will place the Button object into a
variable named mybutton that is
already defined to be a reference
to a Button object?
Fill in the blank.
}
b)
class B {
int method1(int i) { }
int method2(int j) { }
}
c)
class B implements A {
int method1(int i) { }
int method2(int j) { }
}
d)
class B extends A {
int method1(int i) { }
int method2(int j) { }
}
e)
class B implements A {
int method2(int j) { }
int method1(int i) { }
}
Question 13: Which Listener
interface can you implement to
be able to respond to the user
hitting the enter key after typing
into a TextField object?
Question 14: What is written to
the standard output as the result
of executing the following
statements?
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean(true);
if (b1 == b2)
if (b1.equals(b2))
System.out.println("a");
else
System.out.println("b");
else
if (b1.equals(b2))
System.out.println("c");
else
System.out.println("d");
)a
b) b
d) d
Question 15: Which Listener
interfaces can you add to a
TextArea object?
a) TextListener
b) ActionListener
c) MouseMotionListener
d) MouseListener
e) ComponentListener
Question 16: What appears
in the standard output if the
method named problem() in
the code below throws an
instance of class Exception
when the method named
trythis() is invoked?
public void trythis() {
try {
System.out.println("1");
problem();
} catch (RuntimeException
x) {
System.out.println("2");
return;
} catch (Exception x) {
System.out.println("3");
return;
} finally {
System.out.println("4");
}
System.out.println("5");
}
elect all valid answers.
a) "1"
b) "2"
c) "3"
d) "4"
e) "5"
Question 17: What is the
type of the Event object
passed to the
mouseDragged() method
defined in a class that
implements
java.awt.event.MouseMotio
nListener (that is, what is
98
the class name for the
argument)?
estion 18: Examine the
following switch block:
char mychar = 'c';
switch (mychar) {
default:
case 'a':
System.out.println("a"); break;
case 'b':
System.out.println("b"); break;
}
c) s is an array
of 10 arrays.
d) Each element in s is set to ""
e) Each element in s is uninitialized
and must be initialized before it is
referenced.
uestion 21: What will happen if
you try to compile and run the
following class?
class Test {
static int myArg = 1;
public static void main(String[]
args) {
int myArg;
Which of the following questions
are definitely true?
System.out.println(myArg);
Select all valid answers.
}
a) This switch block is illegal,
because only integers can be
used in the switch statement.
}
b) This switch block is fine.
a) This code compiles and displays 0
in the standard output when run.
c) This switch block is illegal,
because the default statement
must come last.
d) When this code runs, nothing
is written to the standard output.
e) When this code runs, the
letter "a" is written to the
standard output.
uestion 19: What keyword
must appear in a method
declaration (followed by the
name of the exception) when
that method might cause an
exception to be thrown and
that method does not handle
the exception?
Select the one right answer.
b) This code compiles and displays 1
in the standard output when run.
c) This code does not compile
because you cannot define a local
variable named the same as a static
variable.
d) This code does not compile
because the local variable is used
before it is initialized.
Question 22: Which declarations
for the main() method in a standalone program are NOT valid?
Question 20: Which
statements accurately
describe the following line of
code?
Select all valid answers.
c) public static void main(String
args)
a) This line of code is illegal.
b) s is a two-dimensional array
containing 10 rows and 10
columns
Select all valid answers.
a) #_pound
b) _underscore
c) 5Interstate
d) Interstate5
Question 24: If the user
invokes a stand-alone
application by typing:
java YourApp 1 2 3
and the main() method defines
its String[] parameter as args,
how can you access the
number 2 using args?
Fill in the blank.
Question 25: Which interface
implementations can you add
as listeners for a TextField
object?
Select all valid answers.
a) ActionListener
b) FocusListener
c) MouseMotionListener
d) WindowListener
e) ContainerListener
Question 26: What must be
true for the RunHandler
class so that instances of
RunHandler can be used as
written in the code below:
class Test {
Select all valid answers.
a) public static void main()
String[][] s = new String[10][];
Question 23: Which of the
following identifiers are
ILLEGAL?
b) public static void main(String[]
string)
d) static public int main(String[]
args)
public static void
main(String[] args) {
Thread t = new
Thread(new RunHandler());
t.start();
}
}
Select all valid answers.
e) static void main(String[] args)
a) RunHandler must implement
the java.lang.Runnable
interface.
99
b) RunHandler must extend the
Thread class.
c) RunHandler must provide a
run() method declared as public
and returning void.
d) RunHandler must provide an
init() method.
Question 27: To determine if
you can invoke
addContainerListener() for a
component referenced using
a variable named c, which
expression(s) can you
evaluate that will give you a
true or false answer to this
questions?
Select all valid answers.
a) c == Container
b) c.equals(Class.Container)
c) c instanceof Container
d) c instanceof Component
e) c implements Container
Question 28: Write a
statement for a constructor
that invokes the no-args,
default constructor in its
superclass.
System.out.println(i);
else
System.out.println(j);
else
System.out.println(k);
Select the one right answer.
a) 3
b) 0
c) 3.2
d) none of these
Question 31: How can you use
the String method indexOf() to
determine which position the
letter 'C' is in given this String:
String s = "ABCDE";
Write a complete statement in your
answer, but you do not have to
assign the letter you retrieve to
another variable.
Question 29: What is written
to the standard output given
the following statement:
Question 32: Given that the
variable g references a valid
Graphics object, what does the
following statement do?
System.out.println(4 & 7);
g.fillRect(2, 3, 10, 20);
Select the one right answer.
Select all valid answers.
a) 4
a) draw the outline of a rectangle in
the current background color
b) 5
c) 6
d) 7
e) 0
Question 30: What will the
following block of code write
to the standard output when
it is executed?
b) draw the outline of a rectangle in
the current foreground color
lect all valid answers.
a) Nothing appears in the
applet
b) One button appears in the
applet but does nothing
c) Two buttons appear in the
applet
d) When the user clicks a
button, nothing happens
e) When the user clicks a
button, it becomes disabled
f) When a user clicks a button,
the other button becomes
enabled
d) fill in a rectangle using the current
foreground color
Select all valid answers.
e) fill in a rectangle in black
int j = 0;
import java.applet.Applet;
import java.awt.event.*;
import java.awt.*;
public class MyApplet extends Applet
{
Button b1, b2;
public void init() {
if (i == j)
b2.setEnabled(false);
}
}
};
b1 = new Button("1");
b1.addActionListener(a);
add(b1);
b2 = new Button("2");
b2.addActionListener(a);
add(b2);
}
}
Question 34: The method
setBackground() defined
for the Graphics class:
Question 33: Describe the
following applet.
if (i < k)
b1.setEnabled(false);
b2.setEnabled(true);
} else {
b1.setEnabled(true);
c) fill in a rectangle using the current
background color
int i = 3;
double k = 3.2;
ActionListener a = new
ActionListener() {
public void
actionPerformed(ActionEvent
evt) {
if (evt.getSource() ==
b1) {
a) takes an integer value
b) takes an instance of class
Color
c) takes an instance of a
Component subclass
d) sets the drawing mode for
the associated Component
object
100
e) sets the drawing color for the
associated Component object
f) changes the background color
for the associated Component
object
Question 35: What does the
following program do when it
is run with the command:
java Mystery Mighty Mouse
class Mystery {
public static void main(String[]
args) {
Changer c = new Changer();
c.method(args);
System.out.println(args[0] +
" " + args[1]);
}
static class Changer {
void method(String[] s) {
String temp = s[0];
s[0] = s[1];
s[1] = temp;
}
}
}
not compile
a) this code will
b) this code compiles but throws an
exception at runtime
c) this code runs but nothing appears
in the standard output
d) this code runs and "constructor" in
the standard output
e) this code runs and writes "null" in
the standard output
Question 37: What can you write
at the comment //A in the code
below so that this program
writes the word "running" to the
standard output?
class RunTest implements Runnable
{
public static void main(String[]
args) {
RunTest rt = new RunTest();
//A
a) This program causes an
ArrayIndexOutOfBoundsExceptio
n to be thrown
//A
import java.applet.*;
//B
class Helper {
}
//C
package myclasses;
//D
public class MyApplet extends
java.applet.Applet {
}
Select all valid answers.
a) A, B, C, D
b) A, C, B, D
c) C, A, B, D
public void run() {
System.out.println("running");
}
c) This program writes "Mighty
Mouse" to the standard output
d) C, A, D, B
e) C, B, A, D
}
b) This program runs but does
not write anything to the
standard output
Question 39: Analyze these
two consequetive lines of
code:
float f = 3.2;
int i = f;
void go() {
start(1);
d) This program writes "Mouse
Mighty" to the standard output
}
Question 36: What happens
when you try to compile and
run the following program?
void start(int i) {
Select all valid answers.
a) this code would not compile
b) this code would compile and
i would be set to 3
}
}
c) the second line could
compile if it were written
instead as:
Select all valid answers.
int i = (byte)f;
a) System.out.println("running");
d) the first line could compile if
it were written instead as:
b) rt.start();
c) rt.go();
elect the one right answer.
Question 38: What order
can you place the following
pieces of a source file in so
that the source file will
compile without errors or
warnings?
Thread t =new Thread(rt);
elect the one right answer.
class Mystery {
String s;
public static void main(String[]
args) {
Mystery m = new Mystery();
m.go();
}
void Mystery() {
s = "constructor";
}
void go() {
System.out.println(s);
}
d) rt.start(1);
float f = 3.2F;
101
Question 40: Construct an
array of 3 String objects
containing the strings "a",
"b", and "c" using the { }
notation. Call the String by
the variable name s.
Question 44:
What will the user interface look
like in an applet given the
following init() method?
public void init() {
ill in the blank.
setLayout(new BorderLayout());
Question 41: What is the final
value of temp in this
sequence?
add("East", new Button("hello"));
Question 47: Analyze the
following code:
class WhatHappens
implements Runnable {
long temp = (int)3.9;
}
temp %= 2;
Select the one right answer.
a) 0
a) Nothing will appear in the applet
b) 1
What line of code can you write
at A that will make a
component referenced by c
disappear from the display?
b) A button will appear in the applet
set in the exact center
public static void
main(String[] args) {
Thread t = new
Thread(this);
t.start();
c) 2
d) 3
e) 4
Select the one right answer.
Question 42: Analyze this line
of code:
if (5 & 7 > 0 && 5 | 2)
System.out.println("true");
Select the one right answer.
a) this line of code will not
compile
b) this code will compile but
nothing will appear in the
standard output
c) this code will compile and
write the word "true" in the
standard output
Question 43: Create a List
object that allows multiple
selections and displays 5
rows at a time.
c) A button will appear on the left
side of the applet
List l =
in your answer.
public void run() {
d) A button will appear on the right
side of the applet
System.out.println("hi");
}
e) A button will fill the entire applet
Question 45: Choose all true
statements about the paint()
method defined in the
Component class:
Select all valid answers.
a) it is protected
b) it takes an instance of class
Graphics
c) it is static
d) it is invoked automatically
whenever you minimize and then
maximize a component, such as a
window
e) there is also a version that takes
an int
Question 46: Given this
ActionListener:
Start by writing:
}
}
Select the one right answer.
a) This program does not
compile
b) This program compiles but
nothing appears in the
standard output
c) This program compiles and
the word "hi" appears in the
standard output, once
d) This program compiles and
the word "hi" appears
continuously in the standard
output until the user hits
control-c to stop the program
Question 48: What is wrong
with the following code?
final class First {
class HandleClick implements
ActionListener {
public void
actionPerformed(ActionEvent evt) {
private int a = 1;
int b = 2;
}
// A
fill in the blank.
}
}
class Second extends First {
public void method() {
System.out.println(a + b);
102
}
new B();
}
}
Select all valid answers.
class B {
B() {
a) You cannot invoke println()
without passing it a String
System.out.println(x);
b) Since a is private, no classes
other than First can access it
}
}
c) Second cannot extend First
Question 49: Analyze the
following two classes.
a) Class B tries to access a private
variable defined in its ouer class.
b) Class A attempts to create an
instance of B when there is no
current instance of class A.
}
c) Class B’s constructor must be
public.
final class Second extends First {
void method() {
System.out.println(i +
j);
if (i > 2)
continue one;
}
}
Select all valid answers.
System.out.println(++x);
a) 10 and 20
if (x > 3)
b) 11 and 21
break two;
}
c) Neither class compiles
c) 12 and 22
d) 13 and 23
}
e) 30, 31, 32, 33
Select all valid answers.
e) Both classes compile, but if
method() is invoked, it throws an
exception
a) This code compiles
Question 50: Why won’t the
following class compile?
c) This method writes the number 0
to the standard output
public static void main(String[]
args) {
for (int j = 10; j < 30;
j+=10) {
}
two:
b) Class Second compiles, but
class First does not
private int x;
three:
one:
a) Class First compiles, but class
Second does not
class A {
for (int i = 0; i < 3; i++) {
int x = 0;
while (x < 10) {
d) Both classes compile, and if
method() is invoked, it writes 3
to the standard output
two:
void looper() {
}
Select the one right answer.
Question 52: What appears
in the standard output
when the method named
testing is invoked?
question 51: Analyze the
following code.
System.out.println(a);
}
h) the number 10 to the
standard output
one:
Select the one right answer.
static int a = 3;
g) the numbers 5 through 9 to
the standard output
void testing() {
}
d) final is not a valid keyword for
a class
class First {
f) the number 4 to the
standard output
b) This code does not compile
d) the numbers 1 and 2 to the
standard output
e) the number 3 to the standard
output
Question 53: What will the
result be for the following
block of code when it is
executed?
int i = 3;
int j = 0;
float k = 3.2F;
long m = -3;
if (Math.ceil(i) < Math.floor(k))
103
if (Math.abs(i) == m)
arr[i] = 0;
if (obj1.equals(obj2))
System.out.println(i);
System.out.println("a");
else
else
Select all valid answers.
a) arr[0] == 0
System.out.println(j);
System.out.println("b");
else
b) arr[0] == 1
else
System.out.println(Math.abs(m)
+ 1);
if (obj1.equals(obj2))
System.out.println("c");
c) arr[1] == 1
else
Select the one right answer.
a) 3
b) 0
c) -3
d) 4
e) none of these
Question 54: The ISO code for
the language you are
interested in is 8859-5.
Assume you have a stream in
a variable named mystream
that’s associated with a file
generated in this 8-bit
character set. If the default
conversion to Unicode in your
environment is for the
encoding 8859-1, how can
you create a new instance of
InputStreamReader that will
perform the conversion from
ISO 8859-5 to Unicode,
automatically? (Start by
writing the keyword new and
do not add a semicolon at the
end.)
ill in the blank.
Question 55: What is written
to the standard output as the
result of executing the
following statements?
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean(true);
Object obj1 = (Object)b1;
Object obj2 = (Object)b2;
System.out.println("d");
Select the one right answer.
a) a
b) b
c) c
e) arr[3] == 0
Question 58: What will
happen if you try to compile
and execute B’s main()
method?
class A {
d) d
int i;
Question 56: What will the user
interface look like in an applet
given the following init()
method?
A(int i) {
public void init() {
}
setLayout(new BorderLayout());
this.i = i * 2;
}
add(new Button("hello"));
}
class B extends A {
Select the one right answer.
public static void
main(String[] args) {
a) Nothing will appear in the applet
B b = new B(2);
b) A button will appear in the applet
set in the exact center
}
B(int i) {
c) A button will appear in the applet
along the top and centered
horizontally
d) A button will appear in the top left
corner
e) A button will fill the entire applet
Question 57: What expressions
are true concerning the following
lines of code?
int[] arr = {1, 2, 3};
if (obj1 == obj2)
d) arr[2] == 0
for (int i=0; i < 2; i++)
System.out.println(i);
}
}
Select the one right answer.
a) The instance variable i is set
to 4
b) The instance variable i is set
to 2
104
c) The instance variable i is set
to 0
c) A catch block
must always be associated with a try
block
How do I set the CLASSPATH
variable for the Java
Development Kit ?
d) This code will not compile
Question 59: Which best
describes the user interface
of an applet given the
following init() method:
d) A finally can never stand on its
own (that is, without being
associated with try block)
e) None of these are true
public void init() {
Back to questions
setLayout(new
BorderLayout());
add("North", new
TextField(10));
add("Center", new
Button("help"));
}
Select all valid answers.
a) The TextField object will be
placed at the top of the applet
and will be 10 columns wide
b) The Button object will be
centered in the applet and will be
just large enough to contain the
text "help"
c) The Button object will be
centered in the applet and will
start at the left edge of the
applet, fit just under the
TextField object above it, and
extend to the right and bottom
edge of the applet
d) The TextField object will be
placed along the top of the
applet and will stretch from the
left edge to the right edge
e) The placement of the Button
object and the TextField object
depends on the overall size of
the applet.
Question 60: Which of the
following statements about
try, catch, and finally are
true?
Select all valid answers.
a) A try block must always be
followed by a catch block
b) A try block can be followed
either by a catch block or a
finally block, or both
Question 1.
Where can I download the Sun Java
Development Kit (SDK) / Java
Runtime Environment (JRE) ?
Answer.
At the time of this writing, the latest
released version is 1.4.2.
This can be downloaded from
Question 2.
Do I want the Java Development Kit
(SDK) or the Java Runtime
Environment (JRE) ?
Answer.
The SDK is the Software
Development Kit. This will allow you
to develop Java software
applications. The SDK includes the
JRE as well as other tools that are
suitable for software development.
The JRE is the Java Runtime
Environment. This will allow you to
run Java software applications, but
does not include the tools to develop
Java software applications.
In conclusion, if you wish to develop
and run Java applications, you want
the SDK.
If you wish to simply run Java
applications, but not develop them,
you want the JRE.
Question 3.
How do I install the Java
Development Kit ?
Answer.
This process is documented at
Question 4.
How do I set the PATH environment
variable for the Java Development
Kit ?
Answer.
The PATH environment variable is set
that that it additionally contains the
bin directory of the installed SDK.
Question 5.
Answer.
Generally, you do not set the
CLASSPATH environment
variable for a standard SDK or
JRE installation. The
CLASSPATH environment
variable is set for other
reasons, usually the installation
of third-party libraries. Some
people (including myself) argue
that setting the CLASSPATH
environment variable at all is
bad practice; it should be set
dynamically at each build. This
keeps the build machine clean
from potential "contamination"
from libraries in the
CLASSPATH. Setting the
CLASSPATH environment
variable was required for
installation of the SDK in
versions prior to 1.2. This
"myth" has unfortunately
carried over to later versions of
Java and confusion has
resulted. A good rule of thumb
is, "If you don't know how to
set the CLASSPATH (since you
are relatively new to Java),
don't set the CLASSPATH at
all". More information on the
CLASSPATH environment
variable can be found at
Question 6.
What/Where is Java API
Documentation ?
Answer.
API is an acronym for
"Application Programming
Interface." Therefore, the Java
API Documentation is a listing
of all the possible uses of the
current core Java API. This
includes packages, classes,
methods, fields and more. Note
that Java API Documentation
changes as the API changes for
each incremental version of the
Java Development Kit.
However, the API (generally)
remains reverse compatible
and if API becomes outdated, it
often becomes "deprecated."
The Java API Documentation is
considered the "bible" of any
Java programmer. An example
of the use of the API
Documentation: the
java.lang.String class has a
105
method called length() which
returns an int value indicating
the length of a String. This can
be confirmed by looking at the
following part of the Java API
Documentation
http://java.sun.com/j2se/1.4.2/d
ocs/api/java/lang/String.html#le
ngth().
Question 7.
What does this mean "Exception
in thread "main"
java.lang.NullPointerException" ?
Answer.
Often called a
NullPointerException or NPE, this
is caused by dereferencing an
object reference to null. That is,
you have an object reference and
you are trying to dereference it
(usually by calling a method or
accessing a field/member) while
the reference isn't referring to an
object instance. The next line of
the output will give the location
(file name and line number) of
the violation. The following code
produces a NullPointerException:
...
String s = null; // s is
referring to null (no object
instance)
int len = s.length(); //
dereferencing a reference to null
- will result in a
java.lang.NullPointerException at
this line
...
The following fixes the problem:
...
String s = "blah"; //
make sure that s is referring to
an object instance.
int len = s.length(); //
dereferencing a reference to a
String instance - ok.
...
Question 8.
What does this mean "Exception
in Thread "main"
java.lang.NoClassDefFoundError
<something> " ?
Answer.
This means that the Java Virtual
Machine (JVM) cannot find the
class that you are referring to.
The error is followed by the class
name that the JVM was asked to
load. The directory that contains
this class must
be in your CLASSPATH environment
variable. If your CLASSPATH is not
set to anything, then the class must
be located in the same directory from
which the JVM is invoked (package
relative). The JVM is generally (but
not always) invoked by executing the
java executable followed by the class
name at a command line.
One common problem arises when
executing a jar file (using the -jar
switch), which ignores all
CLASSPATH settings, except for that
specified in the Java ARchive
manifest file. This may be contrary to
general intuition, but it makes
perfect sense when you think about
it. This is outlined in The JAR File
Specification.
A common error is to append the
.class file extension to the class
name when invoking the JVM; this
will result in an error similar to the
following:
Exception in thread "main"
java.lang.NoClassDefFoundError:
MyClass/class
Fix this problem by removing the
.class file extension from your
command.
Wrong
> java MyClass.class
Right
> java MyClass
Question 9.
What does this mean "non-static
variable (or method) <something>
cannot be referenced from a static
context" ?
Answer.
Well simply put, you are referencing
something that is non-static from a
static context, which is not
permitted. Elaborating on this
concept in this document may be
misleading, so it is best to read the
relevant tutorial on Understanding
Instance and Class Members.
Question 10.
What does this mean "variable
<something> might not have been
initialized" ?
Answer.
This is caused by using a
variable that doesn't have a
value. For example, declaring
an int without initializing it's
value, then using it somehow
(without a value). Note that
class data members are
initialized implicitly. The
following code produces the
compiler error:
...
int x; // x doesn't
have a value "hasn't been
initialized";
System.out.println("
x = " + x); // attempting to
use x before giving it a value
...
To fix this problem, the value x
must be given a value before
using it:
...
int x = 0; // x now
has a value
System.out.println("
x = " + x); // using x with a
value
...
Question 11.
What does this mean
"unreported exception
<something>; must be caught
or declared to be thrown" ?
Answer.
This is caused by a
misunderstanding of the
concepts of exception handling
in Java. Generally, Java has
three types of errors that can
occur, a runtime "Error", a
non-checked "Exception" or a
checked "Exception." A runtime
Error is usually fatal and
should not be handled at all in
your code. A non-checked
Exception is recognizable
because it is of type
java.lang.RuntimeException (or
a subclass) and usually
indicates a programming error,
thus, it probably should not be
handled (of course, there are
always exceptions (no pun
intended) to this rule).
Checked Exceptions are usually
recoverable and it is enforced
by the compiler that you (the
developer) handle them,
hence, the compile error when
you don't. Question 12.
What does this mean "Note:
<something> uses or overrides
106
a deprecated API. Note:
Recompile with -deprecation for
details."?
Answer.
You might have heard of the
term "self-deprecating humor." It
describes humor that minimizes
one's own importance.
Similarly, when a class or
method is deprecated, it means
that the class or method is no
longer considered important. It is
so unimportant, in fact, that it
should no longer be used at all,
as it might well cease to exist in
the future.
The need for deprecation comes
about because as a class
evolves, its API changes.
Methods are renamed for
consistency. New and better
methods are added. Attributes
change. But making such
changes introduces a problem:
You need to keep the old API
around until people make the
transition to the new one, but
you don't want developers to
continue programming to the old
API.
The ability to mark a class or
method as "deprecated" solves
the problem. Existing classes
that use the old API continue to
work, but the compiler can issue
a warning when it finds
references to deprecated items.
Meanwhile, API documentation
can warn the user against using
the deprecated item and tell the
user how to avoid doing so. To
mark API as deprecated, the
implementer of the API uses a
special tag in doc comments:
@deprecated.
Note: "Deprecated" and
"depreciated" are not the same.
"Depreciated" is a financial term
that means "lowered value."
Although the meanings are
similar, classes and methods are
deprecated, not depreciated.
Question 13.
How do I generate a random
number between x and y ?
Answer.
The java.lang.Math class
provides a method called
random() that returns a double
value that is "greater than or
equal to 0.0 and less than 1.0."
Therefore, using some simple
mathematics,
you can generate a value between
any range with the following piece of
code:
double num =
Math.random() * (y - x) + x;
This will generate a random number
between x (inclusive) and y
(exclusive).
Question 14.
What are access modifiers (public,
protected, private, default) ?
Answer.
In the Java programming language,
there are four different types of
access modifier. An access modifier
is applied to classes, class data
members and class methods. These
access modifiers describe what type
of scope or visibility they have. All
classes, class data members and
class methods have some type of
access level (even if one isn't
specified).
These access modifiers are :
public
protected
package-protected (also called
default)
private
To specify a class, data member or
method as having access scope of
type default is to not explicitly
declare any access modifier at all.
A description of the access modifiers
follows, in order of least restrictive to
most restrictive:
public
A public class, data member,
constructor or method has scope to
all other classes. All classes can see
each others' public classes, data
members, constructors and methods.
protected
A protected class, data member,
constructor or method has scope to
itself, it's subclasses and classes
within the same package. A class can
see the protected classes, data
members, constructors and methods
of its' superclass and classes within
the same package. Top level classes
cannot be declared as protected.
package-protected (or default)
A package-protected class, data
member or method has no
access modifier explicitly
specified. A class, data
member or method which is
declared as package-protected
has scope only within its'
package. Classes that are
declared to be in the same
package can see each others'
package-protected classes,
data members and methods.
Classes that are declared with
package-protected access
scope are available to classes
within the same package. The
package-protected access
modifier is also referred to as
default scope or packagefriendly.
private
A private data member or
method has scope only within
itself. A class can see only its'
own private clases, members,
constructors and methods. Top
level classes cannot be
declared private.
Question 15.
What is "inheritance",
"polymorphism (run-time
binding)", "an interface" ?
Answer.
These concepts are not trival.
A good understanding of these
(and other) concepts is
essential to make good use of
the Java programming
language.
Question 16.
What is method overloading ?
Answer.
Method overloading is distinct
from method overriding - they
are two separate concepts.
Method overloading is where a
class provides a method which
has the same name but
different type and/or order of
parameters. Method
overloading is generally used
where a class can perform the
same operation on more than
one type of data. Note that a
class cannot contain two
methods with the same
"signature." A method
signature is defined by it's
name and type/order of it's
parameters. The method return
type and modifiers have no
107
effect on the method signature.
The following is an example of
method overloading:
class AddNumbers
{
public double
add(double a, double b)
{
return a + b;
}
public int add(int a,
int b)
{
return a + b;
}
/*
public long add(int a,
int b) // illegal, a method with
the same signature already
exists
{
return a + b;
}
*/
}
Question 17.
What is method overriding ?
Answer.
Method overriding is distinct
from method overloading - they
are two separate concepts.
Method overriding is where a
class provides a method with the
same signature as a method that
is declared in it's superclass. The
subclass' method does not inherit
the functionality of it's
superclass' method unless it is
done expicitly using the "super"
keyword. The following code
demonstrates method overriding:
class Superclass
{
void
method1()
{
System.out.println("Su
perclass.method1()");
}
void
class
Subclass extends Superclass
{
// Overrides
method1() and loses the functionality
of the superclass method1()
void method1()
{
System.out.println("Subcla
ss.method1()");
}
// Overrides
method2() and explicitly calls the
functionality of the superclass
method2()
void method2()
{
super.method2();
System.out.println("Subcla
ss.method2()");
}
}
Question 18.
Can static methods be overridden ?
Answer.
No. A static method of a subclass
that has the same signature as a
static method of a superclass does
not actually override it. The subclass
method cannot call on the superclass
methods functionality with the
"super" keyword..
Question 19.
Can private methods be overridden ?
Answer.
No. A private method of a subclass
that has the same signature as a
private method of a superclass does
not actually override it. This is
because the two methods work
independantly of each other due to
their access scope. The private
subclass method cannot call on the
private superclass method with the
"super" keyword since this is a
violation of the private access scope.
method2()
{
System.out.println("Su
perclass.method2()");
}
}
Question 20.
What does "immutable" mean ?
Answer.
The term immutable simply means
unchangeable. Immutable objects do
not change once their
constructor has executed. You
may already know that the
java.lang.String class is
immutable, despite the
appearance that it is not, due
to its convenient concatenation
operator. You may also know
that if you need to write code
that constructs a single String
object over a number of
separate statements, it is more
efficient to use the
java.lang.StringBuffer object.
Immutability is implemented as
a design pattern that the
programmer builds into the
class. There are some general
characteristics that are usually
found in all intentionally
immutable objects. These rules
follow:
- A class is instantiated and all
of its properties are set
through the constructor(s).
When the arguments are
passed at creation, it
eliminates any need for setter
methods on the class that
might be called later.
- The class is declared final.
This prevents another
developer from extending your
class and implementing code
that supports mutability.
- The properties of the class
are private. This prevents
other objects from modifying
the attributes directly, and
adds another layer of
protection from subclassed
code over making the class
final (with one very exceptional
rule).
- Other than the
constructor(s), there is no code
in the class that changes the
properties of the object. Any
methods or events for the class
must treat the private
attributes as read-only. In this
way, the final state of the
object is determined when it is
constructed, and no
opportunity exists to change it
for its lifetime.
- If methods are implemented
that perform operations on the
data abstracted by the class,
the result of those operations
are another instance of the
class containing the modified
data.
- If the class is sufficiently
general purpose in scope, it
may be packaged with a
108
companion object that is
mutable. This is the case with
the String and StringBuffer
classes.
Question 21.
Does Java pass parameters by
reference, by value, both or
neither ?
Answer.
Java pass all parameters strictly
by value. This may be contrary
to advice that you receive from
both (claimed) experienced and
inexperienced people. I can
assure you that they need a
walloping; Java is purely pass by
value. To clarify, there is some
deeper understanding that is
essential. This understanding is
not trivial or useless but it is
necessary to understanding how
to use the Java Programming
Language effectively.
Java has two basic data types;
primitive values and object
references. Java does not permit
direct access to objects (as in
.NET), but allows the developer
to declare a reference to an
object type. There are 8
primitive data types (long, int,
short, char, byte, boolean, float
and double). Consider the
following piece of code:
...
Object o = new
Object(); // declares an object
reference called 'o' that refers to
an object of type
java.lang.Object
String s = "blah"; //
declares an object reference
called 's' that refers to an object
of type java.lang.String (a literal
String)
int x; // declares a
primitive type called 'x' of type
int
...
In memory, the above code looks
like this:
Now calling a method and passing
these three parameters (by value)
with the following code:
...
method(o, s, x);
...
void method(Object o2,
String s2, int x2)
{
// What does
memory look like now ?
}
The model in memory now looks like
this:
Question 22.
Can Java applications leak
memory ?
Answer.
Yes. Consider the following
code:
import java.util.*;
public class Stack
{
private
Object[] elements;
private int
size = 0;
public
boolean leak = false;
public
Stack(int initialCapacity)
{
elements = new
Object[initialCapacity];
}
public void
push(Object e)
{
ensureCapacity();
elements[size++] =
e;
}
The "greyed out" areas represent
variables that method2 does not
have access to. Notice that method2
can still "see" the object instances,
but not the original caller's object
references. Therefore, if an object
instance is altered through one of
method2's object references, the
change to the instance will be
reflected in the original caller's object
references. This will give the false
impression that the object was
passed by reference. In fact, the
object reference was passed by
value. If method2 had changed the
value of the references, the change
would not have been reflected to the
caller in any way. The primitive data
type was passed by value and the
effect was not seen at all in the
original caller. To reiterate,
understanding this concept is not
trivial or academic. It is fundamental
to the use of the Java Programming
Language. Java is strictly pass by
value.
public
Object pop()
{
if(size == 0)
{
throw
}
if(leak)
{
return
}
else
{
Objec
eleme
return
}
}
private
void ensureCapacity()
{
if(elements.length
== size)
{
109
}
}
}
The following code is likely to
cause a
java.lang.OutOfMemoryError
caused by a memory leak in the
Stack class:
class Foo
{
private int[]
vals = new int[10000];
}
class Bar
{
public static
void main(String[] args)
{
final int size = 1600;
Stack s = new
Stack(size);
s.leak = true;
for(int i = 0; i < size;
i++)
{
}
for(int i = 0; i < size;
i++)
{
}
System.out.println("Pu
shed and popped " + size + "
objects");
for(int i = 0; i < size;
i++)
{
}
for(int i = 0; i < size;
i++)
{
}
}
Object[] oldElements
Question
= elements;
23.
Can Ielements
invoke the
garbage
collector
?
= new
Object[2
* elements.length
+ 1];
System.arraycopy(oldElements, 0, elements, 0, size); private
SingletonExample()
Answer.
{
No. Both the java.lang.System and
java.lang.Runtime classes provides a
gc() method that "suggests that the
Java Virtual Machine expend effort
toward recycling unused objects in
order to make the memory they
currently occupy available for quick
reuse." It is not guaranteed when or
if the garbage collector will run by
making this call. The common
misconception that this method
invokes the garbage collector is a
source of many subtle errors in Java
applications.
Question 24.
Can I convert my Java application
into a Windows executable (.exe) ?
Answer.
What you want to do is possible, but
it is not recommended. Java is
designed to be a platform
independent language. Compiling a
Java application into a platformspecific executable defeats Java's
design intent. Also, using native
s.push(new
Foo());
compilers
does not
offer the
significant performance
improvements over the Java Runtime
Environment with JIT (Just-In-Time)
enabled. If you want do distribute
your Java application, distribute it
with Sun's Java Runtime
s.pop();
Environment.
Question 25.
What is a "Singleton" class ?
Answer.
A singleton class is a class where
there only exists at most, one
instance during runtime. This can be
enforced
by giving
all constructors
s.push(new
Foo());
private access and providing a public
static method that returns the only
existing instance. The following is an
example of a Singleton class BUT
only if a single thread accesses the
instance. Achieving thread-safe
access
to singleton classes is a very
s.pop();
interesting topic, but is beyond the
scope of this document.
}
class SingletonExample
{
private static
SingletonExample instance;
}
public
static SingletonExample
getInstance()
{
if(instance == null)
{
instan
}
return instance;
}
}
Question 26.
How do I convert a .class file
back to a .java source file ?
Answer.
Converting a compiled Java
class file to its original source
may be a violation of the
licence to use the software.
Typically, there is seldom a
legitimate reason for doing
such a thing. It is important to
realise the unethical nature of
violating the terms of use of
code that does not belong to
you before performing this
operation.
In order to "decompile" a Java
class file to a Java source file,
you will require the use of a
Java decompiler. Some
searching around on a web
search engine for a "Java
decompiler" will likely yield the
desired results.
Question 27.
How do I clear the console
screen ?
Answer.
You can't without making a
native call using JNI or
executing a system command,
and, in both cases, losing
platform independance. You
can "kind of" clear the screen
110
by printing a series of new lines.
...
for(int i = 0; i < 100;
i++)
{
System.out.println();
}
...
The reason for this is that Java
doesn't assume that it's
operating environment has a
console screen. You don't have a
screen for servlets, EJB and
various other environments, so it
makes sense not to assume the
existance of one. Generally,
clearing a console screen means
one of the following:
- You are a university student
trying to "pretty up" your
assignment, in which case, it's
not worth writing bad code in
order to do something that Java
was not designed to do.
- You are using a command line
interface where you should be
using a windowing interface
(such as swing) if you want to
perform operations such as
clearing a screen.
- You have too much time on
your hands (Go and read a good
book on Java, instead of writing
poor code).
Question 28.
How do I create a String that
represents a double (or float)
value with only 2 decimal places
?
Answer.
By using the
java.text.DecimalFormat class.
The following is an example:
double d = 12345.678;
DecimalFormat df =
new DecimalFormat();
df.setMinimumFraction
Digits(2);
df.setMaximumFraction
Digits(2);
String formatted =
df.format(d); // "12345.68"
Question 29.
Does Java support multiple
inheritance ?
Answer.
No. Classes may inherit from one
and only one (not zero, implicitly or
explicitly) class and may implement
zero or many interfaces. Interfaces
may inherit from zero or more
interfaces - this is not (and is not
even close to) multiple inheritance.
The only exception to this rule is
java.lang.Object which does not have
a superclass.
Question 30.
How do I make a
javax.swing.JTextArea scroll to the
end ?
Answer.
First, the JTextArea must be within a
javax.swing.JScrollPane. Then set
the caret position of the JTextArea to
be at the end. Assuming the
JTextArea has a reference called 'ta':
ta.setCaretPosition(ta.getText().lengt
h() - 1);
Question 31.
Can I execute an external command
?
Answer
Yes you can. Be aware of the
consequences of doing such a thing.
Your application then becomes
dependant on the platform which the
external command runs on. It may
(or may not) be worthwhile allowing
the user of your application to
configure the external command,
since it changes under so many
different operating environments.
Alternatively:
You can achieve this by calling one of
the exec methods of the
java.lang.Runtime class, which will
fork a process from the JVM. A
handle to this process is returned
from the method as a
java.lang.Process.
double d = 12345.678;
DecimalFormat df =
new DecimalFormat("#.00");
String formatted =
df.format(d); // "12345.68"
Question 32.
Can I reference the subclass from a
superclass ?
Answer
No. Wanting to do such a thing
generally indicates a design
flaw. It is not possible to
explain where the design flaw
is, since this question is too
general. Therefore, I will
propose some questions that
will hopefully assist you to
understand why this a design
flaw. Firstly, what is "the"
subclass ? A superclass can
have more than one (or even
none) subclasses - this rules
out the concept of "the"
subclass. A subclass is
dependant on its superclass,
and this dependancy is
unidirectional - a superclass
cannot have a dependancy on
a subclass (unless of course, it
is some other relationship
besides inheritance, but that is
beside the point). How can a
developer design a superclass
that knows about ALL of its
subclasses ? Deriving from a
class provides you with the
same functionality as the
superclass - how does the
superclass know about the
subclass, since it is added at a
later date (due to the
unidirectional dependancy) ?
Perhaps what it is in the
subclass actually belongs in the
superclass ? Perhaps you need
to use the Template Method
Design Pattern ? This is clearly
speculation and a more
concrete solution can only be
arrived at with some more
thought on your behalf.
Question 33.
Is it possible to prevent a
thread of execution from
executing for a specified period
of time ?
Answer
It is only possible to prevent
the current thread from
executing for a specified period
of time, but not any arbitrary
thread. This is achieved by
putting the thread into a
"sleep" state. It is important to
realise the after the specified
period of time, the thread
enters the "ready for
execution" state, NOT the
"execution" state. The time at
which the thread enters the
"execution" state after sleeping
(and then entering "ready"
state) is completely
indeterminate and is the
111
responsibility of the thread
scheduler. It can be said that
"sleeping a thread prevents the
current thread of execution from
executing for AT LEAST the
specified period of time".
Therefore, causing a thread to
sleep should not be relied upon
as an accurate timer, as
accuracy is not guaranteed, and
in practice, it seldoms occurs.
The java.lang.Thread class
exposes two static sleep
methods:
java.lang.Thread#sleep(long)
java.lang.Thread#sleep(long,
int)
development
In contrast, a user who is learning
Java, and is using an IDE might
perform the following actions:
java.lang.NoClassDefFoundError
this message means, consults the
help for the IDE, which clearly, won't
reveal any clues
internet group for assistance, where
any explanation that is given, is well
beyond the understanding of the
user
Considering the lack of accuracy
when putting a thread into the
sleep state, there doesn't seem
to be a good reason why anyone
would want to call the method
that takes the number of
nanoseconds as an argument.
the internet, which reveals ad hoc
advice that is unrelated to the actual
problem (instead of the more likely,
IDE setting)
Question 34.
Why shouldn't an Integrated
Development Environment (IDE)
be used for learning Java ?
This example is one of the many
thousands of possibilities that an IDE
can present to a user who is well out
of their depth of understanding.
Some people have a hard time
recognising their shortcomings,
swallowing their pride, and learning
with the appropriate material and
tools. The best way to learn Java is
with a text editor (even Notepad or
vim will do!) and the Java 2 SDK. As
a university teacher, I see this
mistake all too often. Some of the
excuses I hear are outrageous:
Answer
It is an unfortunate fact that
those who have a fundamental
understanding of Java know the
answer to this question, while
those who are still learning, often
choose to ignore it. An IDE hides
the details of the inner workings
of Java, and at times, the user is
abstracted away so much, that
when a problem is encountered,
the user consults the IDE for
resolution, rather than
understanding that "underneath"
the abstractions given by the
IDE, the problem is lurking.
For example, a user who has an
understanding of Java and is
using an IDE might perform the
following actions:
java.lang.NoClassDefFoundError
type of Throwable and consult
the API documentation for that
type
or made
after determining the meaning of
that error type
to what is generally a trivial problem,
which takes several hours, while the
competent user resolved the issue in
less than one minute.
properly
... but you have time to fix the
infinite number of possible
problems that are well beyond
the scope of your understanding
?
problems (yet)
Oh it will. Like I said, I've seen it
far too many times. If it doesn't,
it is purely coincidental (video
tape it - it's a rarity!).
The IDE is doing things that you
don't understand and as soon as
something "breaks", you will be
in big trouble.
s my code for me,
so that I don't have to
The IDE is writing code for
you that you don't
understand. What happens
when the IDE isn't capable
of producing the code
exactly as you want ? Are
you capable of editing it ?
Learning the intricacies of Java
is very important for anyone
who intends on developing
seriously. This may be contrary
to the belief of the untrained
user, and I can certainly see
why. It is difficult to accept
that the tools that you are
using are actually a hindrance,
while they are disguising
themselves as helpful tools.
This opinion is not just my
own, but that of several very
competent developers who
have all learnt The Hard Way
But The Right Way.
Question 35.
When should I use
java.util.Vector/java.util.Hasht
able ?
Answer
The classes java.util.Vector
and java.util.Hashtable are
remnants of JDK 1.1 that have
been kept in the core API to
maintain reverse compatibility
with older code. These classes
were "retrofitted" in JDK 1.2 to
fit into the new Java
Collections Framework. Newer
classes/interfaces were
introduced in JDK 1.2 that
achieve the same function as
Vector and Hashtable, and do
not have to maintain any
backward compatibility.
Lessons that were learnt from
previous versions of the JDK
could be applied to these new
classes without fear of
breaking earlier code. The
same functionality of Vector
can be achieved by using
java.util.ArrayList and the
functionality of Hashtable can
be achieved by using
java.util.HashMap (there is a
minor difference in that
HashMap permits nulls). If you
require thread safety on these
types, you can use
java.util.Collections to
synchronize them, since Vector
and Hashtable are already
thread-safe, and often times,
unnecessarily.
112
In general, you only need to use
a Vector or Hashtable if you are
supporting Java Runtime
Environment versions that are
older than 1.2. More often that
not, the newer classes/interfaces
should be used in order to take
advantage of performance and
maintenance benefits if this is
not the case.
If you insist on using a Vector or
Hashtable for some unforeseen
reason, you should always use
(at least) a java.util.Map
reference to refer to a Hashtable
and/or (at least) a java.util.List
reference to refer to a Vector.
This same guideline applies to
using HashMap and ArrayList.
The reasoning for this, and many
other good practices for the Java
Collections Framework are
detailed in the tutorial.
Question 36.
Can I increase efficiency by using
less import statements ?
Answer
First the term "efficiency" must
be defined.
The quantity and type (wildcard
or fully qualified) of import
statements does not affect
runtime performance of an
application, so in terms of
"efficiency of runtime
performance", the answer is
"no".
The quantity and type of import
statements does affect compiletime performance - that is, less
import statements generally
means your application will
compile faster; also, using fully
qualified import statements
rather than wildcard import
statements generally means your
application will compile faster. If
the term "efficiency" is defined
as the "efficiency of the compiler
to compile my application", the
answer is "yes".
Source code becomes more
maintainable when full qualified
imports are used, and unused
imports are absent. If the term
"efficiency" is defined as the
"efficiency of a code maintainer
to read and maintain the code",
the answer is "yes".
Question 37.
Can I start my java.lang.Thread
more than once ?
Answer
No. A thread that has been run and
completed (by finishing the run()
method) cannot be restarted.
Attempting to restart a thread that
has completed execution (or is
already running) results in a
java.lang.IllegalStateException.
However, you can create and start
more than one thread with an
instance of java.lang.Runnable
(which defines what the thread does
during execution in its run()
method).
Question 38.
What's the difference between
javaw.exe and java.exe ?
Answer
Both of these executables start up a
JVM, however, only javaw.exe is
available on the Microsoft Windows
platform. The javaw.exe executable
allows the user to start the JVM
without the need for a command
console from which to launch it from.
This is useful for applications that do
not require the user to view the
command console on the Microsoft
Windows platform, such as graphical
applications.
Question 39.
How do I exit my application ?
Seldom in an application is
there a need to forcefully
shutdown the JVM. A well
designed application will have
taken into consideration issues
regarding flow control, and
application logic will be
implemented such that the
application exits cleanly
(usually by exiting the main
method) when it is time to do
so. It is important to ensure
that all non-daemon threads
that your application creates
are no longer executing when a
clean exit is intended. Also,
consider that an application
that has more than one exit
point is difficult to maintain.
Question 40.
Why is my GUI application
broken if I set the layout to
null ?
Answer
Quite often, developers of
Swing applications will set the
layout of a java.awt.Container
to null, in order to avoid the
complexities involved is using
Layout Managers. This
approach is fraught with many
pitfalls that the developer may
not be aware of. For instance,
the application may not run
correctly on a system with:
the development system.
ferent screen resolution
to the development system.
the development system.
Answer
Some developers will immediately
jump at this question claiming
"System.exit" is the answer.
However, naively calling this method
can cause potential problems, albeit
the fact that it occurs often.
System.exit(int) forces a JVM
shutdown and returns with the exit
code given as the parameter. It is
important to realise that it is not just
your application that will cease
running, but any other applications
running within the JVM, and the JVM
itself. This may cause undesirable
results, leaving data which is
external to your application (or any
other application under the JVM) in
an inconsistent state.
Setting a layout to null is
generally considered poor
form, and applications that
violate this rule should be
considered defective, since it is
not guaranteed to run on any
system correctly, except for
the system on which it was
developed.
Question 41.
Why shouldn't I use floatingpoint types for representing
monetary values (or any value
that demands accuracy) ?
Answer
113
Java floating-point types (float
and double) are represented in
IEEE 754 (Institute of Electrical
and Electronics Engineers)
format as per Java Language
Specification 4.2.3. IEEE 754
format for floating-point types is
a detailed specification, suffice to
say that a floating-point type is
"an inexact representation of an
ideal real number" and
operations performed on them
are inexact. You can witness
these inaccuracies by performing
an operation as simple as
System.out.println(2.4 *
1.111111); You will immediately
notice that the output is not the
otherwise expected 2.6666664.
This is due to the internal
representation of the floatingpoint type.
The correct approach for storing
monetary values would be to use
an integral type (such as int, or
long) that represents the number
of cents guaranteeing accuracy.
Storing other data where
accuracy is required should also
use some approach that involves
integral types, and not floatingpoint types.
If you happen to encounter an
application where monetary
values have been represented
using an IEEE 754 floating-point
type, please contact me such
that I can arrange for the
"missing bits" of money to be
deposited into my bank account.
compliant with
the specifications for Java set out by
Sun Microsystems, and this fact was
the basis for a successful lawsuit filed
by Sun Microsystems Inc. against
Microsoft Corporation in 2001.
J# is the successor to J++ developed
by Microsoft as part of their .NET
initiative and again, is not compliant
with the specifications for Java set
out by Sun Microsystems.
Javascript is a scripted loosely-typed
(Java is strongly-typed) language
developed by Netscape, which
unfortunately inherited a similar
name to Java that now results in
confusion. Javascript is the language
interpreted by web browsers to
perform certain browser-specific
behaviour along with HTML. It has no
relationship to the Java 2
Programming Language, except for a
similar name.
Question 43.
How do I access an outer class
member/method from an inner class
?
Answer
<OuterClassName>.this.<member/m
ethodname>
Here is an example:
public class Outer
{
private int x;
Question 42.
What's the difference between
Java and J++ and J# and
Javascript ?
public class Inner
{
void
Answer
method()
{
First and foremost, these four
technologies are distinct. That it
to say "Java is not J++ is not J#
is not Javascript".
Java is a programming language
designed by Sun Microsystems
and it is this language that this
web page is dedicated to.
J++ is (was) a programming
language designed my Microsoft
Corporation to compete against
Java. It consists of a very similar
syntax and API specification to
Java, however, it is not
}
}
}
Question 44.
What is the newline character ?
Answer
A lot of misinformed developers will
quickly reply to this question with an
answer of '\n'. The correct answer is
that there isn't one. If you
consult a Unicode table (how
Java characters are
represented), you'll find that
there is no character
designated as the line
terminator. So where did '\n'
come from ? The End Of Line
(EOL) terminating character on
UNIX platforms is the Line
Feed character '\n' (0x000A).
This does NOT apply to all
platforms. For example, the
Microsoft Windows platform
uses two characters, Carriage
Return and Line Feed to
represent an EOL terminator
"\r\n" (0x000D 0x000A); the
Macintosh platform uses the
Carriage Return to represent
the EOL terminator "\r"
(0x000D). Other platforms
may use other character
sequences to represent an EOL
terminator. When you see code
that is written in a fashion
similar to this:
System.out.print("he
llo world\n");
it is important to realize that
you are seeing the string "hello
world" followed by the Line
Feed character, NOT an EOL
terminator as some would
suggest. If this code was
executed on a UNIX platform,
you'd have that character
expressed as an EOL
terminator (UNIX platformspecific behaviour), but this is
not the same as writing an EOL
terminator in Java. Some
Microsoft Windows applications
take into account that a lot of
developers erroneously insist
on using '\n' as an EOL
terminator and act accordingly
(so that you won't see the
consequences). So what if you
wanted an EOL terminator in a
Outer.this.x
= 42;? Since Java
Java
environment
is platform-independant, there
needs to be a way of
representing the EOL
terminator on all the different
platforms. You can obtain the
EOL terminator by accessing
the System property called
"line.separator". Alternatively,
when you write to streams,
you can use a
java.io.BufferedWriter to write
a new line or a
java.io.PrintStream to println.
Doing this will take care of
writing out the correct, and
114
often intended, EOL terminator
(by accessing the line.separator
System property internally). In
the code sample above, if the
intention is to print "hello world"
followed by an EOL terminator
(instead of a Line Feed character
as it does now), you can simply
use the println method, since
System.out is a PrintStream. To
reiterate in conclusion, the
following statement is NOT
equivalent to the statement
given above.
System.out.println("hel
lo world");
Question 45.
How do I use a multi-dimensional
array ?
Answer
A common misconception is that
Java supports the use of multidimensional arrays. In fact, Java
supports arrays whose elements
may be of any type, including
arrays. That is, an array of
arrays and an array of arrays of
arrays is quite possible, while a
"2D array" and a "3D array" is
not. This distinction is important
in coming to terms with the Java
programming language, and is
not purely academic as some
might suggest. Consider the
following code:
// An array that holds
String arrays - NOT a 2D String
array.
String[][] array;
// Iterate the "outer"
array
for(int i = 0; i <
array.length; i++)
{
// Get an
element of the "outer" array.
String[]
element = array[i];
// Iterate the
"inner" array.
// Length is
not constant for all elements.
for(int j = 0;
j < element.length; j++)
{
//
Get an element of an "inner"
array.
String s = element[j];
}
}
It is important to realise, that in the
above code sample, there is no "2
dimensional" array. There is an array
whose elements are String arrays. A
language such as COBOL supports
true multi-dimensional arrays
(known as "tables"). To understand
this distinction is important to use
arrays effectively in Java (and
COBOL too!).