Você está na página 1de 115

1

Question 1) instance of the File class such as the Question 10)


directory separator, depend on the
Which of the following are legal current underlying operating system Which of the following
statements? statements are true?
Question 6).
1) float f=1/3; 1) A byte can represent
2) int i=1/3; Which of the following statements between -128 to 127
3) float f=1.01; are true? 2) A byte can represent
4) double d=999d; between -127 to 128
1) The instanceof operator can be 3) A byte can represent
Question 2) used to determine if a reference is an between -256 to 256
instance of a class, but not an 4) A char can represent
interface. between -2x2 pow 16 2 x2 pow
Which of the following are Java
2) The instanceof operator can be 16 - 1
keywords?
used to determine if a reference is an
instance of a particular primitive Question 11)
1) NULL
wrapper class
2) new
3) The instanceof operator will only What will happen when you
3) instanceOf
determine if a reference is an attempt to compile and run the
4) wend
instance of a class immediately following code
above in the hierarchy but no further
Question 3) up the inheritance chain
class Base{
4) The instanceof operator can be
public void Base(){
Which of the following are valid used to determine if one reference is
statements? of the same class as another
System.out.println("Base");
reference thus
}
1) System.out.println(1+1); }
2) int i=2+'2'; Question 7) public class In extends Base{
3) String s="on"+'one'; public static void
4) byte b=255; Which of the following statements main(String argv[]){
are true? In i=new In();
Question 4) }
1) An interface can only contain }
Which of the following method and not variables
statements are true? 2) Interfaces cannot have 1) Compile time error Base is a
constructors keyword
1) The garbage collection 3) A class may extend only one other 2) Compilation and no output
algorithm in Java is vendor class and implement only one at runtime
implemented interface 3) Output of Base
2) The size of primitives is 4) Interfaces are the Java approach 4) Runtime error Base has no
platform dependent to addressing its lack of multiple valid constructor
3) The default type for a inheritance, but require
numerical literal with decimal implementing classes to create the Question 12)
component is a float. functionality of the Interfaces.
4) You can modify the value in You have a public class called
an Instance of the Integer class Question 8) myclass with the main method
with the setValue method defined as follows
Which of the following are valid
Question 5) statements public static void main(String
parm[]){
Which of the following are true 1) public class MyCalc extends Math
statements? 2) Math.max(s); System.out.println(parm[0]);
3) Math.round(9.99,1); }
1) I/O in Java can only be 4)Math.mod(4,10);
performed using the Listener If you attempt to compile the
classes Question 9) class and run the program as
2) The RandomAccessFile class follows
allows you to move directly to Which of the following are methods
any point a file. of the Runnable interface java myclass hello
3) The creation of a named
instance of the File class creates
1) run What will happen?
a matching file in the underlying
2) start
operating system only when the
3) yield 1) Compile time error, main is
close method is called.
4) stop not correctly defined
4) The characteristics of an
2) Run time error, main is not
2
correctly defined public static void main(String argv[]) 1) A component may have only
3) Compilation and output of { one event listener attached at
java Severn s = new Severn(); a time
4) Compilation and output of } 2) An event listener may be
hello void Severn(){ removed from a component
System.out.println("Severn"); 3) The ActionListener interface
Question 13) } has no corresponding Adapter
} class
4) The processing of an event
1) Compilation and output of the listener requires a try/catch
Which of the following
string "Severn" at runtime block
statements are true?
2) Compile time error
3) Compilation and no output at
1) If a class has any abstract
runtime Question 20)
methods it must be declared
4) Compilation and output of the
abstract itself.
string "Base" Which of the following are Java
2) All methods in an abstract
class must be declared as keywords?
abstract Question 17)
3) When applied to a class, the 1) sizeof
final modifier means it cannot be Which of the following statements 2) main
sub-classed are true? 3) transient
4) transient and volatile are Java 4) volatile
modifiers
1) static methods do not have access Question 21)
Question 14) to the implicit variable called this
2) A static method may be called Which of the following
Which of the following are valid without creating an instance of its statements are true?
methods? class
3) A static method may not be
1) The default constructor has
overriden to be non-static
a return type of void
4) A static method may not be
1) public static native void 2) The default constructor
overloaded
amethod(){} takes a parameter of void
2) public static void amethod(){} 3) The default constructor
3) private protected void Question 18) takes no parameters
amethod(){} 4) The default constructor is
4) static native void amethod(); Which of the following will compile not created if the class has any
without error? constructors of its own.
Question 15)

Which of the following 1) Question 22)


statements are true?
char c='1'; Which of the following
1) Constructors cannot have a System.out.println(c>>1); statements are true?
visibility modifier
2) Constructors can be marked 2) 1) All of the variables in an
public and protected, but not interface are implicitly static
private Integer i=Integer("1"); 2) All of the variables in an
3) Constructors can only have a System.out.println(i>>1); interface are implicitly final
primitive return type 3) All of the methods in an
4) Constructors are not inherited interface are implicitly abstract
3)
4) A method in an interface
can access class level variables
int i=1;
Question 16)
System.out.println(i<<<1);

What will happen when you Question 23)


4)
attempt to compile and run the
following class? Which of the following
int i=1; statements are true?
System.out.println(i<<1);
class Base{
Base(int i){ 1) The String class is
System.out.println("Base"); implemented as a char array,
} elements are addressed using
} Question 19) the stringname[] convention
2) The + operator is
class Severn extends Base{ Which of the following are true? overloaded for concatenation
3
for the String class public static void main(String argv[]) different parameters gives
3) Strings are a primitive type in { multiple uses for the same
Java and the StringBuffer is used boolean b1 = true; method name
as the matching wrapper type if((b1 ==true) || place(true)){ 4) A class is prevented from
4) The size of a string can be System.out.println("Hello accessing methods in its
retrieved using the length Crowle"); immediate ancestor
property }
} Question 30)
Question 24)
public static boolean
Which of the following
Which of the following place(boolean location){
statements are true?
statements are true? if(location==true){

System.out.println("Borcetshire"); 1) The % is used to calculate a


1) A method in an interface must percentage thus: 10 % 20=50
}
not have a body 2) The / operator is used to
System.out.println("Powick");
2) A class may extend one other divide one value by another
return true;
class plus at most one interface 3) The # symbol may not be
}
3) A class may extends at most used as the first character of a
}
one other class plus implement variable
many interfaces 4) The $ symbol may not be
4) An class accesses an interface What will happen when you attempt
used as the first character of a
via the keyword uses to compile and run it?
variable

Question 31)
Question 25) 1) Compile time error
2) Output of "Hello Crowle"
3) Output of Borcetshire and Powick Which of the following
Which of the following statements are true?
followed by "Hello Crowle"
statements are true?
4) No output
1) The default layout manager
1) The following statement will for an Applet is FlowLayout
Question 28)
produce a result of 1. 2) The default layout manager
System.out.println( -1 >>>2); for a Frame is FlowLayout
2) Performing an unsigned left You are given a class hierarchy with
3) A layout manager must be
shift (<<<) on a negative an instance of the class Dog. The
assigned to an Applet before
number will always produce a class Dog is a child of mammal and
the setSize method is called
negative number result the class Mammal is a child of the
4) The FlowLayout manager
3) The following statement will class Vertebrate. The class
attempts to honor the
produce a result of zero, Vertebrate has a method called
preferred size of any
System.out.println(1 >>1); move which prints out the string
components
4) All the Java integral types are "move". The class mammal overrides
signed numbers this method and prints out the string
"walks". The class Dog overrides this Question 32)
method and prints out the string
Question 26)
"walks on paws". Given an instance Which of the following
of the class Dog,. how can you statements are true about a
Which of the following access the ancestor method move in variable created with the static
statements are true? Vertebrate so it prints out the string modifier?
"move";
1) The elements in a Java array 1) Once assigned the value of
can only be of primitive types, 1) d.super().super().move(); a static variable may not be
not objects 2) d.parent().parent().move(); altered
2) Arrays elements are initialized 3) d.move(); 2) A static variable created in a
to default values wherever they 4) none of the above; method will keep the same
are created using the keword value between calls
new 3) Only one instance of a static
Question 29)
3) An array may be dynamically variable will exist for any
resized using the setSize method amount of class instances
4) You can find out the size of an Which of the following most closely 4) The static modifier can only
array using the size method describes the process of overriding? be applied to a primitive value

Question 27) 1) A class with the same name Question 33)


replaces the functionality of a class
defined earlier in the hierarchy
Given the following class Which of the following
2) A method with the same name
statements are true?
completely replaces the functionality
public class Ombersley{ of a method earlier in the hierarchy
3) A method with the same name but
4
1) Java uses a system called UTF public void run(){ makes extensive use of the the
for I/O to support international System.out.println("Running"); GridBagConstraints class.
character sets }
2) The RandomAccessFile is the } Question 39)
most suitable class for
supporting international 1) Compilation and run but no output Given the following class
character sets 2) Compilation and run with the definition
3) An instance of output "Running"
FileInputStream may not be 3) Compile time error with complaint
chained to an instance of public class Droitwich{
of no Thread target
FileOutputStream class one{
4) Compile time error with complaint
4) File I/O activities requires use private class two{
of no access to Thread package
of Exception handling public void
main(){
Question 36)
Question 34)
System.out.println("two");
Assuming any exception handling has }
What will happen when you been set up, which of the following }
attempt to compile and run the will create an instance of the }
following code? RandomAccessFile class }

import java.io.*; 1) RandomAccessFile raf=new Which of the following


class ExBase{ RandomAccessFile("myfile.txt","rw"); statements are true
abstract public void martley() 2) RandomAccessFile raf=new
{ RandomAccessFile( new
} DataInputStream()); 1) The code will not compile
3) RandomAccessFile raf=new because the classes are nested
} RandomAccessFile("myfile.txt"); to more than one level
4) RandomAccessFile raf=new 2) The code will not compile
public class MyEx extends RandomAccessFile( new because class two is marked as
ExBase{ File("myfile.txt")); private
public static void main(String
3) The code will compile and
argv[]){
Question 37) output the string two at
DataInputStream fi = new
runtime
DataInputStream(System.in);
Given the following class definition 4) The code will compile
try{
without error
fi.readChar();
}catch(IOException e){ public class Upton{
System.exit(0); public static void main(String argv[]) Question 40)
} {
finally } Given the following code
{System.out.println("Doing public void amethod(int i){}
finally");} //Here class Base{
} } static int oak=99;
} }
Which of the following would be legal
1) Compile time error to place after the comment //Here ? public class Doverdale extends
2) It will run, wait for a key press 1) public int amethod(int z){} Base{
and then exit 2) public int amethod(int i,int j) public static void main(String
3) It will run, wait for a {return 99;} argv[]){
keypress, print "Doing finally" 3) protected void amethod(long l){ } Doverdale d = new
then exit 4) private void anothermethod(){} Doverdale();
4) At run and immediately exit d.amethod();
Question 38) }
Question 35) public void amethod(){
//Here
Which of the following statements
}
What will happen when you are true?
}
attempt to compile and run the
following code 1) Code must be written if the
Which of the following if placed
programmer wants a frame to close
after the comment //Here, will
public class Borley extends on selecting the system close menu
compile and modify the value
Thread{ 2) The default layout for a Frame is
of the variable oak?
public static void main(String the BorderLayout Manager
argv[]){ 3) The layout manager for a Frame
Borley b = new Borley(); cannot be changed once it has been 1) super.oak=1;
b.start(); assigned 2) oak=33;
} 4) The GridBagLayout manager
5
3) Base.oak=22; t class Base{
4) oak=50.1; Base(){
to a class which extends Thread,
Question 41) which of the following will cause it to System.out.println("Base");
give up cycles to allow another }
thread to execute. }
You are creating an application
that has a form with a text entry
public class Checket extends
field used to enter a persons age. 1) t.yield();
Base{
Which of the following is 2) Thread.yield();
public static void main(String
appropriate for capturing this 3) yield(100); //Or some other
argv[]){
information. suitable amount in milliseconds
Checket c = new
4) yield(t);
Checket();
super();
1) Use the Text field of a Question 45) }
TextField and parse the result
using Integer What will happen when you attempt Checket(){
2) Use the getInteger method of to compile and run the following
the TextField code? System.out.println("Checket");
3) Use the getText method of a }
TextBox and parse the result }
public class Sandys{
using the getInt method of
private int court;
Integer class
public static void main(String argv[]) 1) Compile time error
4) Use the getText method of a
{ 2) Checket followed by Base
TextField and use the parseInt
Sandys s = new Sandys(99); 3) Base followed by Checket
method of the Integer class
System.out.println(s.court); 4) runtime error
}
Sandys(int ballcount){ Question 48)
court=ballcount;
Question 42) }
Which of the following
}
statements are true?
Given the following declaration
1) Static methods cannot be
1) Compile time error, the variable
overriden to be non static
Integer i=new Integer(99); court is defined as private
2) Static methods cannot be
2) Compile time error, s is not
declared as private
initialized when the System.out
3) Private methods cannot be
method is called
How can you now set the value overloaded
3) Compilation and execution with no
of i to 10? 4) An overloaded method
output
cannot throw exceptions not
4) Compilation and run with an
checked in the base class
output of 99
1) i=10;
2) i.setValue(10); Question 49)
Question 46)
3) i.parseInt(10);
4) none of the above Which of the following
Which of the following statements
statements are true?
are true?
Question 43)
1) The automatic garbage
1) A method cannot be overloaded to
Which of the following collection of the JVM prevents
be less public in a child class
statements are true programs from ever running
2) To be overridden a method only
out of memory
needs the same name and parameter
1) constructors cannot be 2) A program can suggest that
types
overloaded garbage collection be
3) To be overridden a method must
2) constructors cannot be performed but not force it
have the same name, parameter and
overridden 3) Garbage collection is
return types
3) a constructor can return a platform independent
4) An overridden method must have
primitive or an object reference 4) An object becomes eligible
the same name, parameter names
4) constructor code executes for garbage collection when all
and parameter types
from the current class up the references denoting it are set
hierarchy to the ancestor class to null.
Question 47)

Question 44) Question 50)


What will happen when you attempt
to compile and run the following
Given a reference called Given the following code
code?
6
public class Sytch{ Head Chefs i++;
int x=2000; Chefs }
public static void main(String Apprentice Chefs }
argv[]){
System.out.println("Ms The system needs to store an 1) Compile time error
"+argv[1]+"Please pay $"+x); employeeid, salary and the holiday 2) Output of 2
} entitlement 3) Output of 1
4) Output of 0
}
How would you best represent this
What will happen if you attempt
information in Javae been given the Question 55)
to compile and run this code with
following information and asked to
the command line
create a set of classes to represent What will happen when you
java Sytch Jones Diggle
it. attempt to compile and run the
following code?
1) Compilation and output of Ms
How would you best represent this
Diggle Please pay $2000
information in Java public class Agg{
2) Compile time error
3) Compilation and output of Ms static public long i=10;
Jones Please pay $2000 1) Create classes for Head Chef, public static void main(String
4) Compilation but runtime error Chef, Apprentice Chef and store the argv[]){
other values in fields switch(i){
2) Create an employee class and default:
Question 51)
derive sub classes for Head Chef,
Chef, Apprentice Chef and store the System.out.println("no value
What will happen when you other values in fields. given");
attempt to compile and run the 3) Create and employee class with case 1:
following code fields for Job title and fields for the
other values. System.out.println("one");
class Base{ 4) Create classes for all of the items case 10:
protected int i = 99; mentioned and create a container
} class to represent employees System.out.println("ten");
public class Ab{ case 5:
private int i=1; Question 53)
public static void main(String System.out.println("five");
argv[]){ }
You need to read in the lines of a
Ab a = new Ab(); }
large text file containing tens of
a.hallow(); }
megabytes of data. Which of the
}
following would be most suitable for
reading in such a file 1) Compile time error
abstract void hallow(){ 2) Output of "ten" followed by
System.out.println("Claines "five"
"+i); 1) new FileInputStream("file.name")
3) Output of "ten"
} 2) new InputStreamReader(new
4) Compilation and run time
FileInputStream("file.name"))
error because of location of
} 3) new BufferedReader(new
default
InputStreamReader(new
FileInputStream("file.name")));
1) Compile time error Question 56)
4) new RandomAccessFile raf=new
2) Compilation and output of
RandomAccessFile("myfile.txt","+rw"
Claines 99
); Given the following class
3) Compilation and output of
Claines 1
4) Compilation and not output at Question 54) public class ZeroPrint{
runtime public static void main(String
What will happen when you attempt argv[]){
to compile and run the following int i =0;
Question 52)
code? //Here
}
You have been asked to create a }
scheduling system for a hotel public class Inc{
and catering organsiation. public static void main(String argv[])
{ Which of the following lines if
Inc inc = new Inc(); placed after the comment
You have been given the //Here will print out 0.
int i =0;
following information and asked
inc.fermin(i);
to create a set of classes to
i = i++; 1) System.out.println(i++);
represent it.
System.out.println(i); 2) System.out.println(i+'0');
} 3) System.out.println(i);
On the catering side of the void fermin(int i){ 4) System.out.println(i--);
organsiation they have
7
Question 57) 1) The x,y coordinates of an instance 1) float f=1/3;
of MouseEvent can be obtained using 2) int i=1/3;
Given the following code the getX() and getY() methods 4) double d=999d;
2) The x,y coordinates of an instance
of MouseEvent can be obtained using The fact that option 3 does not
class Base {}
the X and Y integer fields compile may be a surprise. The
3) The time of a MouseEvent can be problem is because the default
class Agg extends Base{
extracted using the getTime() type for a number with a
public String getFields(){
method decimal component is a double
String name = "Agg";
4) The time of a MouseEvent can be and not a float. The additional
return name;
extracted using the getWhen method trailing d in the option with 999
}
} doesn't help, but it doesn't
Question 60) harm.

public class Avf{ Given the following code Answer to Question 2)


public static void main(String
argv[]){ import java.io.*; Objective 4.3)
Base a = new Agg();
//Here public class Ppvg{
2) new
} public static void main(String argv[])
} {
Ppvg p = new Ppvg(); The option NULL (note the
p.fliton(); upper case letter) is definitely
What code placed after the
} not a keyword. There is some
comment //Here will result in
public int fliton(){ discussion as to i. There is
calling the getFields method
try{ some discussion as to if null is
resulting in the output of the
FileInputStream din = a keyword but for the purpose
string "Agg"?
new FileInputStream("Ppvg.java"); of the exam you should
din.read(); probably assume it is a
1) keyword.
}catch(IOException ioe){
System.out.println(a.getFields())
;
The option instanceOf is a bit
2) System.out.println(a.name);
System.out.println("flytwick"); of a misleading option that
3) System.out.println((Base)
return 99; would probably not occur on
a.getFields());
}finally{ the exam. The real keyword is
4) System.out.println( ((Agg)
instanceof (note that the of has
a).getFields());
no capital letter O). I had the
System.out.println("fliton"); incorrect version in an earlier
Question 58) } version of this tutorial as it
return -1; looks more likely to my eyes.
What will happen when you } The instanceof keyword looks
attempt to compile and run the like a method, but it is actually
following code. } an operator.

public class Pvf{ Assuming the file Ppvg.java is The option wend is probably
available to be read which of the valid in some other language
static boolean Paddy; following statements are true if you to indicate the end of a while
public static void main(String try to compile and run the program? loop, but Java has no such
argv[]){ keyword.
System.out.println(Paddy); 1) The program will run and output
} only "flytwick" Answer to Question 3)
2) The program will run and output
} only "fliton" Objective 4.5)
3) The program will run and output
1) Compile time error both "fliton" and "flytwick"
4) An error will occur at compile time 1) System.out.println(1+1);
2) compilation and output of
because the method fliton attempts 2) int i=2+'2';
false
to return two values Option 3 is not valid because
3) compilation and output of true
single quotes are used to
4) compilation and output of null
indicate a character constant
Answers and not a string. Several
Question 59) people have emailed me to say
Answer to Question 1) that option 3 will compile.
Which of the following When they eventually compiled
statements are true? Objective 4.5) the exact code they have
agreed, it will not compile. Let
me re-state that
8
String s="on"+'one'; particular primitive wrapper class Answer to Question 10)

Will NOT compile. Objective 4.5)


The instanceof operator can only be
Option 4 will not compile because used to make a static comparison 1) A byte can represent
255 is out of the range of a byte with a class type. Java1.1 added the between -128 to 127
isInstance method to the class Class
to allow you to dynamically
Answer to Question 4) The char type is the only
determine a class type. The exam
unsigned type in Java and thus
does not test you on isInstance.
Objective 7.1) cannot represent a negative
number.
Answer to Question 7)
1) The garbage collection
algorithm in Java is vendor For more information on this
Objective 4.1) topic go to
implemented

2) Interfaces cannot have Answer to Question 11)


Threading and garbage collection
constructors
are two of the few areas that are
platform dependent. This is one Objective 1.2)
of the If you try to create a constructor for
reasons why Java is not suitable an Interface the compiler will give
2) Compilation and no output
for realtime programming. It is you an error message something like
at runtime
not a good idea use it to control
your "interface can't have constructors".
Because the method in Base
plane or nuclear power station.
called Base has a return type it
Once an instance of the Integer 4) Interfaces are the Java approach is not a constructor and there
class has a value it cannot be to addressing the single inheritance for does not get called on
changed. model, but require implementing creation of an instance of its
classes to create the functionality of child class In
Answer to Question 5) the Interfaces.
For more information on this
Objective 10.1) An interface may contain variables as topic go to
well as methods. However any
(Not on the official sub objectives variables are final by default and
Answer to Question 12)
but this topic does come up on must be assigned values on creation.
the exam) A class can only extend one other
class (single inheritance) but may Objective 4.2)
implement as many interfaces as you
2) The RandomAccessFile class
like (or is sensible). 4) Compilation and output of
allows you to move directly to
hello
any point a file.
4) The characteristics of an Answer to Question 8)
instance of the File class such as This type of question is
the directory separator, depend Objective 9.1) particularly calculated to catch
on the current underlying out C/C++ programmers who
operating system might expect parameter zero
None of these are valid statements.
to be the name of the
The Math class is final and cannot be
compiler.
The File class can be considered extended. The max method takes
to represent information about a two parameters, round only takes
file rather than a real file object. one parameter and there is no mod For more information on this
You can create a file in the parameter. You may get questions in topic go to
underlying operating system by the exam that have no apparently
passing an instance of a file to a correct answer. If you are absolutely Answer to Question 13)
stream such as sure this is the case, do not check
FileOutputStream. The file will be any of the options. Objective 1.2)
created when you call the close
method of the stream. Answer to Question 9) 1) If a class has any abstract
methods it must be declared
Answer to Question 6) Objective 7.1) abstract itself.
3) The final modifier means
Objective 5.1) 1) The Runnable interface has only that a class cannot be sub-
one method run that needs to be classed
2) The instanceof operator can created in any class that implements 4) transient and volatile are
be used to determine if a it. The start method is used to Java modifiers
reference is an instance of a actually call and start the run
method executing.
9
An abstract class may have non Answer to Question 17) multiple event handlers. The
abstract methods. Any class that ActionListener has not
descends from an abstract class Objective 1.2) matching Adapter class
must implement the abstract because it has only one
methods of the base class or method, the idea of the
1) static methods do not have access
declare them as abstract itself. Adapter classes is to eliminate
to the implicit variable called this
the need to create blank
2) A static method may be called
For more information on this methods.
without creating an instance of its
topic go to class
3) a static may not be overriden to For more information on this
Answer to Question 14) be non-static topic go to

Objective 1.2) The implicit variable this refers to the Answer to Question 20)
current instance of a class and thus
2) public static void amethod(){} and by its nature a static method Objective 4.3)
4) static native void amethod(); cannot have access to it.

Option 1 is not valid because it For more information on this topic go 3) transient
has braces and the native to 4) volatile
modifier means that the method
can have no body. This is Answer to Question 18)
because the body must be Option 1, sizeof is designed to
implemented in some other Objective 5.1) catch out the C/C++
language (often C/C++). Option programmers. Java does not
3 is not valid because private have a sizeof keyword as the
1)
and protected contradict size of primitives should be
themselves. consistent on all Java
char c='1'; implementations. Although a
System.out.println(c>>1); program needs a main method
For more information on this
topic go to with the standard signature to
4) start up it is not a keyword.
The real keywords are less
Answer to Question 15)
int i=1; commonly used and therefore
System.out.println(i<<1); might not be so familiar to you.
Objective 6.2)
For more information on this
4) Constructors are not inherited topic go to
Be aware that Integer (not the upper
case I) is a wrapper class and thus
Constructors can be marked cannot be treated like a primitive. Answer to Question 21)
public, private or protected. The fact that option 1 will compile
Constructors do not have a may be a surprise, but although the Objective 1.3)
return type. char type is normally used to store
character types, it is actually an
3) The default constructor
For more information on this unsigned integer type. The reason
takes no parameters
topic go to option 3 does not compile is that
4) The default constructor is
Java has a >>> operator but not a
not created if the class has any
Answer to Question 16) <<< operator. ;>> operator but not
constructors of its own.
a <<< operator.
Objective 1.3) Option 1 is fairly obviously
For more information on this topic go
wrong as constructors never
to
have a return type. Option 2 is
2) Compile time error very dubious as well as Java
Answer to Question 19) does not offer void as a type
An error occurs when the class for a method or constructor.
Severn attempts to call the zero Objective 4.6)
parameter constructor in the For more information on this
class Base Because the Base 2) An event listener may be removed topic go to
class has an integer constructor from a component
Java does not provide the 3) The ActionListener interface has Answer to Question 22)
"behind the scenes" zero no corresponding Adapter class
parameter constructor.
Objective 4.1)
A component may have multiple
For more information on this event listeners attached. Thus a field
1) All of the variables in an
topic go to may need to respond to both the
interface are implicitly static
mouse and the keyboard, requiring
10
2) All of the variables in an (The result is more like 2) A method with the same
interface are implicitly final 1073741823 ) There is no such Java name completly replaces the
3) All of the methods in an operator as the unsigned left shift. functionality of a method
interface are implictly abstract Although it is normally used for earlier in the hierarchy
storing characters rather than
All the variables in an interface numbers the char Java primitive is Option 3 is more like a
are implicitly static and final. Any actually an unsigned integer type. description of overloading. I
methods in an interface have no like to remind myself of the
body, so may not access any And for information on the size of difference between overloading
type of variable primitives see and overriding in that an
overriden method is like
Answer to Question 23) Answer to Question 26) something overriden in the
road, it is squashed, flat no
longer used and replaced by
Objective 4.5) Objective 4.4)
something else. An overloaded
method has been given extra
2) The + operator is overloaded 2) Arrays elements are initialized to work to do (it is loaded up with
for concatenation for the String default values wherever they are work), but it is still being used
class created using the keyword new. in its original format. This is
just my little mind trick and
In Java Strings are implemented doesn't match to anything that
as a class within the Java.lang You can find the size of an array Java is doing.
package with the special using the length field. The method
distinction that the + operator is length is used to return the number Answer to Question 30)
overloaded. If you thought that of characters in a String. An array
the String class is implemented can contain elements of any type but
Objective 1.2)
as a char array, you may have a they must all be of the same type.
head full of C/++ that needs The size of an array is fixed at
emptying. There is not "wrapper creation. If you want to change its 2) The / operator is used to
class" for String as wrappers are size you can of course create a new divide one value by another
only for primitive types. array and assign the old one to it. A 3) The # symbol may not be
more flexible approach can be to use used as the first character of a
a collection class such as Vector. variable
If you are surprised that option 4
is not a correct answer it is
because length is a method for Answer to Question 27) The % is the modulo operator
the String class, but a property and returns the remainder
for and array and it is easy to get after a division. Thus 10 %
Objective 5.3)
the two confused. 3=1
The $ symbol may be used as
2) Output of "Hello Crowle" the first character of a
Answer to Question 24)
variable, but I would suggest
This code is an example of a short that it is generally not a good
Objective 6.1) circuited operator. Because the first idea. The # symbol cannot be
operand of the || (or) operator used anywhere in the name of
1) A method in an interface must returns true Java sees no reason to a variable. Knowing if a
not have a body evaluate the second. Whatever the variable can start with the # or
3) A class may extends one other value of the second the overall result $ characters may seem like
class plus many interfaces will always be true. Thus the method arbitrary and non essential
called place is never called. knowlege but questions like
A class accesses an interface this do come up on the exam.
using the implements keyword Answer to Question 28)
(not uses)
Objective 6.2)
Answer to Question 25)
4) none of the above; Answer to Question 31)
Objective 5.1)
You may access methods of a direct Objective 8.1)
3) The following statement will parent class through the use of super
produce a result of zero, but classes further up the hierarchy 1) The default layout manager
System.out.println(1 >>1); are not visible. for an Applet is FlowLayout
4) The FlowLayout manager
Although you might not know the Answer to Question 29) attempts to honor the
exact result of the operation -1 preferred size of any
>>> 2 a knowledge of the way components
Objective 6.1)
the bits will be shifted will tell
you that the result is not plus 1.
11
The default layout manager fror finally clause runs, but actually it is makes extensive use of the the
an Application is BorderLayout. about something else. GridBagConstraints class.
An applet will use the default of
FlowLayout if one is not Answer to Question 35) You can change the layout
specifically applied. manager for a Frame or any
Objective 7.1) other container whenever you
Answer to Question 32) like.
2) Compilation and run with the
Objective 1.2) output "Running" Answer to Question 39)

3) Only one instance of a static This is perfectly legitimate if useless Objective 1.2)
variable will exist for any amount sample of creating an instnace of a
of class instances Thread and causing its run method to 4) The code will compile
execute via a call to the start without error
Option 1) is more a description method. The Thread class is part of
of a final variable. Option 2 is the core java.lang package and does There are no restrictions on the
designed to fool Visual Basic not need any explicit import level of nesting for
programmers like me as this is statement. The reference to a Thread inner/nested classes. Inner
how you can use the keyword target is an attempt to mislead with classes may be marked
static in VB. The modifier static a reference to the method of using private. The main method is
can be applied to a class (only an the Runnable interface instead of not declared as public static
innner class) , method or simply inheriting from the Thread void main, and assuming that
variable. super class. the commandline was java
Droitwich it would not be
Answer to Question 33) Answer to Question 36) invoked anyway.

Objective 11.1) Objective 11.1) Answer to Question 40)

1) Java uses a system called UTF 1) RandomAccessFile raf=new Objective 1.2)


for I/O to support international RandomAccessFile("myfile.txt","rw");
character sets 1) super.oak=1;
3) An instance of The RandomAccessFile is an anomaly 2) oak=33;
FileInputStream may not be in the Java I/O architecture. It 3) Base.oak=22;
chained to an instance of descends directly from Object and is
FileOutputStream not part of the Streams architecture. Because the variable oak is
4) File I/O activities requires use
declared as static only one
of Exception handling
Answer to Question 37) copy of it will exist. Thus it can
be changed either through the
Internally Java uses Unicode name of its class or through
Objective 6.2)
which are 16 bit characters. For the name of any instance of
I/O Java uses UTF which may be that class. Because it is created
more thatn 16 bits per chamore 2) public int amethod(int i, int j)
as an integer it canot be
thatn 16 bits per character. {return 99;}
assigned a fractional
Generally InputStreams can only 3) protected void amethod (long l){}
component without a cast.
be chained to other 4) private void anothermethod(){}
InputStreams and
Answer to Question 41)
OutputStreams can only be Option 1 will not compile on two
chained to other OutputStreams. counts. One is the obvious one that it
The piped streams are an claims to return an integer. The Obje Question 41)
exception to this. other is that it is effectivly an
attempt to redefine a method within Objective 4.6)
Answer to Question 34) the same class. The change of name
of the parameter from i to z has no 4) Use the getText method of a
effect and a method cannot be Textfield and use the parseInt
Objective 1.2)
overriden within the same class. method of the Integer class
1) Compile time error
Answer to Question 38) Here is an example of how you
Objective 8.1) might do this
It wil produce an error like
"Abstract and native method
1) Code must be written to cause a Integer.parseInt(txtInputValue.
can't have a body. This is typical
frame to close on selecting the getText());
of the more misleading question
system close menu
where you might think it is
2) The default layout for a Frame is
asking you about the I'm not sure that a question on
the BorderLayout Manager
circumstances under which the this actually will come up in the
4) The GridBagLayout manager
12
exam but it is a very useful thing Answer to Question 45) should not be declared private.
to know in the real world. Option 4 is a jumbled up
Objective 6.2) version of the limitations of
Answer to Question 42) exceptions for overriden
methods
4) Compilation and run with an
Objective 4.6) output of 99
Answer to Question 49)
4) none of the above The fact that the variable court is
declared as private does not stop the Objective 3.1)
The wrapper classes are constructor from being able to
immutable. Once the value has initialise it. 2) A program can suggest that
been set it cannot be changed. A garbage collection be
common use of the wrapper Answer to Question 46) performed but not force it
classes is to take advantage of 4) A reference becomes
their static methods such as eligable for garbage collection
Objective 6.2)
Integer.parseInt(String s) that when it is assigned to null
will returns an integer if the the
3) To be overriden a method must
value has been set it cannot be If a program keeps creating
have the same name, parameter and
changed. A common use of the new references without any
return types
wrapper classes is to take being discarded it may run out
advantage of their static of memory. Unlike most
methods such as Option 1 is a sneaky one in that it aspects of Java garbage
Integer.parseInt(String s) that should read overriden not collection is platform
will returns an integer if the overloaded. An overriden method dependent.
String contains one. must also have the same return
type. Parameter names are purely a
Answer to Question 50)
programmer convenience and are not
Answer to Question 43)
a factor in either overloading and
overriding. Parameter order is a Objective 1.2)
Objective 6.2) factor however.
2) Compile time error
2) constructors cannot be Answer to Question 47)
overriden The main method is static and
Objective 6.2) cannot access the non static
Overloading constructors is a key variable x
technique to allow multiple ways
1) Compile time error
of initialising classes. By Answer to Question 51)
definition, constructors have Objective 1.2)
have no return values so option With the sun JDK it will produce the
3 makes no sense. Option 4 is following error
1) Compile time error
the inverse of what happens as
constructor code will execute "Only constructors can invoke
starting from the oldest ancestor constructors". When compiled with JDK 1.1
class downwards. You can test the following error is produced.
this by writing a class that If you took out the call to super that
inherits from a base class and causes this error the program would Abstract and native methods
getting the constructor to print compile and at runtime it would can't have a body: void
out a message. When you create output Base and then Checket as hallow() abstract void hallow()
the child class you will see the constructors are called from the
order of constructor calling. oldest ancestor class downwards. Answer to Question 52)
Objective 6.1)
Answer to Question 44) Answer to Question 48)
3) Create and employee class
Objective 7.1) Objective 1.2) with fields for Job title and
fields for the other values.
yield is a static method and 1) Static methods cannot be
causes whatever thread is overriden to be non static These questions can appear
currently executing to yield its tricky as the whole business of
cycles. designing class structures is
The JDK1.1 compiler will issue an
more art than science. It is
error message "static methods
1) t.yield(); asking you to decide if an item
cannot be overriden" if you atempt to
2) Thread.yield() of data is best represented by
do thiuot; if you atempt to do this.
the "Is a" or "Has a"
There is no logic or atempt to do
relationship. Thus in this case
(Thanks Roseanne ) this. There is no logic or reason why
any of the job titles mentioned
private methods should not be
will always refer to something
overloaded or that static methods
13
that "Is a" employee. However If you attempt to compile this code the default value for the
the employee "has a" job title with JDK 1.2 you will get an error primitive type boolean is false
that might change. that says something like
"Incompatible type for switch, Answer to Question 59)
One of the important points is to Explicit cast needed to convert long
ask yourself when creating a to int". Answering with option 2
Objective 4.6)
class "Could this change into would have been reasonable because
another class at some point in if the parameter had been an integer
type the lack of break statements 1) The x,y coordinates of an
the future". Thus in this example
would have caused this output. If instance of MouseEvent can be
an apprentice chef would hope
you gave either of the answers you obtained using the getX() and
one day to turn into a chef and if
should probably revise the subject. getY() methods
she is very good will one day be
4) The time of a MouseEvent
head chef. Few other mock
can be extracted using the
exams seem to have this type of Answer to Question 56)
getWhen method
questions but they di come up in
the real exam. Objective 5.1)
If you chose option 4, referring
to the mythical getTime
Answer to Question 53) 1) System.out.println(i++); method you have made a
3) System.out.println(i); reasonable guess based on the
Objective 11.1) 4) System.out.println(i==); normal conventions of Java.
However the conventions do
3) new BufferedReader(new The options for this question might not always hold true. If you
InputStreamReader(new look suspiciously easy if you are not chose option 3 perhaps you are
FileInputStream("file.name"))); aware of the effects of the post- not as aware of the
increment operators. The ++ and == conventions as you should be.
The key to this question is that it operations for examples 1 and 4 only
asks about tens of megabytes of come into effect after the output Answer to Question 60)
data, implying that performance operations, ie after whatever else is
is an issue. A Buffered Reader done to them on that line of code.
Objective 2.3
will optimise the performance of Option 2 should be fairly obvious as
accessing a file. Although the you should know that the single
quote characters indicate a char 2) The program will run and
objectives do not specifically
value, ie storing the character rather output only "fliton"
mention it questions on I/O do
come up on the exam. than the numberical value for 0.
This question tests your
Answer to Question 57) knowledge of the principle that
Answer to Question 54)
the finally clause will almost
always run.
Objective 5.4) Objective 6.2)

Breakdown of Questions by
4) Output of 0 4) System.out.println( ((Agg)
Topic
a).getFields());
The method fermin only receives 30)Objective 1.2)
a copy of the variable i and any The Base type reference to the
48)Objective 1.2)
modifications to it are not instance of the class Agg needs to be
39)Objective 1.2)
reflected in the version in the cast from Base to Agg to get access
40)Objective 1.2)
calling method. The post to its methods.The method invoked
50)Objective 1.2)
increment operator ++ effectivly depends on the object itself, not on
51)Objective 1.2)
modifes the value of i after the the declared type. So, a.getField()
17)Objective 1.2)
initial value has been assiged to tries to invoke a getField method in
32)Objective 1.2)
the left hand side of the equals Base which does not exist. But the
14)Objective 1.2)
operator. This can be a very call to ((Agg)a).getField() will invoke
11)Objective 1.2)
tricky conept to understand the getField() in the Agg class. You
13)Objective 1.2)
will be unlucky to get a question as
34)Objective 1.2)
complex as this on the exam. If you
Answer to Question 55)
think option 1 is valid, have a go at
Objective 2.1) 55)Objective 2.2)
compiling the code.

1) Compile time error 60)Objective 3.4)


Answer to Question 58)
16)Objective 1.3)
This might be considered a
Objective 4.4) 21)Objective 1.3)
"gocha" or deliberate attempt to
mislead you because i has been
2) compilation and output of false 49)Objective 3.1)
given the data type of long and
the parameter must be of long
26)Objective 4.4)
and the parameter must be A variable defined at class level will
either a byte, char, short or int. always be given a default value and
14
1)Objective 4.5) B. public static void C. 0
3)Objective 4.5) main(String args[]); D. 1
10)Objective 4.5) C. public static void E. 2
MAIN(String args[]); 32. In Java what
D. public static void expression can be used
main(String args); to represent number of
22)Objective 4.1) E. public static void elements in an array
7) Objective 4.1) main(char args[]); named arr ?
12)Objective 4.2) 2. What all gets printed when 33. How would the number
2) Objective 4.3) the following code is 5 be represented in
23)Objective 4.5) compiled and run ? Select all hex using upto four
42)Objective 4.6) correct answers. characters.
41)Objective 4.6) 3. 34. Which of the following
19)Objective 4.6) 4. public class xyz { is a Java keyword.
20)Objective 4.3) 5. public static void Select all correct
48)Objective 4.4) main(String args[]) { answers.
59)Objective 4.6) 6. for(int i = 0; i < 2; i++) A. extern
{ B. synchronized
7. for(int j = 2; j>= 0; C. volatile
6) Objective 5.1) j•) { D. friend
25)Objective 5.1) 8. if(i == j) break; E. friendly
18)Objective 5.1) 9. F. transient
27)Objective 5.3) System.out.println("i=" + i + G. this
54)Objective 5.4) " j="+j); H. then
56)Objective 5.1) 10. } 35. Is the following
11. } statement true or false.
24)Objective 6.1) 12. } The constructor of a
29)Objective 6.1) 13. } class must not have a
52)Objective 6.1) 14. return type.
A. i=0 j=0 A. true
45)Objective 6.2) B. i=0 j=1 B. false
46)Objective 6.2) C. i=0 j=2 36. What is the number of
47)Objective 6.2) D. i=1 j=0 bytes used by Java
43)Objective 6.2) E. i=1 j=1 primitive long. Select
37)Objective 6.2) F. i=1 j=2 the one correct
28)Objective 6.2) G. i=2 j=0 answer.
15)Objective 6.2) H. i=2 j=1 A. The number of
I. i=2 j=2 bytes is
4)Objective 7.1) 15. What gets printed when the compiler
9)Objective 7.1) following code is compiled dependent.
35)Objective 7.1) and run with the following B. 2
44)Objective 7.1) arguments - C. 4
java test 2 D. 8
31)Objective 8.1) Select the one correct E. 64
38)Objective 8.1) answer. 37. What is the result of
16. invoking the method
8)Objective 9.1) 17. public class test { substring(2, 4) on the
18. public static void string "example"?
5)Objective 10.1) main(String args[]) { Include the answer in
19. Integer intObj = quotes as the result is
33)Objective 11.1) Integer.valueOf(args[args.le of type String.
36)Objective 11.1) ngth - 1]); 38. Which of the following
53)Objective 11.1) 20. int i = intObj.intValue(); is correct ? Select all
21. correct answers.
End of document 22. if(args.length > 1) A. The native
23. System.out.println(i); keyword
24. if(args.length > 0) indicates that
- Sample test 1
25. System.out.println(i - the method is
1); implemented in
1. Which of the following 26. else another
are correct definitions of 27. System.out.println(i - language like
method main of a class. 2); C/C++.
Select all correct 28. } B. The only
answeres. 29. } statements
A. public static int 30. that can appear
main(char 31. before an
args[]); A. test import
B. test -1 statement in a
15
Java file are language, typicaly in 73. What all gets printed
comments. C/C++. when the following gets
C. The method C. A static variable compiled and run.
definitions inside indicates there is Select all correct
interfaces are only one copy of that answers.
public and variable. 74.
abstract. They D. A method defined as 75. public class test {
cannot be private private indicates that 76. public static void
or protected. it is accessible to all main(String args[]) {
D. A class other classes in the 77. int i=1, j=1;
constructor may same package. 78. try {
have public or 43. What all gets printed when 79. i++;
protected keyord the following program is 80. j•;
before them, compiled and run. Select all 81. if(i/j > 1)
nothing else. correct answers. 82. i++;
39. What is the result of 44. 83. }
evaluating the expression 45. public class test { 84.
14 ^ 23. Select the one 46. public static void catch(ArithemticExcepti
correct answer. main(String args[]) { on e) {
A. 25 47. int i, j=1; 85.
B. 37 48. i = (j>1)?2:1; System.out.println(0);
C. 6 49. switch(i) { 86. }
D. 31 50. case 0: 87.
E. 17 System.out.println(0); catch(ArrayIndexOutOf
F. 9 break; BoundsException e) {
G. 24 51. case 1: 88.
40. Which of the following System.out.println(1); System.out.println(1);
are true. Select all 52. case 2: 89. }
correct answers. System.out.println(2); 90. catch(Exception
A. && operator is break; e) {
used for short- 53. case 3: 91.
circuited logical System.out.println(3); System.out.println(2);
AND. break; 92. }
B. ~ operator is the 54. } 93. finally {
bit-wise XOR 55. } 94.
operator. 56. } System.out.println(3);
C. | operator is used 57. 95. }
to perform 58. 96.
bitwise OR and A. 0 System.out.println(4);
also short- B. 1 97. }
circuited logical C. 2 98. }
OR. D. 3 99.
D. The unsigned 59. What all gets printed when 100.
right shift the following program is A. 0
operator in Java compiled and run. Select all B. 1
is >>. correct answers. C. 2
41. Name the access 60. D. 3
modifier which when 61. public class test { E. 4
used with a method, 62. public static void 101. What all gets
makes it available to all main(String args[]) { printed when the
the classes in the same 63. int i=0, j=2; following gets compiled
package and to all the 64. do { and run. Select all
subclasses of the class. 65. i=++i; correct answer.
42. Which of the following is 66. j•; 102.
true. Select all correct 67. } while(j>0); 103. public class test {
answers. 68. System.out.println(i); 104. public static void
A. A class that is 69. } main(String args[]) {
abstract may not 70. } 105. int i=1, j=1;
be instantiated. 71. 106. try {
B. The final keyword 72. 107. i++;
indicates that the A. 0 108. j•;
body of a method B. 1 109. if(i == j)
is to be found C. 2 110. i++;
elsewhere. The D. The program does 111. }
code is written in not compile because 112.
non-Java of statement "i=+ catch(ArithmeticExcepti
+i;" on e) {
16
113. 150. public static void A. By invoking the
System.out.println(0); main(String args[]) { free method on
114. } 151. String s1 = "abc"; the object.
115. 152. String s2 = new B. By calling
catch(ArrayIndexOutOfB String("abc"); system.gc()
oundsException e) { 153. method.
116. 154. if(s1 == s2) C. By setting all
System.out.println(1); 155. references to
117. } System.out.println(1); the object to
118. catch(Exception 156. else new values
e) { 157. (say null).
119. System.out.println(2); D. Garbage
System.out.println(2); 158. if(s1.equals(s2)) collection
120. } 159. cannot be
121. finally { System.out.println(3); forced. The
122. 160. else programmer
System.out.println(3); 161. cannot force
123. } System.out.println(4); the compiler to
124. 162. } free the
System.out.println(4); 163. } memory used
125. } 164. by an object.
126. } 165. 171. What gets
127. A. 1 printed when the
128. B. 2 following code is
A. 0 C. 3 compiled. Select the
B. 1 D. 4 one correct answer.
C. 2 166. The default layout 172.
D. 3 manager for a Frame is ... 173. public class test {
E. 4 A. FlowLayout 174. public static void
129. What all gets B. BorderLayout main(String args[]) {
printed when the C. GridLayout 175. int i = 1;
following gets compiled D. GridBagLayout 176. do {
and run. Select all E. CardLayout 177. i•;
correct answer. 167. Which of the 178. } while (i > 2);
130. following are valid adapter 179.
131. public class test { classes in Java. Select all System.out.println(i);
132. public static void correct answers. 180. }
main(String args[]) { A. ComponentAdapter 181. }
133. String s1 = "abc"; B. ActionAdapter 182.
134. String s2 = "abc"; C. AdjustmentAdapter 183.
135. if(s1 == s2) D. ItemAdapter A. 0
136. E. FocusAdapter B. 1
System.out.println(1); 168. Which of the C. 2
137. else following are legal array D. -1
138. declarations. Select all 184. Which of these
System.out.println(2); correct answers. is a legal definition of a
139. if(s1.equals(s2)) A. int i[5][]; method named m
140. B. int i[][]; assuming it throws
System.out.println(3); C. int []i[]; IOException, and
141. else D. int i[5][5]; returns void. Also
142. E. int[][] a; assume that the
System.out.println(4); 169. What is the range of method does not take
143. } values that can be specified any arguments. Select
144. } for an int. Select the one all correct answers.
145. correct answer. A. void m()
146. A. The range of values throws
A. 1 is compiler IOException{}
B. 2 dependent. B. void m() throw
C. 3 B. -231 to 231 - 1 IOException{}
D. 4 C. -231-1 to 231 C. void m(void)
147. What all gets D. -215 to 215 - 1 throws
printed when the E. -215-1 to 215 IOException{}
following gets compiled 170. How can you ensure D. m() throws
and run. Select all that the memory allocated by IOException{}
correct answer. an object is freed. Select the E. void m()
148. one correct answer. throws
149. public class test { IOException
17
F. void m() {} C. It is possible for a B. The wait(),
throws program to make an notify(),
IOException object available for notifyAll() must
185. Which of the Garbage Collection. be executed in
following are legal D. The finalize method sybchronized
identifier names in Java. of an object is code.
Select all correct invoked before C. The notify()
answers. garbage collection is method can be
A. %abcd performed on the used to signal
B. $abcd object. and move
C. 1abcd 199. If a base class has a waiting threads
D. package method defined as to ready-to-run
E. _a_long_name void method() { } state.
186. At what stage in Which of the following are D. The Thread
the following method legal prototypes in a derived class is an
does the string "abc" class of this class. Select all abstract class.
becomes available for correct answers. 205. In which class
garbage collection. Select A. void method() { } is the wait() method
the one correct answer. B. int method() { return defined. Select the one
187. 0;} correct answer.
188. void method X() { C. void method(int i) A. Applet
189. String r = new {} B. Runnable
String("abc"); D. private void C. Thread
190. String s = "abc"; method() { } D. Object
191. r = r+1; //1 200. In which all cases 206. Which keyword
192. r = null; //2 does an exception gets when applied on a
193. s = s + r; //3 generated. Select all correct method indicates that
194. } //4 answers. only one thread should
195. int i = 0, j = 1; execute the method at
196. A. if((i == 0) || (j/i == a time. Select the one
A. Before statement 1)) correct answer.
labelled 1 B. if((i == 0) | (j/i == A. transient
B. Before statement 1)) B. volatile
labelled 2 C. if((i != 0) && (j/i == C. synchronized
C. Before statement 1)) D. native
labelled 3 D. if((i != 0) & (j/i == E. static
D. Before statement 1)) F. final
labelled 4 201. Which method 207. What is the
E. Never. defined in the EventObject name of the Collection
197. String s = new class returns the Object that interface used to
String("xyz"); generated an event. The represent elements in a
Assuming the above method should be given in sequence (in a
declaration, which of the the format - return_type particular order).
following statements method_name(); Select the one correct
would compile. Select all 202. Which of the answer.
correct answers. following object receives A. Collection
A. s = 2 * s; ActionEvent. Select all the B. Set
B. int i = s[0]; correct answers. C. List
C. s = s + s; A. List D. Map
D. s = s >> 2; B. Button 208. Which of these
E. None of the C. Choice classes implement the
above. D. CheckBox Collection interface
198. Which of the E. TextField SortedMap. Select all
following statements F. MenuItem correct answers.
related to Garbage 203. Name the class that A. HashMap
Collection are correct. may be used to create B. HashTable
Select all correct submenus in pull-down C. TreeMap
answers. menus. D. HashSet
A. It is posible for a 204. Which of the E. TreeSet
program to free following statements are F. Vector
memory at a true. Select all correct 209. Which is the
given time. answers. only layout manager
B. Garbage A. The wait method which always honours
Collection feature defined in the Thread the size of a
of Java ensures class, can be used to component. Select the
that the program convert a thread one correct answers.
never runs out of from Running state A. FlowLayout
memory. to Waiting state. B. GridLayout
18
C. BorderLayout 224. } B. The member
D. CardLayout 225. variable called
E. GridBagLayout A. 4 length
210. Which of the B. 5 C. The method
following are true about C. 6 size() returns
interfaces. Select all D. 6.1 the number of
correct answers. E. 9 characters.
A. Methods declared 226. Is the following D. The method
in interfaces are statement true or false. As length()
implicitly private. the toString method is returns the
B. Variables defined in the Object class, number of
declared in System.out.println can be characters.
interfaces are used to print any object. 244. Select the one
implicitly public, A. true correct answer. Which
static, and final. B. false method defined in
C. An interface can 227. Which of these Integer class can be
extend any classes defined in java.io and used to convert an
number of used for file-handling are Integer object to
interfaces. abstract. Select all correct primitive int type.
D. The keyword answers. A. valueOf
implements A. InputStream B. intValue
indicate that an B. PrintStream C. getInt
interface inherits C. Reader D. getInteger
from another. D. FileInputStream 245. Name the
211. Assume that E. FileWriter return type of method
class A extends class B, 228. Which of these are hashCode() defined in
which extends class C. valid Event Listener Object class, which is
Also all the three classes interfaces. Select all correct used to get the unique
implement the method answer. hash value of an
test(). How can a method A. MouseMotionListener Object.
in class A invoke the B. WindowListener 246. Which of the
test() method defined in C. DialogListener following are correct.
class C. Select the one D. PaintListener Select all correct
correct answers. 229. Name the collection answers.
A. test(); interface used to represent A. An import
B. super.test(); collections that maintain statement, if
C. super.super.test( unique elements. defined, must
); 230. What is the result of be the first
D. ::test(); compiling and running the statement of
E. C.test(); following program. the file.
F. It is not possible 231. B. private
to invoke test() 232. public class test { members are
method defined 233. public static void accessible to all
in C from a main(String args[]) { classes in the
method in A. 234. String str1="abc"; same package.
212. What is the 235. String str2="def"; C. An abstract
return type of method 236. String class can be
round(double d) defined str3=str1.concat(str2); declared as
in Math class. 237. final.
213. What gets 238. str1.concat(str2); D. Local variables
written on the screen 239. cannot be
when the following System.out.println(str1); declared as
program is compiled and 240. } static.
run. Select the one right 241. } 247. Name the
answer. 242. keyword which makes
214. A. abc a variable belong to a
215. public class test { B. def class, rather than being
216. public static void C. abcabc defined for each
main(String args[]) { D. abcdef instance of the class.
217. int i; E. defabc Select the one correct
218. float f = 2.3f; F. abcdefdef answer.
219. double d = 2.7; 243. Select the one A. static
220. i = ((int)Math.ceil(f)) correct answer. The number B. final
* ((int)Math.round(d)); of characters in an object of C. abstract
221. a class String is given by D. native
222. A. The member variable E. volatile
System.out.println(i); called size F. transient
223. }
19
248. Which of these 25. d ***** Look carefully at code
are core interfaces in the 26. a and answer the following
collection framework. 27. a questions ( Q2 to Q8)
Select all correct 28. b, e 1 import java.applet.Applet;
answers. 29. d 2 import java.awt.*;
A. Tree 30. c 3 import java.awt.event.*;
B. Stack 31. c, d 4 public class hello4 extends
C. Queue 32. a, c Applet {
D. Array 33. b, d 5 public void init(){
E. LinkedList 34. Object getSource(); 6 add(new
F. Map 35. a, b, e, f myButton("BBB"));
249. Which abstract 36. Menu 7 }
class is the superclass of 37. b, c 8 public void
all menu-related classes. 38. d paint(Graphics screen) {
250. Which of these 39. c 9 }
statements are true. 40. c 10 class myButton extends
Select all correct 41. c Button{
answers. 42. a 11 myButton(String
A. For each try 43. b, c label){
block there must 44. f 12 super(label);
be at least one 45. long 13 }
catch block 46. e 14 public String
defined. 47. a paramString(){
B. A try block may 48. a, c 15 return
be followed by 49. a, b super.paramString();
any number of 50. Set 16 }
finally blocks. 51. a 17 }
C. A try block must 52. d 18 public static void
be followed by at 53. b main(String[] args){
least one finally 54. int 19 Frame myFrame = new
or catch block. 55. d Frame(
D. If both catch and 56. a 20
finally blocks are 57. f "Copyright Amit");
defined, catch 58. MenuComponent 21
block must 59. c, d myFrame.setSize(300,100);
precede the 22 Applet myApplet = new
finally block. Q 1. What is the output of the hello4();
following 23 Button b = new
StringBuffer sb1 = new Button("My Button");
Answers to Sample Test 1 StringBuffer("Amit"); 24 myApplet.add(b);
1. b StringBuffer sb2= new 25 b.setLabel(b.getLabel()
2. b, c, f StringBuffer("Amit"); +"New");
3. d String ss1 = "Amit"; 26 // myButton b1 =(new
4. arr.length System.out.println(sb1==sb2); hello4()).new
5. Any of these is correct - myButton("PARAMBUTTON");
0x5, 0x05, 0X05, 0X5 System.out.println(sb1.equals(sb2)); 27
6. b, c, f, g System.out.println(b1.paramSt
7. a System.out.println(sb1.equals(ss1)); ring());
8. d 28
9. "am" System.out.println("Poddar".substrin myFrame.add(myApplet);
10. a, c. b is not correct. A g(3)); 29
package statement may Ans: myFrame.setVisible(true);
appear before an import a) false 30
statement. false myFrame.addWindowListener(
11. a false new WindowAdapter(){
12. a dar 31 public void
13. protected b) false windowClosing(WindowEvent
14. a, c true e){
15. b, c false 32
16. c Poddar System.exit(0);}});
17. a, d, e c) Compiler Error 33 }
18. d, e d) true 34 } //End hello4 class.
19. a, c true
20. b, c false Q2. If you run the above
21. b dar program via appletviewer
22. a, e ( defining a HTML file), You see
23. b, c, e Correct Answer is a) on screen.
24. b a) Two buttons
20
b) One button with label as java.awt.Button is a protected
"BBB" method.(Assume line 26 is Correct Answer is a)
c) One button with label as "My uncommented)
ButtonNew" Q 10) What is the output
d) One button with label as "My a) Code will not compile. (Assuming written inside
Button" b) Code will compile but will give a main)
run time error. String s1 = new
Correct answer is b) c) Code will compile and no run time String("amit");
error. String s2 =
Q3. In the above code if line 26 s1.replace('m','i');
is uncommented and program Correct answer is c) . As you can s1.concat("Poddar");
runs as standalone application access a protected variable in the System.out.println(s1);
same package.
a) Compile Error System.out.println((s1+s2).ch
b) Run time error Q8.If line no 26 is replaced with arAt(5));
c) It will print the the label as Button b1 = new
PARAMBUTTON for button b1 Button("PARAMBUTTON").(Hint a) Compile error
:paramString() method in b) amitPoddar
Correct answer is c) java.awt.Button is a protected o
method.(Assume line 26 is c) amitPoddar
Q4 In the code if you compile as uncommented) i
"javac hello4.java" following files d) amit
will be generated. a) Code will not compile. i
a) hello4.class, b) Code will compile but will give a
myButton.class,hello41.class run time error. Correct answer is d)As String is
b)hello4.class, c) Code will compile and no run time imutable.so s1 is always
hello4$myButton.class,hello4$1.c error. "amit". and s2 is "aiit".
lass
c)hello4.clas,hello4$myButton.cl Correct answer is a) Because Q 11) What is the output
ass protected variables and methods can (Assuming written inside
not be accssed in another package main)
Correct answer is b) directly. They can only be accessed if String s1 = new
the class is subclassed and instance String("amit");
Q5. If above program is run as a of subclass is used.
standalone application. How System.out.println(s1.replace('
many buttons will be displayed Q9. What is the output of following if m','r'));
the return value is "the value 0 if the System.out.println(s1);
a) Two buttons argument string is equal to this String s3="arit";
b) One button with label as string; a value less than 0 if this String s4="arit";
"BBB" string is lexicographically less than String s2 =
c) One button with label as "My the string argument; and a value s1.replace('m','r');
ButtonNew" greater than 0 if this string is
d) One button with label as "My lexicographically greater than the System.out.println(s2==s3);
Button" string argument" (Assuming written
inside main) System.out.println(s3==s4);
correct answer is C)
String s5 = "AMIT"; a) arit
Q6. If from line no 14 keyword String s6 = "amit"; amit
"public" is removed, what will System.out.println(s5.compareTo(s6) false
happen.( Hint :paramString() ); true
method in java.awt.Button is a System.out.println(s6.compareTo(s5) b) arit
protected method. (Assume line ); arit
26 is uncommented) System.out.println(s6.compareTo(s6) false
); true
a) Code will not compile. c) amit
b) Code will compile but will give Ans amit
a run time error. a> -32 false
c) Code will compile and no run 32 true
time error. 0 d) arit
b> 32 amit
Correct answer is a). As you can 32 true
not override a method with 0 true
weaker access privileges c> 32 Correct answer is a) s3==s4
-32 is true because java points
Q7. If from line no 14 keyword 0 both s3 and s4 to same
"public" is replaced with d> 0 memory location in string pool
"protected", what will happen. 0
(Hint :paramString() method in 0
21
Q12) Which one does not extend myFrame.add(cb1);
java.lang.Number myFrame.add(cb2);
1)Integer myFrame.add(cb3); Q19) Answer based on
2)Boolean a) cb1 following code
3)Character b) cb2,cb1 1 Choice c1 = new Choice();
4)Long c) cb1,cb2,cb3 2 c1.add("First");
5)Short d) cb3 3 c1.addItem("Second");
4 c1.add("Third");
Correct answer is 2) and 3) Correct Answer is d) As in a 5
CheckboxGroup only one can be c1.insert("Lastadded",1000);
Q13) Which one does not have a selected 6
valueOf(String) method System.out.println(c1.getItem
1)Integer Q16) Which checkbox will be selected Count());
2)Boolean in the following code ( Assume with
3)Character main and added to a Frame) a) Compile time error
4)Long Frame myFrame = new b) Run time error at line 5
5)Short Frame("Test"); c) No error and line 6 will
Correct answer is 3) CheckboxGroup cbg = new print 1000
CheckboxGroup(); d) No error and line 6 will
Q.14) What is the output of Checkbox cb1 = new print 4
following (Assuming written Checkbox("First",true,cbg);
inside main) Checkbox cb2 = new Correct ANswer is d)
String s1 = "Amit"; Checkbox("Scond",true,cbg);
String s2 = "Amit"; Checkbox cb3 = new Q20) Which one of the
String s3 = new Checkbox("THird",true,cbg); following does not extends
String("abcd"); myFrame.add(cb1); java.awt.Component
String s4 = new myFrame.add(cb2);
String("abcd"); myFrame.add(cb3); a) CheckBox
a) cb1 b) Canvas
System.out.println(s1.equals(s2) b) cb2,cb1 c) CheckbocGroup
); c) cb1,cb2,cb3 d) Label
d) cb3
System.out.println((s1==s2)); Correct answer is c)
Correct Answer is d) As in a
System.out.println(s3.equals(s4) CheckboxGroup only one can be Q21) What is default layout
); selected manager for panels and
applets?
System.out.println((s3==s4)); Q17) What will be the output of line a) Flowlayout
a) true 5 b) Gridlayout
true 1 Choice c1 = new Choice(); c) BorderLayout
true 2 c1.add("First");
false 3 c1.addItem("Second"); Correct answer is a)
b) true 4 c1.add("Third");
true 5 Q22) For awt components
true System.out.println(c1.getItemCount( which of the following
true )); statements are true?
c) true a) 1
false b) 2 a) If a component is not
true c) 3 explicitly assigned a font, it
false d) None of the above usese the same font that it
Correct answer is a) container uses.
Correct Answer is c) b) If a component is not
Q15. Which checkbox will be explicitly assigned a
selected in the following code Q18) What will be the order of four foreground color , it usese the
( Assume with main and added items added same foreground color that it
to a Frame) Choice c1 = new Choice(); container uses.
Frame myFrame = new c1.add("First"); c) If a component is not
Frame("Test"); c1.addItem("Second"); explicitly assigned a backround
CheckboxGroup cbg = new c1.add("Third"); color , it usese the same
CheckboxGroup(); c1.insert("Lastadded",2); background color that it
Checkbox cb1 = new container uses.
Checkbox("First",true,cbg); System.out.println(c1.getItemCount( d) If a component is not
Checkbox cb2 = new )); explicitly assigned a layout
Checkbox("Scond",true,cbg); a) First,Second,Third,Fourth manager , it usese the same
Checkbox cb3 = new b) First,Second,Lastadded,Third layout manager that it
Checkbox("THird",false,cbg); c) Lastadded,First,Second,Third container uses.

cbg.setSelectedCheckbox(cb3); Correct ANswer is b) correct answer is a),b),c)


22
Round f6 is -5
Q23)java.awt.Component class Round f7 is 5 System.out.println(b1+b2+b3)
method getLocation() returns ; The output is
Point (containg x and y Correct answer is b) a) Compile time error
cordinate).What does this x and b) Run time error
y specify c) truetruefalse
Q26. Given Integer.MIN_VALUE = d) truetruetrue
a) Specify the postion of -2147483648
components lower-left Integer.MAX_VALUE = Correct answer is a) As there is
component in the coordinate 2147483647 no method to support Boolean
space of the component's parent. + Boolean
b) Specify the postion of What is the output of following Boolean b1 = new
components upper-left Boolean("TRUE");
component in the coordinate { Think
space of the component's parent. float f4 = Integer.MIN_VALUE; ----->System.out.println(b1); /
c) Specify the postion of float f5 = Integer.MAX_VALUE; / Is this valid or not?
components upper-left float f7 = -2147483655f;
component in the coordinate System.out.println("Round f4 is " + Q 29. What is the output
space of the screen. Math.round(f4)); {
System.out.println("Round f5 is " + Float f1 = new
correct answer is b) Math.round(f5)); Float("4.4e99f");
System.out.println("Round f7 is " + Float f2 = new Float("-
Q24. Q. What will be the output Math.round(f7)); 4.4e99f");
of follwing } Double d1 = new
{ Double("4.4e99");
double d1 = -0.5d; a)Round f4 is -2147483648 System.out.println(f1);
System.out.println("Ceil for d1 " Round f5 is 2147483647 System.out.println(f2);
+ Math.ceil(d1)); Round f7 is -2147483648 System.out.println(d1);
System.out.println("Floor for d1 " }
+Math.floor(d1)); b)Round f4 is -2147483648
} Round f5 is 2147483647 a) Runtime error
Round f7 is -2147483655 b) Infinity
Answers: -Infinity
a) Ceil for d1 0 correct answer is a) 4.4E99
Floor for d1 -1; //Reason If the argument is negative c) Infinity
b) Ceil for d1 0 infinity or any value less than or -Infinity
Floor for d1 -1.0; equal to the value of Infinity
c) Ceil for d1 0.0 Integer.MIN_VALUE, the result is d) 4.4E99
Floor for d1 -1.0; equal to the value of -4.4E99
d) Ceil for d1 -0.0 Integer.MIN_VALUE. 4.4E99
Floor for d1 -1.0; If the argument is positive infinity
or any value greater than or equal to Correct answer is b)
correct answer is d) as 0.0 is the value of Integer.MAX_VALUE, the
treated differently from -0.0 result is
equal to the value of Q30 Q. Which of the following
Q25. What is the output of Integer.MAX_VALUE. // From JDK api wrapper classes can not
following documentation take a "String" in constructor
{
float f4 = -5.5f; Q27) 1) Boolean
float f5 = 5.5f; 1 Boolean b1 = new 2) Integer
float f6 = -5.49f; Boolean("TRUE"); 3) Long
float f7 = 5.49f; 2 Boolean b2 = new 4) Character
System.out.println("Round f4 is " Boolean("true"); 5) Byte
+ Math.round(f4)); 3 Boolean b3 = new 6) Short
System.out.println("Round f5 is " Boolean("JUNK");
+ Math.round(f5)); 4 System.out.println("" + b1 + b2 correct answer is 4)
System.out.println("Round f6 is " + b3);
+ Math.round(f6)); Q31. What is the output of
System.out.println("Round f7 is " a) Comiler error following
+ Math.round(f7)); b) RunTime error Double d2 = new Double("-
} c)truetruefalse 5.5");
a)Round f4 is -6 d)truetruetrue Double d3 = new Double("-
Round f5 is 6 5.5");
Round f6 is -5 Correct answer is c)
Round f7 is 5 System.out.println(d2==d3);
Q 28) In the above question if line 4
b)Round f4 is -5 is changed to System.out.println(d2.equals(d
Round f5 is 6 3));
23
Correct answer is c) Reason- Applet a) C:\java\12345.msg
a) true uses FlowLayout which honors C:\java\dir1\..\12345.msg
true Button's preferred size.
b) false b) C:\java\dir1\12345.msg
false Q35. What is the output C:\java\dir1\..\12345.msg
c) true public static void main(String
false args[]){ c) C:\java\dir1\..\12345.msg
d) false Frame f = new Frame("Visual"); C:\java\dir1\..\12345.msg
true f.setSize(300,300);
f.setVisible(true); correct answer is a) as
Correct answer is d) Point p = f.getLocation(); getCanonicalPath Returns the
System.out.println("x is " + canonical form of this File
Q32) Which one of the following p.x); object's pathname. The precise
always honors the components's System.out.println("y is " + definition of canonical form is
preferred size. p.y); system-dependent, but it
a) FlowLayout } usually
b) GridLayout specifies an absolute pathname
c) BorderLayout a) x is 300 in which all relative references
y is 300 and references to the current
Correct answer is a) b) x is 0 user directory have been
y is 0 completely resolved.
Q33) Look at the following code c) x is 0 WHERE AS
import java.awt.*; y is 300 getAbsolutePath Returns the
public class visual extends absolute pathname of the file
java.applet.Applet{ correct answer is b) Because postion represented by this object. If
static Button b = new is always relative to parent container this object represents an
Button("TEST"); and in this absolute pathname, then
public void init(){ case Frame f is the topemost return the pathname.
add(b); container Otherwise, return a pathname
} that is a concatenation of the
public static void main(String Q36) Which one of the following current user directory, the
args[]){ always ignores the components's separator character, and the
Frame f = new preferred size. pathname of this file object.
Frame("Visual"); a) FlowLayout
f.setSize(300,300); b) GridLayout
f.add(b); c) BorderLayout Q 38) Suppose we copy
f.setVisible(true); IO.class from C:\java\dir1 to
} Correct answer is b) c:\java
} What will be the output of
Q37) Consider a directory structure running "java IO" from
What will happen if above code is like this (NT or 95) C:\java.
run as a standalone application C:\JAVA\12345.msg --FILE a) C:\java\12345.msg
\dir1\IO.class -- IO.class is C:\java\..\12345.msg
a) Displays an empty frame under dir1
b) Displays a frame with a button b) C:\12345.msg
covering the entire frame Consider the following code C:\java\..\12345.msg
c) Displays a frame with a button
large enough to accomodate its import java.io.*; c) C:\java\..\12345.msg
label. public class IO { C:\java\\..\12345.msg
public static void main(String
Correct answer is b) Reason- args[]) { correct answer is b)
Frame uses Border Layout which File f = new
places the button to CENTRE File("..\\12345.msg"); Q39) Which one of the
(By default) and ignores try{ following methods of
Button's preferred size. java.io.File throws IOException
System.out.println(f.getCanonicalPat and why
Q34 If the code in Q33 is h());
compiled and run via a) getCanonicalPath and
appletviewer what will happen System.out.println(f.getAbsolutePath getAbsolutePath both require
a) Displays an empty applet ()); filesystem queries.
b) Displays a applet with a }catch(IOException e){ b) Only getCannonicalPath as it
button covering the entire frame System.out.println(e); require filesystem queries.
c) Displays a applet with a } c) Only getAbsolutePath as it
button large enough to } require filesystem queries.
accomodate its label. }
Correct answer is b)
What will be the output of running
"java IO" from C:\java\dir1
24
Q40) What will be the output if \12345.msg
Consider a directory structure false System.out.println(sb1.equals(
like this (NT or 95) false sb2));
C:\JAVA\12345.msg --FILE
\dir1\IO.class -- IO.class c) 12345.msg System.out.println(sb1.equals(
is under dir1 \ ss1));
true
import java.io.*; 12345.msg System.out.println("Poddar".su
public class IO { false bstring(3));
public static void false Ans:
main(String args[]) { d) \12345.msg a) false
File f = new \ false
File("12345.msg"); true false
String arr[] = 12345.msg dar
f.list(); false b) false
false true
System.out.println(arr.length); false
} correct answer is d) Poddar
} c) Compiler Error
Q42) If in question no 41 the line d) true
a) Compiler error as 12345.msg File f1 = new true
is a file not a directory File("\\12345.msg"); is replaced with false
b) java.lang.NullPointerException File f1 = new File("12345.msg"); dar
at run time What will be the output
c) No error , but nothing will be Correct Answer is a)
printed on screen a) 12345.msg
\ ***** Look carefully at code
Correct ansewer is b) true and answer the following
12345.msg questions ( Q2 to Q8)
Q41) What will be the output true 1 import java.applet.Applet;
Consider a directory structure true 2 import java.awt.*;
like this (NT or 95) 3 import java.awt.event.*;
C:\JAVA\12345.msg --FILE b) 12345.msg 4 public class hello4 extends
null Applet {
import java.io.*; true 5 public void init(){
public class IO { 12345.msg 6 add(new
public static void true myButton("BBB"));
main(String args[]) { true 7 }
File f1 = new 8 public void
File("\\12345.msg"); c) 12345.msg paint(Graphics screen) {
null 9 }
System.out.println(f1.getPath()); false 10 class myButton extends
12345.msg Button{
System.out.println(f1.getParent() true 11 myButton(String
); true label){
12 super(label);
System.out.println(f1.isAbsolute( d) \12345.msg 13 }
)); \ 14 public String
true paramString(){
System.out.println(f1.getName() 12345.msg 15 return
); false super.paramString();
false 16 }
System.out.println(f1.exists()); 17 }
18 public static void
System.out.println(f1.isFile()); main(String[] args){
} Correct answer is c) 19 Frame myFrame = new
} Frame(
20
a) \12345.msg "Copyright Amit");
\ Q 1. What is the output of the 21
true following myFrame.setSize(300,100);
12345.msg StringBuffer sb1 = new 22 Applet myApplet = new
true StringBuffer("Amit"); hello4();
true StringBuffer sb2= new 23 Button b = new
StringBuffer("Amit"); Button("My Button");
b) \12345.msg String ss1 = "Amit"; 24 myApplet.add(b);
\ System.out.println(sb1==sb2); 25 b.setLabel(b.getLabel()
true +"New");
25
26 // myButton b1 =(new correct answer is C)
hello4()).new String s5 = "AMIT";
myButton("PARAMBUTTON"); Q6. If from line no 14 keyword String s6 = "amit";
27 "public" is removed, what will System.out.println(s5.compare
System.out.println(b1.paramStri happen.( Hint :paramString() To(s6));
ng()); method in java.awt.Button is a System.out.println(s6.compare
28 myFrame.add(myApplet); protected method. (Assume line 26 is To(s5));
29 myFrame.setVisible(true); uncommented) System.out.println(s6.compare
30 To(s6));
myFrame.addWindowListener(ne a) Code will not compile.
w WindowAdapter(){ b) Code will compile but will give a Ans
31 public void run time error. a> -32
windowClosing(WindowEvent e){ c) Code will compile and no run time 32
32 error. 0
System.exit(0);}}); b> 32
33 } Correct answer is a). As you can not 32
34 } //End hello4 class. override a method with weaker 0
access privileges c> 32
Q2. If you run the above -32
program via appletviewer Q7. If from line no 14 keyword 0
( defining a HTML file), You see "public" is replaced with "protected", d> 0
on screen. what will happen.(Hint 0
a) Two buttons :paramString() method in 0
b) One button with label as java.awt.Button is a protected
"BBB" method.(Assume line 26 is Correct Answer is a)
c) One button with label as "My uncommented)
ButtonNew" Q 10) What is the output
d) One button with label as "My a) Code will not compile. (Assuming written inside
Button" b) Code will compile but will give a main)
run time error. String s1 = new
Correct answer is b) c) Code will compile and no run time String("amit");
error. String s2 =
Q3. In the above code if line 26 s1.replace('m','i');
is uncommented and program Correct answer is c) . As you can s1.concat("Poddar");
runs as standalone application access a protected variable in the System.out.println(s1);
same package.
a) Compile Error System.out.println((s1+s2).ch
b) Run time error Q8.If line no 26 is replaced with arAt(5));
c) It will print the the label as Button b1 = new
PARAMBUTTON for button b1 Button("PARAMBUTTON").(Hint a) Compile error
:paramString() method in b) amitPoddar
Correct answer is c) java.awt.Button is a protected o
method.(Assume line 26 is c) amitPoddar
Q4 In the code if you compile as uncommented) i
"javac hello4.java" following files d) amit
will be generated. a) Code will not compile. i
a) hello4.class, b) Code will compile but will give a
myButton.class,hello41.class run time error. Correct answer is d)As String is
b)hello4.class, c) Code will compile and no run time imutable.so s1 is always
hello4$myButton.class,hello4$1.c error. "amit". and s2 is "aiit".
lass
c)hello4.clas,hello4$myButton.cl Correct answer is a) Because Q 11) What is the output
ass protected variables and methods can (Assuming written inside
not be accssed in another package main)
Correct answer is b) directly. They can only be accessed if String s1 = new
the class is subclassed and instance String("amit");
Q5. If above program is run as a of subclass is used.
standalone application. How System.out.println(s1.replace('
many buttons will be displayed Q9. What is the output of following if m','r'));
the return value is "the value 0 if the System.out.println(s1);
a) Two buttons argument string is equal to this String s3="arit";
b) One button with label as string; a value less than 0 if this String s4="arit";
"BBB" string is lexicographically less than String s2 =
c) One button with label as "My the string argument; and a value s1.replace('m','r');
ButtonNew" greater than 0 if this string is
d) One button with label as "My lexicographically greater than the System.out.println(s2==s3);
Button" string argument" (Assuming written
inside main) System.out.println(s3==s4);
26
c) true c) 3
a) arit false d) None of the above
amit true
false false Correct Answer is c)
true Correct answer is a)
b) arit Q18) What will be the order of
arit Q15. Which checkbox will be selected four items added
false in the following code ( Assume with Choice c1 = new Choice();
true main and added to a Frame) c1.add("First");
c) amit Frame myFrame = new c1.addItem("Second");
amit Frame("Test"); c1.add("Third");
false CheckboxGroup cbg = new c1.insert("Lastadded",2);
true CheckboxGroup();
d) arit Checkbox cb1 = new System.out.println(c1.getItem
amit Checkbox("First",true,cbg); Count());
true Checkbox cb2 = new a) First,Second,Third,Fourth
true Checkbox("Scond",true,cbg); b)
Correct answer is a) s3==s4 is Checkbox cb3 = new First,Second,Lastadded,Third
true because java points both s3 Checkbox("THird",false,cbg); c)
and s4 to same memory location cbg.setSelectedCheckbox(cb3); Lastadded,First,Second,Third
in string pool myFrame.add(cb1);
myFrame.add(cb2); Correct ANswer is b)
Q12) Which one does not extend myFrame.add(cb3);
java.lang.Number a) cb1
1)Integer b) cb2,cb1 Q19) Answer based on
2)Boolean c) cb1,cb2,cb3 following code
3)Character d) cb3 1 Choice c1 = new Choice();
4)Long 2 c1.add("First");
5)Short Correct Answer is d) As in a 3 c1.addItem("Second");
CheckboxGroup only one can be 4 c1.add("Third");
Correct answer is 2) and 3) selected 5
c1.insert("Lastadded",1000);
Q13) Which one does not have a Q16) Which checkbox will be selected 6
valueOf(String) method in the following code ( Assume with System.out.println(c1.getItem
1)Integer main and added to a Frame) Count());
2)Boolean Frame myFrame = new
3)Character Frame("Test"); a) Compile time error
4)Long CheckboxGroup cbg = new b) Run time error at line 5
5)Short CheckboxGroup(); c) No error and line 6 will
Correct answer is 3) Checkbox cb1 = new print 1000
Checkbox("First",true,cbg); d) No error and line 6 will
Q.14) What is the output of Checkbox cb2 = new print 4
following (Assuming written Checkbox("Scond",true,cbg);
inside main) Checkbox cb3 = new Correct ANswer is d)
String s1 = "Amit"; Checkbox("THird",true,cbg);
String s2 = "Amit"; myFrame.add(cb1); Q20) Which one of the
String s3 = new myFrame.add(cb2); following does not extends
String("abcd"); myFrame.add(cb3); java.awt.Component
String s4 = new a) cb1
String("abcd"); b) cb2,cb1 a) CheckBox
c) cb1,cb2,cb3 b) Canvas
System.out.println(s1.equals(s2) d) cb3 c) CheckbocGroup
); d) Label
Correct Answer is d) As in a
System.out.println((s1==s2)); CheckboxGroup only one can be Correct answer is c)
selected
System.out.println(s3.equals(s4) Q21) What is default layout
); Q17) What will be the output of line manager for panels and
5 applets?
System.out.println((s3==s4)); 1 Choice c1 = new Choice(); a) Flowlayout
a) true 2 c1.add("First"); b) Gridlayout
true 3 c1.addItem("Second"); c) BorderLayout
true 4 c1.add("Third");
false 5 Correct answer is a)
b) true System.out.println(c1.getItemCount(
true )); Q22) For awt components
true a) 1 which of the following
true b) 2 statements are true?
27
{
a) If a component is not float f4 = -5.5f; Q27)
explicitly assigned a font, it float f5 = 5.5f; 1 Boolean b1 = new
usese the same font that it float f6 = -5.49f; Boolean("TRUE");
container uses. float f7 = 5.49f; 2 Boolean b2 = new
b) If a component is not System.out.println("Round f4 is " + Boolean("true");
explicitly assigned a foreground Math.round(f4)); 3 Boolean b3 = new
color , it usese the same System.out.println("Round f5 is " + Boolean("JUNK");
foreground color that it Math.round(f5)); 4 System.out.println("" + b1
container uses. System.out.println("Round f6 is " + + b2 + b3);
c) If a component is not explicitly Math.round(f6));
assigned a backround color , it System.out.println("Round f7 is " + a) Comiler error
usese the same background color Math.round(f7)); b) RunTime error
that it container uses. } c)truetruefalse
d) If a component is not a)Round f4 is -6 d)truetruetrue
explicitly assigned a layout Round f5 is 6
manager , it usese the same Round f6 is -5 Correct answer is c)
layout manager that it container Round f7 is 5
uses. Q 28) In the above question if
b)Round f4 is -5 line 4 is changed to
correct answer is a),b),c) Round f5 is 6
Round f6 is -5 System.out.println(b1+b2+b3)
Q23)java.awt.Component class Round f7 is 5 ; The output is
method getLocation() returns a) Compile time error
Point (containg x and y Correct answer is b) b) Run time error
cordinate).What does this x and c) truetruefalse
y specify d) truetruetrue
Q26. Given Integer.MIN_VALUE =
a) Specify the postion of -2147483648 Correct answer is a) As there is
components lower-left Integer.MAX_VALUE = no method to support Boolean
component in the coordinate 2147483647 + Boolean
space of the component's parent. Boolean b1 = new
b) Specify the postion of What is the output of following Boolean("TRUE");
components upper-left Think
component in the coordinate { ----->System.out.println(b1); /
space of the component's parent. float f4 = Integer.MIN_VALUE; / Is this valid or not?
c) Specify the postion of float f5 = Integer.MAX_VALUE;
components upper-left float f7 = -2147483655f; Q 29. What is the output
component in the coordinate System.out.println("Round f4 is " + {
space of the screen. Math.round(f4)); Float f1 = new
System.out.println("Round f5 is " + Float("4.4e99f");
correct answer is b) Math.round(f5)); Float f2 = new Float("-
System.out.println("Round f7 is " + 4.4e99f");
Q24. Q. What will be the output Math.round(f7)); Double d1 = new
of follwing } Double("4.4e99");
{ System.out.println(f1);
double d1 = -0.5d; a)Round f4 is -2147483648 System.out.println(f2);
System.out.println("Ceil for d1 " Round f5 is 2147483647 System.out.println(d1);
+ Math.ceil(d1)); Round f7 is -2147483648 }
System.out.println("Floor for d1 "
+Math.floor(d1)); b)Round f4 is -2147483648 a) Runtime error
} Round f5 is 2147483647 b) Infinity
Round f7 is -2147483655 -Infinity
Answers: 4.4E99
a) Ceil for d1 0 correct answer is a) c) Infinity
Floor for d1 -1; //Reason If the argument is negative -Infinity
b) Ceil for d1 0 infinity or any value less than or Infinity
Floor for d1 -1.0; equal to the value of d) 4.4E99
c) Ceil for d1 0.0 Integer.MIN_VALUE, the result is -4.4E99
Floor for d1 -1.0; equal to the value of 4.4E99
d) Ceil for d1 -0.0 Integer.MIN_VALUE.
Floor for d1 -1.0; If the argument is positive infinity Correct answer is b)
or any value greater than or equal to
correct answer is d) as 0.0 is the value of Integer.MAX_VALUE, the
treated differently from -0.0 result is Q30 Q. Which of the following
equal to the value of wrapper classes can not
Q25. What is the output of Integer.MAX_VALUE. // From JDK api take a "String" in constructor
following documentation
28
1) Boolean File f = new
2) Integer Correct answer is b) Reason- Frame File("..\\12345.msg");
3) Long uses Border Layout which places the try{
4) Character button to CENTRE
5) Byte (By default) and ignores Button's System.out.println(f.getCanoni
6) Short preferred size. calPath());

correct answer is 4) Q34 If the code in Q33 is compiled System.out.println(f.getAbsolut


and run via appletviewer what will ePath());
Q31. What is the output of happen }catch(IOException e)
following a) Displays an empty applet {
Double d2 = new Double("- b) Displays a applet with a button
5.5"); covering the entire frame System.out.println(e);
Double d3 = new Double("- c) Displays a applet with a button }
5.5"); large enough to accomodate its label. }
System.out.println(d2==d3); }
Correct answer is c) Reason- Applet
System.out.println(d2.equals(d3) uses FlowLayout which honors What will be the output of
); Button's preferred size. running "java IO" from
C:\java\dir1
a) true Q35. What is the output a) C:\java\12345.msg
true public static void main(String C:\java\dir1\..\12345.msg
b) false args[]){
false Frame f = new Frame("Visual"); b) C:\java\dir1\12345.msg
c) true f.setSize(300,300); C:\java\dir1\..\12345.msg
false f.setVisible(true);
d) false Point p = f.getLocation(); c) C:\java\dir1\..\12345.msg
true System.out.println("x is " + C:\java\dir1\..\12345.msg
p.x);
Correct answer is d) System.out.println("y is " + correct answer is a) as
p.y); getCanonicalPath Returns the
Q32) Which one of the following } canonical form of this File
always honors the components's object's pathname. The precise
preferred size. a) x is 300 definition of canonical form is
a) FlowLayout y is 300 system-dependent, but it
b) GridLayout b) x is 0 usually
c) BorderLayout y is 0 specifies an absolute pathname
c) x is 0 in which all relative references
Correct answer is a) y is 300 and references to the current
user directory have been
Q33) Look at the following code correct answer is b) Because postion completely resolved.
import java.awt.*; is always relative to parent container WHERE AS
public class visual extends and in this getAbsolutePath Returns the
java.applet.Applet{ case Frame f is the topemost absolute pathname of the file
static Button b = new container represented by this object. If
Button("TEST"); this object represents an
public void init(){ Q36) Which one of the following absolute pathname, then
add(b); always ignores the components's return the pathname.
} preferred size. Otherwise, return a pathname
public static void main(String a) FlowLayout that is a concatenation of the
args[]){ b) GridLayout current user directory, the
Frame f = new c) BorderLayout separator character, and the
Frame("Visual"); pathname of this file object.
f.setSize(300,300); Correct answer is b)
f.add(b);
f.setVisible(true); Q37) Consider a directory structure Q 38) Suppose we copy
} like this (NT or 95) IO.class from C:\java\dir1 to
} C:\JAVA\12345.msg --FILE c:\java
\dir1\IO.class -- IO.class is What will be the output of
What will happen if above code is under dir1 running "java IO" from
run as a standalone application C:\java.
Consider the following code a) C:\java\12345.msg
a) Displays an empty frame C:\java\..\12345.msg
b) Displays a frame with a button import java.io.*;
covering the entire frame public class IO { b) C:\12345.msg
c) Displays a frame with a button public static void main(String C:\java\..\12345.msg
large enough to accomodate its args[]) {
label. c) C:\java\..\12345.msg
29
C:\java\\..\12345.msg false
System.out.println(f1.getName());
correct answer is b) System.out.println(f1.exists()); Correct answer is c)
System.out.println(f1.isFile());
Q39) Which one of the following }
methods of java.io.File throws } Location: ... > Declarations
IOException and why and Access Control > Objective
a) \12345.msg 1.1 > Item 1
a) getCanonicalPath and \ -----------------------------------
getAbsolutePath both require true -----------------------------------
filesystem queries. 12345.msg ----------
b) Only getCannonicalPath as it true Click the Exhibit button.
require filesystem queries. true Which two lines of code will
c) Only getAbsolutePath as it compile correctly? (Choose
require filesystem queries. b) \12345.msg two.)
\ 1. class CharArray2 {
Correct answer is b) true 2. public static void
\12345.msg main( String [] args) {
Q40) What will be the output if false 3. char b = 'b';
Consider a directory structure false 4. char c = 'C';
like this (NT or 95) 5. char [] c1 = {'a', 'b',
C:\JAVA\12345.msg --FILE c) 12345.msg 'c'};
\dir1\IO.class -- IO.class \ 6. char [] c2 = {'a', b , 'c'};
is under dir1 true 7. char [] c3 = ('a', 'b', 'c');
12345.msg 8. char [] c4 = [3];
import java.io.*; false 9. char [] c5 = [3] {'a', 'b',
public class IO { false 'c'};
public static void d) \12345.msg 10. char [] c6 = [] {'a', 'b',
main(String args[]) { \ c};
File f = new true 11. }
File("12345.msg"); 12345.msg 12. }
String arr[] = false A line 5
f.list(); false B line 6
C line 7
System.out.println(arr.length); correct answer is d) D line 8
} E line 9
} Q42) If in question no 41 the line F line 10
File f1 = new Answer:
a) Compiler error as 12345.msg File("\\12345.msg"); is replaced with Options A and B are the correct
is a file not a directory File f1 = new File("12345.msg"); answers. This question
b) java.lang.NullPointerException What will be the output explores a Java syntax
at run time shortcut. A and B represent
c) No error , but nothing will be a) 12345.msg acceptable syntax to declare,
printed on screen \ construct, and initialize an
true array in a single line of code.
Correct ansewer is b) 12345.msg Location: ... > Declarations
true and Access Control > Objective
Q41) What will be the output true 1.1 > Item 2
Consider a directory structure -----------------------------------
like this (NT or 95) b) 12345.msg -----------------------------------
C:\JAVA\12345.msg --FILE null ----------
true Click the Exhibit button.
import java.io.*; 12345.msg 1. class Test{
public class IO { true 2. public static void
public static void true main( String [] args) {
main(String args[]) { 3. int [] y;
File f1 = new c) 12345.msg 4. int [] z = new int [] {1,
File("\\12345.msg"); null 2, 3};
false 5. y = z;
System.out.println(f1.getPath()); 12345.msg 6. z[1] = 7;
true 7. for (int x= 0;x<3; x++)
System.out.println(f1.getParent() true {
); 8. System.out.print("
d) \12345.msg y[" + x + "] = " + y[x]);
System.out.println(f1.isAbsolute( \ 9. }
)); true 10. }
12345.msg 11. }
false
30
What is the result? several instances of XXX were 2. public long doMath() {
A y[0] = 0 y[1] = 1 y[2] = 2 instantiated it would be impossible to 3. return 343L;
B y[0] = 7 y[1] = 2 y[2] = 3 know which instance the static 4. }
C y[0] = 1 y[1] = 7 y[2] = 3 should belong to. 5. }
D y[0] = 1 y[1] = 2 y[2] = 3 6.
E Compilation fails Location: ... > Declarations and 7. class L extends XL {
F An exception is thrown at Access Control > Objective 1.3 > 8.
runtime Item 1 9. }
Answer: -----------------------------------------
Option C is the correct answer. y ---- Which two methods inserted at
and z are reference variables. Click the Exhibit button. line 8, will not compile?
Line 5 assigns y to refer to the 1. class Foo { (Choose two.)
same array as z, there is still 2. Foo(String s) { } a public void doMath() { }
only one array (however there 3. } B public void doMath(int i)
are two array references). When 4. class Bar extends Foo { } {}
line 6 executes, it changes a C public int doMath() { return
value in the only array there is, Which statement is true? 343 }
(the one both y and z refer to). A Class Bar will not compile D public long doMath(int i)
Therefore when the array is B Class Bar has a public constructor { return 343 }
accessed via y, the updated C Class Bar's constructor invokes answer:
value is displayed. super() Options A and C are the correct
ocation: ... > Declarations and D Class Foo's constructor does not answers. A and C represent an
Access Control > Objective 1.2 > invoke super() illegal override of the class XL
Item 1 answer: doMath() method. Because the
------------------------------------- Option A is the correct answer. The arguments have not changed,
-- compiler attempts to create a default the return type cannot change.
Which declaration ensures that a constructor for class Bar, because Location: ... > Declarations
class cannot be subclassed? Bar has not defined any constructors. and Access Control > Objective
A abstract class MyClass { } The class Bar constructor will include 1.4 > Item 2
B final public class MyClass { } a call to super(). Since class Foo -----------------------------------
C final abstract class MyClass does not have a no-arg constructor, -----------------------------------
{} class Bar will not compile because ----------
D static private class MyClass the default constructor the compiler Click the Exhibit button to
{} is attempting to build includes a call view the code.
E static protected class MyClass to super(), and there is no matching 1. class Test {
{} no-arg constructor in class Foo. 2. public short doStuff(int i)
Answer: { return 27; }
Option B is the correct answer. Location: ... > Declarations and 3. }
The final modifier insures that a Access Control > Objective 1.3 > 4.
class can not be subclassed. Item 2 5. public class SubTest extends
Q31. class XXX { ----------------------------------------- Test {
2. long doStuff (int input) { --------------------------------------- 6. public int doStuff(int x)
3. static long x = 7; Given: { return 30; }
4. return (long) input / x; 1. class Pizza { } 7.
5. } Which of these represents the 8. public static void
6. functionality of the default main(String [] args) {
7. public static void main(String constructor for Pizza? 9. Test t = new Test();
[] args) { A Pizza() 10. SubTest s = new
8. XXX xxx = new XXX(); B Pizza() {super();} SubTest();
9. C public void Pizza() 11. int t1 = t.doStuff(30);
System.out.println(xxx.doStuff(4 D public Pizza() {super();} 12. int s1 = s.doStuff(27);
2)); E There is no default constructor for 13. System.out.println( t1 +
10. } Pizza " " + s1);
11. } Answer: 14. }
Option B is the correct answer. The 15. }
What will be the result? compiler creates a default
A 6 constructor for Pizza, with default What is the result?
B 7 access (matching the access of the A 27 30
C 42 class), and a no-arg call to super(). B 30 27
D Compilation fails C 27 27
E An exception is thrown at Location: ... > Declarations and D 30 30
runtime Access Control > Objective 1.4 > E Compilation fails
Answer: Item 1 F An exception is thrown at
Option D is the correct answer. ----------------------------------------- runtime
The compiler will notice that in --------------------------------------- Answer:
Line 3 the code is declaring a Click the Exhibit button to view the Option E is the correct answer.
static variable, but it's in a local code. Line 6 is an illegal override of
method, which is not legal. If 1. class XL {
31
the doStuff() method in class Option E is the correct answer. Line -----------------------------------
Test. three is illegal, it should probably ----------
read if (toggle == 1) {. Which two statements are
Location: ... > Flow Control, true? (Choose two.)
Assertions, and Exception Location: ... > Flow Control, A catch(Foo f) can catch Foo
Handling > Objective 2.1 > Item Assertions, and Exception Handling > or any of its superclasses
1 Objective 2.2 > Item 1 B If you throw an Error, it
------------------------------------- --------------------------------------- does not need to be enclosed
-------- Click the Exhibit button to view the in a try block
Click the Exhibit button to view code. C Any statement that can
the code. 7. int x,y; throw an Exception must be
1. for (int x = 3; x > = 0; x--) { 8. next: for(x = 5, y = 1 ; ; ) { enclosed in a try block
2. switch (x - 1) { 9. --x; D An overriding method must
3. case 0: 10. for ( ; x > -1 ; y++) { declare any Exceptions
System.out.print("foo "); 11. if ( x < y ) { declared by the overridden
4. case 1: 12. break next; method
System.out.print("bar "); 13. } E An overriding method can
5. case 2: 14. } throw a superclass of the
System.out.print("baz "); 15. } Exception declared by the
6. case 3: 16. System.out.println(x + " " + y); overridden method
System.out.print("foo "); What is the result? F An overriding method is
7. } A 23 permitted to throw a
8. } B 34 RuntimeException, even if it
C 45 has not been declared by the
What is the result? D 56 overridden method.
A baz bar foo E Compilation fails Answer:
B foo baz bar foo F An exception is thrown at runtime Options B and F are the correct
C baz bar foo bar foo foo nswer: answers. Overriding methods
D baz foo bar baz foo foo bar Option C is the correct answer. The are not allowed to throw new
baz foo variable x is decremented once, in or broader checked exceptions.
E Compilation fails line 9, then the program loops A checked exception is any
F An exception is thrown at through the inner for loop, exception extending from class
runtime incrementing y until x < y, at which Exception, but not extending
answer: point y equals 5 and the break is from RuntimeException. Errors
Option D is the correct answer. executed. do not need to be enclosed in
As the switch expression iterates try blocks.
from 2 to -1 the cases start at 2, Location: ... > Flow Control,
1, and 0 and fall through. Assertions, and Exception Handling > Location: ... > Flow Control,
Objective 2.2 > Item 2 Assertions, and Exception
Location: ... > Flow Control, ----------------------------------------- Handling > Objective 2.4 >
Assertions, and Exception ---- Item 1
Handling > Objective 2.1 > Item Click the Exhibit button to view the -----------------------------------
2 code. -----
------------------------------------- 13. long x = 20, y = 30; Click the Exhibit button to
--- 14. while ( ++x < = y ) { view the code.
Click the Exhibit button to view 15. --y; 1. public class Test243 {
the code. 16. if ( x > y ) { 2. public static void main
1. for (int toggle = 0, y = 0; y < 17. break; (String [] args) {
6; y++ ) { 18. } 3. try {
2. toggle = y % 2; 19. } 4. String s = "two";
3. if (toggle) { 20. System.out.print(x + " " + y); 5. int i =
4. System.out.print("true "); What is the result? Integer.parseInt(s);
5. } A 26 25 6. System.out.print("i =
6. else { B 25 25 " + i);
7. System.out.print("false "); C 25 24 7. } catch (Exception ex) {
8. } D 25 26 8. System.out.print("
9. } E 26 26 Exception ");
Answer: 9. }
What is the result? Option A is the correct answer. The catch(NumberFormatException
A true true true true true true while statement on line 14 exc) {
B true false true false true false increments x before doing the 10. System.out.print("
C false true false true false true comparison test. The break NumberFormatException ");
D false false false false false statement is never reached. 11. } finally {
false 12. System.out.print("
E Compilation fails Location: ... > Flow Control, finally ");
F An exception is thrown at Assertions, and Exception Handling > 13. }
runtime Objective 2.3 > Item 1 14. System.out.print("
Answer: done ");
32
15. } the exception is thrown, the catch F The -enableassertions flag
16. } and finally blocks run, and then the tells the VM to enable
What is the result? main() method runs to completion assertions
A Exception finally (printing four at the end). Answer:
B i = two finally done Options D and F are the correct
C Exception finally done Location: ... > Flow Control, answers. The -esa flag means
D NumberFormatException Assertions, and Exception Handling > enable system assertions.
finally Objective 2.5 > Item 1
E NumberFormatException ----------------------------------------- ocation: ... > Garbage
finally done ---- Collection > Objective 3.1 >
F Compilation fails Item 1
-----------------------------------
Answer: ----
Option F is the correct answer. Which two fragments are examples
The NumberFormatException will of inappropriate uses of assertions? which two statements are true
be caught by the Exception (Choose two.) about the garbage collection
catch. The compiler recognizes A assert (!(foo == null)); system? (Choose two.)
that the second catch can never foo.go();
be reached. You must always put B public void method(boolean b) {
the catch blocks in order going assert (b); A Calling Runtime.gc() will
from most specific to broadest. If C if (x > y) { reclaim memory.
the exceptions are siblings (i.e. z = x; B It guarantees that
one does not extend from the } else { programs will not have
other), then the order does not assert (x < 4); memory leaks
matter. } C Objects will never be
D private void test(int z) { collected as long as they are
Location: ... > Flow Control, assert (f.setSize(z) > 5); accessible from live threads.
Assertions, and Exception } D Objects that have finalize()
Handling > Objective 2.4 > Item E public int methodA(int x) { methods always have their
2 assert (s > 3); finalize() methods called before
------------------------------------- } the program ends.
-------- Click the Exhibit button Answer: E If object 'A' has at least one
to view the code. Options B and D are the correct other object with a reference
1. public class Test244 { answers. B's violation is checking an to it, then object 'A' will not be
2. public static void main (String argument of a public method. D's garbage collected.
[] args) { violation is to allow the assert to F Objects instantiated within
3. try { have side effects, in this case by a method and referenced only
4. foo(); calling a setter method on a by a local variable are created
5. System.out.print(" one reference. E is an appropriate use of in the garbage collectible heap.
"); an assertion because it is not
6. } catch(Exception e) { checking the argument of a public nswer:
7. System.out.print(" two method. Options C and F are the correct
"); answers. C is correct because
8. } finally { References: an object accessible from a live
9. System.out.print(" three http://java.sun.com/j2se/1.4/docs/g thread may yet be called by
"); uide/lang/assert.html#usage- the JVM. F is correct because
10. } conditions all objects are created in the
11. System.out.print(" four "); garbage collectible heap.
12. }
13. Location: ... > Garbage
14. public static void foo() { Location: ... > Flow Control, Collection > Objective 3.2 >
15. throw new Assertions, and Exception Handling > Item 1
RuntimeException(); Objective 2.6 > Item 1 -----------------------------------
16. } ----------------------------------------- ----------
17. } ---------------------------------- Click the Exhibit button to
Which two statements are true? view the code.
What is the result? (Choose one) (Choose two.) 1. class Test {
A three A The -ae flag tells the VM to 2. public static void
B two three enable assertions main(String [] args) {
C three four B The -ea flag tells the compiler to 3. Test2 t2 = new Test2();
D two three four enable assertions 4. Test2 t3;
E one two three four C The -assert flag tells the VM to 5. t3 = t2.m1();
F Compilation fails enable assertions 6. t2 = t2.linker(t2,t3);
Answer: D The -esa flag tells the VM to 7. t2 = null;
Option D is the correct answer. enable some assertions 8. t3 = null;
Method foo() throws a E The -assertions flag tells the 9. }
RuntimeException, which does compiler to enable assertions 10. }
not need to be declared. When 11.
33
12. class Test2 { 1. package com.abc.package1; 1.
13. Test2 link; 2. import java.util.*; 2. public class NewCollections
14. Test2 m1() { 3. public class WeakHash extends {
15. Test2 x = new Test2(); WeakHashMap { 3. public static void
16. return x; 4. int x = 5; main(String [] args) {
17. } 5. Object getDuplicate(Object key) 4. java.util.WeakHashMap
18. Test2 linker(Test2 z1, { hm = new
Test2 z2) { 6. return null; java.util.WeakHashMap();
19. z1.link = z2; 7. } 5. Object o1 = null;
20. z2.link = z1; 8. } 6. o1 = hm.put(o1, o1);
21. return z1; 9. 7. }
22. } 10. private class NewWeakHash 8. }
23. } extends WeakHash {
11. public NewWeakHash() { Which statement must be
Which statement is true? 12. int x = 7; added at line 1 to allow this
13. } code to compile?
14. A import java.util.*;
A After line 8 no objects can be 15. public static void main(String B no statement is required
garbage collected. args [] ) { C import
B After line 7 one object can be 16. WeakHash wh = new java.util.WeakHashMap;
garbage collected. WeakHash(); D include
C After line 7 no objects can be 17. } java.util.WeakHashMap;
garbage collected. 18. }
D After line 6 at least one nswer:
object has more than two What is the result? Option B is the correct answer.
references A Compilation succeeds When a fully qualified name is
E The z1 and z2 references B Compilation fails because of an used, you don't have to import
must be nulled to make any error on line 6 the classes or packages.
objects eligible for garbage C Compilation fails because of an
collection. error on line 10 Location: ... > Language
Answer: D Compilation fails because of an Fundamentals > Objective 4.2
Option C is the correct answer. error on line 16 > Item 1
After line 7 the t3 reference is E An exception is thrown at runtime -----------------------------------
still valid and because of the link Answer: -----
variables both of the Test2 Option C is the correct answer.
objects are still accessible. Classes cannot be declared private. Which two are valid method
signatures in an interface?
Location: ... > Garbage 1. package com.abc.package1; (Choose two.)
Collection > Objective 3.3 > 2. import java.util.*; A short doShort();
Item 1 3. public class WeakHash extends B static char doChar();
------------------------------------- WeakHashMap { C protected byte doByte();
--- 4. int x = 5; D public boolean
Click the Exhibit button to view 5. Object getDuplicate(Object key) doBoolean(int x);
the code. { E final public String
7. Dog [] da = new Dog[2]; 6. return null; doString(int x);
8. Dog clover = new Dog(); 7. } Answer:
9. da[1] = clover; 8. } Options A and D are the
10. clover = null; 9. correct answers. A is correct
11. Dog fido = new Dog(); 10. private class NewWeakHash because interface methods are
12. Dog spot = new Dog(); extends WeakHash { implicitly public. D is correct
When is the clover object 11. public NewWeakHash() { because interface can be
eligible for garbage collection? 12. int x = 7; declared public even though
A after line 9 13. } they are so implicitly.
B after line 10 14.
C after line 11 15. public static void main(String Location: ... > Language
D never in this code args [] ) { Fundamentals > Objective 4.3
Answer: 16. WeakHash wh = new > Item 1
Option D is the correct answer. WeakHash(); -----------------------------------
The last reference to clover 17. } -----
(da[1]), is never nulled. 18. } Click the Exhibit button to
view the code.
Location: ... > Language Location: ... > Language 1. public class ABC {
Fundamentals > Objective 4.1 > Fundamentals > Objective 4.1 > 2. public static void
Item 1 Item 2 main(String [] args ) {
------------------------------------- ----------------------------------------- 3. String a = args[3];
-- ---- 4. String b = args[2];
Click the Exhibit button to view Click the Exhibit button to view the 5. String c = args[1];
the code. code.
34
6. System.out.println("c = " D interface
+ c); E anonymous Answer:
7. } Answer: Option C is the correct answer.
8. } Options A and D are the correct The elements in array y are
And the command line answers. 'interface' and 'super' are implicitly initialized to zeros,
invocation: both valid keywords. C is wrong and then elements 0 and 1 are
java ABC A B C because 'unsigned' is a keyword in C, updated.
What is the result? C++, but not Java. E is wrong
a c= because 'anonymous' is a Java Location: ... > Language
B c=A concept but not a keyword. B Fundamentals > Objective 4.6
C c=B 'Boolean' is a class. The Java > Item 1
D c=C primitive keyword is 'boolean'. -----------------------------------
E Compilation fails ----
F An exception is thrown at Location: ... > Language Which one is valid?
runtime Fundamentals > Objective 4.5 > A boolean b2 = 1;
Item 1 B boolean b3 = null;
Answer: ---------------------------------------- C boolean b1 = FALSE;
Option F is the correct answer. Click the Exhibit button to view the D boolean b4 = "false";
Line 3 will fail; args[3] is out of code. E boolean b5 = (4 < 1);
bounds. 1. class IvarLocal { answer:
2. static int x; Option E is the correct answer.
Location: ... > Language 3. public static void main(String The expression (4 < 1)
Fundamentals > Objective 4.4 > args []) { resolves to false.
Item 1 4. int y;
------------------------------------- 5. System.out.println("x = " + x + Location: ... > Language
-- " y = " + y); Fundamentals > Objective 4.6
Click the Exhibit button to view 6. } > Item 2
the code. 7. } -----------------------------------
1. class Test { ----
2. public static void What is the result? Which three are valid?
main(String [] args) { A x=y= (Choose three.)
3. construct Test(int i) { B x=y=0 A float f1 = 0x123.45;
4. for (int y=0; y<i; y++) C x=0y= B float f2 = 3.14f;
5. System.out.print(" " + D x=0y=0 C float f3 = (double) 1.8;
y); E Compilation fails D float f4 = 1.0;
6. } F An exception is thrown at runtime E float f5 = (float) '\'';
7. } F float f6 = '\ubabe';
8. }
Answer:
And command line invocation: Answer: Options B, E, and F are the
Option E is the correct answer. The correct answers. B is explicitly
java Test 6 compiler will be concerned about cast to a float. E casts a char
whether y has been initialized. (which is an unsigned int) to a
What is the result? float. F casts a Unicode char to
a 12345 Location: ... > Language a float.
B 012345 Fundamentals > Objective 4.5 >
C Compilation fails Item 2 Location: ... > Operators and
D An exception is thrown at ---------------------------------------- Assignments > Objective 5.1 >
runtime Click the Exhibit button to view the Item 2
Answer: code. -----------------------------------
Option C is the correct answer. 7. short x = 1; ----------
The word 'construct' is not a 8. int [] y = new int[4]; Given:
valid modifier keyword in the 9. y[0] = x;
Java language. Constructors are 10. y[1] = x+1; 10. int x = -1, y = -2;
identified by having the same 11. for(int z= 0;z<4; z++) { 11. System.out.println( (x<0)
name as the class, but having no 12. System.out.println(" " + ^ (y<0) ) ;
return type. y[z]);
13. } What is the result?
Location: ... > Language A true
Fundamentals > Objective 4.4 > What is the result? B false
Item 2 A 0123 C Compilation fails
------------------------------------- B 1223 D The code runs with no
-------- C 1200 output
Which two are keywords? D 1 2 null null E An exception is thrown at
(Choose two.) E Compilation fails runtime
A super F An exception is thrown at runtime Answer:
B Boolean
C unsigned
35
Option B is the correct answer. boolean expressions will be 12. for ( int i=0;
Both equality tests resolve to evaluated regardless of the outcome i<flags.length; i++ ) {
true - true XOR true is false. of a preceding evaluation. As there 13. flags[i] = ((i%2)==0);
are booleans that resolve to false in 14. }
Location: ... > Operators and all three composite boolean 15. }
Assignments > Objective 5.2 > expressions the outcome must be 16. public void arrayTest () {
Item 1 false. 17. boolean[] initial = null;
------------------------------------- 18. op3( initial );
-------- Location: ... > Operators and 19.
click the Exhibit button to view Assignments > Objective 5.3 > Item System.out.println( initial[0] );
the code. 2 20. }
10. int[] arr1 = new int[2]; ---------------------------------------
11. int[] arr2 = Click the Exhibit button to view the What is the result if method
(int[])arr1.clone(); code. arrayTest() is called?
12. System.out.println( "Array 1 10. public boolean t1() { return
equals array 2 - " + "hello".equals("HELLO"); } A true
arr1.equals( arr2 ) ); 11. public boolean t2() { return ! B null
t1(); } C false
What is the result? 12. D Compilation fails
A Array 1 equals array 2 - 13. public void op () { E The code runs with no
B Array 1 equals array 2 - true 14. System.out.println( (t1() && output
C Array 1 equals array 2 - null t2()) | t2() ); F An exception is thrown at
D Array 1 equals array 2 - false 15. } runtime
E Compilation fails
F An exception is thrown at Which four are true? (Choose four.)
runtime A Compilation fails Answer:
B Calling op() means t2() is always Option F is the correct answer.
Answer: called once An exception is thrown at
Option D is the correct answer. C Calling op() means t1() is always runtime. Defining and
Arrays inherit the default called once initializing the array in op3()
Object.equals implementation D The output from op() is always has no effect on the callers
which compares references not the value true reference which remains null.
equivalence of content therefore E Calling op() means t2() is always Therefore the access on
comparing two distinct arrays will called twice initial[0] causes a
always yield false even if the F Calling op() means t1() is always java.lang.NullPointerException
compared arrays are clones. called twice
G Reversing the first expression to Location: ... > Operators and
Location: ... > Operators and (t2() && t1()) does not affect the Assignments > Objective 5.4 >
Assignments > Objective 5.3 > output Item 2
Item 1 -----------------------------------
------------------------------------- Answer: -----
--- Options B, D, F, and G are the Click the Exhibit button to
Click the Exhibit button to view correct answers. view the code.
the code. t1() resolves to false t2() resolves to 10. public StringBuffer
10. boolean flag1 = true; not t1() - true reordering the first op4( StringBuffer sb ) {
11. boolean flag2 = false; expression does not affect the 11. sb.append("-widgets");
12. System.out.println( ( flag2 & outcome because it is a double && 12. return sb;
flag1 ) & ( flag1 & flag2 ) ); The first call to t1() returns false and 13. }
will shortcut the && expression to 14. public void roundRobinTest
Which two are true? (Choose false and the non shortcut | to the () {
two.) second t2() returns true resulting in 15. StringBuffer sb = new
overall true. Due to shortcut t2() is StringBuffer();
A The code outputs the value only ever called once t1() is called 16. sb.append("acme");
false once in the expression and a second 17. op4(sb);
B The output may vary if the time from t2(), therefore is called 18. sb.append("-and-
ordering is changed twice nuggets");
C flag1 and flag2 are both 19.
evaluated exactly once Location: ... > Operators and System.out.println( sb.toString
D The output is always true Assignments > Objective 5.4 > Item () );
regardless of the ordering 1 20. }
E The output is always false -----------------------------------------
regardless of the ordering --------------------------------------- What is the result if method
click the Exhibit button to view the roundRobinTest() is called?
Answer: code.
Options A and E are the correct 10. public void op3( boolean[] flags ) A acme
answers. The entire logical { B acme-widgets
statement is composed of non 11. flags = new boolean[3]; C -and-nuggets
shortcutting and therefore ALL D acme-and-nuggets
36
E -widgets-and-nuggets Chapter 3: Extending Classes -- B Compilation fails for code -
F acme-widgets-and-nuggets ISBN: 0-201-70433-1 new P();
C Compilation fails for code -
Answer: Location: ... > Objective 6.1 > Item new Q("");
Option F is the correct answer. 2 D Compilation fails for code -
sb is created in roundRobinTest ----------------------------------------- new P('a');
and its reference passed by value ---- Click the Exhibit button to view E Compilation fails for code -
into op4 where the shared object the code. new Q((short)1);
is modified. The same sb is then 1. interface D {} F Compilation fails for code -
returned to the caller, but the 2. class E implements D {} new Q( new Q(3) instanceof
caller never assigns or re-assigns 3. class F extends E { P );
its local sb reference and it 4. F() {} Answer:
appears that modifications in op4 5. } Options B, C, and D are the
are lost, but as this is a shared 6. class G extends F implements D correct answers. The
object by reference all {} relationship and declaration of
modifications remain, so the 7. class X { P & Q are sound. This question
output is acme-widgets-and- 8. public static void main( String[] is quite simple couched in
nuggets args ) { seemingly complex code.
9. E e = new F(); Simply test the argument
Location: ... > Objective 6.1 > 10. D d = new G(); passed in the new call with a
Item 1 11. } constructor in the target class,
------------------------------------- 12. } if a match is found it compiles.
-- The last three options here do
Click the Exhibit button to view Which three are true? (Choose not have matching
the code. three.) constructors.
1. class A { A The declaration of G is illegal
2. private static class B { B E is said to be a superclass of F Location: ... > Objective 6.2
3. private static String msg C G is said to be a superclass of E > Item 2
= "ok" ; D The assignment at line 10 is legal -----------------------------------
4. } E A variable can be declared using ----
5. public static String access() an interface type Click the Exhibit button to view
{ F Compilation fails the code.
6. return B.msg; 10. abstract class X {
7. } answer: 11. public final void op(){}
8. } B, D, and E. B is correct because 12. abstract final void op();
9. class X { class F extends class E, making E a 13. void op( String s ){}
10. public static void superclass of F. D and E are correct 14. abstract synchronized
main( String[] args ) { because the code compiles void op(int i) throws Exception;
11. successfully, the declaration of G 15. abstract private void
System.out.println( A.access() ); reimplementing D is legal, as is the op( String a, int i );
12. } declaration of d using an interface D 16. }
13. } as its type.
Which three are true? (Choose
Which two are true? (Choose Location: ... > Objective 6.2 > Item three.)
two.) 1
A Compilation fails ----------------------------------------
B The code outputs the value Click the Exhibit button to view the
ok code. A Line 10 is uncompilable
C An exception is thrown at 10. class P { B Line 11 is uncompilable
runtime 11. P( String s ){} C Line 12 is uncompilable
D Any private members of B 12. P( short s ){} D Line 13 is uncompilable
can be accessed from class A 13. } E Line 14 is uncompilable
only through accessor methods 14. class Q extends P { F Line 15 is uncompilable
E The private modifier on msg 15. protected Q() Answer:
must be weakened to default or { super((short)3); } Options C, E, and F are the
public for this code to work 16. public Q( int i ) { super( new correct answers.
correctly Integer(i).toString() ); } line 10 ok, the class must be
Answer: 17. Q( boolean b ) { super(""); } declared abstract
Options B and D are the correct 18. Q( short s ) { super( s ); } line 11 ok, the initial method
answers. Access to an nested 19. } declaration signature
classes private methods and line 12 fails, cannot combine
variables is granted to the If the following new statements are abstract and final, conflict of
encapsulating classes methods. invoked in a separate class in the intentions
same package as classes P and Q, line 13 ok, the first successful
Reference: which three are true? (Choose overload of op(), but with
The Java Programming three.) differing access privileges
Language, Third Edition, by A Compilation fails for code - new
Arnold, Gosling & Holmes, Q();
37
line 14 fails, cannot combine 14. } 3. Widget(boolean daemon)
abstract with implementation {
details like synchronized Which two are true? (Choose two.) 4.
line 15 fails, cannot combine A Line 5 is uncompilable this.setDaemon(daemon);
abstract and private, no way to B Line 9 is uncompilable 5. this.start();
implement in subclass C Line 10 is uncompilable 6. }
D Line 11 is uncompilable 7. }
Location: ... > Objective 6.3 > E Line 12 is uncompilable 8.
Item 1 F Compilation succeeds 9. for ( int i= 0;i<10; i++ ) {
------------------------------------- 10. new Widget(((i
-------- %2)==0));
Click the Exhibit button to view Answer: 11. }
the code. Options B and E are the correct 12. }
1. interface XX {} answers. Line 9 attempts to
2. interface YY extends XX {} instantiate an interface. Line 12 is an Which two statements are
3. abstract class ZZ implements incompatible assignment; you can't true? (Choose two.)
XX {} assign a superclass object to a A Compilation fails.
4. class AA extends ZZ subclass reference type. B Only five threads are
implements YY { Location: ... > Objective 6.3 > created.
5. private class BB{} Item 2 C An exception is thrown at
6. } Click the Exhibit button to view runtime.
7. class Main extends AA { the code. D Ten independent threads
8. public static void 1. class Outer { are created.
main( String[] args ) { 2. class Inner {} E Ten threads are created but
9. XX xx1 = new XX (); 3. } only five execute.
10. XX xx2 = new AA (); 4. class ExtendedOuter extends F The program terminates
11. ZZ zz1 = new Main (); Outer { after the tenth thread is
12. Main m = new AA(); 5. class ExtendedInner extends created.
13. } Inner {} Answer:
14. } 6. } Options D and F are the correct
7. class Main extends Outer.Inner { answers. The program creates
Which two are true? (Choose 8. Main( Outer ref ) { precisely 10 threads, every
two.) 9. ref.super(); other of which is marked as
A Line 5 is uncompilable 10. } daemon thread. Each thread
B Line 9 is uncompilable 11. public static void main( String[] executes on the default run()
C Line 10 is uncompilable args ) { method so all will terminate
D Line 11 is uncompilable 12. new Main( new and therefore the program
E Line 12 is uncompilable ExtendedOuter() ); terminates.
F Compilation succeeds 13. }
Answer: 14. } Reference:
Options B and E are the correct The Java Programming
answers. Line 9 attempts to What is the result? Language, Third Edition, by
instantiate an interface. Line 12 A Compilation fails Arnold, Gosling & Holmes,
is an incompatible assignment; B An exception is thrown at runtime Chapter 10: Threads
you can't assign a superclass C The code runs with no output ISBN: 0-201-70433-1
object to a subclass reference
type. Answer: location: ... > Threads >
Option C is the correct answer. An Objective 7.1 > Item 2
Location: ... > Objective 6.3 > inner class can extend another, -----------------------------------
Item 1 unrelated, inner class provided an -----------------------------------
Click the Exhibit button to view appropriate enclosing instance is ----------
the code. supplied to the superclass. The Click the Exhibit button to
1. interface XX {} resulting inner class then has two view the code.
2. interface YY extends XX {} enclosing instances, one for the 11. public static void
3. abstract class ZZ implements extended class and one for the main( String[] args ) {
XX {} superclass. Therefore this code 12. class Widget extends
4. class AA extends ZZ cleanly compiles and outputs java.lang.Thread {
implements YY { nothing. 13. Widget() {
5. private class BB{} Location: ... > Threads > Objective 14. this.start();
6. } 7.1 > Item 1 15. }
7. class Main extends AA { ----------------------------------------- 16. }
8. public static void --------------------------------------- 17.
main( String[] args ) { Click the Exhibit button to view the 18. Widget w = new
9. XX xx1 = new XX (); code. Widget();
10. XX xx2 = new AA (); 1. public static void main( String[] 19. w.setDaemon(true);
11. ZZ zz1 = new Main (); args ) { 20. }
12. Main m = new AA(); 2. class Widget extends
13. } java.lang.Thread { Which statement is true?
38
A Compilation fails. marked as Daemon threads, the Click the Exhibit button to
B The program never program contains no user threads view the code.
terminates. once main terminates, so the 10. class X {
C One daemon thread is program as a whole terminates. A 11. synchronized void iTest()
created. number of the daemon threads may {
D An exception is thrown at never execute due to the early 12. while(true) {
runtime. termination of the program and the 13. Thread.yield();
E The program terminates after priority levels assigned. 14. }
the thread is created. Reference: 15. }
Answer: The Java Programming Language, 16. synchronized static void
Option D is the correct answer. Third Edition, by Arnold, Gosling & sTest() {}
An exception is thrown at Holmes, Chapter 10: Threads 17. public void op() {}
runtime - ISBN: 0-201-70433-1 18. }
va.lang.IllegalThreadStateExcepti
on setdaemon(true) can not be Location: ... > Threads > Objective And, given a single instance of
invoked on an active thread. 7.2 > Item 2 X, and two or more concurrent
Reference: threads, which statement is
The Java Programming Click the Exhibit button to view the true?
Language, Third Edition, by code. A Multiple threads can
Arnold, Gosling & Holmes 1. class Worker extends execute iTest() concurrently.
Chapter 10: Threads java.lang.Thread { B Any thread calling iTest()
ISBN: 0-201-70433-1 2. public void run() { will be blocked pending a call
3. while ( true ) { to notify.
Location: ... > Threads > 4. synchronized( this ) { C While a thread is executing
Objective 7.2 > Item 1 5. try { iTest(), any call on sTest() will
------------------------------------- 6. wait(); block pending lock access.
------------------------------------- 7. } catch (Exception e) {} D While a thread is executing
------ 8. } iTest(), no other threads may
Click the Exhibit button to view 9. System.out.println("ok"); execute any methods declared
the code. 10. } in X.
1. class Worker extends 11. } E While a thread is executing
java.lang.Thread { 12. public static void main( String[] iTest(), op() may be
2. public void run() { args ) { concurrently executed inside
3. while ( true ) {} 13. new Worker().start(); the same instance of X.
4. } 14. } Answer:
5. 15. } Option E is the correct answer.
6. public static void Static methods synchronize on
main( String[] args ) { Which two statements are true? the class object, not on an
7. for (int i=0; (Choose two.) instance object, so concurrent
i<MAX_PRIORITY; i++ ){ A Compilation fails. calls to iTest() and sTest() will
8. Worker w = new B The program never terminates. not block each other. op() is
Worker(); C The program runs with no output. not synchronized so may be
9. D The value ok is repeatedly called concurrently with
w.setPriortity( MIN_PRIORITY+i ) output. anything else.
; E The program terminates and
10. w.setDaemon(true); outputs ok precisely once. Reference:
11. w.start(); F The Worker thread never blocks The Java Programming
12. } inside the wait method because there Language, Third Edition, by
13. } are no other threads executing. Arnold, Gosling & Holmes,
14. } answer: Chapter 10: Threads
Options B and C are the correct ISBN: 0-201-70433-1
Which two statements are true? answers. This program simply Location: ... > Threads >
(Choose two.) launches a single user thread that Objective 7.3 > Item 2
immediately blocks inside the wait() -----------------------------------
A Compilation fails. method The thread is never -----------------------------------
B An exception is thrown at unblocked because no other thread is ----------
runtime. executing to call the notify on the Click the Exhibit button to
C All threads are guaranteed to lock. view the code.
execute. Reference: 1. class WorkerT extends
D Some of the threads may The Java Programming Language, java.lang.Thread {
never execute. Third Edition, by Arnold, Gosling & 2. private static StringBuffer
E The program runs forever Holmes, Chapter 10: Threads sb = new StringBuffer();
with no output. ISBN: 0-201-70433-1 3. public void run() {
F The program terminates when Location: ... > Threads > Objective 4. notify();
the main() method completes. 7.3 > Item 1 5. try {
Answer: ----------------------------------------- 6. wait();
Options D and F are the correct --------------------------------------- 7. } catch (Exception e) {}
answers. As all threads are 8. }
39
9. public static void ISBN: 0-201-70433-1 -----------------------------------
main( String[] args ) { Location: ... > Threads > Objective ---------- Click the Exhibit
10. for (int i= 0;i<10; i++) { 7.4 > Item 2 button to view the code.
11. new WorkerT().start(); ---------------------------------------- 1. public class Test823 {
12. } which two statements are correct? 2. public static void
13. } (Choose two.) main(String [] args) {
14. } A To call notify() a thread must 3. String a = "freddy";
own the monitor lock. 4. String b =
Which statement is true? B The notify() and notifyAll() a.substring(0,3);
A Compilation fails. methods are defined in the Thread 5. b.toUpperCase();
B All 10 threads block. class. 6. System.out.println(a +=
C An exception is thrown at C The notify() and notifyAll() b);
runtime. methods are defined in the Object 7. }
D All 10 threads execute to class. 8. }
completion. D A thread can only call notify() if What is the result?
E Each thread is unlocked by another thread has previously called A freddyFRE
the following thread until only wait(). B freddyfre
the final thread remains blocked. E The notify() and notifyAll() C freddyFRED
Answer: methods are defined in the Runnable D freddyfred
Option C is the correct answer. interface. E Compilation fails.
An exception is thrown Answer: Answer:
java.lang.IllegalMonitorStateExce Options A and C are the correct Option B is the correct answer.
ption: current thread not owner. answers. The a String reference is never
The caller of wait(), notify(), or modified, and the
notifyAll() must own the monitor Reference: toUpperCase() call is not
lock that is, they must be The Java Programming Language, assigned to b so b's original
executing inside a synchronized Third Edition, by Arnold, Gosling & object does not change.
method or section to be able to Holmes, Chapter 10: Threads Location: ... > Fundamental
successfully call any of these ISBN: 0-201-70433-1 Classes in the java.lang
methods. package > Objective 8.2 >
Location: ... > Fundamental Classes Item 2
Reference: in the java.lang package > Objective -----------------------------------
The Java Programming 8.1 > Item 1 -----
Language, Third Edition, by --------------------------------------- Click the Exhibit button to
Arnold, Gosling & Holmes, Click the Exhibit button to view the view the code.
Chapter 10: Threads code. 1. public class Test825 {
ISBN: 0-201-70433-1 1. public class Test813 { 2. public static void
Location: ... > Threads > 2. public static void main(String [] main(String [] args) {
Objective 7.4 > Item 1 args) { 3. String a = "big";
------------------------------------- 3. double a = Math.round(5.5); 4. String b = a;
------------------------------------- 4. double b = Math.round(5.2); 5. a = a + "bird";
------ 5. double c = Math.round(-5.0); 6. a = b;
Which three statements are 6. double d = Math.round(-5.4); 7. b = "bird";
true? (Choose three.) 7. double e = Math.round(-5.5); 8. System.out.println(a =
A The Object class defines a 8. System.out.print( "Results: " + a+b);
wait() method. a+""+b+""+c+""+d+"" 9. }
B The Thread class overrides + e); 10. }
a wait() method. 9. }
C The Runnable interface 10. } What is the result?
defines a wait() method. A bigbird
D wait() can be called at any What is the result? B birdbird
time by an executing thread. A Results: 6.0 5.0 -5.0 -5.0 -5.0 C bigbigbird
E The wait() method used in B Results: 6.0 5.0 -5.0 -5.0 -6.0 D bigbirdbird
thread communication releases C Results: 5.0 5.0 -5.0 -5.0 -5.0 E Compilation fails.
an object lock. D Results: 6.0 5.0 -5.0 -4.0 -5.0 Answer:
F The wait() method is E Results: 6.0 5.0 5.0 5.0 6.0 Option A is the correct answer.
overloaded and also has the F Compilation fails. In line 4, b is set to refer to the
following signature public final String literal "big". The String
void wait(long timeout). nswer: referenced by b is not changed
Option A is the correct answer. Both by the change to a in line 5,
answer: positive and negative numbers are because Strings are
Options A, E, and F are the rounded up to the larger number. For immutable. In line 5, a new
correct answers. a positive number such as 5.5, the String object "bigbird" is
Reference: greater number is 6, but for -5.5 the created, and assigned to a. At
The Java Programming greater number is -5.0. this point (line 5) b is still
Language, Third Edition, by Location: ... > Fundamental referring to "big" and a is now
Arnold, Gosling & Holmes, Classes in the java.lang package > referring to "bigbird". In line
Chapter 10: Threads Objective 8.2 > Item 1 6,then, a is set to refer to the
40
String literal "big" referenced by E Compilation fails. A TreeSet is sorted so the
b, so both a and b refer to the F An uncaught exception is thrown Strings come out in
String literal "big". In line 7, b is at runtime. alphabetical order
set to reference a String literal Answer: Location: ... > The
"bird", while a is left unchanged Option E is the correct answer. Byte Collections Framework >
and still refers to "big". Finally, a does not have a constructor that Objective 9.2 > Item 1
+ b is printed out, producing takes an int. The Byte constructor -----------------------------------
"bigbird". must be passed a previously declared ---- If class X implements
byte variable, or explicitly cast an int hashcode() and equals()
value. correctly, and given two
Location: ... > Fundamental instances (o1 and o2) of class
Classes in the java.lang package Location: ... > The Collections X, which two are true? (Choose
> Objective 8.3 > Item 1 Framework > Objective 9.1 > Item 1 two.)
------------------------------------- -----------------------------------------
-- Which creates a new ---- Which two statements are true A if o1.hashcode() and
Character object? of class java.util.HashMap? (Choose o2.hashcode() are not the
A Character a = new two.) same, then o1 and o2 must not
Character("c"); A Its methods are thread-safe. be equal
B Character a = B It allows null references to be B o1.hashcode() and
Character.getCharacter('s'); stored. o2.hashcode() might be the
C Character a = new C It provides fast, bi-directional same if o1 and o2 are
Character(new char[]{'s'}); iteration. considered equal
D Character a = D It implements java.util.Hashable. C o1.hashcode() and
Character.valueOf("c".toChar()); E It tracks when its elements were o2.hashcode() must be the
E Character a = new last accessed. same if o1 and o2 are
Character((new char[]{'s'})[0]); F Its elements can be accesssed considered equal
Answer: using a unique key. D if o1 and o2 are not equal,
Option E is the correct answer. Answer: then o1.hashcode() and
The Character class has only one Options B and F are the correct o2.hashcode() must not be the
constructor, and it takes a char answers. HashMap implements same
primitive. Answer "E" constructs java.util.Map, which allows elements Answer:
an anonymous char array holding to be accessed using a unique key. Options A and C are the correct
a single char, then accesses the Whereas HashTable does not permit answers. Hashcode suggests
array element at index 0, thus null references to be stored, the likelihood of equality, while
returning a char to the Character HashMap allows both keys and equality requires that
constructor. elements to be null. hashcodes must be the same.
Location: ... > Fundamental Location: ... > The Collections The rules for correct
Classes in the java.lang package Framework > Objective 9.1 > Item 2 implementation of hashcode
> Objective 8.3 > Item 2 --------------------------------- and equals require that if two
------------------------------------- Click the Exhibit button to view the objects are equal, their
--- code. hashcodes MUST be the same.
Click the Exhibit button to view 1. TreeSet s = new TreeSet(); If two objects are unequal,
the code. 2. s.add("Fred"); however, they may still have
1. public class Test834 { 3. s.add("Mike"); the same hashcode. So, object
2. public static void main(String 4. s.add("Zeus"); equivalency guarantees
[] args) { 5. s.add("Fred"); hashcode equivalency, but
3. try { 6. s.add("Amy"); hashcode equivalency does not
4. Double d = new 7. Iterator i = s.iterator(); guarantee object equivalency.
Double(new 8. while(i.hasNext()) {
Byte(6).doubleValue()); 9. System.out.print(i.next() + ",
5. String s = d.toString(); "); Java Programmer
6. 10. } Certification Mock
System.out.println(Integer.parse What is the result?
Int(s)); A Fred, Mike, Zeus, Amy, Question 1)
7. } B Amy, Fred, Mike, Zeus,
catch(NumberFormatException C Fred, Mike, Zeus, Fred, Amy,
What will happen when you
ex) { D Amy, Fred, Fred, Mike, Zeus,
attempt to compile and run
8. E Five elements will be printed, but
this code?
System.out.println("failed"); the order is not guaranteed.
9. } F Four elements will be printed, but
10. } the order is not guaranteed. abstract class Base{
11. } abstract public void
myfunc();
What is the result? public void another(){
A 6 Answer:
B 6.0 Option B is the correct answer. A System.out.println("Another
C null TreeSet is a Set, which eliminates method");
D failed duplicates, so Fred only goes in once. }
}
41
4) transient class Base{
public class Abs extends Base{ 5) vagrant public final void amethod(){
public static void
main(String argv[]){ Question 4) System.out.println("amethod")
Abs a = new Abs(); ;
a.amethod(); }
What will happen when you attempt
} }
to compile and run this code?
public void myfunc(){
public class Fin extends Base{
System.out.println("My Func"); class Base{ public static void main(String
} abstract public void myfunc(); argv[]){
public void amethod(){ public void another(){ Base b = new Base();
myfunc(); System.out.println("Another b.amethod();
} method"); }
} } }
}
1) The code will compile and run, 1) Compile time error
public class Abs extends Base{
printing out the words "My Func" indicating that a class with any
public static void main(String
2) The compiler will complain final methods must be declared
argv[]){
that the Base class has non final itself
Abs a = new Abs();
abstract methods 2) Compile time error
a.amethod();
3) The code will compile but indicating that you cannot
}
complain at run time that the inherit from a class with final
Base class has non abstract methods
public void myfunc(){
methods 3) Run time error indicating
System.out.println("My
4) The compiler will complain that Base is not defined as final
func");
that the method myfunc in the 4) Success in compilation and
}
base class has no body, nobody output of "amethod" at run
at all to looove it time.
public void amethod(){
myfunc();
Question 2) } Question 7)
}
What will happen when you
What will happen when you 1) The code will compile and run, attempt to compile and run
attempt to compile and run this printing out the words "My Func" this code?
code? 2) The compiler will complain that
the Base class is not declared as public class Mod{
public class MyMain{ abstract. public static void main(String
public static void main(String 3) The code will compile but argv[]){
argv){ complain at run time that the Base }
System.out.println("Hello class has non abstract methods public static native void
cruel world"); 4) The compiler will complain that amethod();
} the method myfunc in the base class
} has no body, nobody at all to looove }
it
1) The compiler will complain 1) Error at compilation: native
that main is a reserved word and Question 5) method cannot be static
cannot be used for a class 2) Error at compilation native
2) The code will compile and Why might you define a method as method must return value
when run will print out "Hello native? 3) Compilation but error at run
cruel world" time unless you have made
3) The code will compile but will code containing native
1) To get to access hardware that
complain at run time that no amethod available
Java does not know about
constructor is defined 4) Compilation and execution
2) To define a new data type such as
4) The code will compile but will without error
an unsigned integer
complain at run time that main is
3) To write optimised code for
not correctly defined Question 8)
performance in a language such as
C/C++
Question 3) 4) To overcome the limitation of the What will happen when you
private scope of a method attempt to compile and run
Which of the following are Java this code?
modifiers? Question 6)
private class Base{}
1) public public class Vis{
What will happen when you attempt
2) private transient int iVal;
to compile and run this code?
3) friendly public static void
42
main(String elephant[]){ Question 11)
} Question 14)
} You want to loop through an array
and stop when you come to the last How do you change the current
1)Compile time error: Base element. Being a good java layout manager for a container
cannot be private programmer and forgetting
2)Compile time error indicating everything you ever knew about 1) Use the setLayout method
that an integer cannot be C/C++ you know that arrays contain 2) Once created you cannot
transient information about their size. Which of change the current layout
3)Compile time error transient the following can you use? manager of a component
not a data type 3) Use the setLayoutManager
4)Compile time error malformed 1)myarray.length(); method
main method 2)myarray.length; 4) Use the updateLayout
3)myarray.size method
Question 9) 4)myarray.size();
Question 15)
What happens when you attempt Question 12)
to compile and run these two Which of the following are
files in the same directory? What best describes the appearance fields of the
of an application with the following GridBagConstraints class?
//File P1.java code?
package MyPackage; 1) ipadx
class P1{ import java.awt.*; 2) fill
void afancymethod(){ public class FlowAp extends Frame{ 3) insets
System.out.println("What a public static void main(String argv[]) 4) width
fancy method"); {
} FlowAp fa=new FlowAp();
Question 16)
} fa.setSize(400,300);
//File P2.java fa.setVisible(true);
public class P2 extends P1{ What most closely matches the
public static void main(String } appearance when this code
argv[]){ runs?
P2 p2 = new P2(); FlowAp(){
p2.afancymethod(); add(new Button("One")); import java.awt.*;
} add(new Button("Two")); public class CompLay extends
} add(new Button("Three")); Frame{
add(new Button("Four")); public static void main(String
1) Both compile and P2 outputs }//End of constructor argv[]){
"What a fancy method" when run CompLay cl = new
2) Neither will compile CompLay();
3) Both compile but P2 has an }
error at run time }//End of Application
4) P1 compiles cleanly but P2 has CompLay(){
an error at compile time 1) A Frame with buttons marked One Panel p = new Panel();
to Four placed on each edge.
2) A Frame with buutons marked p.setBackground(Color.pink);
Question 10)
One to four running from the top to p.add(new Button("One"));
bottom p.add(new Button("Two"));
You want to find out the value of p.add(new
3) A Frame with one large button
the last element of an array. You Button("Three"));
marked Four in the Centre
write the following code. What add("South",p);
4) An Error at run time indicating you
will happen when you compile setLayout(new
have not set a LayoutManager
and run it.? FlowLayout());
setSize(300,300);
Question 13)
public class MyAr{ setVisible(true);
public static void main(String }
argv[]){ How do you indicate where a }
int[] i = new int[5]; component will be positioned using
System.out.println(i[5]); Flowlayout?
1) The buttons will run from
} left to right along the bottom
} 1) North, South,East,West of the Frame
2) Assign a row/column grid 2) The buttons will run from
1) An error at compile time reference left to right along the top of
2) An error at run time 3) Pass a X/Y percentage parameter the frame
3) The value 0 will be output to the add method 3) The buttons will not be
4) The string "null" will be output 4) Do nothing, the FlowLayout will displayed
position the component
43
4) Only button three will show 1) true Question 24)
occupying all of the frame 2) false
Under what circumstances
Question 17) Question 20) might you use the yield
method of the Thread class
Which statements are correct Which most closely matches a
about the anchor field? description of a Java Map? 1) To call from the currently
running thread to allow
1) It is a field of the 1) A vector of arrays for a 2D another thread of the same or
GridBagLayout manager for geographic representation higher priority to run
controlling component placement 2) A class for containing unique array 2) To call on a waiting thread
2) It is a field of the elements to allow it to run
GridBagConstraints class for 3) A class for containing unique 3) To allow a thread of higher
controlling component placement vector elements priority to run
3) A valid setting for the anchor 4) An interface that ensures that 4) To call from the currently
field is implementing classes cannot contain running thread with a
GridBagConstraints.NORTH duplicate keys parameter designating which
4) The anchor field controls the thread should be allowed to
height of components added to a run
container
Question 21) Question 25)
Question 18)
How does the set collection deal with What will happen when you
What will happen when you duplicate elements? attempt to compile and run the
attempt to compile and run the following code
following code? 1) An exception is thrown if you
attempt to add an element with a public class Hope{
public class Bground extends duplicate value public static void
Thread{ 2) The add method returns false if main(String argv[]){
public static void main(String you attempt to add an element with Hope h = new
argv[]){ a duplicate value Hope();
Bground b = new 3) A set may contain elements that }
Bground(); return duplicate values from a call to
b.run(); the equals method protected Hope(){
} 4) Duplicate values will cause an for(int i =0; i <10; i
public void start(){ error at compile time ++){
for (int i = 0; i <10;
i++){ System.out.println(i);
}
System.out.println("Value of i = }
Question 22) }
" + i);
}
} What can cause a thread to stop 1) Compilation error:
} executing? Constructors cannot be
declared protected
1) A compile time error 1) The program exits via a call to 2) Run time error:
indicating that no run method is System.exit(0); Constructors cannot be
defined for the Thread class 2) Another thread is given a higher declared protected
2) A run time error indicating priority 3) Compilation and running
that no run method is defined for 3) A call to the thread's stop method. with output 0 to 10
the Thread class 4) A call to the halt method of the 4) Compilation and running
3) Clean compile and at run time Thread class? with output 0 to 9
the values 0 to 9 are printed out
4) Clean compile but no output Question 23) Question 26)
at runtime
For a class defined inside a method, What will happen when you
Question 19) what rule governs access to the attempt to compile and run the
variables of the enclosing method? following code
Is the following statement true
or false? 1) The class can access any variable public class MySwitch{
When using the GridBagLayout 2) The class can only access static public static void main(String
manager, each new component variables argv[]){
requires a new instance of the 3) The class can only access MySwitch ms= new
GridBagConstraints class. transient variables MySwitch();
4) The class can only access final ms.amethod();
variables }
44
1) Compilation succeeds and at run Question 31)
time an output of 0 and false
public void amethod(){ 2) Compilation succeeds and at run What will happen when you
int k=10; time an output of 0 and true attempt to compile and run the
switch(k){ 3) Compile time error b is not following code
default: //Put the default at initialised
the bottom, not here 4) Compile time error z must be
import java.io.*;
System.out.println("This assigned a char value
class Base{
is the default output");
public void amethod()throws
break; Question 29) FileNotFoundException{}
case 10:
}
System.out.println("ten");
What will happen when you attempt public class ExcepDemo
case 20:
to compile and run the following code extends Base{
with the command line "hello there" public static void
System.out.println("twenty");
main(String argv[]){
break;
public class Arg{ ExcepDemo e = new
}
String[] MyArg; ExcepDemo();
}
public static void main(String }
}
argv[]){
MyArg=argv; public void amethod(){}
1) None of these options protected ExcepDemo(){
}
2) Compile time error target of try{
switch must be an integral type DataInputStream
public void amethod(){
3) Compile and run with output din = new
"This is the default output" DataInputStream(System.in);
System.out.println(argv[1]);
4) Compile and run with output
}
of the single line "ten" System.out.println("Pausing");
}
din.readByte();
Question 27)
1) Compile time error
System.out.println("Continuing
2) Compilation and output of "hello"
Which of the following is the ");
3) Compilation and output of "there"
correct syntax for suggesting this.amethod();
4) None of the above
that the JVM performs garbage }catch(IOException
collection ioe) {}
Question 30)
}
1) System.free();
What will happen when you attempt }
2)
to compile and run the following code
System.setGarbageCollection();
3) System.out.gc(); 1) Compile time error caused
4) System.gc(); public class StrEq{ by protected constructor
public static void main(String argv[]) 2) Compile time error caused
{ by amethod not declaring
Question 28)
StrEq s = new StrEq(); Exception
} 3) Runtime error caused by
private StrEq(){ amethod not declaring
What will happen when you String s = "Marcus"; Exception
attempt to compile and run the String s2 = new 4) Compile and run with output
following code String("Marcus"); of "Pausing" and "Continuing"
if(s == s2){ after a key is hit
public class As{
int i = 10; System.out.println("we have a Question 32)
int j; match");
char z= 1; }else{
boolean b; What will happen when you
public static void main(String System.out.println("Not equal"); attempt to compile and run
argv[]){ } this program
As a = new As(); }
a.amethod(); }
public class Outer{
}
public String name = "Outer";
public void amethod(){ 1) Compile time error caused by public static void main(String
System.out.println(j); private constructor argv[]){
System.out.println(b); 2) Output of "we have a match" Inner i = new Inner();
3) Output of "Not equal" i.showName();
} 4) Compile time error by attempting }//End of main
} to compare strings using == private class Inner{
String name =new
45
String("Inner"); m.amethod(); 1) None of these options
void showName(){ } 2) cycle
public void amethod(){ 3) one
System.out.println(name); static int i; 4) two
} System.out.println(i);
}//End of Inner class } Question 39)
} }
Which of the following
1) Compile and run with output 1) Compilation and output of the
statements are true?
of "Outer" value 0
2) Compile and run with output 2) Compile time error because i has
not been initialized 1) At the root of the collection
of "Inner"
3) Compilation and output of null hierarchy is a class called
3) Compile time error because
4) Compile time error Collection
Inner is declared as private
2) The collection interface
4) Compile time error because of
Question 35) contains a method called
the line creating the instance of
enumerator
Inner
3) The interator method
Which of the following will compile returns an instance of the
Question 33) correctly Vector class
4) The Set interface is
What will happen when you 1) short myshort = 99S; designed for unique elements
attempt to compile and run this 2) String name = 'Excellent tutorial
code Mr Green'; Question 40)
3) char c = 17c;
//Demonstration of event 4)int z = 015;
Which of the following
handling statements are correct?
import java.awt.*; Question 36)
import java.awt.event.*;
1) If multiple listeners are
public class MyWc extends Frame Which of the following are Java key
added to a component only
implements WindowListener{ words
events for the last listener
public static void main(String 1)double
added will be processed
argv[]){ 2)Switch
2) If multiple listeners are
MyWc mwc = new MyWc(); 3)then
added to a component the
} 4)instanceof
events will be processed for all
public void
but with no guarantee in the
windowClosing(WindowEvent we) Question 37) order
{
3) Adding multiple listeners to
System.exit(0);
a comnponent will cause a
}//End of
What will be output by the following compile time error
windowClosing
line? 4) You may remove as well add
public void MyWc(){
listeners to a component.
setSize(300,300);
setVisible(true); System.out.println(Math.floor(-2.1));
} Question 41)
}//End of class 1) -2
2) 2.0 Given the following code
1) Error at compile time 3) -3
2) Visible Frame created that 4) -3.0 class Base{}
that can be closed public class MyCast extends
3) Compilation but no output at Question 38) Base{
run time static boolean b1=false;
4) Error at compile time because static int i = -1;
Given the following main method in a
of comment before import static double d = 10.1;
class called Cycle and a command
statements public static void
line of
main(String argv[]){
Question 34) MyCast m = new
java Cycle one two MyCast();
Base b = new Base();
Which option most fully describes
what will be output? //Here
will happen when you attempt to
}
compile and run the following
public static void main(String }
code
bicycle[]){
System.out.println(bicycle[0]);
public class MyAr{
} Which of the following, if
public static void main(String
inserted at the comment
argv[]) {
//Here will allow the code to
MyAr m = new MyAr();
46
compile and run without error Which of the following statements System.out.println(010|4);
are true
1) b=m; 1) 14
2) m=b; 1) An inner class may be defined as 2) 0
3) d =i; static 3) 6
4) b1 =i; 2) There are NO circumstances 4) 12
where an inner class may be defined
Question 42) as private Question 48)
3) A programmer may only provide
Which of the following one constructor for an anonymous
Given the following variables
statements about threading are class
true 4) An inner class may extend
another class char c = 'c';
int i = 10;
1) You can only obtain a double d = 10;
mutually exclusive lock on Question 45)
long l = 1;
methods in a class that extends String s = "Hello";
Thread or implements runnable What will happen when you attempt
2) You can obtain a mutually to compile and run the following code
Which of the following will
exclusive lock on any object
compile without error?
3) A thread can obtain a int Output=10;
mutually exclusive lock on an boolean b1 = false;
object by calling a synchronized 1)c=c+i;
if((b1==true) &&
method on that object. 2)s+=i;
((Output+=10)==20)){
4) Thread scheduling algorithms 3)i+=s;
System.out.println("We are equal
are platform dependent 4)c+=s;
"+Output);
}else
Question 43) { Question 49)
System.out.println("Not equal!
Your chief Software designer has "+Output); Which of the following will
shown you a sketch of the new } compile without error?
Computer parts system she is
about to create. At the top of the 1) Compile error, attempting to 1) File f = new
hierarchy is a Class called peform binary comparison on logical File("/","autoexec.bat");
Computer and under this are two data type 2) DataInputStream d = new
child classes. One is called 2) Compilation and output of "We are DataInputStream(System.in);
LinuxPC and one is called equal 10" 3) OutputStreamWriter o =
WindowsPC. 3) Compilation and output of "Not new
equal! 20" OutputStreamWriter(System.o
The main difference between the 4) Compilation and output of "Not ut);
two is that one runs the Linux equal! 10" 4) RandomAccessFile r = new
operating System and the other RandomAccessFile("OutFile");
runs the Windows System (of Question 46)
course another difference is that Question 50)
one needs constant re-booting Given the following variables which
and the other runs reliably). of the following lines will compile Given the folowing classes
Under the WindowsPC are two without error? which of the following will
Sub classes one called Server compile without error?
and one Called Workstation. How
String s = "Hello";
might you appraise your
long l = 99; interface IFace{}
designers work?
double d = 1.11; class CFace implements
int i = 1; IFace{}
int j = 0; class Base{}
1) Give the goahead for further 1) j= i <<s; public class ObRef extends
design using the current scheme Base{
2) Ask for a re-design of the 2) j= i<<j; public static void
hierarchy with changing the main(String argv[]){
Operating System to a field 3) j=i<<d; ObRef ob = new ObRef();
rather than Class type Base b = new Base();
3) Ask for the option of 4)j=i<<l; Object o1 = new
WindowsPC to be removed as it Object();
will soon be obsolete Question 47) IFace o2 = new CFace();
4) Change the hierarchy to }
remove the need for the }
superfluous Computer Class. What will be output by the following
line of code? 1)o1=o2;
2)b=ob;
Question 44)
47
3)ob=b; String mystring){} 3) System.out.println(iam);
4)o1=b; 4) public void Amethod(int i, String 4) System.out.println(iArgs);
s) {}
Question 51)
Question 53) Question 55)
Given the following code what
will be the output? Given the following class definition Which of the following are
which of the following can be legally methods of the Thread class?
class ValHold{ placed after the comment line
public int i = 10; //Here ? 1) yield()
} 2) sleep(long msec)
class Base{ 3) go()
public class ObParm{ public Base(int i){} 4) stop()
public static void main(String }
argv[]){
Question 56)
ObParm o = new
ObParm();
o.amethod(); Which of the following methods
public class MyOver extends Base{
} are members of the Vector
public static void main(String arg[]){
public void amethod(){ class and allow you to input a
MyOver m = new
int i = 99; new element
MyOver(10);
ValHold v = new }
ValHold(); MyOver(int i){ 1) addElement
v.i=30; super(i); 2) insert
another(v,i); } 3) append
4) addItem
System.out.print( v.i ); MyOver(String s, int i){
}//End of amethod this(i); Question 57)
//Here
public void another(ValHold } Which of the following
v, int i){ } statements are true?
i=0;
v.i = 20;
1)MyOver m = new MyOver(); 1) Adding more classes via
ValHold vh = new
2)super(); import statements will cause a
ValHold();
3)this("Hello",10); performance overhead, only
v = vh;
4)Base b = new Base(10); import classes you actually
System.out.print(v.i);
System.out.print(i); use.
}//End of another Question 54) 2) Under no circumstances can
a class be defined with the
} Given the following class definition, private modifier
which of the following statements 3) A inner class may under
would be legal after the comment some circumstances be defined
1) 10030
//Here with the protected modifier
2) 20030
4) An interface cannot be
3) 209930
instantiated
4) 10020 class InOut{

String s= new String("Between"); Question 58)


Question 52)
public void amethod(final int
iArgs){ Which of the following are
Given the following class
int iam; correct event handling
definition, which of the following
class Bicycle{ methods
methods could be legally placed
public void sayHello()
after the comment
{
//Here 1) mousePressed(MouseEvent
//Here } e){}
public class Rid{ }//End of bicycle class 2) MousePressed(MouseClick e)
public void amethod(int i, }//End of amethod {}
String s){} public void another(){ 3) functionKey(KeyPress k){}
//Here int iOther; 4)
} } componentAdded(ContainerEve
nt e){}
1)public void amethod(String s, }
int i){}
2)public int amethod(int i, String 1) System.out.println(s);
s){} 2) System.out.println(iOther);
3)public void amethod(int i,
48
Question 59) 1) public Answer 9)
2) private
Which of the following are 4) transient Objective 1.2)
methods of the Collection
interface? The keyword transient is easy to 4) P1 compiles cleanly but P2
1) iterator forget as is not frequently used. has an error at compile time
2) isEmpty Although a method may be
3) toArray considered to be friendly like in C++
The package statement in
4) setText it is not a Java keyword.
P1.java is the equivalent of
placing the file in a different
Question 60) nswer 4) directory to the file P2.java and
thus when the compiler tries to
Which of the following best Objective 1.2) compile P2 an error occurs
describes the use of the indicating that superclass P1
synchronized keyword? 2) The compiler will complain that cannot be found.
the Base class is not declared as
1) Allows two process to run in abstract. Answer 10)
paralell but to communicate with
each other If a class contains abstract methods Objective 4.2)
2) Ensures only one thread at a it must itself be declared as abstract
time may access a method or
2) An error at run time
object
Answer 5)
3) Ensures that two or more
processes will start and end at This code will compile, but at
the same time Objective 1.2) run-time you will get an
4) Ensures that two or more ArrayIndexOutOfBounds
Threads will start and end at the 1) To get to access hardware that exception. This becuase
same time Java does not know about counting in Java starts from 0
3) To write optimised code for and so the 5th element of this
performance in a language such as array would be i[4].
Answers
C/C++
Remember that arrays will
Answer 1)
Answer 6) always be initialized to default
values wherever they are
Objective 1.2) created.
Objective 1.2)
1) The code will compile and run, Answer 11)
printing out the words "My Func" 4) Success in compilation and output
of "amethod" at run time.
Objective 1.1)
A class that contains an abstract
method must be declared A final method cannot be ovverriden
in a sub class, but apart from that it 2)myarray.length;
abstract itself, but may contain
non abstract methods. does not cause any other
restrictions. The String class has a length()
method to return the number
Answer 2)
Answer 7) of characters. I have
sometimes become confused
Objective 4.1) between the two.
Objective 1.2)
4) The code will compile but will Answer 12)
complain at run time that main is 4) Compilation and execution without
not correctly defined error
Objective 8.2)

In this example the parameter is It would cause a run time error if you
had a call to amethod though. 3) A Frame with one large
a string not a string array as
button marked Four in the
needed for the correct main
Centre
method Answer 8)

The default layout manager for


Objective 1.2)
a Frame is the BorderLayout
manager. This Layout manager
Answer 3) 1)Compile time error: Base cannot defaults to placing components
be private in the centre if no constraint is
Objective 4.3) passed with the call to the add
A top leve (non nested) class cannot method.
be private.
Answer 13)
49
Objective 8.2) Answer 19)
1) To call from the currently
4) Do nothing, the FlowLayout Objective 8.2) running thread to allow
will position the component another thread of the same or
higher priority to run
2) false
Answer 14)
You can re-use the same instance of Option 3 looks plausible but
the GridBagConstraints when added there is no guarantee that the
Objective 8.2)
successive components. thread that grabs the cpu time
will be of a higher priority. It
1) Use the setLayout method will depend on the threading
Answer 20)
algorithm of the Java Virtual
Answer 15) Machine and the underlying
Objective 10.1) operating system
Objective 8.2)
4) An interface that ensures that nswer 25)
implementing classes cannot contain
1) ipadx
duplicates
2) fill Objective 6.2)
3) insets
Answer 21)
Answer 16) 4) Compilation and running
Objective 10.1) with output 0 to 9
Objective 8.2)
2) The add method returns false if Answer 26)
you attempt to add an element with
2) The buttons will run from left
a duplicate value
to right along the top of the Objective 2.1)
frame
I find it a surprise that you do not
1) None of these options
The call to the setLayout(new get an exception.
FlowLayout()) resets the Layout Because of the lack of a break
manager for the entire frame and Answer 22) statement after the break 10;
so the buttons end up at the top statement the actual output
rather than the bottom. Objective 7.1) will be

wer 17) 1) The program exits via a call to "ten" followed by "twenty"
exit(0);
Objective 8.2) 2) The priority of another thread is Answer 27)
increased
2) It is a field of the 3) A call to the stop method of the Objective 3.1)
GridBagConstraints class for Thread class
controlling component placement 4) System.gc();
3) A valid settting for the anchor
field is Note that this question asks what
Answer 28)
GridBagconstraints.NORTH can cause a thread to stop executing,
not what will cause a thread to stop
executing. Java threads are Objective 4.4)
nswer 18)
somewhat platform dependent and
you should be carefull when making 1) Compilation succeeds and at
Objective 7.1)
assumptions about Thread priorities. run time an output of 0 and
On some platforms you may find that false
4) Clean compile but no output a Thread with higher priorities gets The default value for a boolean
at runtime to "hog" the processor. You can read declared at class level is false,
up on this in more detail at and integer is 0;

This is a bit of a sneaky one as I Answer 23) Answer 29)


have swapped around the names
of the methods you need to
Objective 4.1) Objective 1.2)
define and call when running a
thread. If the for loop were
defined in a method called public 4) The class can only access final 1) Compile time error
void run() and the call in the variables
main method had been to You will get an error saying
b.start() The list of values from 0 Answer 24) something like "Cant make a
to 9 would have been output. static reference to a non static
Objective 7.1) variable". Note that the main
method is static. Even if main
50
was not static the array argv is 1) Error at compile time Objective 4.2)
local to the main method and
would thus not be visible within If you implement an interface you 3) one
amethod. must create bodies for all methods in
that interface. This code will produce Command line parameters
Answer 30) an error saying that MyWc must be start from 0 and from the first
declared abstract because it does not parameter after the name of
Objective 5.2) define all of the methods in the compile (normally Java)
WindowListener. Option 4 is
nonsense as comments can appear
3) Output of "Not equal" nswer 39)
anywhere. Option 3 suggesting that
it might compile but not produce
Despite the actual character output is ment to mislead on the Objective 10.1)
strings matching, using the == basis that what looks like a
operator will simply compare constructor is actually an ordinary 4) The Set is designed for
memory location. Because the method as it has a return type. unique elements.
one string was created with the
new operator it will be in a
Answer 34) Collection is an interface, not a
different location in memory to
class. The Collection interface
the other string.
Objective 1.2) includes a method called
iterator. This returns an
nswer 31) instance of the Iterator class
4) Compile time error
which has some similarities
Objective 2.3) with Enumerators.
An error will be caused by attempting The name set should give away
to define an integer as static within a the purpose of the Set
4) Compile and run with output
method. The lifetime of a field within interface as it is analogous to
of "Pausing" and "Continuing"
a method is the duration of the the Set concept in relational
after a key is hit
running of the method. A static field databases which implies
exists once only for the class. An uniquness.
An overriden method in a sub approach like this does work with
class must not throw Exceptions Visual Basic.
not thrown in the base class. In Answer 40)
the case of the method amethod
Answer 35)
it throws no exceptions and will Objective 8.1)
thus compile without complain.
There is no reason that a Objective 4.5)
2) If multiple listeners are
constructor cannot be protected. added to a component the
4)int z = 015; events will be processed for all
Answer 32) but with no guarantee in the
The letters c and s do not exist as order
Objective 6.3) literal indicators and a String must 4) You may remove as well add
be enclosed with double quotes, not listeners to a component.
single as in this case.
4) Compile time error because of
the line creating the instance of It ought to be fairly intuitive
Inner Answer 36) that a component ought to be
able to have multiple listeners.
Objective 4.3) After all, a text field might
want to respond to both the
This looks like a question about
mouse and keyboard
inner classes but it is also a 1)double
reference to the fact that the 4)instanceof
main method is static and thus nswer 41)
you cannot directly access a non Note the upper case S on switch
static method. The line causing means it is not a keyword and the Objective 5.1)
the error could be fixed by word then is part of Visual Basic but
changing it to say not Java. Also, instanceof looks like a 1) b=m;
method but is actually a keyword, 3) d =i;
Inner i = new Outer().new
Inner(); Answer 37) You can assign up the
inheritance tree from a child to
Then the code would compile and Objective 9.1) a parent but not the other way
run producing the output "Inner" without an explicit casting. A
4) -3.0 boolean can only ever be
Answer 33) assigned a boolean value.
nswer 38)
Objective 4.6) Answer 42)
51
Objective 7.3) 1) An inner class may be defined as 1000
static
2) You can obtain a mutually 4) An inner class may extend 0100
exclusive lock on any object another class
3) A thread can obtain a ----
mutually exclusive lock on an A static inner class is also sometimes
object by calling a synchronized known as a top level nested class. 1100
method on that object. There is some debate if such a class
4) Thread scheduling algorithms should be called an inner class. I ----
are platform dependent tend to think it should be on the
basis that it is created inside the Which is 12 in decimal
Yes that says dependent and not opening braces of another class. How
independent. could a programmer provide a The | bitwise operator means
constructor for an anonymous class?. that for each position where
Remember a constructor is a method there is a 1, results in a 1 in
Answer 43)
with no return type and the same the same position in the
name as the class. Inner classes may answer.
Objective 6.1) be defined as private
Answer 48)
2) Ask for a re-design of the Answer 45)
hierarchy with changing the
Operating System to a field Objective 5.1)
Objective 5.3)
rather than Class type
2)s+=i;
4) Compilation and output of "Not
This question is about the
equal! 10"
requirement to understand the Only a String acts as if the +
difference between the "is-a" and operator were overloaded
the "has-a" relationship. Where a The output will be "Not equal 10".
class is inherited you have to ask This illustrates that the Output +=10
Answer 49)
if it represents the "is-a" calculation was never performed
relationship. As the difference because processing stopped after the
first operand was evaluated to be Objective 10.1)
between the root and the two
children are the operating false. If you change the value of b1
system you need to ask are to true processing occurs as you Although the objectives do not
Linux and Windows types of would expect and the output is "We specifically mention the need
computers.The answer is no, are equal 20";. to understand the I/O Classes,
they are both types of Operating feedback from people who
Systems. So option two Answer 46) have taken the exam indicate
represents the best of the that you will get questions on
options. You might consider this topic. As you will probably
Objective 5.1)
having operating system as an need to know this in the real
interface instead but that is world of Java programming,
2)j= i<<j; get familiar with the basics. I
another story.
have assigned these questions
4)j=i<<l; to Objective 10.1 as that is a
Of course there are as many
fairly vague objective.
ways to design an object
hierarchy as ways to pronounce
Answer 47) 1) File f = new
Bjarne Strousjoup, but this is the
sort of answer that Sun will File("/","autoexec.bat");
proabably be looking for in the Objective 5.3) 2) DataInputStream d = new
exam. Questions have been DataInputStream(System.in);
asked in discussion forums if this 4) 12 3) OutputStreamWriter o =
type of question really comes up new
in the exam. I think this is OutputStreamWriter(System.o
As well as the binary OR objective
because some other mock exams ut);
this questions requires you to
do not contain any questions like understand the octal notation which
this. I assure you that this type means that the leading letter zero Option 4, with the
of question can come up in the (not the letter O)) means that the RandomAccess file will not
exam. These types of question first 1 indicates the number contains compile because the
are testing your understanding of one eight and nothing else. Thus this constructor must also be
the difference between the is-a calculation in decimal mean passed a mode parameter
and has-a relationship in class which must be either "r" or
design. "rw"
8|4
nswer 44) Answer 50)
To convert this to binary means
Objective 4.1) Objective 5.1)
52
1)o1=o2; variables outside the enclosing Answer 60)
method.
2)b=ob; Objective 7.3)
Answer 55)
4)o1=b;
2) Ensures only one thread at
Objective 7.2) a time may access a method or
object
Answer 51)
1) yield()
2) sleep Question 1: Given the
Objective 5.4) 4) stop() following class
definition:
4) 10020 Note, the methods stop and suspend class A {
have been deprecated with the Java2
In the call release, and you may get questions protected int i;
on the exam that expect you to know
another(v,i); this. Check out the Java2 Docs for an A(int i) {
explanation
this.i = i;
A reference to v is passed and
thus any changes will be intact Answer 56)
}
after this call.
Objective 10.1)
}
nswer 52)
1) addElement
Which of the following would
Objective 6.2) be a valid inner class for this
Answer 57) class?
1) public void amethod(String s,
int i){} Objective 4.1) Select all valid answers.
4) public void Amethod(int i,
String s) {} The import statement allows you to a)
use a class directly instead of fully
Overloaded methods are qualifying it with the full package
class B {
differentiated only on the name, adding more classess with the
number, type and order of import statement does not cause a
}
parameters, not on the return runtime performance overhad. I
type of the method or the names assure you this is true. An inner class
of the parameters. can be defined with the protected b)
modifier, though I am not certain
Answer 53) why you would want to do it. An class B extends A {
inner class can be defined with the
private modifier, try compiling some }
Objective 6.2)
sample code before emailing me to
ask about this. c)
4)Base b = new Base(10);
3)A inner class may under some class B {
circumstances be defined with the
Any call to this or super must be protected modifier B() {
the first line in a constructor. As 4) An interface cannot be
the method already has a call to instantiated System.out.println("i = " +
this, no more can be inserted.
i);
Answer 58)
}
Objective 4.6)
nswer 54) }
1) mousePressed(MouseEvent e){}
Objective 4.1) 4) componentAdded(ContainerEvent d)
e){}
1) System.out.println(s); class B {
4) System.out.println(iArgs); Answer 59)
class A {
A class within a method can only Objective 10.1)
see final variables of the }
enclosing method. However it the
1) iterator }
normal visibility rules apply for
2) isEmpty
3) toArray
53
e) this program will count from a) 4
startHere to endHere?
class A { b) 5
Select all valid answers.
} c) 6
a)
Question 2: What statements
d) 7
are true concerning Runnable a = new Runnable() {
the method notify()
that is used in e) 0
public void run() {
conjunction with
wait()? for (int i = startHere; i <= Question 5: Given the
endHere; i++) { following class:
Select all valid answers. class Counter {
System.out.println(i);
a) if there is more than one public static void
thread waiting on a condition, } main(String[] args) {
only the thread that has been
waiting the longest is notified } Thread t = new
Thread(new
}; CounterBehavior());
b) if there is more than one
thread waiting on a
t.start();
condition,there is no way to
predict which thread will be b) }
notifed
a implements Runnable { }
c) notify() is defined in the
Thread class public void run() { Which of the following is a
valid definition of
d) it is not strictly necessary to for (int i = startHere; i <= CounterBehavior that would
own the lock for the object you endHere; i++) { make Counter’s main() method
invoke notify() for count from 1 to 100, counting
System.out.println(i); once per second?
e) notify() should only be
}
invoked from within a while loop Select the one right answer.
}
Question 3: Given the a)This class is an inner class to
following class: }; Counter:
class Counter {

public int startHere = 1;


c) class CounterBehavior {
public int endHere = 100;
Thread a = new Thread() { for (int i = 1; i <= 100; i+
public static void main(String[] +);
args) { public void run() {
try {
new Counter().go(); for (int i = startHere; i <=
endHere; i++) { System.out.println(i);
}
System.out.println(i); Thread.sleep(1000);
void go() {
} } catch
// A (InterruptedException x) {}
}
Thread t = new Thread(a); }
};
t.start(); }
Question 4: What is written to
} the standard output given
the following statement:
} b) This class is an inner class
System.out.println(4 | 7);
to Counter:
What block of code can you Select the one right answer.
replace at line A above so that
54
class CounterBehavior InputStreamReader reader =
implements Runnable { private void method2() { new
InputStreamReader(stream,
public void run() { } "8859-8");

for (int i = 1; i <= 100; i+ } BufferedReader buffer = new


+); BufferedReader(reader);
}
try { s = buffer.readLine();
}
System.out.println(i); b)

Thread.sleep(1000);
InputStreamReader reader =
class D extends A {
new
} catch
InputStreamReader(stream);
(InterruptedException x) {} public float z;
BufferedReader buffer = new
} }
BufferedReader(reader);
}
s = buffer.readLine();
}
What can method2() access directly, c)
without a reference to another
instance?
InputStreamReader reader =
c) This class is a top-level class: new
InputStreamReader(myfile,
"8859-8");
Select all valid answers.
static class CounterBehavior BufferedReader buffer = new
implements Runnable { a) the variable x defined in A BufferedReader(reader);

public void run() { s = buffer.readLine();


b) the variable y defined in A
try { d)
c) method1 defined in B
for (int i = 1; i <= 100; i+
+) { InputStreamReader reader =
d) the variable z defined in D
new
System.out.println(i); InputStreamReader(myfile);
Question 7: You have an 8-bit file
using the character set BufferedReader buffer = new
Thread.sleep(1000);
defined by ISO 8859-8. BufferedReader(reader);
You are writing an
}
application to display this s = buffer.readLine();
file in a TextArea. The
} catch
local encoding is already
(InterruptedException x) {} e)
set to 8859-8. How can
you write a chunk of code
} FileReader reader = new
to read the first line from
this file? FileReader(myfile);
}
BufferedReader buffer = new
Question 6: Given the You have three variables accessible
BufferedReader(reader);
following class to you:
definition: s = buffer.readLine();
class A {  myfile is the name of the file
you want to read Question 8: How can you
public int x;  stream is an InputStream write a line of code
object associated with this for an applet’s init()
private int y; file method that
 s is a String object determines how
class B { wide the applet is?
Select all valid answers.
protected void method1() { Select all valid answers.

} a)
a) int width = this.getY();
class C {
55
b) int width = this.getSize().w; class B implements A { Question 13: Which Listener
int method1(int i) { } interface can you
c) int width = getSize(); int method2(int j) { } implement to be able
} to respond to the
d) int width = getSize().w; d) user hitting the
class B extends A { enter key after
e) int width = getWidth(); int method1(int i) { } typing into a
int method2(int j) { } TextField object?
Question 9: For a variable }
width font, how e) Question 14: What is
"wide" is a TextField class B implements A { written to the
created using the int method2(int j) { } standard output as
expression: int method1(int i) { } the result of
new TextField(20) } executing the
following
Question 11: Given the following statements?
Select the one right answer.
code: Boolean b1 = new
import java.awt.*; Boolean(true);
a) 20 times the average of all the
import java.awt.event.*; Boolean b2 = new
characters in the font used for
public class MyApplet extends Boolean(true);
this TextField object
java.applet.Applet { if (b1 == b2)
public void init() { if (b1.equals(b2))
b) 20 times the width of the Button b = new System.out.println("a");
letter M Button("Button1"); else
b.addMouseListener(new System.out.println("b");
c) 20 times the width of the ClickHandler()); else
letter a add(b); if (b1.equals(b2))
} System.out.println("c");
d) 20 inches class ClickHandler extends else
MouseAdapter { System.out.println("d");
public void
e) 20 picas mouseClicked(MouseEvent evt) { )a
// A
Question 10: Given this }
interface definition: b) b
}
interface A { }
c) c
int method1(int i); What line of code at A writes the
mouse’s horizontal location to the d) d
int method2(int j); standard output at the time of the
} event? Question 15: Which Listener
which of the following classes interfaces can you
implement this interface and is Fill in the blank. add to a TextArea
not abstract? object?
Question 12: Given the same
Select all valid answers. code as in question 10, a) TextListener
how can you write a line
a) of code at A that will place b) ActionListener
the Button object into a
class B implements A { variable named mybutton c) MouseMotionListener
that is already defined to
int method1() { } be a reference to a Button
object? d) MouseListener
int method2() { }
Fill in the blank. e) ComponentListener
}

b)

class B {

int method1(int i) { }

int method2(int j) { }

}
c)
56
Question 16: What appears in Which of the following questions are
the standard output if definitely true? System.out.println(myArg);
the method named
problem() in the code Select all valid answers. }
below throws an
instance of class }
a) This switch block is illegal,
Exception when the
because only integers can be used in
method named Select the one right answer.
the switch statement.
trythis() is invoked?
public void trythis() { a) This code compiles and
b) This switch block is fine.
try { displays 0 in the standard
System.out.println("1"); output when run.
problem(); c) This switch block is illegal,
} catch (RuntimeException x) because the default statement must
come last. b) This code compiles and
{
displays 1 in the standard
System.out.println("2");
output when run.
return; d) When this code runs, nothing is
} catch (Exception x) { written to the standard output.
System.out.println("3"); c) This code does not compile
return; because you cannot define a
e) When this code runs, the letter "a"
} finally { local variable named the same
is written to the standard output.
System.out.println("4"); as a static variable.
}
System.out.println("5"); uestion 19: What keyword must
d) This code does not compile
} appear in a method
because the local variable is
declaration (followed by
used before it is initialized.
the name of the
elect all valid answers. exception) when that
method might cause an Question 22: Which
a) "1" exception to be thrown declarations for the
and that method does not main() method in a
handle the exception? stand-alone program
b) "2"
are NOT valid?

c) "3" Question 20: Which statements


accurately describe the Select all valid answers.
following line of code?
d) "4"
a) public static void main()
Select all valid answers.
e) "5"
b) public static void
String[][] s = new String[10][]; main(String[] string)
Question 17: What is the type
of the Event object
a) This line of code is illegal. c) public static void
passed to the
main(String args)
mouseDragged()
method defined in a b) s is a two-dimensional array
class that implements containing 10 rows and 10 columns d) static public int
java.awt.event.Mouse main(String[] args)
MotionListener (that c) s is an array of 10 arrays.
is, what is the class e) static void main(String[]
name for the args)
d) Each element in s is set to ""
argument)?

e) Each element in s is uninitialized Question 23: Which of the


estion 18: Examine the following identifiers
following switch block: and must be initialized before it is
referenced. are ILLEGAL?
char mychar = 'c';

uestion 21: What will happen if Select all valid answers.


switch (mychar) {
you try to compile and run
the following class? a) #_pound
default:
class Test { b) _underscore
c) 5Interstate
case 'a':
static int myArg = 1; d) Interstate5
System.out.println("a"); break;

case 'b': public static void main(String[] Question 24: If the user
System.out.println("b"); break; args) { invokes a stand-
alone application by
} int myArg; typing:
java YourApp 1 2 3
57
and the main() method defines Question 27: To determine if you System.out.println(k);
its String[] parameter as args, can invoke
how can you access the number addContainerListener() Select the one right answer.
2 using args? for a component
referenced using a
a) 3
Fill in the blank. variable named c, which
expression(s) can you
evaluate that will give you b) 0
Question 25: Which interface
a true or false answer to
implementations can you add as
this questions? c) 3.2
listeners for a TextField object?

Select all valid answers. d) none of these


Select all valid answers.

a) c == Container Question 31: How can you


a) ActionListener
b) c.equals(Class.Container) use the String
c) c instanceof Container method indexOf() to
b) FocusListener d) c instanceof Component determine which
e) c implements Container position the letter 'C'
c) MouseMotionListener is in given this
Question 28: Write a statement String:
d) WindowListener for a constructor that String s = "ABCDE";
invokes the no-args,
default constructor in its
e) ContainerListener Write a complete statement in
superclass.
your answer, but you do not
Question 26: What must be have to assign the letter you
Question 29: What is written to
true for the retrieve to another variable.
the standard output given
RunHandler class so the following statement:
that instances of Question 32: Given that the
System.out.println(4 & 7);
RunHandler can be variable g references
used as written in the a valid Graphics
code below: Select the one right answer. object, what does
class Test { the following
a) 4 statement do?
public static void main(String[] g.fillRect(2, 3, 10, 20);
args) { b) 5
Select all valid answers.
Thread t = new Thread(new c) 6
RunHandler());
a) draw the outline of a
d) 7 rectangle in the current
t.start();
background color
} e) 0
b) draw the outline of a
} Question 30: What will the rectangle in the current
following block of code foreground color
Select all valid answers. write to the standard
output when it is c) fill in a rectangle using the
executed? current background color
a) RunHandler must implement
the java.lang.Runnable interface. int i = 3;
d) fill in a rectangle using the
int j = 0; current foreground color
b) RunHandler must extend the
Thread class.
double k = 3.2; e) fill in a rectangle in black
c) RunHandler must provide a if (i < k)
run() method declared as public Question 33: Describe the
and returning void. following applet.
if (i == j)
import java.applet.Applet;
d) RunHandler must provide an System.out.println(i); import java.awt.event.*;
init() method. import java.awt.*;
else public class MyApplet extends
Applet {
System.out.println(j); Button b1, b2;
public void init() {
else ActionListener a = new
ActionListener() {
58
public void f) changes the background color for c) this code runs but nothing
actionPerformed(ActionEvent the associated Component object appears in the standard output
evt) {
if (evt.getSource() == Question 35: What does the d) this code runs and
b1) { following program do "constructor" in the standard
when it is run with the output
b1.setEnabled(false); command:
b2.setEnabled(true);
java Mystery Mighty Mouse e) this code runs and writes
} else {
"null" in the standard output
b1.setEnabled(true);
class Mystery {
b2.setEnabled(false);
public static void main(String[] Question 37: What can you
}
args) { write at the
}
Changer c = new Changer(); comment //A in the
};
c.method(args); code below so that
b1 = new Button("1");
System.out.println(args[0] + " " this program writes
b1.addActionListener(a);
+ args[1]); the word "running"
add(b1);
} to the standard
b2 = new Button("2");
static class Changer { output?
b2.addActionListener(a);
void method(String[] s) {
add(b2); class RunTest implements
String temp = s[0];
} Runnable {
s[0] = s[1];
}
s[1] = temp;
public static void
}
lect all valid answers. main(String[] args) {
}
}
RunTest rt = new
a) Nothing appears in the applet
RunTest();
elect the one right answer.
b) One button appears in the Thread t =new Thread(rt);
applet but does nothing a) This program causes an
ArrayIndexOutOfBoundsException to //A
c) Two buttons appear in the be thrown
applet }
b) This program runs but does not
d) When the user clicks a button, write anything to the standard output public void run() {
nothing happens
c) This program writes "Mighty
System.out.println("running");
e) When the user clicks a button, Mouse" to the standard output
it becomes disabled
}
d) This program writes "Mouse
f) When a user clicks a button, Mighty" to the standard output void go() {
the other button becomes
enabled Question 36: What happens when start(1);
you try to compile and run
Question 34: The method the following program? }
setBackground() class Mystery {
defined for the String s; void start(int i) {
Graphics class: public static void main(String[]
args) { }
Select all valid answers. Mystery m = new Mystery();
m.go(); }

a) takes an integer value }


void Mystery() { Select all valid answers.
s = "constructor";
b) takes an instance of class
} a)
Color
void go() { System.out.println("running");
System.out.println(s);
c) takes an instance of a }
Component subclass
b) rt.start();
d) sets the drawing mode for the elect the one right answer.
associated Component object
a) this code will not compile
e) sets the drawing color for the c) rt.go();
associated Component object
b) this code compiles but throws an
exception at runtime
59
d) rt.start(1); Question 40: Construct an array
of 3 String objects setLayout(new
Question 38: What order can containing the strings "a", BorderLayout());
you place the "b", and "c" using the { }
following pieces of a notation. Call the String add("East", new
source file in so that by the variable name s. Button("hello"));
the source file will
compile without errors Question 41: What is the final }
or warnings? value of temp in this
//A sequence? Select the one right answer.
import java.applet.*; long temp = (int)3.9;
//B a) Nothing will appear in the
class Helper { temp %= 2; applet
}
//C a) 0 b) A button will appear in the
package myclasses;
applet set in the exact center
//D
b) 1
public class MyApplet extends
java.applet.Applet { c) A button will appear on the
c) 2 left side of the applet
}
d) 3 d) A button will appear on the
Select all valid answers. right side of the applet
e) 4
a) A, B, C, D e) A button will fill the entire
Select the one right answer. applet
b) A, C, B, D
Question 42: Analyze this line of Question 45: Choose all true
code: statements about
c) C, A, B, D
the paint() method
if (5 & 7 > 0 && 5 | 2) defined in the
d) C, A, D, B System.out.println("true"); Component class:

e) C, B, A, D Select the one right answer. Select all valid answers.

Question 39: Analyze these a) this line of code will not compile a) it is protected
two consequetive lines
of code: b) this code will compile but nothing b) it takes an instance of class
float f = 3.2; will appear in the standard output Graphics

int i = f; c) this code will compile and write c) it is static


the word "true" in the standard
Select all valid answers. output
d) it is invoked automatically
whenever you minimize and
a) this code would not compile Question 43: Create a List object then maximize a component,
that allows multiple such as a window
selections and displays 5
b) this code would compile and i
rows at a time.
would be set to 3 e) there is also a version that
takes an int
c) the second line could compile
if it were written instead as: Question 46: Given this
Start by writing: ActionListener:
int i = (byte)f; class HandleClick implements
List l = ActionListener {
d) the first line could compile if it
were written instead as: in your answer. public void
actionPerformed(ActionEvent
float f = 3.2F; fill in the blank. evt) {

// A
Question 44: What will the user
interface look like in an
}
applet given the following
init() method?
}
public void init() {
60
What line of code can you write System.out.println(a + b); public static void
at A that will make a component main(String[] args) {
referenced by c disappear from }
the display? new B();
}
ill in the blank. }
Select all valid answers.
class B {
Question 47: Analyze the
following code: a) You cannot invoke println()
B() {
class WhatHappens implements without passing it a String
Runnable { System.out.println(x);
b) Since a is private, no classes other
public static void main(String[] than First can access it }
args) {
c) Second cannot extend First }
Thread t = new Thread(this);
d) final is not a valid keyword for a }
t.start();
class
Select the one right answer.
}
Question 49: Analyze the
public void run() { following two classes. a) Class B tries to access a
class First { private variable defined in its
System.out.println("hi"); ouer class.
static int a = 3;
} b) Class A attempts to create
} an instance of B when there is
} no current instance of class A.

Select the one right answer. c) Class B’s constructor must


final class Second extends First { be public.
a) This program does not
void method() {
compile question 51: Analyze the
following code.
System.out.println(a);
b) This program compiles but void looper() {
nothing appears in the standard }
output int x = 0;
}
c) This program compiles and the one:
word "hi" appears in the Select the one right answer.
standard output, once while (x < 10) {

a) Class First compiles, but class two:


d) This program compiles and Second does not
the word "hi" appears
System.out.println(++x);
continuously in the standard
b) Class Second compiles, but class
output until the user hits control-
First does not if (x > 3)
c to stop the program

c) Neither class compiles break two;


Question 48: What is wrong
with the following }
code? d) Both classes compile, and if
method() is invoked, it writes 3 to }
final class First {
the standard output
private int a = 1; Select all valid answers.
e) Both classes compile, but if
int b = 2; method() is invoked, it throws an
exception a) This code compiles
}
Question 50: Why won’t the b) This code does not compile
following class compile?
class A { c) This method writes the
class Second extends First { number 0 to the standard
private int x; output
public void method() {
61
d) the numbers 1 and 2 to the int j = 0;
standard output Boolean b2 = new
float k = 3.2F; Boolean(true);
e) the number 3 to the standard
output long m = -3; Object obj1 = (Object)b1;

if (Math.ceil(i) < Math.floor(k)) Object obj2 = (Object)b2;


f) the number 4 to the standard
output
if (Math.abs(i) == m)

g) the numbers 5 through 9 to System.out.println(i); if (obj1 == obj2)


the standard output
else if (obj1.equals(obj2))
h) the number 10 to the
standard output System.out.println(j); System.out.println("a");

Question 52: What appears in else else


the standard output
when the method System.out.println(Math.abs(m) + System.out.println("b");
named testing is 1);
invoked? else

void testing() { if (obj1.equals(obj2))

one: Select the one right answer.


System.out.println("c");

two: a) 3 else

for (int i = 0; i < 3; i++) { System.out.println("d");


b) 0
three:
c) -3 Select the one right answer.
for (int j = 10; j < 30;
j+=10) { d) 4 a) a

System.out.println(i + j); e) none of these b) b

if (i > 2)
Question 54: The ISO code for c) c
the language you are
continue one;
interested in is 8859-5. d) d
Assume you have a
}
stream in a variable
Question 56: What will the
named mystream that’s
} user interface look
associated with a file
like in an applet
generated in this 8-bit
} given the following
character set. If the
init() method?
default conversion to
Select all valid answers. Unicode in your public void init() {
environment is for the
a) 10 and 20 encoding 8859-1, how can setLayout(new
you create a new instance BorderLayout());
b) 11 and 21 of InputStreamReader
that will perform the add(new Button("hello"));
conversion from ISO
c) 12 and 22 }
8859-5 to Unicode,
automatically? (Start by
d) 13 and 23 writing the keyword new Select the one right answer.
and do not add a
e) 30, 31, 32, 33 semicolon at the end.) a) Nothing will appear in the
applet
Question 53: What will the ill in the blank.
result be for the b) A button will appear in the
following block of Question 55: What is written to applet set in the exact center
code when it is the standard output as
executed? the result of executing the c) A button will appear in the
int i = 3; following statements? applet along the top and
Boolean b1 = new Boolean(true); centered horizontally
62
d) A button will appear in the top a) A try block must always be
left corner } followed by a catch block

e) A button will fill the entire } b) A try block can be followed


applet either by a catch block or a
Select the one right answer. finally block, or both
Question 57: What
expressions are true a) The instance variable i is set to 4 c) A catch block must always
concerning the be associated with a try block
following lines of b) The instance variable i is set to 2
code? d) A finally can never stand on
int[] arr = {1, 2, 3}; c) The instance variable i is set to 0 its own (that is, without being
associated with try block)
for (int i=0; i < 2; i++)
d) This code will not compile
e) None of these are true
arr[i] = 0;
Question 59: Which best
describes the user
Select all valid answers.
interface of an applet
given the following init()
a) arr[0] == 0 method:
public void init() { Question 21
What will happen if you
setLayout(new BorderLayout()); compile/run the following
b) arr[0] == 1
code?
add("North", new TextField(10));
1: public class Q21
add("Center", new Button("help")); 2: {
c) arr[1] == 1
3: int maxElements;
} 4:
5: void Q21()
Select all valid answers. 6: {
d) arr[2] == 0
7: maxElements =
100;
a) The TextField object will be placed
8:
at the top of the applet and will be
System.out.println(maxElemen
e) arr[3] == 0 10 columns wide
ts);
9: }
Question 58: What will b) The Button object will be centered 10:
happen if you try to in the applet and will be just large 11: Q21(int i)
compile and execute enough to contain the text "help" 12: {
B’s main() method?
13: maxElements = i;
class A { c) The Button object will be centered 14:
in the applet and will start at the left System.out.println(maxElemen
int i; edge of the applet, fit just under the ts);
TextField object above it, and extend 15: }
A(int i) { to the right and bottom edge of the 16:
applet 17: public static void
this.i = i * 2; main(String[] args)
d) The TextField object will be placed 18: {
} 19: Q21 a = new
along the top of the applet and will
stretch from the left edge to the right Q21();
} 20: Q21 b = new
edge
Q21(999);
21: }
e) The placement of the Button 22: }
class B extends A { object and the TextField object
depends on the overall size of the A) Prints 100 and 999.
public static void main(String[] applet. B) Prints 999 and 100.
args) { C) Compilation error at line
Question 60: Which of the 3, variable maxElements was
B b = new B(2); following statements not initialized.
about try, catch, and D) Compillation error at line
} finally are true? 19.

B(int i) { Answer
Select all valid answers.
System.out.println(i);
63
Question 22 What is the output for the Answer
What will happen if run the following lines of code?
following code? Question 28
1: System.out.println(" " +2 + What will happen if you
1: Boolean[] b1 = new 3); invoke the following method?
Boolean[10]; 2: System.out.println(2 + 3);
2: 3: System.out.println(2 + 3 +""); 1: public void check()
3: boolean[] b2 = new 4: System.out.println(2 + "" +3); 2: {
boolean[10]; 3:
4: System.out.println(Math.min(-
6: A) Compilation error at line 3 0.0,+0.0));
B) Prints 23, 5, 5 and 23. 4:
System.out.println("The value of C) Prints 5, 5, 5 and 23. System.out.println(Math.max(-
b1[1] = " +b1[1]); D) Prints 23, 5, 23 and 23. 0.0,+0.0));
7: 5:
Answer System.out.println(Math.min(-
System.out.println("The value of 0.0,+0.0) ==
b2[1] = " +b2[1]); Question 25 Math.max(0.0,+0.0));
The following declaration(as a 6: }
A) Prints "The value of b1[1] member variable) is legal.
= false" A) prints -0.0, +0.0 and
"The value of b2[1] = static final transient int false.
false". maxElements = 100; B) prints -0.0, +0.0 and
true.
B) Prints "The value of b1[1] A) True. C) prints 0.0, 0.0 and false.
= null" B) False. D) prints 0.0, 0.0 and true.
"The value of b2[1] =
null". Answer Answer

C) Prints "The value of b1[1] Question 26 Question 29


= null" What will happen if you What will happen if you
"The value of b2[1] = compile/run the following lines of compile/run this code?
false". code?
1: int i = 012;
D) Prints "The value of b1[1] 1: int[] iArray = new int[10]; 2: int j = 034;
= false" 2: 3: int k = 056;
"The value of b2[1] = 3: iArray.length = 15; 4: int l = 078;
null". 4: 5:
5: 6: System.out.println(i);
Answer System.out.println(iArray.length); 7: System.out.println(j);
8: System.out.println(k);
Question 23 A) Prints 10.
Which of the following are B) Prints 15. A) Prints 12,34 and 56.
valid array C) Compilation error, you can't B) Prints 24,68 and 112.
declarations/definitions? change the length of an array. C) Prints 10, 28 and 46.
D) Runtime exception at line 3. D) Compilation error.
1: int iArray1[10];
2: int iArray2[]; Answer Answer
3: int iArray3[] = new
int[10];
Question 27 Question 30
4: int iArray4[10] = new
What will happen if you When executed the following
int[10];
compile/run the folowing lines of line of code will print
5: int []iArray5 = new
code?
int[10];
6: int iArray6[] = new int[]; System.out.println(-1 *
1: Vector a = new Vector(); Double.NEGATIVE_INFINITY);
7: int iArray7[] = null;
2:
3: a.addElement(10); A) -Infinity
A) 1.
4: B) Infinity
B) 2.
5: C) NaN
C) 3.
System.out.println(a.elementAt(0)); D) -NaN
D) 4.
E) 5.
A) Prints 10. Answer
F) 6.
B) Prints 11.
G) 7.
C) Compilation error at line 3.
D) Prints some garbage.
Answer Question No 21

Question 24
64
D. Constructors should not D. Here integers are assinged by 14:
return any value. Java won't octal values. Octal numbers will 15: static Test t3 =
allow to indicate with void. contain digits from 0 to 7. new Test(3);
In this case void Q21() is an 8 is illegal digit for an octal 16:
ordinary method which has the value, so you get compilation error. 17: public static void
same name of the Class. main(String[] args)
Back to Question 29 18: {
Back to Question 21 19: Q12 Q = new
Question No 30 Q12();
Question No 22 B. Compile and see the result. 20: }
C. By default objects will be 21: }
initialized to null and primitives Question 11
to their corresponding default What will happen if you compile/run A) Test(1)
vaulues. the following code? Test(2)
The same rule applies to Test(3)
array of objects and primitves. 1: public class Q11
2: { B) Test(3)
Back to Question 22 3: static String str1 = "main Test(2)
method with String[] args"; Test(1)
Question No 23 4: static String str2 = "main
B,C,E and G. You can't specify method with int[] args"; C) Test(2)
the array dimension in type 5: Test(1)
specification(left hand side), 6: public static void Test(3)
so A and D are invalid. In main(String[] args)
line 6 the array dimension is 7: { D) Test(1)
missing(right hand side) so F is 8: Test(3)
invalid. System.out.println(str1); Test(2)
You can intialize an array 9: }
with null. so G is valid. 10: Answer
11: public static void
Back to Question 23 main(int[] args) Question 13
12: { What is the output of the
Question No 24 13: following code?
B. System.out.println(str2);
14: } 1: int i = 16;
Back to Question 24 15: } 2: int j = 17;
3:
Question No 25 A) Duplicate method main(), 4: System.out.println("i
A. compilation error at line 6. >> 1 = " + (i >> 1));
B) Duplicate method main(), 5: System.out.println("j
Back to Question 25 compilation error at line 11. >> 1 = " + (j >> 1));
C) Prints "main method with main
Question No 26 String[] args". A) Prints "i >> 1 = 8"
C. Once array is created then D) Prints "main method with main "j >> 1 = 8"
it is not possible to change the int[] args".
length of the array. B) Prints "i >> 1 = 7"
Answer "j >> 1 = 7"
Back to Question 26
Question 12 C) Prints "i >> 1 = 8"
Question No 27 What is the output of the following "j >> 1 = 9"
C. You can't add primitives to code?
Vector. Here 10 is int type D) Prints "i >> 1 = 7"
primitive. 1: class Test "j >> 1 = 8"
2: {
Back to Question 27 3: Test(int i) Q 1. What is the
4: { output of the following
Question No 28 5: StringBuffer sb1 = new
B. The order of floating/double System.out.println("Test(" +i +")"); StringBuffer("Amit");
values is 6: } StringBuffer sb2= new
-Infinity --> Negative 7: } StringBuffer("Amit");
Numbers/Fractions --> -0.0 --> 8: String ss1 = "Amit";
+0.0 --> Positive 9: public class Q12
Numbers/Fractions --> Infinity. 10: { System.out.println(sb1==sb2);
11: static Test t1 = new
Back to Question 28 Test(1); System.out.println(sb1.equals(
12: sb2));
Question No 29 13: Test t2 = new
Test(2);
65
27
System.out.println(sb1.equals(ss System.out.println(b1.paramString() a) Code will not compile.
1)); ); b) Code will compile but will
28 myFrame.add(myApplet); give a run time error.
System.out.println("Poddar".subs 29 myFrame.setVisible(true); c) Code will compile and no run
tring(3)); 30 time error.
Ans: myFrame.addWindowListener(new
a) false WindowAdapter(){ Correct answer is a). As you
false 31 public void can not override a method with
false windowClosing(WindowEvent e){ weaker access privileges
dar 32
b) false System.exit(0);}}); Q7. If from line no 14 keyword
true 33 } "public" is replaced with
false 34 } //End hello4 class. "protected", what will happen.
Poddar (Hint :paramString() method in
c) Compiler Error Q2. If you run the above program via java.awt.Button is a protected
d) true appletviewer ( defining a HTML file), method.(Assume line 26 is
true You see on screen. uncommented)
false a) Two buttons
dar b) One button with label as "BBB" a) Code will not compile.
c) One button with label as "My b) Code will compile but will
Correct Answer is a) ButtonNew" give a run time error.
d) One button with label as "My c) Code will compile and no run
***** Look carefully at code and Button" time error.
answer the following questions
( Q2 to Q8) Correct answer is b) Correct answer is c) . As you
1 import java.applet.Applet; can access a protected variable
2 import java.awt.*; Q3. In the above code if line 26 is in the same package.
3 import java.awt.event.*; uncommented and program runs as
4 public class hello4 extends standalone application Q8.If line no 26 is replaced
Applet { with Button b1 = new
5 public void init(){ a) Compile Error Button("PARAMBUTTON").(Hint
6 add(new b) Run time error :paramString() method in
myButton("BBB")); c) It will print the the label as java.awt.Button is a protected
7 } PARAMBUTTON for button b1 method.(Assume line 26 is
8 public void paint(Graphics uncommented)
screen) { Correct answer is c)
9 } a) Code will not compile.
10 class myButton extends Q4 In the code if you compile as b) Code will compile but will
Button{ "javac hello4.java" following files will give a run time error.
11 myButton(String be generated. c) Code will compile and no run
label){ a) hello4.class, time error.
12 super(label); myButton.class,hello41.class
13 } b)hello4.class, Correct answer is a) Because
14 public String hello4$myButton.class,hello4$1.class protected variables and
paramString(){ c)hello4.clas,hello4$myButton.class methods can not be accssed in
15 return another package directly. They
super.paramString(); Correct answer is b) can only be accessed if the
16 } class is subclassed and
17 } Q5. If above program is run as a instance of subclass is used.
18 public static void standalone application. How many
main(String[] args){ buttons will be displayed Q9. What is the output of
19 Frame myFrame = new following if the return value is
Frame( a) Two buttons "the value 0 if the argument
20 "Copyright b) One button with label as "BBB" string is equal to this string; a
Amit"); c) One button with label as "My value less than 0 if this string
21 ButtonNew" is lexicographically less than
myFrame.setSize(300,100); d) One button with label as "My the string argument; and a
22 Applet myApplet = new Button" value greater than 0 if this
hello4(); string is lexicographically
23 Button b = new correct answer is C) greater than the string
Button("My Button"); argument" (Assuming written
24 myApplet.add(b); Q6. If from line no 14 keyword inside main)
25 b.setLabel(b.getLabel() "public" is removed, what will
+"New"); happen.( Hint :paramString() String s5 = "AMIT";
26 // myButton b1 =(new method in java.awt.Button is a String s6 = "amit";
hello4()).new protected method. (Assume line 26 is System.out.println(s5.compare
myButton("PARAMBUTTON"); uncommented) To(s6));
66
System.out.println(s6.compareTo false myFrame.add(cb1);
(s5)); true myFrame.add(cb2);
System.out.println(s6.compareTo d) arit myFrame.add(cb3);
(s6)); amit a) cb1
true b) cb2,cb1
Ans true c) cb1,cb2,cb3
a> -32 Correct answer is a) s3==s4 is true d) cb3
32 because java points both s3 and s4
0 to same memory location in string Correct Answer is d) As in a
b> 32 pool CheckboxGroup only one can
32 be selected
0 Q12) Which one does not extend
c> 32 java.lang.Number Q16) Which checkbox will be
-32 1)Integer selected in the following code (
0 2)Boolean Assume with main and added
d> 0 3)Character to a Frame)
0 4)Long Frame myFrame = new
0 5)Short Frame("Test");
CheckboxGroup cbg =
Correct Answer is a) Correct answer is 2) and 3) new CheckboxGroup();
Checkbox cb1 = new
Q 10) What is the output Q13) Which one does not have a Checkbox("First",true,cbg);
(Assuming written inside main) valueOf(String) method Checkbox cb2 = new
String s1 = new 1)Integer Checkbox("Scond",true,cbg);
String("amit"); 2)Boolean Checkbox cb3 = new
String s2 = s1.replace('m','i'); 3)Character Checkbox("THird",true,cbg);
s1.concat("Poddar"); 4)Long myFrame.add(cb1);
System.out.println(s1); 5)Short myFrame.add(cb2);
Correct answer is 3) myFrame.add(cb3);
System.out.println((s1+s2).char a) cb1
At(5)); Q.14) What is the output of following b) cb2,cb1
(Assuming written inside main) c) cb1,cb2,cb3
a) Compile error String s1 = "Amit"; d) cb3
b) amitPoddar String s2 = "Amit";
o String s3 = new String("abcd"); Correct Answer is d) As in a
c) amitPoddar String s4 = new String("abcd"); CheckboxGroup only one can
i System.out.println(s1.equals(s2)); be selected
d) amit System.out.println((s1==s2));
i System.out.println(s3.equals(s4)); Q17) What will be the output
System.out.println((s3==s4)); of line 5
Correct answer is d)As String is a) true 1 Choice c1 = new Choice();
imutable.so s1 is always "amit". true 2 c1.add("First");
and s2 is "aiit". true 3 c1.addItem("Second");
false 4 c1.add("Third");
Q 11) What is the output b) true 5
(Assuming written inside main) true System.out.println(c1.getItem
String s1 = new true Count());
String("amit"); true a) 1
c) true b) 2
System.out.println(s1.replace('m' false c) 3
,'r')); true d) None of the above
System.out.println(s1); false
String s3="arit"; Correct answer is a) Correct Answer is c)
String s4="arit";
String s2 = s1.replace('m','r'); Q15. Which checkbox will be selected Q18) What will be the order of
System.out.println(s2==s3); in the following code ( Assume with four items added
System.out.println(s3==s4); main and added to a Frame) Choice c1 = new Choice();
Frame myFrame = new c1.add("First");
a) arit Frame("Test"); c1.addItem("Second");
amit CheckboxGroup cbg = new c1.add("Third");
false CheckboxGroup(); c1.insert("Lastadded",2);
true Checkbox cb1 = new
b) arit Checkbox("First",true,cbg); System.out.println(c1.getItem
arit Checkbox cb2 = new Count());
false Checkbox("Scond",true,cbg); a) First,Second,Third,Fourth
true Checkbox cb3 = new b)
c) amit Checkbox("THird",false,cbg); First,Second,Lastadded,Third
amit cbg.setSelectedCheckbox(cb3);
67
c) Round f7 is 5
Lastadded,First,Second,Third correct answer is a),b),c)
Correct answer is b)
Correct ANswer is b) Q23)java.awt.Component class
method getLocation() returns Point
(containg x and y cordinate).What Q26. Given
Q19) Answer based on following does this x and y specify Integer.MIN_VALUE =
code -2147483648
1 Choice c1 = new Choice(); a) Specify the postion of components Integer.MAX_VALUE =
2 c1.add("First"); lower-left component in the 2147483647
3 c1.addItem("Second"); coordinate space of the component's
4 c1.add("Third"); parent. What is the output of following
5 b) Specify the postion of components
c1.insert("Lastadded",1000); upper-left component in the {
6 coordinate space of the component's float f4 = Integer.MIN_VALUE;
System.out.println(c1.getItemCo parent. float f5 = Integer.MAX_VALUE;
unt()); c) Specify the postion of components float f7 = -2147483655f;
upper-left component in the System.out.println("Round f4
a) Compile time error coordinate space of the screen. is " + Math.round(f4));
b) Run time error at line 5 System.out.println("Round f5
c) No error and line 6 will print correct answer is b) is " + Math.round(f5));
1000 System.out.println("Round f7
d) No error and line 6 will print Q24. Q. What will be the output of is " + Math.round(f7));
4 follwing }
{
Correct ANswer is d) double d1 = -0.5d; a)Round f4 is -2147483648
System.out.println("Ceil for d1 " + Round f5 is 2147483647
Q20) Which one of the following Math.ceil(d1)); Round f7 is -2147483648
does not extends System.out.println("Floor for d1 "
java.awt.Component +Math.floor(d1)); b)Round f4 is -2147483648
} Round f5 is 2147483647
a) CheckBox Round f7 is -2147483655
b) Canvas Answers:
c) CheckbocGroup a) Ceil for d1 0 correct answer is a)
d) Label Floor for d1 -1; //Reason If the argument is
b) Ceil for d1 0 negative infinity or any value
Correct answer is c) Floor for d1 -1.0; less than or equal to the value
c) Ceil for d1 0.0 of Integer.MIN_VALUE, the
Q21) What is default layout Floor for d1 -1.0; result is
manager for panels and applets? d) Ceil for d1 -0.0 equal to the value of
a) Flowlayout Floor for d1 -1.0; Integer.MIN_VALUE.
b) Gridlayout If the argument is positive
c) BorderLayout correct answer is d) as 0.0 is treated infinity or any value greater
differently from -0.0 than or equal to the value of
Correct answer is a) Integer.MAX_VALUE, the result
Q25. What is the output of following is
Q22) For awt components which { equal to the value of
of the following statements are float f4 = -5.5f; Integer.MAX_VALUE. // From
true? float f5 = 5.5f; JDK api documentation
float f6 = -5.49f;
a) If a component is not float f7 = 5.49f; Q27)
explicitly assigned a font, it System.out.println("Round f4 is " + 1 Boolean b1 = new
usese the same font that it Math.round(f4)); Boolean("TRUE");
container uses. System.out.println("Round f5 is " + 2 Boolean b2 = new
b) If a component is not Math.round(f5)); Boolean("true");
explicitly assigned a foreground System.out.println("Round f6 is " + 3 Boolean b3 = new
color , it usese the same Math.round(f6)); Boolean("JUNK");
foreground color that it System.out.println("Round f7 is " + 4 System.out.println("" + b1
container uses. Math.round(f7)); + b2 + b3);
c) If a component is not explicitly }
assigned a backround color , it a)Round f4 is -6 a) Comiler error
usese the same background color Round f5 is 6 b) RunTime error
that it container uses. Round f6 is -5 c)truetruefalse
d) If a component is not Round f7 is 5 d)truetruetrue
explicitly assigned a layout
manager , it usese the same b)Round f4 is -5 Correct answer is c)
layout manager that it container Round f5 is 6
uses. Round f6 is -5
68
Q 28) In the above question if a) true public static void
line 4 is changed to true main(String args[]){
b) false Frame f = new
System.out.println(b1+b2+b3); false Frame("Visual");
The output is c) true f.setSize(300,300);
a) Compile time error false f.setVisible(true);
b) Run time error d) false Point p =
c) truetruefalse true f.getLocation();
d) truetruetrue System.out.println("x is
Correct answer is d) " + p.x);
Correct answer is a) As there is System.out.println("y is
no method to support Boolean + Q32) Which one of the following " + p.y);
Boolean always honors the components's }
Boolean b1 = new preferred size.
Boolean("TRUE"); a) FlowLayout a) x is 300
Think b) GridLayout y is 300
----->System.out.println(b1); // c) BorderLayout b) x is 0
Is this valid or not? y is 0
Correct answer is a) c) x is 0
Q 29. What is the output y is 300
{ Q33) Look at the following code
Float f1 = new Float("4.4e99f"); import java.awt.*; correct answer is b) Because
Float f2 = new Float("-4.4e99f"); public class visual extends postion is always relative to
Double d1 = new java.applet.Applet{ parent container and in this
Double("4.4e99"); static Button b = new case Frame f is the
System.out.println(f1); Button("TEST"); topemost container
System.out.println(f2); public void init(){
System.out.println(d1); add(b); Q36) Which one of the
} } following always ignores the
public static void main(String components's preferred size.
a) Runtime error args[]){ a) FlowLayout
b) Infinity Frame f = new b) GridLayout
-Infinity Frame("Visual"); c) BorderLayout
4.4E99 f.setSize(300,300);
c) Infinity f.add(b); Correct answer is b)
-Infinity f.setVisible(true);
Infinity } Q37) Consider a directory
d) 4.4E99 } structure like this (NT or 95)
-4.4E99 C:\JAVA\12345.msg --FILE
4.4E99 What will happen if above code is run \dir1\IO.class --
as a standalone application IO.class is under dir1
Correct answer is b)
a) Displays an empty frame Consider the following code
b) Displays a frame with a button
Q30 Q. Which of the following covering the entire frame import java.io.*;
wrapper classes can not c) Displays a frame with a button public class IO {
take a "String" in constructor large enough to accomodate its label. public static void
main(String args[]) {
1) Boolean Correct answer is b) Reason- Frame File f = new
2) Integer uses Border Layout which places the File("..\\12345.msg");
3) Long button to CENTRE try{
4) Character (By default) and ignores Button's
5) Byte preferred size. System.out.println(f.getCanoni
6) Short calPath());
Q34 If the code in Q33 is compiled
correct answer is 4) and run via appletviewer what will System.out.println(f.getAbsolut
happen ePath());
Q31. What is the output of a) Displays an empty applet }catch(IOException e)
following b) Displays a applet with a button {
Double d2 = new Double("- covering the entire frame
5.5"); c) Displays a applet with a button System.out.println(e);
Double d3 = new Double("- large enough to accomodate its label. }
5.5"); }
System.out.println(d2==d3); Correct answer is c) Reason- Applet }
uses FlowLayout which honors
System.out.println(d2.equals(d3) Button's preferred size. What will be the output of
); running "java IO" from
Q35. What is the output C:\java\dir1
69
a) C:\java\12345.msg true
C:\java\dir1\..\12345.msg import java.io.*; 12345.msg
public class IO { false
b) C:\java\dir1\12345.msg public static void false
C:\java\dir1\..\12345.msg main(String args[]) {
File f = new correct answer is d)
c) C:\java\dir1\..\12345.msg File("12345.msg");
C:\java\dir1\..\12345.msg String arr[] = f.list(); Q42) If in question no 41 the
line
correct answer is a) as System.out.println(arr.length); File f1 = new
getCanonicalPath Returns the } File("\\12345.msg"); is
canonical form of this File } replaced with File f1 = new
object's pathname. The precise File("12345.msg");
definition of canonical form is a) Compiler error as 12345.msg is a What will be the output
system-dependent, but it usually file not a directory c) 12345.msg
specifies an absolute pathname b) java.lang.NullPointerException at null
in which all relative references run time false
and references to the current c) No error , but nothing will be 12345.msg
user directory have been printed on screen true
completely resolved. true
WHERE AS Correct ansewer is b)
getAbsolutePath Returns the
absolute pathname of the file Q41) What will be the output
represented by this object. If this Consider a directory structure like
object represents an absolute this (NT or 95) Correct answer is c)
pathname, then return the C:\JAVA\12345.msg --FILE
pathname. Otherwise, return a
pathname that is a concatenation import java.io.*;
of the current user directory, the public class IO {
Location: ... > Declarations
separator character, and the public static void main(String
and Access Control > Objective
pathname of this file object. args[]) {
1.1 > Item 1
File f1 = new
-----------------------------------
File("\\12345.msg");
-----
Q 38) Suppose we copy IO.class
Click the Exhibit button.
from C:\java\dir1 to c:\java System.out.println(f1.getPath());
Which two lines of code will
What will be the output of
compile correctly? (Choose
running "java IO" from C:\java. System.out.println(f1.getParent());
two.)
a) C:\java\12345.msg
1. class CharArray2 {
C:\java\..\12345.msg System.out.println(f1.isAbsolute());
2. public static void
main( String [] args) {
b) C:\12345.msg System.out.println(f1.getName());
3. char b = 'b';
C:\java\..\12345.msg System.out.println(f1.exists());
4. char c = 'C';
System.out.println(f1.isFile());
5. char [] c1 = {'a', 'b',
c) C:\java\..\12345.msg }
'c'};
C:\java\\..\12345.msg }
6. char [] c2 = {'a', b , 'c'};
7. char [] c3 = ('a', 'b', 'c');
correct answer is b) a) \12345.msg
8. char [] c4 = [3];
\
9. char [] c5 = [3] {'a', 'b',
Q39) Which one of the following true
'c'};
methods of java.io.File throws 12345.msg
10. char [] c6 = [] {'a', 'b',
IOException and why true
c};
true
11. }
a) getCanonicalPath and
12. }
getAbsolutePath both require b) \12345.msg
A line 5
filesystem queries. \
B line 6
b) Only getCannonicalPath as it true
C line 7
require filesystem queries. \12345.msg
D line 8
c) Only getAbsolutePath as it false
E line 9
require filesystem queries. false
F line 10
Answer:
Correct answer is b) c) 12345.msg
Options A and B are the correct
\
answers. This question
Q40) What will be the output if true
explores a Java syntax
Consider a directory structure 12345.msg
shortcut. A and B represent
like this (NT or 95) false
acceptable syntax to declare,
C:\JAVA\12345.msg --FILE false
construct, and initialize an
\dir1\IO.class -- IO.class d) \12345.msg
array in a single line of code.
is under dir1 \
70
Location: ... > Declarations and 8. XXX xxx = new XXX(); E There is no default
Access Control > Objective 1.1 > 9. constructor for Pizza
Item 2 System.out.println(xxx.doStuff(42)); Answer:
------------------------------------- 10. } Option B is the correct answer.
--Click the Exhibit button. 11. } The compiler creates a default
1. class Test{ constructor for Pizza, with
2. public static void What will be the result? default access (matching the
main( String [] args) { A 6 access of the class), and a no-
3. int [] y; B 7 arg call to super().
4. int [] z = new int [] {1, 2, C 42
3}; D Compilation fails Location: ... > Declarations
5. y = z; E An exception is thrown at runtime and Access Control > Objective
6. z[1] = 7; Answer: 1.4 > Item 1
7. for (int x= 0;x<3; x++) { Option D is the correct answer. The -----------------------------------
8. System.out.print(" y[" compiler will notice that in Line 3 the -----
+ x + "] = " + y[x]); code is declaring a static variable, Click the Exhibit button to
9. } but it's in a local method, which is view the code.
10. } not legal. If several instances of XXX 1. class XL {
11. } were instantiated it would be 2. public long doMath() {
impossible to know which instance 3. return 343L;
What is the result? the static should belong to. 4. }
A y[0] = 0 y[1] = 1 y[2] = 2 5. }
B y[0] = 7 y[1] = 2 y[2] = 3 Location: ... > Declarations and 6.
C y[0] = 1 y[1] = 7 y[2] = 3 Access Control > Objective 1.3 > 7. class L extends XL {
D y[0] = 1 y[1] = 2 y[2] = 3 Item 1 8.
E Compilation fails ---------------------------------------- 9. }
F An exception is thrown at
runtime Click the Exhibit button. Which two methods inserted at
Answer: 1. class Foo { line 8, will not compile?
Option C is the correct answer. y 2. Foo(String s) { } (Choose two.)
and z are reference variables. 3. } a public void doMath() { }
Line 5 assigns y to refer to the 4. class Bar extends Foo { } B public void doMath(int i)
same array as z, there is still {}
only one array (however there Which statement is true? C public int doMath() { return
are two array references). When A Class Bar will not compile 343 }
line 6 executes, it changes a B Class Bar has a public constructor D public long doMath(int i)
value in the only array there is, C Class Bar's constructor invokes { return 343 }
(the one both y and z refer to). super() answer:
Therefore when the array is D Class Foo's constructor does not Options A and C are the correct
accessed via y, the updated invoke super() answers. A and C represent an
value is displayed. answer: illegal override of the class XL
ocation: ... > Declarations and Option A is the correct answer. The doMath() method. Because the
Access Control > Objective 1.2 > compiler attempts to create a default arguments have not changed,
Item 1 constructor for class Bar, because the return type cannot change.
------------------------------------- Bar has not defined any constructors. Location: ... > Declarations
--------Which declaration ensures The class Bar constructor will include and Access Control > Objective
that a class cannot be a call to super(). Since class Foo 1.4 > Item 2
subclassed? does not have a no-arg constructor, -----------------------------------
A abstract class MyClass { } class Bar will not compile because ---------- Click the Exhibit
B final public class MyClass { } the default constructor the compiler button to view the code.
C final abstract class MyClass is attempting to build includes a call 1. class Test {
{} to super(), and there is no matching 2. public short doStuff(int i)
D static private class MyClass no-arg constructor in class Foo. { return 27; }
{} 3. }
E static protected class MyClass Location: ... > Declarations and 4.
{} Access Control > Objective 1.3 > 5. public class SubTest extends
Answer: Item 2 Test {
Option B is the correct answer. --------------------------------------- 6. public int doStuff(int x)
The final modifier insures that a Given: { return 30; }
class can not be subclassed. 1. class Pizza { } 7.
Q31. class XXX { Which of these represents the 8. public static void
2. long doStuff (int input) { functionality of the default main(String [] args) {
3. static long x = 7; constructor for Pizza? 9. Test t = new Test();
4. return (long) input / x; A Pizza() 10. SubTest s = new
5. } B Pizza() {super();} SubTest();
6. C public void Pizza() 11. int t1 = t.doStuff(30);
7. public static void main(String D public Pizza() {super();} 12. int s1 = s.doStuff(27);
[] args) {
71
13. System.out.println( t1 + " 6. else { E 26 26
" + s1); 7. System.out.print("false "); Answer:
14. } 8. } Option A is the correct answer.
15. } 9. } The while statement on line 14
increments x before doing the
What is the result? What is the result? comparison test. The break
A 27 30 A true true true true true true statement is never reached.
B 30 27 B true false true false true false
C 27 27 C false true false true false true Location: ... > Flow Control,
D 30 30 D false false false false false false Assertions, and Exception
E Compilation fails E Compilation fails Handling > Objective 2.3 >
F An exception is thrown at F An exception is thrown at runtime Item 1
runtime Answer: -----------------------------------
Answer: Option E is the correct answer. Line -----
Option E is the correct answer. three is illegal, it should probably Which two statements are
Line 6 is an illegal override of the read if (toggle == 1) {. true? (Choose two.)
doStuff() method in class Test. A catch(Foo f) can catch Foo
Location: ... > Flow Control, or any of its superclasses
Location: ... > Flow Control, Assertions, and Exception Handling > B If you throw an Error, it
Assertions, and Exception Objective 2.2 > Item 1 does not need to be enclosed
Handling > Objective 2.1 > Item ----------------------------------- in a try block
1 Click the Exhibit button to view the C Any statement that can
------------------------------------- code. throw an Exception must be
--- 7. int x,y; enclosed in a try block
Click the Exhibit button to view 8. next: for(x = 5, y = 1 ; ; ) { D An overriding method must
the code. 9. --x; declare any Exceptions
1. for (int x = 3; x > = 0; x--) { 10. for ( ; x > -1 ; y++) { declared by the overridden
2. switch (x - 1) { 11. if ( x < y ) { method
3. case 0: 12. break next; E An overriding method can
System.out.print("foo "); 13. } throw a superclass of the
4. case 1: 14. } Exception declared by the
System.out.print("bar "); 15. } overridden method
5. case 2: 16. System.out.println(x + " " + y); F An overriding method is
System.out.print("baz "); What is the result? permitted to throw a
6. case 3: A 23 RuntimeException, even if it
System.out.print("foo "); B 34 has not been declared by the
7. } C 45 overridden method.
8. } D 56 Answer:
E Compilation fails Options B and F are the correct
What is the result? F An exception is thrown at runtime answers. Overriding methods
A baz bar foo nswer: are not allowed to throw new
B foo baz bar foo Option C is the correct answer. The or broader checked exceptions.
C baz bar foo bar foo foo variable x is decremented once, in A checked exception is any
D baz foo bar baz foo foo bar line 9, then the program loops exception extending from class
baz foo through the inner for loop, Exception, but not extending
E Compilation fails incrementing y until x < y, at which from RuntimeException. Errors
F An exception is thrown at point y equals 5 and the break is do not need to be enclosed in
runtime executed. try blocks.
answer:
Option D is the correct answer. Location: ... > Flow Control, Location: ... > Flow Control,
As the switch expression iterates Assertions, and Exception Handling > Assertions, and Exception
from 2 to -1 the cases start at 2, Objective 2.2 > Item 2 Handling > Objective 2.4 >
1, and 0 and fall through. ----------------------------------------- Item 1
---- Click the Exhibit button to view -----------------------------------
Location: ... > Flow Control, the code. -----
Assertions, and Exception 13. long x = 20, y = 30; Click the Exhibit button to
Handling > Objective 2.1 > Item 14. while ( ++x < = y ) { view the code.
2 15. --y; 1. public class Test243 {
------------------------------------- 16. if ( x > y ) { 2. public static void main
-- 17. break; (String [] args) {
Click the Exhibit button to view 18. } 3. try {
the code. 19. } 4. String s = "two";
1. for (int toggle = 0, y = 0; y < 20. System.out.print(x + " " + y); 5. int i =
6; y++ ) { What is the result? Integer.parseInt(s);
2. toggle = y % 2; A 26 25 6. System.out.print("i =
3. if (toggle) { B 25 25 " + i);
4. System.out.print("true "); C 25 24 7. } catch (Exception ex) {
5. } D 25 26
72
8. System.out.print(" 16. } Which two statements are
Exception "); 17. } true? (Choose two.)
9. } A The -ae flag tells the VM to
catch(NumberFormatException What is the result? (Choose one) enable assertions
exc) { A three B The -ea flag tells the
10. System.out.print(" B two three compiler to enable assertions
NumberFormatException "); C three four C The -assert flag tells the VM
11. } finally { D two three four to enable assertions
12. System.out.print(" E one two three four D The -esa flag tells the VM
finally "); F Compilation fails to enable some assertions
13. } Answer: E The -assertions flag tells
14. System.out.print(" done Option D is the correct answer. the compiler to enable
"); Method foo() throws a assertions
15. } RuntimeException, which does not F The -enableassertions flag
16. } need to be declared. When the tells the VM to enable
What is the result? exception is thrown, the catch and assertions
A Exception finally finally blocks run, and then the Answer:
B i = two finally done main() method runs to completion Options D and F are the correct
C Exception finally done (printing four at the end). answers. The -esa flag means
D NumberFormatException enable system assertions.
finally Location: ... > Flow Control,
E NumberFormatException Assertions, and Exception Handling > ocation: ... > Garbage
finally done Objective 2.5 > Item 1 Collection > Objective 3.1 >
F Compilation fails ---------------------------------------- Item 1
-----------------------------------
Answer: ----------
Option F is the correct answer. Which two fragments are examples which two statements are true
The NumberFormatException will of inappropriate uses of assertions? about the garbage collection
be caught by the Exception (Choose two.) system? (Choose two.)
catch. The compiler recognizes A assert (!(foo == null));
that the second catch can never foo.go();
be reached. You must always put B public void method(boolean b) { A Calling Runtime.gc() will
the catch blocks in order going assert (b); reclaim memory.
from most specific to broadest. If C if (x > y) { B It guarantees that
the exceptions are siblings (i.e. z = x; programs will not have
one does not extend from the } else { memory leaks
other), then the order does not assert (x < 4); C Objects will never be
matter. } collected as long as they are
D private void test(int z) { accessible from live threads.
Location: ... > Flow Control, assert (f.setSize(z) > 5); D Objects that have finalize()
Assertions, and Exception } methods always have their
Handling > Objective 2.4 > Item E public int methodA(int x) { finalize() methods called before
2 assert (s > 3); the program ends.
------------------------------------- } E If object 'A' has at least one
------------------------------------- Answer: other object with a reference
------ Options B and D are the correct to it, then object 'A' will not be
Click the Exhibit button to view answers. B's violation is checking an garbage collected.
the code. argument of a public method. D's F Objects instantiated within
1. public class Test244 { violation is to allow the assert to a method and referenced only
2. public static void main (String have side effects, in this case by by a local variable are created
[] args) { calling a setter method on a in the garbage collectible heap.
3. try { reference. E is an appropriate use of
4. foo(); an assertion because it is not nswer:
5. System.out.print(" one checking the argument of a public Options C and F are the correct
"); method. answers. C is correct because
6. } catch(Exception e) { an object accessible from a live
7. System.out.print(" two References: thread may yet be called by
"); http://java.sun.com/j2se/1.4/docs/g the JVM. F is correct because
8. } finally { uide/lang/assert.html#usage- all objects are created in the
9. System.out.print(" three conditions garbage collectible heap.
");
10. } Location: ... > Garbage
11. System.out.print(" four "); Collection > Objective 3.2 >
12. } Location: ... > Flow Control, Item 1
13. Assertions, and Exception Handling >
14. public static void foo() { Objective 2.6 > Item 1 -----------------------------------
15. throw new ------------------------------------ -----
RuntimeException();
73
Click the Exhibit button to view C after line 11 15. public static void
the code. D never in this code main(String args [] ) {
1. class Test { Answer: 16. WeakHash wh = new
2. public static void Option D is the correct answer. The WeakHash();
main(String [] args) { last reference to clover (da[1]), is 17. }
3. Test2 t2 = new Test2(); never nulled. 18. }
4. Test2 t3;
5. t3 = t2.m1(); Location: ... > Language Location: ... > Language
6. t2 = t2.linker(t2,t3); Fundamentals > Objective 4.1 > Fundamentals > Objective 4.1
7. t2 = null; Item 1 > Item 2
8. t3 = null; ----------------------------------------- -----------------------------------
9. } Click the Exhibit button to view the -----
10. } code. Click the Exhibit button to
11. 1. package com.abc.package1; view the code.
12. class Test2 { 2. import java.util.*; 1.
13. Test2 link; 3. public class WeakHash extends 2. public class NewCollections
14. Test2 m1() { WeakHashMap { {
15. Test2 x = new Test2(); 4. int x = 5; 3. public static void
16. return x; 5. Object getDuplicate(Object key) main(String [] args) {
17. } { 4. java.util.WeakHashMap
18. Test2 linker(Test2 z1, 6. return null; hm = new
Test2 z2) { 7. } java.util.WeakHashMap();
19. z1.link = z2; 8. } 5. Object o1 = null;
20. z2.link = z1; 9. 6. o1 = hm.put(o1, o1);
21. return z1; 10. private class NewWeakHash 7. }
22. } extends WeakHash { 8. }
23. } 11. public NewWeakHash() {
12. int x = 7; Which statement must be
Which statement is true? 13. } added at line 1 to allow this
14. code to compile?
15. public static void main(String A import java.util.*;
A After line 8 no objects can be args [] ) { B no statement is required
garbage collected. 16. WeakHash wh = new C import
B After line 7 one object can be WeakHash(); java.util.WeakHashMap;
garbage collected. 17. } D include
C After line 7 no objects can be 18. } java.util.WeakHashMap;
garbage collected.
D After line 6 at least one What is the result? nswer:
object has more than two A Compilation succeeds Option B is the correct answer.
references B Compilation fails because of an When a fully qualified name is
E The z1 and z2 references error on line 6 used, you don't have to import
must be nulled to make any C Compilation fails because of an the classes or packages.
objects eligible for garbage error on line 10
collection. D Compilation fails because of an Location: ... > Language
Answer: error on line 16 Fundamentals > Objective 4.2
Option C is the correct answer. E An exception is thrown at runtime > Item 1
After line 7 the t3 reference is Answer: -----------------------------------
still valid and because of the link Option C is the correct answer. ------
variables both of the Test2 Classes cannot be declared private.
objects are still accessible. Which two are valid method
1. package com.abc.package1; signatures in an interface?
Location: ... > Garbage 2. import java.util.*; (Choose two.)
Collection > Objective 3.3 > 3. public class WeakHash extends A short doShort();
Item 1 WeakHashMap { B static char doChar();
------------------------------------- 4. int x = 5; C protected byte doByte();
---- 5. Object getDuplicate(Object key) D public boolean
Click the Exhibit button to view { doBoolean(int x);
the code. 6. return null; E final public String
7. Dog [] da = new Dog[2]; 7. } doString(int x);
8. Dog clover = new Dog(); 8. } Answer:
9. da[1] = clover; 9. Options A and D are the
10. clover = null; 10. private class NewWeakHash correct answers. A is correct
11. Dog fido = new Dog(); extends WeakHash { because interface methods are
12. Dog spot = new Dog(); 11. public NewWeakHash() { implicitly public. D is correct
When is the clover object 12. int x = 7; because interface can be
eligible for garbage collection? 13. } declared public even though
A after line 9 14. they are so implicitly.
B after line 10
74
Location: ... > Language name as the class, but having no 12. System.out.println(" "
Fundamentals > Objective 4.3 > return type. + y[z]);
Item 1 13. }
------------------------------------- Location: ... > Language
---- Fundamentals > Objective 4.4 > What is the result?
Click the Exhibit button to view Item 2 A 0123
the code. ---------------------------------------- B 1223
1. public class ABC { Which two are keywords? (Choose C 1200
2. public static void two.) D 1 2 null null
main(String [] args ) { A super E Compilation fails
3. String a = args[3]; B Boolean F An exception is thrown at
4. String b = args[2]; C unsigned runtime
5. String c = args[1]; D interface
6. System.out.println("c = " E anonymous
+ c); Answer:
7. } Options A and D are the correct Answer:
8. } answers. 'interface' and 'super' are Option C is the correct answer.
And the command line both valid keywords. C is wrong The elements in array y are
invocation: because 'unsigned' is a keyword in C, implicitly initialized to zeros,
java ABC A B C C++, but not Java. E is wrong and then elements 0 and 1 are
What is the result? because 'anonymous' is a Java updated.
a c= concept but not a keyword. B
B c=A 'Boolean' is a class. The Java Location: ... > Language
C c=B primitive keyword is 'boolean'. Fundamentals > Objective 4.6
D c=C > Item 1
E Compilation fails Location: ... > Language -----------------------------------
F An exception is thrown at Fundamentals > Objective 4.5 > Which one is valid?
runtime Item 1 A boolean b2 = 1;
---------------------------------------- B boolean b3 = null;
Answer: Click the Exhibit button to view the C boolean b1 = FALSE;
Option F is the correct answer. code. D boolean b4 = "false";
Line 3 will fail; args[3] is out of 1. class IvarLocal { E boolean b5 = (4 < 1);
bounds. 2. static int x; answer:
3. public static void main(String Option E is the correct answer.
Location: ... > Language args []) { The expression (4 < 1)
Fundamentals > Objective 4.4 > 4. int y; resolves to false.
Item 1 5. System.out.println("x = " + x +
----------------------------------- " y = " + y); Location: ... > Language
Click the Exhibit button to view 6. } Fundamentals > Objective 4.6
the code. 7. } > Item 2
1. class Test { -----------------------------------
2. public static void What is the result? Which three are valid?
main(String [] args) { A x=y= (Choose three.)
3. construct Test(int i) { B x=y=0 A float f1 = 0x123.45;
4. for (int y=0; y<i; y++) C x=0y= B float f2 = 3.14f;
5. System.out.print(" " + D x=0y=0 C float f3 = (double) 1.8;
y); E Compilation fails D float f4 = 1.0;
6. } F An exception is thrown at runtime E float f5 = (float) '\'';
7. } F float f6 = '\ubabe';
8. }
Answer:
And command line invocation: Answer: Options B, E, and F are the
Option E is the correct answer. The correct answers. B is explicitly
java Test 6 compiler will be concerned about cast to a float. E casts a char
whether y has been initialized. (which is an unsigned int) to a
What is the result? float. F casts a Unicode char to
a 12345 Location: ... > Language a float.
B 012345 Fundamentals > Objective 4.5 >
C Compilation fails Item 2 Location: ... > Operators and
D An exception is thrown at ----------------------------------------- Assignments > Objective 5.1 >
runtime Click the Exhibit button to view the Item 2
Answer: code. -----------------------------------
Option C is the correct answer. 7. short x = 1; Given:
The word 'construct' is not a 8. int [] y = new int[4];
valid modifier keyword in the 9. y[0] = x; 10. int x = -1, y = -2;
Java language. Constructors are 10. y[1] = x+1; 11. System.out.println( (x<0)
identified by having the same 11. for(int z= 0;z<4; z++) { ^ (y<0) ) ;
75
What is the result? C flag1 and flag2 are both Location: ... > Operators and
A true evaluated exactly once Assignments > Objective 5.4 >
B false D The output is always true Item 1
C Compilation fails regardless of the ordering -----------------------------------
D The code runs with no output E The output is always false -----------------------------------
E An exception is thrown at regardless of the ordering ----------
runtime click the Exhibit button to view
Answer: Answer: the code.
Option B is the correct answer. Options A and E are the correct 10. public void op3( boolean[]
Both equality tests resolve to answers. The entire logical statement flags ) {
true - true XOR true is false. is composed of non shortcutting and 11. flags = new boolean[3];
therefore ALL boolean expressions 12. for ( int i=0;
Location: ... > Operators and will be evaluated regardless of the i<flags.length; i++ ) {
Assignments > Objective 5.2 > outcome of a preceding evaluation. 13. flags[i] = ((i%2)==0);
Item 1 As there are booleans that resolve to 14. }
------------------------------------- false in all three composite boolean 15. }
------------------------------------- expressions the outcome must be 16. public void arrayTest () {
------ false. 17. boolean[] initial = null;
18. op3( initial );
click the Exhibit button to view Location: ... > Operators and 19.
the code. Assignments > Objective 5.3 > Item System.out.println( initial[0] );
10. int[] arr1 = new int[2]; 2 20. }
11. int[] arr2 = -----------------------------------
(int[])arr1.clone(); Click the Exhibit button to view the What is the result if method
12. System.out.println( "Array 1 code. arrayTest() is called?
equals array 2 - " + 10. public boolean t1() { return
arr1.equals( arr2 ) ); "hello".equals("HELLO"); } A true
11. public boolean t2() { return ! B null
What is the result? t1(); } C false
A Array 1 equals array 2 - 12. D Compilation fails
B Array 1 equals array 2 - true 13. public void op () { E The code runs with no
C Array 1 equals array 2 - null 14. System.out.println( (t1() && output
D Array 1 equals array 2 - false t2()) | t2() ); F An exception is thrown at
E Compilation fails 15. } runtime
F An exception is thrown at
runtime Which four are true? (Choose four.)
A Compilation fails Answer:
Answer: B Calling op() means t2() is always Option F is the correct answer.
Option D is the correct answer. called once An exception is thrown at
Arrays inherit the default C Calling op() means t1() is always runtime. Defining and
Object.equals implementation called once initializing the array in op3()
which compares references not D The output from op() is always has no effect on the callers
equivalence of content therefore the value true reference which remains null.
comparing two distinct arrays will E Calling op() means t2() is always Therefore the access on
always yield false even if the called twice initial[0] causes a
compared arrays are clones. F Calling op() means t1() is always java.lang.NullPointerException
called twice
Location: ... > Operators and G Reversing the first expression to Location: ... > Operators and
Assignments > Objective 5.3 > (t2() && t1()) does not affect the Assignments > Objective 5.4 >
Item 1 output Item 2
------------------------------------- -----------------------------------
------------------------------------- Answer: -----------------------------------
------ Options B, D, F, and G are the ----------
Click the Exhibit button to view correct answers. Click the Exhibit button to
the code. t1() resolves to false t2() resolves to view the code.
10. boolean flag1 = true; not t1() - true reordering the first 10. public StringBuffer
11. boolean flag2 = false; expression does not affect the op4( StringBuffer sb ) {
12. System.out.println( ( flag2 & outcome because it is a double && 11. sb.append("-widgets");
flag1 ) & ( flag1 & flag2 ) ); The first call to t1() returns false and 12. return sb;
will shortcut the && expression to 13. }
Which two are true? (Choose false and the non shortcut | to the 14. public void roundRobinTest
two.) second t2() returns true resulting in () {
overall true. Due to shortcut t2() is 15. StringBuffer sb = new
A The code outputs the value only ever called once t1() is called StringBuffer();
false once in the expression and a second 16. sb.append("acme");
B The output may vary if the time from t2(), therefore is called 17. op4(sb);
ordering is changed twice 18. sb.append("-and-
nuggets");
76
19. E The private modifier on msg must 15. protected Q()
System.out.println( sb.toString() be weakened to default or public for { super((short)3); }
); this code to work correctly 16. public Q( int i )
20. } Answer: { super( new
Options B and D are the correct Integer(i).toString() ); }
What is the result if method answers. Access to an nested classes 17. Q( boolean b )
roundRobinTest() is called? private methods and variables is { super(""); }
granted to the encapsulating classes 18. Q( short s )
A acme methods. { super( s ); }
B acme-widgets 19. }
C -and-nuggets Reference:
D acme-and-nuggets The Java Programming Language, If the following new statements
E -widgets-and-nuggets Third Edition, by Arnold, Gosling & are invoked in a separate class
F acme-widgets-and-nuggets Holmes, Chapter 3: Extending in the same package as classes
Classes -- ISBN: 0-201-70433-1 P and Q, which three are true?
Answer: (Choose three.)
Option F is the correct answer. Location: ... > Objective 6.1 > Item A Compilation fails for code -
sb is created in roundRobinTest 2 new Q();
and its reference passed by value ----------------------------------------- B Compilation fails for code -
into op4 where the shared object --------------------------------------- new P();
is modified. The same sb is then Click the Exhibit button to view the C Compilation fails for code -
returned to the caller, but the code. new Q("");
caller never assigns or re-assigns 1. interface D {} D Compilation fails for code -
its local sb reference and it 2. class E implements D {} new P('a');
appears that modifications in op4 3. class F extends E { E Compilation fails for code -
are lost, but as this is a shared 4. F() {} new Q((short)1);
object by reference all 5. } F Compilation fails for code -
modifications remain, so the 6. class G extends F implements D new Q( new Q(3) instanceof
output is acme-widgets-and- {} P );
nuggets 7. class X { Answer:
8. public static void main( String[] Options B, C, and D are the
Location: ... > Objective 6.1 > args ) { correct answers. The
Item 1 9. E e = new F(); relationship and declaration of
------------------------------------- 10. D d = new G(); P & Q are sound. This question
------------------------------------- 11. } is quite simple couched in
------ 12. } seemingly complex code.
Click the Exhibit button to view Simply test the argument
the code. Which three are true? (Choose passed in the new call with a
1. class A { three.) constructor in the target class,
2. private static class B { A The declaration of G is illegal if a match is found it compiles.
3. private static String msg B E is said to be a superclass of F The last three options here do
= "ok" ; C G is said to be a superclass of E not have matching
4. } D The assignment at line 10 is legal constructors.
5. public static String access() E A variable can be declared using
{ an interface type Location: ... > Objective 6.2
6. return B.msg; F Compilation fails > Item 2
7. } -----------------------------------
8. } answer:
9. class X { B, D, and E. B is correct because Click the Exhibit button to view
10. public static void class F extends class E, making E a the code.
main( String[] args ) { superclass of F. D and E are correct 10. abstract class X {
11. because the code compiles 11. public final void op(){}
System.out.println( A.access() ); successfully, the declaration of G 12. abstract final void op();
12. } reimplementing D is legal, as is the 13. void op( String s ){}
13. } declaration of d using an interface D 14. abstract synchronized
as its type. void op(int i) throws Exception;
Which two are true? (Choose 15. abstract private void
two.) Location: ... > Objective 6.2 > Item op( String a, int i );
A Compilation fails 1 16. }
B The code outputs the value -----------------------------------------
ok --------------------------------------- Which three are true? (Choose
C An exception is thrown at Click the Exhibit button to view the three.)
runtime code.
D Any private members of B 10. class P {
can be accessed from class A 11. P( String s ){}
only through accessor methods 12. P( short s ){} A Line 10 is uncompilable
13. } B Line 11 is uncompilable
14. class Q extends P { C Line 12 is uncompilable
77
D Line 13 is uncompilable Click the Exhibit button to view the appropriate enclosing instance
E Line 14 is uncompilable code. is supplied to the superclass.
F Line 15 is uncompilable 1. interface XX {} The resulting inner class then
Answer: 2. interface YY extends XX {} has two enclosing instances,
Options C, E, and F are the 3. abstract class ZZ implements XX one for the extended class and
correct answers. {} one for the superclass.
line 10 ok, the class must be 4. class AA extends ZZ implements Therefore this code cleanly
declared abstract YY { compiles and outputs nothing.
line 11 ok, the initial method 5. private class BB{} Location: ... > Threads >
declaration signature 6. } Objective 7.1 > Item 1
line 12 fails, cannot combine 7. class Main extends AA { -----------------------------------
abstract and final, conflict of 8. public static void main( String[] -----------------------------------
intentions args ) { ----------
line 13 ok, the first successful 9. XX xx1 = new XX (); Click the Exhibit button to
overload of op(), but with 10. XX xx2 = new AA (); view the code.
differing access privileges 11. ZZ zz1 = new Main (); 1. public static void
line 14 fails, cannot combine 12. Main m = new AA(); main( String[] args ) {
abstract with implementation 13. } 2. class Widget extends
details like synchronized 14. } java.lang.Thread {
line 15 fails, cannot combine 3. Widget(boolean daemon)
abstract and private, no way to Which two are true? (Choose two.) {
implement in subclass A Line 5 is uncompilable 4.
B Line 9 is uncompilable this.setDaemon(daemon);
Location: ... > Objective 6.3 > C Line 10 is uncompilable 5. this.start();
Item 1 D Line 11 is uncompilable 6. }
------------------------------------- E Line 12 is uncompilable 7. }
------------------------------------- F Compilation succeeds 8.
--- 9. for ( int i= 0;i<10; i++ ) {
Click the Exhibit button to view 10. new Widget(((i
the code. Answer: %2)==0));
1. interface XX {} Options B and E are the correct 11. }
2. interface YY extends XX {} answers. Line 9 attempts to 12. }
3. abstract class ZZ implements instantiate an interface. Line 12 is an
XX {} incompatible assignment; you can't Which two statements are
4. class AA extends ZZ assign a superclass object to a true? (Choose two.)
implements YY { subclass reference type. A Compilation fails.
5. private class BB{} Location: ... > Objective 6.3 > B Only five threads are
6. } Item 2 created.
7. class Main extends AA { Click the Exhibit button to view C An exception is thrown at
8. public static void the code. runtime.
main( String[] args ) { 1. class Outer { D Ten independent threads
9. XX xx1 = new XX (); 2. class Inner {} are created.
10. XX xx2 = new AA (); 3. } E Ten threads are created but
11. ZZ zz1 = new Main (); 4. class ExtendedOuter extends only five execute.
12. Main m = new AA(); Outer { F The program terminates
13. } 5. class ExtendedInner extends after the tenth thread is
14. } Inner {} created.
6. } Answer:
Which two are true? (Choose 7. class Main extends Outer.Inner { Options D and F are the correct
two.) 8. Main( Outer ref ) { answers. The program creates
A Line 5 is uncompilable 9. ref.super(); precisely 10 threads, every
B Line 9 is uncompilable 10. } other of which is marked as
C Line 10 is uncompilable 11. public static void main( String[] daemon thread. Each thread
D Line 11 is uncompilable args ) { executes on the default run()
E Line 12 is uncompilable 12. new Main( new method so all will terminate
F Compilation succeeds ExtendedOuter() ); and therefore the program
Answer: 13. } terminates.
Options B and E are the correct 14. }
answers. Line 9 attempts to Reference:
instantiate an interface. Line 12 What is the result? The Java Programming
is an incompatible assignment; A Compilation fails Language, Third Edition, by
you can't assign a superclass B An exception is thrown at runtime Arnold, Gosling & Holmes,
object to a subclass reference C The code runs with no output Chapter 10: Threads
type. ISBN: 0-201-70433-1
Answer:
Location: ... > Objective 6.3 > Option C is the correct answer. An location: ... > Threads >
Item 1 inner class can extend another, Objective 7.1 > Item 2
unrelated, inner class provided an
78
------------------------------------- 14. } answer:
------------------------------------- Options B and C are the correct
------ Which two statements are true? answers. This program simply
Click the Exhibit button to view (Choose two.) launches a single user thread
the code. that immediately blocks inside
11. public static void A Compilation fails. the wait() method The thread
main( String[] args ) { B An exception is thrown at is never unblocked because no
12. class Widget extends runtime. other thread is executing to
java.lang.Thread { C All threads are guaranteed to call the notify on the lock.
13. Widget() { execute. Reference:
14. this.start(); D Some of the threads may never The Java Programming
15. } execute. Language, Third Edition, by
16. } E The program runs forever with no Arnold, Gosling & Holmes,
17. output. Chapter 10: Threads
18. Widget w = new Widget(); F The program terminates when the ISBN: 0-201-70433-1
19. w.setDaemon(true); main() method completes. Location: ... > Threads >
20. } Answer: Objective 7.3 > Item 1
Options D and F are the correct -----------------------------------
Which statement is true? answers. As all threads are marked -----------------------------------
A Compilation fails. as Daemon threads, the program ----------
B The program never contains no user threads once main Click the Exhibit button to
terminates. terminates, so the program as a view the code.
C One daemon thread is whole terminates. A number of the 10. class X {
created. daemon threads may never execute 11. synchronized void iTest()
D An exception is thrown at due to the early termination of the {
runtime. program and the priority levels 12. while(true) {
E The program terminates after assigned. 13. Thread.yield();
the thread is created. Reference: 14. }
Answer: The Java Programming Language, 15. }
Option D is the correct answer. Third Edition, by Arnold, Gosling & 16. synchronized static void
An exception is thrown at Holmes, Chapter 10: Threads sTest() {}
runtime - ISBN: 0-201-70433-1 17. public void op() {}
va.lang.IllegalThreadStateExcepti 18. }
on setdaemon(true) can not be Location: ... > Threads > Objective
invoked on an active thread. 7.2 > Item 2 And, given a single instance of
Reference: X, and two or more concurrent
The Java Programming Click the Exhibit button to view the threads, which statement is
Language, Third Edition, by code. true?
Arnold, Gosling & Holmes 1. class Worker extends A Multiple threads can
Chapter 10: Threads java.lang.Thread { execute iTest() concurrently.
ISBN: 0-201-70433-1 2. public void run() { B Any thread calling iTest()
3. while ( true ) { will be blocked pending a call
Location: ... > Threads > 4. synchronized( this ) { to notify.
Objective 7.2 > Item 1 5. try { C While a thread is executing
------------------------------------- 6. wait(); iTest(), any call on sTest() will
------------------------------------- 7. } catch (Exception e) {} block pending lock access.
------ 8. } D While a thread is executing
Click the Exhibit button to view 9. System.out.println("ok"); iTest(), no other threads may
the code. 10. } execute any methods declared
1. class Worker extends 11. } in X.
java.lang.Thread { 12. public static void main( String[] E While a thread is executing
2. public void run() { args ) { iTest(), op() may be
3. while ( true ) {} 13. new Worker().start(); concurrently executed inside
4. } 14. } the same instance of X.
5. 15. } Answer:
6. public static void Option E is the correct answer.
main( String[] args ) { Which two statements are true? Static methods synchronize on
7. for (int i=0; (Choose two.) the class object, not on an
i<MAX_PRIORITY; i++ ){ A Compilation fails. instance object, so concurrent
8. Worker w = new B The program never terminates. calls to iTest() and sTest() will
Worker(); C The program runs with no output. not block each other. op() is
9. D The value ok is repeatedly not synchronized so may be
w.setPriortity( MIN_PRIORITY+i ) output. called concurrently with
; E The program terminates and anything else.
10. w.setDaemon(true); outputs ok precisely once.
11. w.start(); F The Worker thread never blocks Reference:
12. } inside the wait method because there The Java Programming
13. } are no other threads executing. Language, Third Edition, by
79
Arnold, Gosling & Holmes, C The Runnable interface defines 9. }
Chapter 10: Threads a wait() method. 10. }
ISBN: 0-201-70433-1 D wait() can be called at any time
Location: ... > Threads > by an executing thread. What is the result?
Objective 7.3 > Item 2 E The wait() method used in A Results: 6.0 5.0 -5.0 -5.0
------------------------------------- thread communication releases an -5.0
------------------------------------- object lock. B Results: 6.0 5.0 -5.0 -5.0
------ F The wait() method is -6.0
Click the Exhibit button to view overloaded and also has the following C Results: 5.0 5.0 -5.0 -5.0
the code. signature public final void wait(long -5.0
1. class WorkerT extends timeout). D Results: 6.0 5.0 -5.0 -4.0
java.lang.Thread { -5.0
2. private static StringBuffer sb answer: E Results: 6.0 5.0 5.0 5.0 6.0
= new StringBuffer(); Options A, E, and F are the correct F Compilation fails.
3. public void run() { answers.
4. notify(); Reference: nswer:
5. try { The Java Programming Language, Option A is the correct answer.
6. wait(); Third Edition, by Arnold, Gosling & Both positive and negative
7. } catch (Exception e) {} Holmes, Chapter 10: Threads numbers are rounded up to the
8. } ISBN: 0-201-70433-1 larger number. For a positive
9. public static void Location: ... > Threads > Objective number such as 5.5, the
main( String[] args ) { 7.4 > Item 2 greater number is 6, but for
10. for (int i= 0;i<10; i++) { ----------------------------------------- -5.5 the greater number is
11. new WorkerT().start(); --------------------------------------- -5.0.
12. } which two statements are correct? Location: ... > Fundamental
13. } (Choose two.) Classes in the java.lang
14. } A To call notify() a thread must package > Objective 8.2 >
own the monitor lock. Item 1
Which statement is true? B The notify() and notifyAll() -----------------------------------
A Compilation fails. methods are defined in the Thread -----------------------------------
B All 10 threads block. class. ----------
C An exception is thrown at C The notify() and notifyAll() Click the Exhibit button to
runtime. methods are defined in the Object view the code.
D All 10 threads execute to class. 1. public class Test823 {
completion. D A thread can only call notify() if 2. public static void
E Each thread is unlocked by another thread has previously called main(String [] args) {
the following thread until only wait(). 3. String a = "freddy";
the final thread remains blocked. E The notify() and notifyAll() 4. String b =
Answer: methods are defined in the Runnable a.substring(0,3);
Option C is the correct answer. interface. 5. b.toUpperCase();
An exception is thrown Answer: 6. System.out.println(a +=
java.lang.IllegalMonitorStateExce Options A and C are the correct b);
ption: current thread not owner. answers. 7. }
The caller of wait(), notify(), or 8. }
notifyAll() must own the monitor Reference: What is the result?
lock that is, they must be The Java Programming Language, A freddyFRE
executing inside a synchronized Third Edition, by Arnold, Gosling & B freddyfre
method or section to be able to Holmes, Chapter 10: Threads C freddyFRED
successfully call any of these ISBN: 0-201-70433-1 D freddyfred
methods. E Compilation fails.
Location: ... > Fundamental Classes Answer:
Reference: in the java.lang package > Objective Option B is the correct answer.
The Java Programming 8.1 > Item 1 The a String reference is never
Language, Third Edition, by ----------------------------------------- modified, and the
Arnold, Gosling & Holmes, --------------------------------------- toUpperCase() call is not
Chapter 10: Threads Click the Exhibit button to view the assigned to b so b's original
ISBN: 0-201-70433-1 code. object does not change.
Location: ... > Threads > 1. public class Test813 { Location: ... > Fundamental
Objective 7.4 > Item 1 2. public static void main(String [] Classes in the java.lang
------------------------------------- args) { package > Objective 8.2 >
------------------------------------- 3. double a = Math.round(5.5); Item 2
------ 4. double b = Math.round(5.2); -----------------------------------
Which three statements are 5. double c = Math.round(-5.0); -----------------------------------
true? (Choose three.) 6. double d = Math.round(-5.4); ----------
A The Object class defines a 7. double e = Math.round(-5.5); Click the Exhibit button to
wait() method. 8. System.out.print( "Results: " + view the code.
B The Thread class overrides a+""+b+""+c+""+d+"" 1. public class Test825 {
a wait() method. + e);
80
2. public static void main(String returning a char to the Character Location: ... > The
[] args) { constructor. Collections Framework >
3. String a = "big"; Location: ... > Fundamental Objective 9.1 > Item 2
4. String b = a; Classes in the java.lang package > -----------------------------------
5. a = a + "bird"; Objective 8.3 > Item 2 -----
6. a = b; ----------------------------------------- Click the Exhibit button to
7. b = "bird"; --------------------------------------- view the code.
8. System.out.println(a = Click the Exhibit button to view the 1. TreeSet s = new TreeSet();
a+b); code. 2. s.add("Fred");
9. } 1. public class Test834 { 3. s.add("Mike");
10. } 2. public static void main(String [] 4. s.add("Zeus");
args) { 5. s.add("Fred");
What is the result? 3. try { 6. s.add("Amy");
A bigbird 4. Double d = new Double(new 7. Iterator i = s.iterator();
B birdbird Byte(6).doubleValue()); 8. while(i.hasNext()) {
C bigbigbird 5. String s = d.toString(); 9. System.out.print(i.next()
D bigbirdbird 6. + ", ");
E Compilation fails. System.out.println(Integer.parseInt( 10. }
Answer: s)); What is the result?
Option A is the correct answer. 7. } A Fred, Mike, Zeus, Amy,
In line 4, b is set to refer to the catch(NumberFormatException ex) { B Amy, Fred, Mike, Zeus,
String literal "big". The String 8. System.out.println("failed"); C Fred, Mike, Zeus, Fred,
referenced by b is not changed 9. } Amy,
by the change to a in line 5, 10. } D Amy, Fred, Fred, Mike,
because Strings are immutable. 11. } Zeus,
In line 5, a new String object E Five elements will be
"bigbird" is created, and assigned What is the result? printed, but the order is not
to a. At this point (line 5) b is A 6 guaranteed.
still referring to "big" and a is B 6.0 F Four elements will be
now referring to "bigbird". In line C null printed, but the order is not
6,then, a is set to refer to the D failed guaranteed.
String literal "big" referenced by E Compilation fails.
b, so both a and b refer to the F An uncaught exception is thrown
String literal "big". In line 7, b is at runtime.
set to reference a String literal Answer: Answer:
"bird", while a is left unchanged Option E is the correct answer. Byte Option B is the correct answer.
and still refers to "big". Finally, a does not have a constructor that A TreeSet is a Set, which
+ b is printed out, producing takes an int. The Byte constructor eliminates duplicates, so Fred
"bigbird". must be passed a previously declared only goes in once. A TreeSet is
byte variable, or explicitly cast an int sorted so the Strings come out
value. in alphabetical order
Location: ... > Fundamental Location: ... > The
Classes in the java.lang package Location: ... > The Collections Collections Framework >
> Objective 8.3 > Item 1 Framework > Objective 9.1 > Item 1 Objective 9.2 > Item 1
------------------------------------- ----------------------------------------- --
------------------------------------- --------------------------------------- If class X implements
--- Which two statements are true of hashcode() and equals()
Which creates a new Character class java.util.HashMap? (Choose correctly, and given two
object? two.) instances (o1 and o2) of class
A Character a = new A Its methods are thread-safe. X, which two are true? (Choose
Character("c"); B It allows null references to be two.)
B Character a = stored.
Character.getCharacter('s'); C It provides fast, bi-directional A if o1.hashcode() and
C Character a = new iteration. o2.hashcode() are not the
Character(new char[]{'s'}); D It implements java.util.Hashable. same, then o1 and o2 must not
D Character a = E It tracks when its elements were be equal
Character.valueOf("c".toChar()); last accessed. B o1.hashcode() and
E Character a = new F Its elements can be accesssed o2.hashcode() might be the
Character((new char[]{'s'})[0]); using a unique key. same if o1 and o2 are
Answer: Answer: considered equal
Option E is the correct answer. Options B and F are the correct C o1.hashcode() and
The Character class has only one answers. HashMap implements o2.hashcode() must be the
constructor, and it takes a char java.util.Map, which allows elements same if o1 and o2 are
primitive. Answer "E" constructs to be accessed using a unique key. considered equal
an anonymous char array holding Whereas HashTable does not permit D if o1 and o2 are not equal,
a single char, then accesses the null references to be stored, then o1.hashcode() and
array element at index 0, thus HashMap allows both keys and o2.hashcode() must not be the
elements to be null. same
81
Answer: 11: static void show() 19: }
Options A and C are the correct 12: {
answers. Hashcode suggests the 13: System.out.println("Show A) Compilation error at line 3.
likelihood of equality, while method in Q2 class"); B) Compilation error at line 10.
equality requires that hashcodes 14: } C) No compilation error, but
must be the same. The rules for 15: public static void runtime exception at line 3.
correct implementation of main(String[] args) D) No compilation error, but
hashcode and equals require that 16: { runtime exception at line 10.
if two objects are equal, their 17: Test t = new Test();
hashcodes MUST be the same. If 18: t.show();
two objects are unequal, 19: Q2 q = new Q2(); ---------
however, they may still have the 20: q.show(); Question 4
same hashcode. So, object 21: ---------
equivalency guarantees 22: t = q; The following code will give
hashcode equivalency, but 23: t.show();
hashcode equivalency does not 24: 1: class Test
guarantee object equivalency. 25: q = t; 2: {
---------- 26: q.show(); 3: static void show()
Question 1 27: } 4: {
-------- 28: } 5:
What will happen if you System.out.println("Static
compile/run this code? A) prints "Show method in Test method in Test");
class" 6: }
1: public class Q1 extends "Show method in Q2 class" 7: }
Thread "Show method in Q2 class" 8: public class Q4 extends
2: { "Show method in Q2 class" Test
3: public void run() 9: {
4: { B) prints "Show method in Test 10: void show()
5: class" 11: {
System.out.println("Before start "Show method in Q2 class" 12:
method"); "Show method in Test class" System.out.println("Overridden
6: this.stop(); "Show method in Test class" static method in Q4");
7: System.out.println("After 13: }
stop method"); C) prints "Show method in Test 14: public static void
8: } class" main(String[] args)
9: "Show method in Q2 class" 15: {
10: public static void "Show method in Test class" 16: }
main(String[] args) "Show method in Q2 class" 17: }
11: {
12: Q1 a = new Q1(); D) Compilation error. A) Compilation error at line 3.
13: a.start(); B) Compilation error at line 10.
14: } --------------- C) No compilation error, but
15: } Question 3 runtime exception at line 3.
--------------- D) No compilation error, but
A) Compilation error at line 7. The following code will give runtime exception at line 10.
B) Runtime exception at line 7. --------------
C) Prints "Before start method" 1: class Test Question 5
and "After stop method". 2: { --------------
D) Prints "Before start method" 3: void show() The following code will print
only. 4: {
-------------- 5: System.out.println("non- 1: int i = 1;
Question 2 static method in Test"); 2: i <<= 31;
-------------- 6: } 3: i >>= 31;
What will happen if you 7: } 4: i >>= 1;
compile/run the following code? 8: public class Q3 extends Test 5:
9: { 6: int j = 1;
1: class Test 10: static void show() 7: j >>= 31;
2: { 11: { 8: j >>= 31;
3: static void show() 12: 9:
4: { System.out.println("Overridden non- 10: System.out.println("i = "
5: static method in Q3"); +i );
System.out.println("Show 13: } 11: System.out.println("j = "
method in Test class"); 14: +j);
6: } 15: public static void
7: } main(String[] args) A) i = 1
8: 16: { j=1
9: public class Q2 extends Test 17: Q3 a = new Q3();
10: { 18: } B) i = -1
82
j=1
1: public class Q8 A) Compilation error at line 9 .
C) i = 1 2: { B) Runtime error exception at
j = -1 3: int i = 20; line 9.
4: static C) Prints "True".
D) i = -1 5: { D) Prints "False".
j=0 6: int i = 10;
--------------- 7: -----------------------------------
Question 6 8: } -------------------
--------------- 9: public static void Question 11
The following code will print main(String[] args) -----------------------------------
10: { -------------------
1: Double a = new 11: Q8 a = new Q8(); What will happen if you
Double(Double.NaN); 12: System.out.println(a.i); compile/run the following
2: Double b = new 13: } code?
Double(Double.NaN); 14: }
3: 1: public class Q11
4: if( Double.NaN == A) Compilation error, variable "i" 2: {
Double.NaN ) declared twice. 3: static String str1 =
5: B) Compilation error, static "main method with String[]
System.out.println("True"); initializers for initialization purpose args";
6: else only. 4: static String str2 =
7: C) Prints 10. "main method with int[] args";
System.out.println("False"); D) Prints 20. 5:
8: 6: public static void
9: if( a.equals(b) ) ----------------------------------------- main(String[] args)
10: ------------- 7: {
System.out.println("True"); Question 9 8:
11: else ----------------------------------------- System.out.println(str1);
12: ------------- 9: }
System.out.println("False"); The following code will give 10:
11: public static void
A) True 1: Byte b1 = new Byte("127"); main(int[] args)
True 2: 12: {
3: if(b1.toString() == 13:
B) True b1.toString()) System.out.println(str2);
False 4: System.out.println("True"); 14: }
5: else 15: }
C) False 6: System.out.println("False");
True A) Duplicate method main(),
A) Compilation error, toString() is compilation error at line 6.
D) False not avialable for Byte. B) Duplicate method main(),
False B) Prints "True". compilation error at line 11.
C) Prints "False". C) Prints "main method with
------------------------------------- main String[] args".
----------------- Question 10 D) Prints "main method with
Question 7 ----------------------------------------- main int[] args".
------------------------------------- -------------
----------------- What will happen if you compile/run -----------------------------------
The following code will print this code? -------------------
Question 12
1: if( new Boolean("true") == 1: public class Q10 -----------------------------------
new Boolean("true")) 2: { -------------------
2: 3: public static void What is the output of the
System.out.println("True"); main(String[] args) following code?
3: else 4: {
4: 5: int i = 10; 1: class Test
System.out.println("False"); 6: int j = 10; 2: {
7: boolean b = false; 3: Test(int i)
A) Compilation error. 8: 4: {
B) No compilation error, but 9: if( b = i == j) 5:
runtime exception. 10: System.out.println("Test(" +i
C) Prints "True". System.out.println("True"); +")");
D) Prints "False". 11: else 6: }
--------- 12: 7: }
Question 8 System.out.println("False"); 8:
--------- 13: } 9: public class Q12
The following code will give 14: } 10: {
83
11: static Test t1 = new 1: int i = 45678; 10. char [] c6 = [] {'a', 'b',
Test(1); 2: int j = ~i; c};
12: 3: 11. }
13: Test t2 = new 4: System.out.println(j); 12. }
Test(2); A line 5
14: A) Compilation error at line 2. ~ B line 6
15: static Test t3 = new operator applicable to boolean values C line 7
Test(3); only. D line 8
16: B) Prints 45677. E line 9
17: public static void C) Prints -45677. F line 10
main(String[] args) D) Prints -45679. Answer:
18: { Options A and B are the correct
19: Q12 Q = new Q12(); ----------------------------------------- answers. This question
20: } ------------- explores a Java syntax
21: } Question 15 shortcut. A and B represent
----------------------------------------- acceptable syntax to declare,
A) Test(1) ------------- construct, and initialize an
Test(2) What will happen when you invoke array in a single line of code.
Test(3) the following method? Location: ... > Declarations
and Access Control > Objective
B) Test(3) 1: void infiniteLoop() 1.1 > Item 2
Test(2) 2: { -----------------------------------
Test(1) 3: byte b = 1; -----------------------------------
4: ----------
C) Test(2) 5: while ( ++b > 0 ) Click the Exhibit button.
Test(1) 6: ; 1. class Test{
Test(3) 7: System.out.println("Welcome 2. public static void
to Java"); main( String [] args) {
D) Test(1) 8: } 3. int [] y;
Test(3) 4. int [] z = new int [] {1,
Test(2) A) The loop never ends(infiniteLoop). 2, 3};
B) Prints "Welcome to Java". 5. y = z;
------------------------------------- C) Compilation error at line 5. ++ 6. z[1] = 7;
----------------- operator should not be used for byte 7. for (int x= 0;x<3; x++)
Question 13 type variables. {
------------------------------------- 8. System.out.print("
----------------- ---------------------- y[" + x + "] = " + y[x]);
What is the output of the ANSWER-------------------------------- 9. }
following code? ------------------------ 10. }
Question No 11. }
1: int i = 16; : 1 2 3 4 5 6 7 8 9 10 11 12 13 14
2: int j = 17; 15 What is the result?
3: Correct Answer A y[0] = 0 y[1] = 1 y[2] =
4: System.out.println("i >> 1 : 2
= " + (i >> 1)); DDBBDCDDCCCDADB B y[0] = 7 y[1] = 2 y[2] =
5: System.out.println("j >> 1 Your Answer 3
= " + (j >> 1)); A-------------- C y[0] = 1 y[1] = 7 y[2] =
3
A) Prints i >> 1 = 8 D y[0] = 1 y[1] = 2 y[2] =
j >> 1 = 8 3
Location: ... > Declarations and E Compilation fails
B) Prints i >> 1 = 7 Access Control > Objective 1.1 > F An exception is thrown at
j >> 1 = 7 Item 1 runtime
----------------------------------------- Answer:
C) Prints i >> 1 = 8 --------------------------------------- Option C is the correct answer.
j >> 1 = 9 Click the Exhibit button. y and z are reference
Which two lines of code will compile variables. Line 5 assigns y to
D) Prints i >> 1 = 7 correctly? (Choose two.) refer to the same array as z,
j >> 1 = 8 1. class CharArray2 { there is still only one array
2. public static void main( String [] (however there are two array
------------------------------------- args) { references). When line 6
----------------- 3. char b = 'b'; executes, it changes a value in
Question 14 4. char c = 'C'; the only array there is, (the
------------------------------------- 5. char [] c1 = {'a', 'b', 'c'}; one both y and z refer to).
----------------- 6. char [] c2 = {'a', b , 'c'}; Therefore when the array is
What is the output of the 7. char [] c3 = ('a', 'b', 'c'); accessed via y, the updated
following code? 8. char [] c4 = [3]; value is displayed.
9. char [] c5 = [3] {'a', 'b', 'c'};
84
ocation: ... > Declarations and A Class Bar will not compile answer:
Access Control > Objective 1.2 > B Class Bar has a public constructor Options A and C are the correct
Item 1 C Class Bar's constructor invokes answers. A and C represent an
------------------------------------- super() illegal override of the class XL
------------------------------------- D Class Foo's constructor does not doMath() method. Because the
------ invoke super() arguments have not changed,
Which declaration ensures that a answer: the return type cannot change.
class cannot be subclassed? Option A is the correct answer. The Location: ... > Declarations
A abstract class MyClass { } compiler attempts to create a default and Access Control > Objective
B final public class MyClass { } constructor for class Bar, because 1.4 > Item 2
C final abstract class MyClass Bar has not defined any constructors. -----------------------------------
{} The class Bar constructor will include -----------------------------------
D static private class MyClass a call to super(). Since class Foo ----------
{} does not have a no-arg constructor, Click the Exhibit button to
E static protected class MyClass class Bar will not compile because view the code.
{} the default constructor the compiler 1. class Test {
Answer: is attempting to build includes a call 2. public short doStuff(int i)
Option B is the correct answer. to super(), and there is no matching { return 27; }
The final modifier insures that a no-arg constructor in class Foo. 3. }
class can not be subclassed. 4.
Q31. class XXX { Location: ... > Declarations and 5. public class SubTest extends
2. long doStuff (int input) { Access Control > Objective 1.3 > Test {
3. static long x = 7; Item 2 6. public int doStuff(int x)
4. return (long) input / x; ----------------------------------------- { return 30; }
5. } --------------------------------------- 7.
6. Given: 8. public static void
7. public static void main(String 1. class Pizza { } main(String [] args) {
[] args) { Which of these represents the 9. Test t = new Test();
8. XXX xxx = new XXX(); functionality of the default 10. SubTest s = new
9. constructor for Pizza? SubTest();
System.out.println(xxx.doStuff(4 A Pizza() 11. int t1 = t.doStuff(30);
2)); B Pizza() {super();} 12. int s1 = s.doStuff(27);
10. } C public void Pizza() 13. System.out.println( t1 +
11. } D public Pizza() {super();} " " + s1);
E There is no default constructor for 14. }
What will be the result? Pizza 15. }
A 6 Answer:
B 7 Option B is the correct answer. The What is the result?
C 42 compiler creates a default A 27 30
D Compilation fails constructor for Pizza, with default B 30 27
E An exception is thrown at access (matching the access of the C 27 27
runtime class), and a no-arg call to super(). D 30 30
Answer: E Compilation fails
Option D is the correct answer. Location: ... > Declarations and F An exception is thrown at
The compiler will notice that in Access Control > Objective 1.4 > runtime
Line 3 the code is declaring a Item 1 Answer:
static variable, but it's in a local ----------------------------------------- Option E is the correct answer.
method, which is not legal. If --------------------------------------- Line 6 is an illegal override of
several instances of XXX were Click the Exhibit button to view the the doStuff() method in class
instantiated it would be code. Test.
impossible to know which 1. class XL {
instance the static should belong 2. public long doMath() { Location: ... > Flow Control,
to. 3. return 343L; Assertions, and Exception
4. } Handling > Objective 2.1 >
Location: ... > Declarations and 5. } Item 1
Access Control > Objective 1.3 > 6. -----------------------------------
Item 1 7. class L extends XL { -----------------------------------
------------------------------------- 8. ----------
------------------------------------- 9. } Click the Exhibit button to
------ view the code.
Which two methods inserted at line 1. for (int x = 3; x > = 0; x--)
Click the Exhibit button. 8, will not compile? (Choose two.) {
1. class Foo { a public void doMath() { } 2. switch (x - 1) {
2. Foo(String s) { } B public void doMath(int i) { } 3. case 0:
3. } C public int doMath() { return System.out.print("foo ");
4. class Bar extends Foo { } 343 } 4. case 1:
D public long doMath(int i) { return System.out.print("bar ");
Which statement is true? 343 }
85
5. case 2: 10. for ( ; x > -1 ; y++) { E An overriding method can
System.out.print("baz "); 11. if ( x < y ) { throw a superclass of the
6. case 3: 12. break next; Exception declared by the
System.out.print("foo "); 13. } overridden method
7. } 14. } F An overriding method is
8. } 15. } permitted to throw a
16. System.out.println(x + " " + y); RuntimeException, even if it
What is the result? What is the result? has not been declared by the
A baz bar foo A 23 overridden method.
B foo baz bar foo B 34 Answer:
C baz bar foo bar foo foo C 45 Options B and F are the correct
D baz foo bar baz foo foo bar D 56 answers. Overriding methods
baz foo E Compilation fails are not allowed to throw new
E Compilation fails F An exception is thrown at runtime or broader checked exceptions.
F An exception is thrown at nswer: A checked exception is any
runtime Option C is the correct answer. The exception extending from class
answer: variable x is decremented once, in Exception, but not extending
Option D is the correct answer. line 9, then the program loops from RuntimeException. Errors
As the switch expression iterates through the inner for loop, do not need to be enclosed in
from 2 to -1 the cases start at 2, incrementing y until x < y, at which try blocks.
1, and 0 and fall through. point y equals 5 and the break is
executed. Location: ... > Flow Control,
Location: ... > Flow Control, Assertions, and Exception
Assertions, and Exception Location: ... > Flow Control, Handling > Objective 2.4 >
Handling > Objective 2.1 > Item Assertions, and Exception Handling > Item 1
2 Objective 2.2 > Item 2 -----------------------------------
------------------------------------- ----------------------------------------- -----------------------------------
------------------------------------- --------------------------------------- ----------
------ Click the Exhibit button to view the Click the Exhibit button to
Click the Exhibit button to view code. view the code.
the code. 13. long x = 20, y = 30; 1. public class Test243 {
1. for (int toggle = 0, y = 0; y < 14. while ( ++x < = y ) { 2. public static void main
6; y++ ) { 15. --y; (String [] args) {
2. toggle = y % 2; 16. if ( x > y ) { 3. try {
3. if (toggle) { 17. break; 4. String s = "two";
4. System.out.print("true "); 18. } 5. int i =
5. } 19. } Integer.parseInt(s);
6. else { 20. System.out.print(x + " " + y); 6. System.out.print("i =
7. System.out.print("false "); What is the result? " + i);
8. } A 26 25 7. } catch (Exception ex) {
9. } B 25 25 8. System.out.print("
C 25 24 Exception ");
What is the result? D 25 26 9. }
A true true true true true true E 26 26 catch(NumberFormatException
B true false true false true false Answer: exc) {
C false true false true false true Option A is the correct answer. The 10. System.out.print("
D false false false false false while statement on line 14 NumberFormatException ");
false increments x before doing the 11. } finally {
E Compilation fails comparison test. The break 12. System.out.print("
F An exception is thrown at statement is never reached. finally ");
runtime 13. }
Answer: Location: ... > Flow Control, 14. System.out.print("
Option E is the correct answer. Assertions, and Exception Handling > done ");
Line three is illegal, it should Objective 2.3 > Item 1 15. }
probably read if (toggle == 1) {. ----------------------------------------- 16. }
--------------------------------------- What is the result?
Location: ... > Flow Control, Which two statements are true? A Exception finally
Assertions, and Exception (Choose two.) B i = two finally done
Handling > Objective 2.2 > Item A catch(Foo f) can catch Foo or any C Exception finally done
1 of its superclasses D NumberFormatException
------------------------------------- B If you throw an Error, it does not finally
------------------------------------- need to be enclosed in a try block E NumberFormatException
------ C Any statement that can throw an finally done
Click the Exhibit button to view Exception must be enclosed in a try F Compilation fails
the code. block
7. int x,y; D An overriding method must Answer:
8. next: for(x = 5, y = 1 ; ; ) { declare any Exceptions declared by Option F is the correct answer.
9. --x; the overridden method The NumberFormatException
86
will be caught by the Exception
catch. The compiler recognizes which two statements are true
that the second catch can never about the garbage collection
be reached. You must always put Which two fragments are examples system? (Choose two.)
the catch blocks in order going of inappropriate uses of assertions?
from most specific to broadest. If (Choose two.)
the exceptions are siblings (i.e. A assert (!(foo == null)); A Calling Runtime.gc() will
one does not extend from the foo.go(); reclaim memory.
other), then the order does not B public void method(boolean b) { B It guarantees that
matter. assert (b); programs will not have
C if (x > y) { memory leaks
Location: ... > Flow Control, z = x; C Objects will never be
Assertions, and Exception } else { collected as long as they are
Handling > Objective 2.4 > Item assert (x < 4); accessible from live threads.
2 } D Objects that have finalize()
------------------------------------- D private void test(int z) { methods always have their
------------------------------------- assert (f.setSize(z) > 5); finalize() methods called before
------ } the program ends.
Click the Exhibit button to view E public int methodA(int x) { E If object 'A' has at least one
the code. assert (s > 3); other object with a reference
1. public class Test244 { } to it, then object 'A' will not be
2. public static void main (String Answer: garbage collected.
[] args) { Options B and D are the correct F Objects instantiated within
3. try { answers. B's violation is checking an a method and referenced only
4. foo(); argument of a public method. D's by a local variable are created
5. System.out.print(" one violation is to allow the assert to in the garbage collectible heap.
"); have side effects, in this case by
6. } catch(Exception e) { calling a setter method on a nswer:
7. System.out.print(" two reference. E is an appropriate use of Options C and F are the correct
"); an assertion because it is not answers. C is correct because
8. } finally { checking the argument of a public an object accessible from a live
9. System.out.print(" three method. thread may yet be called by
"); the JVM. F is correct because
10. } References: all objects are created in the
11. System.out.print(" four "); http://java.sun.com/j2se/1.4/docs/g garbage collectible heap.
12. } uide/lang/assert.html#usage-
13. conditions Location: ... > Garbage
14. public static void foo() { Collection > Objective 3.2 >
15. throw new Item 1
RuntimeException(); -----------------------------------
16. } Location: ... > Flow Control, -----------------------------------
17. } Assertions, and Exception Handling > ----------
Objective 2.6 > Item 1 Click the Exhibit button to
What is the result? (Choose one) ----------------------------------------- view the code.
A three ---------------------------------- 1. class Test {
B two three Which two statements are true? 2. public static void
C three four (Choose two.) main(String [] args) {
D two three four A The -ae flag tells the VM to 3. Test2 t2 = new Test2();
E one two three four enable assertions 4. Test2 t3;
F Compilation fails B The -ea flag tells the compiler to 5. t3 = t2.m1();
Answer: enable assertions 6. t2 = t2.linker(t2,t3);
Option D is the correct answer. C The -assert flag tells the VM to 7. t2 = null;
Method foo() throws a enable assertions 8. t3 = null;
RuntimeException, which does D The -esa flag tells the VM to 9. }
not need to be declared. When enable some assertions 10. }
the exception is thrown, the E The -assertions flag tells the 11.
catch and finally blocks run, and compiler to enable assertions 12. class Test2 {
then the main() method runs to F The -enableassertions flag tells 13. Test2 link;
completion (printing four at the the VM to enable assertions 14. Test2 m1() {
end). Answer: 15. Test2 x = new Test2();
Options D and F are the correct 16. return x;
Location: ... > Flow Control, answers. The -esa flag means enable 17. }
Assertions, and Exception system assertions. 18. Test2 linker(Test2 z1,
Handling > Objective 2.5 > Item Test2 z2) {
1 ocation: ... > Garbage Collection > 19. z1.link = z2;
------------------------------------- Objective 3.1 > Item 1 20. z2.link = z1;
------------------------------------- ----------------------------------------- 21. return z1;
------ --------------------------------------- 22. }
87
23. } 9.
10. private class NewWeakHash Which statement must be
Which statement is true? extends WeakHash { added at line 1 to allow this
11. public NewWeakHash() { code to compile?
12. int x = 7; A import java.util.*;
A After line 8 no objects can be 13. } B no statement is required
garbage collected. 14. C import
B After line 7 one object can be 15. public static void main(String java.util.WeakHashMap;
garbage collected. args [] ) { D include
C After line 7 no objects can be 16. WeakHash wh = new java.util.WeakHashMap;
garbage collected. WeakHash();
D After line 6 at least one 17. } nswer:
object has more than two 18. } Option B is the correct answer.
references When a fully qualified name is
E The z1 and z2 references What is the result? used, you don't have to import
must be nulled to make any A Compilation succeeds the classes or packages.
objects eligible for garbage B Compilation fails because of an
collection. error on line 6 Location: ... > Language
Answer: C Compilation fails because of an Fundamentals > Objective 4.2
Option C is the correct answer. error on line 10 > Item 1
After line 7 the t3 reference is D Compilation fails because of an -----------------------------------
still valid and because of the link error on line 16 -----------------------------------
variables both of the Test2 E An exception is thrown at runtime ----------
objects are still accessible. Answer:
Option C is the correct answer. Which two are valid method
Location: ... > Garbage Classes cannot be declared private. signatures in an interface?
Collection > Objective 3.3 > (Choose two.)
Item 1 1. package com.abc.package1; A short doShort();
------------------------------------- 2. import java.util.*; B static char doChar();
------------------------------------- 3. public class WeakHash extends C protected byte doByte();
------ WeakHashMap { D public boolean
Click the Exhibit button to view 4. int x = 5; doBoolean(int x);
the code. 5. Object getDuplicate(Object key) E final public String
7. Dog [] da = new Dog[2]; { doString(int x);
8. Dog clover = new Dog(); 6. return null; Answer:
9. da[1] = clover; 7. } Options A and D are the
10. clover = null; 8. } correct answers. A is correct
11. Dog fido = new Dog(); 9. because interface methods are
12. Dog spot = new Dog(); 10. private class NewWeakHash implicitly public. D is correct
When is the clover object extends WeakHash { because interface can be
eligible for garbage collection? 11. public NewWeakHash() { declared public even though
A after line 9 12. int x = 7; they are so implicitly.
B after line 10 13. }
C after line 11 14. Location: ... > Language
D never in this code 15. public static void main(String Fundamentals > Objective 4.3
Answer: args [] ) { > Item 1
Option D is the correct answer. 16. WeakHash wh = new -----------------------------------
The last reference to clover WeakHash(); -----------------------------------
(da[1]), is never nulled. 17. } ----------
18. } Click the Exhibit button to
Location: ... > Language view the code.
Fundamentals > Objective 4.1 > Location: ... > Language 1. public class ABC {
Item 1 Fundamentals > Objective 4.1 > 2. public static void
------------------------------------- Item 2 main(String [] args ) {
------------------------------------- ----------------------------------------- 3. String a = args[3];
------ --------------------------------------- 4. String b = args[2];
Click the Exhibit button to view Click the Exhibit button to view the 5. String c = args[1];
the code. code. 6. System.out.println("c = "
1. package com.abc.package1; 1. + c);
2. import java.util.*; 2. public class NewCollections { 7. }
3. public class WeakHash 3. public static void main(String [] 8. }
extends WeakHashMap { args) { And the command line
4. int x = 5; 4. java.util.WeakHashMap hm = invocation:
5. Object getDuplicate(Object new java.util.WeakHashMap(); java ABC A B C
key) { 5. Object o1 = null; What is the result?
6. return null; 6. o1 = hm.put(o1, o1); a c=
7. } 7. } B c=A
8. } 8. } C c=B
88
D c=C is a Java concept but not a keyword. Location: ... > Language
E Compilation fails B 'Boolean' is a class. The Java Fundamentals > Objective 4.6
F An exception is thrown at primitive keyword is 'boolean'. > Item 1
runtime -----------------------------------
Location: ... > Language -----------------------------------
Answer: Fundamentals > Objective 4.5 > ----------
Option F is the correct answer. Item 1 Which one is valid?
Line 3 will fail; args[3] is out of ----------------------------------------- A boolean b2 = 1;
bounds. --------------------------------------- B boolean b3 = null;
Click the Exhibit button to view the C boolean b1 = FALSE;
Location: ... > Language code. D boolean b4 = "false";
Fundamentals > Objective 4.4 > 1. class IvarLocal { E boolean b5 = (4 < 1);
Item 1 2. static int x; answer:
------------------------------------- 3. public static void main(String Option E is the correct answer.
------------------------------------- args []) { The expression (4 < 1)
------ 4. int y; resolves to false.
Click the Exhibit button to view 5. System.out.println("x = " + x +
the code. " y = " + y); Location: ... > Language
1. class Test { 6. } Fundamentals > Objective 4.6
2. public static void 7. } > Item 2
main(String [] args) { -----------------------------------
3. construct Test(int i) { What is the result? -----------------------------------
4. for (int y=0; y<i; y++) A x=y= ----------
5. System.out.print(" " + B x=y=0 Which three are valid?
y); C x=0y= (Choose three.)
6. } D x=0y=0 A float f1 = 0x123.45;
7. } E Compilation fails B float f2 = 3.14f;
8. } F An exception is thrown at runtime C float f3 = (double) 1.8;
D float f4 = 1.0;
And command line invocation: E float f5 = (float) '\'';
F float f6 = '\ubabe';
java Test 6 Answer:
Option E is the correct answer. The Answer:
What is the result? compiler will be concerned about Options B, E, and F are the
a 12345 whether y has been initialized. correct answers. B is explicitly
B 012345 cast to a float. E casts a char
C Compilation fails Location: ... > Language (which is an unsigned int) to a
D An exception is thrown at Fundamentals > Objective 4.5 > float. F casts a Unicode char to
runtime Item 2 a float.
Answer: -----------------------------------------
Option C is the correct answer. --------------------------------------- Location: ... > Operators and
The word 'construct' is not a Click the Exhibit button to view the Assignments > Objective 5.1 >
valid modifier keyword in the code. Item 2
Java language. Constructors are 7. short x = 1; -----------------------------------
identified by having the same 8. int [] y = new int[4]; -----------------------------------
name as the class, but having no 9. y[0] = x; ----------
return type. 10. y[1] = x+1; Given:
11. for(int z= 0;z<4; z++) {
Location: ... > Language 12. System.out.println(" " + 10. int x = -1, y = -2;
Fundamentals > Objective 4.4 > y[z]); 11. System.out.println( (x<0)
Item 2 13. } ^ (y<0) ) ;
-------------------------------------
------------------------------------- What is the result? What is the result?
------ A 0123 A true
Which two are keywords? B 1223 B false
(Choose two.) C 1200 C Compilation fails
A super D 1 2 null null D The code runs with no
B Boolean E Compilation fails output
C unsigned F An exception is thrown at runtime E An exception is thrown at
D interface runtime
E anonymous Answer:
Answer: Option B is the correct answer.
Options A and D are the correct Answer: Both equality tests resolve to
answers. 'interface' and 'super' Option C is the correct answer. The true - true XOR true is false.
are both valid keywords. C is elements in array y are implicitly
wrong because 'unsigned' is a initialized to zeros, and then Location: ... > Operators and
keyword in C, C++, but not Java. elements 0 and 1 are updated. Assignments > Objective 5.2 >
E is wrong because 'anonymous' Item 1
89
------------------------------------- that resolve to false in all three 15. }
------------------------------------- composite boolean expressions the 16. public void arrayTest () {
------ outcome must be false. 17. boolean[] initial = null;
18. op3( initial );
click the Exhibit button to view Location: ... > Operators and 19.
the code. Assignments > Objective 5.3 > Item System.out.println( initial[0] );
10. int[] arr1 = new int[2]; 2 20. }
11. int[] arr2 = -----------------------------------------
(int[])arr1.clone(); --------------------------------------- What is the result if method
12. System.out.println( "Array 1 Click the Exhibit button to view the arrayTest() is called?
equals array 2 - " + code.
arr1.equals( arr2 ) ); 10. public boolean t1() { return A true
"hello".equals("HELLO"); } B null
What is the result? 11. public boolean t2() { return ! C false
A Array 1 equals array 2 - t1(); } D Compilation fails
B Array 1 equals array 2 - true 12. E The code runs with no
C Array 1 equals array 2 - null 13. public void op () { output
D Array 1 equals array 2 - false 14. System.out.println( (t1() && F An exception is thrown at
E Compilation fails t2()) | t2() ); runtime
F An exception is thrown at 15. }
runtime
Which four are true? (Choose four.) Answer:
Answer: A Compilation fails Option F is the correct answer.
Option D is the correct answer. B Calling op() means t2() is always An exception is thrown at
Arrays inherit the default called once runtime. Defining and
Object.equals implementation C Calling op() means t1() is always initializing the array in op3()
which compares references not called once has no effect on the callers
equivalence of content therefore D The output from op() is always reference which remains null.
comparing two distinct arrays will the value true Therefore the access on
always yield false even if the E Calling op() means t2() is always initial[0] causes a
compared arrays are clones. called twice java.lang.NullPointerException
F Calling op() means t1() is always
Location: ... > Operators and called twice Location: ... > Operators and
Assignments > Objective 5.3 > G Reversing the first expression to Assignments > Objective 5.4 >
Item 1 (t2() && t1()) does not affect the Item 2
------------------------------------- output -----------------------------------
------------------------------------- -----------------------------------
------ Answer: ----------
Click the Exhibit button to view Options B, D, F, and G are the Click the Exhibit button to
the code. correct answers. view the code.
10. boolean flag1 = true; t1() resolves to false t2() resolves to 10. public StringBuffer
11. boolean flag2 = false; not t1() - true reordering the first op4( StringBuffer sb ) {
12. System.out.println( ( flag2 & expression does not affect the 11. sb.append("-widgets");
flag1 ) & ( flag1 & flag2 ) ); outcome because it is a double && 12. return sb;
The first call to t1() returns false and 13. }
Which two are true? (Choose will shortcut the && expression to 14. public void roundRobinTest
two.) false and the non shortcut | to the () {
second t2() returns true resulting in 15. StringBuffer sb = new
A The code outputs the value overall true. Due to shortcut t2() is StringBuffer();
false only ever called once t1() is called 16. sb.append("acme");
B The output may vary if the once in the expression and a second 17. op4(sb);
ordering is changed time from t2(), therefore is called 18. sb.append("-and-
C flag1 and flag2 are both twice nuggets");
evaluated exactly once 19.
D The output is always true Location: ... > Operators and System.out.println( sb.toString
regardless of the ordering Assignments > Objective 5.4 > Item () );
E The output is always false 1 20. }
regardless of the ordering -----------------------------------------
--------------------------------------- What is the result if method
Answer: click the Exhibit button to view the roundRobinTest() is called?
Options A and E are the correct code.
answers. The entire logical 10. public void op3( boolean[] flags ) A acme
statement is composed of non { B acme-widgets
shortcutting and therefore ALL 11. flags = new boolean[3]; C -and-nuggets
boolean expressions will be 12. for ( int i=0; i<flags.length; i+ D acme-and-nuggets
evaluated regardless of the +){ E -widgets-and-nuggets
outcome of a preceding 13. flags[i] = ((i%2)==0); F acme-widgets-and-nuggets
evaluation. As there are booleans 14. }
90
Answer: B Compilation fails for code -
Option F is the correct answer. Location: ... > Objective 6.1 > Item new P();
sb is created in roundRobinTest 2 C Compilation fails for code -
and its reference passed by value ----------------------------------------- new Q("");
into op4 where the shared object --------------------------------------- D Compilation fails for code -
is modified. The same sb is then Click the Exhibit button to view the new P('a');
returned to the caller, but the code. E Compilation fails for code -
caller never assigns or re-assigns 1. interface D {} new Q((short)1);
its local sb reference and it 2. class E implements D {} F Compilation fails for code -
appears that modifications in op4 3. class F extends E { new Q( new Q(3) instanceof
are lost, but as this is a shared 4. F() {} P );
object by reference all 5. } Answer:
modifications remain, so the 6. class G extends F implements D Options B, C, and D are the
output is acme-widgets-and- {} correct answers. The
nuggets 7. class X { relationship and declaration of
8. public static void main( String[] P & Q are sound. This question
Location: ... > Objective 6.1 > args ) { is quite simple couched in
Item 1 9. E e = new F(); seemingly complex code.
------------------------------------- 10. D d = new G(); Simply test the argument
------------------------------------- 11. } passed in the new call with a
------ 12. } constructor in the target class,
Click the Exhibit button to view if a match is found it compiles.
the code. Which three are true? (Choose The last three options here do
1. class A { three.) not have matching
2. private static class B { A The declaration of G is illegal constructors.
3. private static String msg B E is said to be a superclass of F
= "ok" ; C G is said to be a superclass of E Location: ... > Objective 6.2
4. } D The assignment at line 10 is legal > Item 2
5. public static String access() E A variable can be declared using -----------------------------------
{ an interface type -----------------------------------
6. return B.msg; F Compilation fails ----------
7. }
8. } answer: Click the Exhibit button to view
9. class X { B, D, and E. B is correct because the code.
10. public static void class F extends class E, making E a 10. abstract class X {
main( String[] args ) { superclass of F. D and E are correct 11. public final void op(){}
11. because the code compiles 12. abstract final void op();
System.out.println( A.access() ); successfully, the declaration of G 13. void op( String s ){}
12. } reimplementing D is legal, as is the 14. abstract synchronized
13. } declaration of d using an interface D void op(int i) throws Exception;
as its type. 15. abstract private void
Which two are true? (Choose op( String a, int i );
two.) Location: ... > Objective 6.2 > Item 16. }
A Compilation fails 1
B The code outputs the value ----------------------------------------- Which three are true? (Choose
ok --------------------------------------- three.)
C An exception is thrown at Click the Exhibit button to view the
runtime code.
D Any private members of B 10. class P {
can be accessed from class A 11. P( String s ){} A Line 10 is uncompilable
only through accessor methods 12. P( short s ){} B Line 11 is uncompilable
E The private modifier on msg 13. } C Line 12 is uncompilable
must be weakened to default or 14. class Q extends P { D Line 13 is uncompilable
public for this code to work 15. protected Q() E Line 14 is uncompilable
correctly { super((short)3); } F Line 15 is uncompilable
Answer: 16. public Q( int i ) { super( new Answer:
Options B and D are the correct Integer(i).toString() ); } Options C, E, and F are the
answers. Access to an nested 17. Q( boolean b ) { super(""); } correct answers.
classes private methods and 18. Q( short s ) { super( s ); } line 10 ok, the class must be
variables is granted to the 19. } declared abstract
encapsulating classes methods. line 11 ok, the initial method
If the following new statements are declaration signature
Reference: invoked in a separate class in the line 12 fails, cannot combine
The Java Programming same package as classes P and Q, abstract and final, conflict of
Language, Third Edition, by which three are true? (Choose intentions
Arnold, Gosling & Holmes, three.) line 13 ok, the first successful
Chapter 3: Extending Classes -- A Compilation fails for code - new overload of op(), but with
ISBN: 0-201-70433-1 Q(); differing access privileges
91
line 14 fails, cannot combine 13. } 2. class Widget extends
abstract with implementation 14. } java.lang.Thread {
details like synchronized 3. Widget(boolean daemon)
line 15 fails, cannot combine Which two are true? (Choose two.) {
abstract and private, no way to A Line 5 is uncompilable 4.
implement in subclass B Line 9 is uncompilable this.setDaemon(daemon);
C Line 10 is uncompilable 5. this.start();
Location: ... > Objective 6.3 > D Line 11 is uncompilable 6. }
Item 1 E Line 12 is uncompilable 7. }
------------------------------------- F Compilation succeeds 8.
------------------------------------- 9. for ( int i= 0;i<10; i++ ) {
--- 10. new Widget(((i
Click the Exhibit button to view Answer: %2)==0));
the code. Options B and E are the correct 11. }
1. interface XX {} answers. Line 9 attempts to 12. }
2. interface YY extends XX {} instantiate an interface. Line 12 is an
3. abstract class ZZ implements incompatible assignment; you can't Which two statements are
XX {} assign a superclass object to a true? (Choose two.)
4. class AA extends ZZ subclass reference type. A Compilation fails.
implements YY { Location: ... > Objective 6.3 > B Only five threads are
5. private class BB{} Item 2 created.
6. } Click the Exhibit button to view C An exception is thrown at
7. class Main extends AA { the code. runtime.
8. public static void 1. class Outer { D Ten independent threads
main( String[] args ) { 2. class Inner {} are created.
9. XX xx1 = new XX (); 3. } E Ten threads are created but
10. XX xx2 = new AA (); 4. class ExtendedOuter extends only five execute.
11. ZZ zz1 = new Main (); Outer { F The program terminates
12. Main m = new AA(); 5. class ExtendedInner extends after the tenth thread is
13. } Inner {} created.
14. } 6. } Answer:
7. class Main extends Outer.Inner { Options D and F are the correct
Which two are true? (Choose 8. Main( Outer ref ) { answers. The program creates
two.) 9. ref.super(); precisely 10 threads, every
A Line 5 is uncompilable 10. } other of which is marked as
B Line 9 is uncompilable 11. public static void main( String[] daemon thread. Each thread
C Line 10 is uncompilable args ) { executes on the default run()
D Line 11 is uncompilable 12. new Main( new method so all will terminate
E Line 12 is uncompilable ExtendedOuter() ); and therefore the program
F Compilation succeeds 13. } terminates.
Answer: 14. }
Options B and E are the correct Reference:
answers. Line 9 attempts to What is the result? The Java Programming
instantiate an interface. Line 12 A Compilation fails Language, Third Edition, by
is an incompatible assignment; B An exception is thrown at runtime Arnold, Gosling & Holmes,
you can't assign a superclass C The code runs with no output Chapter 10: Threads
object to a subclass reference ISBN: 0-201-70433-1
type. Answer:
Option C is the correct answer. An location: ... > Threads >
Location: ... > Objective 6.3 > inner class can extend another, Objective 7.1 > Item 2
Item 1 unrelated, inner class provided an -----------------------------------
Click the Exhibit button to view appropriate enclosing instance is -----------------------------------
the code. supplied to the superclass. The ----------
1. interface XX {} resulting inner class then has two Click the Exhibit button to
2. interface YY extends XX {} enclosing instances, one for the view the code.
3. abstract class ZZ implements extended class and one for the 11. public static void
XX {} superclass. Therefore this code main( String[] args ) {
4. class AA extends ZZ cleanly compiles and outputs 12. class Widget extends
implements YY { nothing. java.lang.Thread {
5. private class BB{} Location: ... > Threads > Objective 13. Widget() {
6. } 7.1 > Item 1 14. this.start();
7. class Main extends AA { ----------------------------------------- 15. }
8. public static void --------------------------------------- 16. }
main( String[] args ) { Click the Exhibit button to view the 17.
9. XX xx1 = new XX (); code. 18. Widget w = new
10. XX xx2 = new AA (); 1. public static void main( String[] Widget();
11. ZZ zz1 = new Main (); args ) { 19. w.setDaemon(true);
12. Main m = new AA(); 20. }
92
Options D and F are the correct -----------------------------------
Which statement is true? answers. As all threads are marked -----------------------------------
A Compilation fails. as Daemon threads, the program ----------
B The program never contains no user threads once main Click the Exhibit button to
terminates. terminates, so the program as a view the code.
C One daemon thread is whole terminates. A number of the 10. class X {
created. daemon threads may never execute 11. synchronized void iTest()
D An exception is thrown at due to the early termination of the {
runtime. program and the priority levels 12. while(true) {
E The program terminates after assigned. 13. Thread.yield();
the thread is created. Reference: 14. }
Answer: The Java Programming Language, 15. }
Option D is the correct answer. Third Edition, by Arnold, Gosling & 16. synchronized static void
An exception is thrown at Holmes, Chapter 10: Threads sTest() {}
runtime - ISBN: 0-201-70433-1 17. public void op() {}
va.lang.IllegalThreadStateExcepti 18. }
on setdaemon(true) can not be Location: ... > Threads > Objective
invoked on an active thread. 7.2 > Item 2 And, given a single instance of
Reference: X, and two or more concurrent
The Java Programming Click the Exhibit button to view the threads, which statement is
Language, Third Edition, by code. true?
Arnold, Gosling & Holmes 1. class Worker extends A Multiple threads can
Chapter 10: Threads java.lang.Thread { execute iTest() concurrently.
ISBN: 0-201-70433-1 2. public void run() { B Any thread calling iTest()
3. while ( true ) { will be blocked pending a call
Location: ... > Threads > 4. synchronized( this ) { to notify.
Objective 7.2 > Item 1 5. try { C While a thread is executing
------------------------------------- 6. wait(); iTest(), any call on sTest() will
------------------------------------- 7. } catch (Exception e) {} block pending lock access.
------ 8. } D While a thread is executing
Click the Exhibit button to view 9. System.out.println("ok"); iTest(), no other threads may
the code. 10. } execute any methods declared
1. class Worker extends 11. } in X.
java.lang.Thread { 12. public static void main( String[] E While a thread is executing
2. public void run() { args ) { iTest(), op() may be
3. while ( true ) {} 13. new Worker().start(); concurrently executed inside
4. } 14. } the same instance of X.
5. 15. } Answer:
6. public static void Option E is the correct answer.
main( String[] args ) { Which two statements are true? Static methods synchronize on
7. for (int i=0; (Choose two.) the class object, not on an
i<MAX_PRIORITY; i++ ){ A Compilation fails. instance object, so concurrent
8. Worker w = new B The program never terminates. calls to iTest() and sTest() will
Worker(); C The program runs with no output. not block each other. op() is
9. D The value ok is repeatedly not synchronized so may be
w.setPriortity( MIN_PRIORITY+i ) output. called concurrently with
; E The program terminates and anything else.
10. w.setDaemon(true); outputs ok precisely once.
11. w.start(); F The Worker thread never blocks Reference:
12. } inside the wait method because there The Java Programming
13. } are no other threads executing. Language, Third Edition, by
14. } answer: Arnold, Gosling & Holmes,
Options B and C are the correct Chapter 10: Threads
Which two statements are true? answers. This program simply ISBN: 0-201-70433-1
(Choose two.) launches a single user thread that Location: ... > Threads >
immediately blocks inside the wait() Objective 7.3 > Item 2
A Compilation fails. method The thread is never -----------------------------------
B An exception is thrown at unblocked because no other thread is -----------------------------------
runtime. executing to call the notify on the ----------
C All threads are guaranteed to lock. Click the Exhibit button to
execute. Reference: view the code.
D Some of the threads may The Java Programming Language, 1. class WorkerT extends
never execute. Third Edition, by Arnold, Gosling & java.lang.Thread {
E The program runs forever Holmes, Chapter 10: Threads 2. private static StringBuffer
with no output. ISBN: 0-201-70433-1 sb = new StringBuffer();
F The program terminates when Location: ... > Threads > Objective 3. public void run() {
the main() method completes. 7.3 > Item 1 4. notify();
Answer: 5. try {
93
6. wait(); The Java Programming Language, greater number is 6, but for
7. } catch (Exception e) {} Third Edition, by Arnold, Gosling & -5.5 the greater number is
8. } Holmes, Chapter 10: Threads -5.0.
9. public static void ISBN: 0-201-70433-1 Location: ... > Fundamental
main( String[] args ) { Location: ... > Threads > Objective Classes in the java.lang
10. for (int i= 0;i<10; i++) { 7.4 > Item 2 package > Objective 8.2 >
11. new WorkerT().start(); ----------------------------------------- Item 1
12. } --------------------------------------- -----------------------------------
13. } which two statements are correct? -----------------------------------
14. } (Choose two.) ----------
A To call notify() a thread must Click the Exhibit button to
Which statement is true? own the monitor lock. view the code.
A Compilation fails. B The notify() and notifyAll() 1. public class Test823 {
B All 10 threads block. methods are defined in the Thread 2. public static void
C An exception is thrown at class. main(String [] args) {
runtime. C The notify() and notifyAll() 3. String a = "freddy";
D All 10 threads execute to methods are defined in the Object 4. String b =
completion. class. a.substring(0,3);
E Each thread is unlocked by D A thread can only call notify() if 5. b.toUpperCase();
the following thread until only another thread has previously called 6. System.out.println(a +=
the final thread remains blocked. wait(). b);
Answer: E The notify() and notifyAll() 7. }
Option C is the correct answer. methods are defined in the Runnable 8. }
An exception is thrown interface. What is the result?
java.lang.IllegalMonitorStateExce Answer: A freddyFRE
ption: current thread not owner. Options A and C are the correct B freddyfre
The caller of wait(), notify(), or answers. C freddyFRED
notifyAll() must own the monitor D freddyfred
lock that is, they must be Reference: E Compilation fails.
executing inside a synchronized The Java Programming Language, Answer:
method or section to be able to Third Edition, by Arnold, Gosling & Option B is the correct answer.
successfully call any of these Holmes, Chapter 10: Threads The a String reference is never
methods. ISBN: 0-201-70433-1 modified, and the
toUpperCase() call is not
Reference: Location: ... > Fundamental Classes assigned to b so b's original
The Java Programming in the java.lang package > Objective object does not change.
Language, Third Edition, by 8.1 > Item 1 Location: ... > Fundamental
Arnold, Gosling & Holmes, ----------------------------------------- Classes in the java.lang
Chapter 10: Threads --------------------------------------- package > Objective 8.2 >
ISBN: 0-201-70433-1 Click the Exhibit button to view the Item 2
Location: ... > Threads > code. -----------------------------------
Objective 7.4 > Item 1 1. public class Test813 { -----------------------------------
------------------------------------- 2. public static void main(String [] ----------
------------------------------------- args) { Click the Exhibit button to
------ 3. double a = Math.round(5.5); view the code.
Which three statements are 4. double b = Math.round(5.2); 1. public class Test825 {
true? (Choose three.) 5. double c = Math.round(-5.0); 2. public static void
A The Object class defines a 6. double d = Math.round(-5.4); main(String [] args) {
wait() method. 7. double e = Math.round(-5.5); 3. String a = "big";
B The Thread class overrides 8. System.out.print( "Results: " + 4. String b = a;
a wait() method. a+""+b+""+c+""+d+"" 5. a = a + "bird";
C The Runnable interface + e); 6. a = b;
defines a wait() method. 9. } 7. b = "bird";
D wait() can be called at any 10. } 8. System.out.println(a =
time by an executing thread. a+b);
E The wait() method used in What is the result? 9. }
thread communication releases A Results: 6.0 5.0 -5.0 -5.0 -5.0 10. }
an object lock. B Results: 6.0 5.0 -5.0 -5.0 -6.0
F The wait() method is C Results: 5.0 5.0 -5.0 -5.0 -5.0 What is the result?
overloaded and also has the D Results: 6.0 5.0 -5.0 -4.0 -5.0 A bigbird
following signature public final E Results: 6.0 5.0 5.0 5.0 6.0 B birdbird
void wait(long timeout). F Compilation fails. C bigbigbird
D bigbirdbird
answer: nswer: E Compilation fails.
Options A, E, and F are the Option A is the correct answer. Both Answer:
correct answers. positive and negative numbers are Option A is the correct answer.
Reference: rounded up to the larger number. For In line 4, b is set to refer to the
a positive number such as 5.5, the String literal "big". The String
94
referenced by b is not changed 7. } B Amy, Fred, Mike, Zeus,
by the change to a in line 5, catch(NumberFormatException ex) { C Fred, Mike, Zeus, Fred,
because Strings are immutable. 8. System.out.println("failed"); Amy,
In line 5, a new String object 9. } D Amy, Fred, Fred, Mike,
"bigbird" is created, and assigned 10. } Zeus,
to a. At this point (line 5) b is 11. } E Five elements will be
still referring to "big" and a is printed, but the order is not
now referring to "bigbird". In line What is the result? guaranteed.
6,then, a is set to refer to the A 6 F Four elements will be
String literal "big" referenced by B 6.0 printed, but the order is not
b, so both a and b refer to the C null guaranteed.
String literal "big". In line 7, b is D failed
set to reference a String literal E Compilation fails.
"bird", while a is left unchanged F An uncaught exception is thrown
and still refers to "big". Finally, a at runtime. Answer:
+ b is printed out, producing Answer: Option B is the correct answer.
"bigbird". Option E is the correct answer. Byte A TreeSet is a Set, which
does not have a constructor that eliminates duplicates, so Fred
takes an int. The Byte constructor only goes in once. A TreeSet is
Location: ... > Fundamental must be passed a previously declared sorted so the Strings come out
Classes in the java.lang package byte variable, or explicitly cast an int in alphabetical order
> Objective 8.3 > Item 1 value. Location: ... > The
------------------------------------- Collections Framework >
------------------------------------- Location: ... > The Collections Objective 9.2 > Item 1
--- Framework > Objective 9.1 > Item 1 -----------------------------------
Which creates a new Character ----------------------------------------- -----------------------------------
object? --------------------------------------- ----------
A Character a = new Which two statements are true of If class X implements
Character("c"); class java.util.HashMap? (Choose hashcode() and equals()
B Character a = two.) correctly, and given two
Character.getCharacter('s'); A Its methods are thread-safe. instances (o1 and o2) of class
C Character a = new B It allows null references to be X, which two are true? (Choose
Character(new char[]{'s'}); stored. two.)
D Character a = C It provides fast, bi-directional
Character.valueOf("c".toChar()); iteration. A if o1.hashcode() and
E Character a = new D It implements java.util.Hashable. o2.hashcode() are not the
Character((new char[]{'s'})[0]); E It tracks when its elements were same, then o1 and o2 must not
Answer: last accessed. be equal
Option E is the correct answer. F Its elements can be accesssed B o1.hashcode() and
The Character class has only one using a unique key. o2.hashcode() might be the
constructor, and it takes a char Answer: same if o1 and o2 are
primitive. Answer "E" constructs Options B and F are the correct considered equal
an anonymous char array holding answers. HashMap implements C o1.hashcode() and
a single char, then accesses the java.util.Map, which allows elements o2.hashcode() must be the
array element at index 0, thus to be accessed using a unique key. same if o1 and o2 are
returning a char to the Character Whereas HashTable does not permit considered equal
constructor. null references to be stored, D if o1 and o2 are not equal,
Location: ... > Fundamental HashMap allows both keys and then o1.hashcode() and
Classes in the java.lang package elements to be null. o2.hashcode() must not be the
> Objective 8.3 > Item 2 Location: ... > The Collections same
------------------------------------- Framework > Objective 9.1 > Item 2 Answer:
------------------------------------- ----------------------------------------- Options A and C are the correct
------ --------------------------------------- answers. Hashcode suggests
Click the Exhibit button to view Click the Exhibit button to view the the likelihood of equality, while
the code. code. equality requires that
1. public class Test834 { 1. TreeSet s = new TreeSet(); hashcodes must be the same.
2. public static void main(String 2. s.add("Fred"); The rules for correct
[] args) { 3. s.add("Mike"); implementation of hashcode
3. try { 4. s.add("Zeus"); and equals require that if two
4. Double d = new 5. s.add("Fred"); objects are equal, their
Double(new 6. s.add("Amy"); hashcodes MUST be the same.
Byte(6).doubleValue()); 7. Iterator i = s.iterator(); If two objects are unequal,
5. String s = d.toString(); 8. while(i.hasNext()) { however, they may still have
6. 9. System.out.print(i.next() + ", the same hashcode. So, object
System.out.println(Integer.parse "); equivalency guarantees
Int(s)); 10. } hashcode equivalency, but
What is the result? hashcode equivalency does not
A Fred, Mike, Zeus, Amy, guarantee object equivalency.
95
Question 2: What statements are
true concerning the public void run() {
method notify() that is
Question 1: Given the used in conjunction with for (int i = startHere; i <=
following class wait()? endHere; i++) {
definition:
class A { Select all valid answers. System.out.println(i);

protected int i; }
a) if there is more than one thread
waiting on a condition, only the
A(int i) { }
thread that has been waiting the
longest is notified
this.i = i; };

b) if there is more than one thread


}
waiting on a condition,there is no
way to predict which thread will be b)
}
notifed
a implements Runnable {
Which of the following would be
c) notify() is defined in the Thread
a valid inner class for this class? public void run() {
class

Select all valid answers. for (int i = startHere; i <=


d) it is not strictly necessary to own
the lock for the object you invoke endHere; i++) {
a) notify() for
System.out.println(i);
class B { e) notify() should only be invoked }
from within a while loop
}
}
Question 3: Given the following
b) class: };
class Counter {
class B extends A {
public int startHere = 1;
} c)
public int endHere = 100;
c) Thread a = new Thread() {
public static void main(String[]
args) { public void run() {
class B {
new Counter().go(); for (int i = startHere; i <=
B() { endHere; i++) {
System.out.println("i = " + }
System.out.println(i);
i);
void go() {
}
}
// A
}
}
Thread t = new Thread(a);
};
d) t.start();
Question 4: What is written
class B { } to the standard
output given the
class A { } following statement:
System.out.println(4 | 7);
} What block of code can you replace
at line A above so that this program Select the one right answer.
} will count from startHere to
endHere?
a) 4
e)
Select all valid answers.
b) 5
class A {
a)
} c) 6
Runnable a = new Runnable() {
d) 7
96
e) 0 Thread.sleep(1000);
public float z;
Question 5: Given the } catch (InterruptedException
following class: x) {} }
class Counter {
}
public static void main(String[]
}
args) { What can method2() access
directly, without a reference to
}
Thread t = new Thread(new another instance?
CounterBehavior());

t.start();
c) This class is a top-level class:
Select all valid answers.
}

} a) the variable x defined in A


static class CounterBehavior
implements Runnable {
Which of the following is a valid b) the variable y defined in A
definition of CounterBehavior public void run() {
that would make Counter’s c) method1 defined in B
main() method count from 1 to try {
100, counting once per second? d) the variable z defined in D
for (int i = 1; i <= 100; i++) {
Select the one right answer.
System.out.println(i);
a)This class is an inner class to Question 7: You have an 8-
Counter: Thread.sleep(1000);
bit file using the
} character set defined
by ISO 8859-8. You
} catch (InterruptedException x) are writing an
class CounterBehavior { application to
{}
display this file in a
for (int i = 1; i <= 100; i++); TextArea. The local
}
encoding is already
try { set to 8859-8. How
}
can you write a
System.out.println(i); chunk of code to
Question 6: Given the following
read the first line
Thread.sleep(1000); class definition:
from this file?
class A {
} catch
You have three variables
(InterruptedException x) {} public int x;
accessible to you:
} private int y;
 myfile is the name of
} class B { the file you want to
read
protected void method1() {  stream is an
InputStream object
b) This class is an inner class to } associated with this file
Counter:  s is a String object
class C {
Select all valid answers.
private void method2() {
class CounterBehavior
implements Runnable { } a)

public void run() { } InputStreamReader reader =


new
for (int i = 1; i <= 100; i+ } InputStreamReader(stream,
+); "8859-8");
}
try { BufferedReader buffer = new
BufferedReader(reader);
System.out.println(i);
class D extends A { s = buffer.readLine();
97
b) Question 9: For a variable width int method2(int j) { }
font, how "wide" is a int method1(int i) { }
InputStreamReader reader = TextField created using }
new the expression:
InputStreamReader(stream); new TextField(20) Question 11: Given the
following code:
BufferedReader buffer = new Select the one right answer. import java.awt.*;
BufferedReader(reader); import java.awt.event.*;
public class MyApplet extends
a) 20 times the average of all the
s = buffer.readLine(); java.applet.Applet {
characters in the font used for this
public void init() {
TextField object
c) Button b = new
Button("Button1");
b) 20 times the width of the letter M b.addMouseListener(new
InputStreamReader reader =
ClickHandler());
new InputStreamReader(myfile,
c) 20 times the width of the letter a add(b);
"8859-8");
}
d) 20 inches class ClickHandler extends
BufferedReader buffer = new
MouseAdapter {
BufferedReader(reader);
public void
e) 20 picas
mouseClicked(MouseEvent evt)
s = buffer.readLine();
{
Question 10: Given this interface // A
d) definition: }
interface A { }
InputStreamReader reader = }
new InputStreamReader(myfile); int method1(int i);
What line of code at A writes
BufferedReader buffer = new int method2(int j); the mouse’s horizontal location
BufferedReader(reader); } to the standard output at the
which of the following classes time of the event?
s = buffer.readLine(); implement this interface and is not
abstract?
Fill in the blank.
e)
Select all valid answers.
Question 12: Given the
FileReader reader = new same code as in
FileReader(myfile); a) question 10, how
can you write a line
BufferedReader buffer = new class B implements A { of code at A that will
BufferedReader(reader); place the Button
int method1() { } object into a variable
s = buffer.readLine(); named mybutton
int method2() { } that is already
Question 8: How can you defined to be a
write a line of code for } reference to a
an applet’s init() Button object?
method that b)
determines how wide
Fill in the blank.
the applet is? class B {

Select all valid answers. int method1(int i) { }

int method2(int j) { }
a) int width = this.getY();
}
b) int width = this.getSize().w;
c)
class B implements A {
c) int width = getSize();
int method1(int i) { }
int method2(int j) { }
d) int width = getSize().w;
}
d)
e) int width = getWidth();
class B extends A {
int method1(int i) { }
int method2(int j) { }
}
e)
class B implements A {
98
Question 13: Which Listener } catch (RuntimeException x) { d) When this code runs,
interface can you System.out.println("2"); nothing is written to the
implement to be able return; standard output.
to respond to the user } catch (Exception x) {
hitting the enter key System.out.println("3"); e) When this code runs, the
after typing into a return; letter "a" is written to the
TextField object? } finally { standard output.
System.out.println("4");
Question 14: What is written }
uestion 19: What keyword
to the standard output System.out.println("5");
must appear in a
as the result of }
method declaration
executing the
(followed by the
following statements? elect all valid answers. name of the
Boolean b1 = new Boolean(true); exception) when
Boolean b2 = new Boolean(true); a) "1" that method might
if (b1 == b2) cause an exception
if (b1.equals(b2)) to be thrown and
b) "2"
System.out.println("a"); that method does
else not handle the
System.out.println("b"); c) "3"
exception?
else
if (b1.equals(b2)) d) "4" Question 20: Which
System.out.println("c"); statements
else e) "5" accurately describe
System.out.println("d"); the following line of
Question 17: What is the type of code?
)a the Event object passed to
the mouseDragged() Select all valid answers.
b) b method defined in a class
that implements String[][] s = new String[10]
c) c java.awt.event.MouseMoti [];
onListener (that is, what
is the class name for the
d) d a) This line of code is illegal.
argument)?

Question 15: Which Listener estion 18: Examine the following b) s is a two-dimensional array
interfaces can you add switch block: containing 10 rows and 10
to a TextArea object? columns
char mychar = 'c';

a) TextListener switch (mychar) { c) s is an array of 10 arrays.

b) ActionListener default: d) Each element in s is set to


""
c) MouseMotionListener case 'a': System.out.println("a");
break; e) Each element in s is
d) MouseListener uninitialized and must be
case 'b': System.out.println("b"); initialized before it is
break; referenced.
e) ComponentListener
}
uestion 21: What will
happen if you try to
Which of the following questions are compile and run the
Question 16: What appears in definitely true? following class?
the standard output if
the method named class Test {
Select all valid answers.
problem() in the code
below throws an static int myArg = 1;
instance of class a) This switch block is illegal,
Exception when the because only integers can be used in public static void
method named the switch statement. main(String[] args) {
trythis() is invoked?
b) This switch block is fine. int myArg;
public void trythis() {
try {
System.out.println("1"); c) This switch block is illegal,
System.out.println(myArg);
problem(); because the default statement must
come last.
}
99
Fill in the blank. Question 27: To determine
} if you can invoke
Question 25: Which interface addContainerListene
Select the one right answer. implementations can you add as r() for a component
listeners for a TextField object? referenced using a
variable named c,
a) This code compiles and
which expression(s)
displays 0 in the standard output Select all valid answers.
can you evaluate
when run.
that will give you a
a) ActionListener true or false answer
b) This code compiles and to this questions?
displays 1 in the standard output b) FocusListener
when run.
Select all valid answers.
c) MouseMotionListener
c) This code does not compile
a) c == Container
because you cannot define a
d) WindowListener b) c.equals(Class.Container)
local variable named the same as
c) c instanceof Container
a static variable.
e) ContainerListener d) c instanceof Component
e) c implements Container
d) This code does not compile
because the local variable is used Question 26: What must be true
Question 28: Write a
before it is initialized. for the RunHandler class
statement for a
so that instances of
constructor that
RunHandler can be used
Question 22: Which invokes the no-args,
as written in the code
declarations for the default constructor
below:
main() method in a in its superclass.
stand-alone program class Test {
are NOT valid? Question 29: What is
public static void main(String[] written to the
args) { standard output
Select all valid answers.
given the following
Thread t = new Thread(new statement:
a) public static void main() RunHandler());
System.out.println(4 & 7);
b) public static void t.start();
main(String[] string) Select the one right answer.
}
c) public static void main(String a) 4
args) }
b) 5
d) static public int main(String[] Select all valid answers.
args) c) 6
a) RunHandler must implement the
e) static void main(String[] args) java.lang.Runnable interface. d) 7

Question 23: Which of the b) RunHandler must extend the e) 0


following identifiers Thread class.
are ILLEGAL? Question 30: What will the
c) RunHandler must provide a run() following block of
Select all valid answers. method declared as public and code write to the
returning void. standard output
a) #_pound when it is executed?
b) _underscore d) RunHandler must provide an init() int i = 3;
c) 5Interstate method.
d) Interstate5 int j = 0;

Question 24: If the user double k = 3.2;


invokes a stand-alone
application by typing: if (i < k)
java YourApp 1 2 3
if (i == j)
and the main() method defines
System.out.println(i);
its String[] parameter as args,
how can you access the number
else
2 using args?
100
System.out.println(j); ActionListener a = new Question 35: What does the
ActionListener() { following program
else public void do when it is run
actionPerformed(ActionEvent evt) { with the command:
System.out.println(k); if (evt.getSource() == b1) { java Mystery Mighty Mouse

Select the one right answer. b1.setEnabled(false); class Mystery {


b2.setEnabled(true); public static void
} else { main(String[] args) {
a) 3
b1.setEnabled(true); Changer c = new
b2.setEnabled(false); Changer();
b) 0 } c.method(args);
} System.out.println(args[0]
c) 3.2 }; + " " + args[1]);
b1 = new Button("1"); }
d) none of these b1.addActionListener(a); static class Changer {
add(b1); void method(String[] s) {
b2 = new Button("2"); String temp = s[0];
Question 31: How can you b2.addActionListener(a);
use the String method s[0] = s[1];
add(b2); s[1] = temp;
indexOf() to }
determine which }
} }
position the letter 'C'
is in given this String: }
lect all valid answers.
String s = "ABCDE";
elect the one right answer.
a) Nothing appears in the applet
Write a complete statement in
your answer, but you do not a) This program causes an
have to assign the letter you b) One button appears in the applet ArrayIndexOutOfBoundsExcepti
retrieve to another variable. but does nothing on to be thrown

Question 32: Given that the c) Two buttons appear in the applet b) This program runs but does
variable g references a not write anything to the
valid Graphics object, d) When the user clicks a button, standard output
what does the nothing happens
following statement c) This program writes "Mighty
do? e) When the user clicks a button, it Mouse" to the standard output
g.fillRect(2, 3, 10, 20); becomes disabled
d) This program writes "Mouse
Select all valid answers. f) When a user clicks a button, the Mighty" to the standard output
other button becomes enabled
a) draw the outline of a rectangle Question 36: What happens
in the current background color Question 34: The method when you try to
setBackground() defined compile and run the
for the Graphics class: following program?
b) draw the outline of a rectangle
in the current foreground color class Mystery {
Select all valid answers. String s;
public static void
c) fill in a rectangle using the main(String[] args) {
current background color a) takes an integer value
Mystery m = new
Mystery();
d) fill in a rectangle using the b) takes an instance of class Color m.go();
current foreground color }
c) takes an instance of a Component void Mystery() {
e) fill in a rectangle in black subclass s = "constructor";
}
void go() {
Question 33: Describe the d) sets the drawing mode for the
associated Component object System.out.println(s);
following applet.
}
import java.applet.Applet;
import java.awt.event.*; e) sets the drawing color for the
import java.awt.*; associated Component object
elect the one right answer.
public class MyApplet extends
Applet { f) changes the background color for
Button b1, b2; the associated Component object a) this code will not compile
public void init() {
101
b) this code compiles but throws Question 40: Construct an
an exception at runtime d) rt.start(1); array of 3 String
objects containing
c) this code runs but nothing Question 38: What order can you the strings "a", "b",
appears in the standard output place the following pieces and "c" using the { }
of a source file in so that notation. Call the
the source file will String by the
d) this code runs and
compile without errors or variable name s.
"constructor" in the standard
warnings?
output
//A Question 41: What is the
import java.applet.*; final value of temp in
e) this code runs and writes this sequence?
//B
"null" in the standard output
class Helper { long temp = (int)3.9;
}
Question 37: What can you //C temp %= 2;
write at the package myclasses;
comment //A in the //D a) 0
code below so that public class MyApplet extends
this program writes java.applet.Applet {
the word "running" to b) 1
the standard output? }
class RunTest implements c) 2
Runnable { Select all valid answers.
d) 3
public static void main(String[]
a) A, B, C, D
args) { e) 4
RunTest rt = new RunTest(); b) A, C, B, D
Select the one right answer.
Thread t =new Thread(rt); c) C, A, B, D
Question 42: Analyze this
//A line of code:
d) C, A, D, B
if (5 & 7 > 0 && 5 | 2)
} System.out.println("true");
e) C, B, A, D
public void run() {
Select the one right answer.
Question 39: Analyze these two
consequetive lines of
System.out.println("running"); code: a) this line of code will not
compile
float f = 3.2;
}
int i = f; b) this code will compile but
void go() { nothing will appear in the
standard output
Select all valid answers.
start(1);
c) this code will compile and
} a) this code would not compile
write the word "true" in the
standard output
void start(int i) { b) this code would compile and i
would be set to 3
} Question 43: Create a List
object that allows
c) the second line could compile if it multiple selections
} were written instead as: and displays 5 rows
at a time.
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: Start by writing:

b) rt.start(); float f = 3.2F; List l =

in your answer.

c) rt.go();
fill in the blank.
102
Question 44: What will the // A public void method() {
user interface look like
in an applet given the } System.out.println(a + b);
following init()
method? } }
public void init() {
What line of code can you write at A }
setLayout(new that will make a component
BorderLayout()); referenced by c disappear from the Select all valid answers.
display?
add("East", new a) You cannot invoke println()
Button("hello")); ill in the blank. without passing it a String

}
Question 47: Analyze the b) Since a is private, no classes
following code: other than First can access it
Select the one right answer.
class WhatHappens implements
Runnable { c) Second cannot extend First
a) Nothing will appear in the
applet public static void main(String[] d) final is not a valid keyword
args) { for a class
b) A button will appear in the
applet set in the exact center Thread t = new Thread(this);
Question 49: Analyze the
following two
c) A button will appear on the t.start();
classes.
left side of the applet
} class First {

d) A button will appear on the static int a = 3;


public void run() {
right side of the applet
System.out.println("hi"); }
e) A button will fill the entire
applet }

Question 45: Choose all true } final class Second extends First
statements about the {
paint() method Select the one right answer.
defined in the void method() {
Component class:
a) This program does not compile System.out.println(a);
Select all valid answers.
b) This program compiles but nothing }
appears in the standard output
a) it is protected }
c) This program compiles and the
b) it takes an instance of class word "hi" appears in the standard Select the one right answer.
Graphics output, once
a) Class First compiles, but
c) it is static d) This program compiles and the class Second does not
word "hi" appears continuously in the
d) it is invoked automatically standard output until the user hits b) Class Second compiles, but
whenever you minimize and then control-c to stop the program class First does not
maximize a component, such as
a window Question 48: What is wrong with c) Neither class compiles
the following code?
e) there is also a version that final class First { d) Both classes compile, and if
takes an int
method() is invoked, it writes 3
private int a = 1; to the standard output
Question 46: Given this
ActionListener: int b = 2;
e) Both classes compile, but if
class HandleClick implements method() is invoked, it throws
ActionListener { }
an exception

public void
actionPerformed(ActionEvent
evt) { class Second extends First {
103
Question 50: Why won’t the b) This code does not compile Question 53: What will the
following class result be for the
compile? c) This method writes the number 0 following block of
class A { to the standard output code when it is
executed?
private int x; d) the numbers 1 and 2 to the int i = 3;
standard output
public static void main(String[] int j = 0;
args) {
e) the number 3 to the standard
float k = 3.2F;
output
new B();
long m = -3;
} f) the number 4 to the standard
output if (Math.ceil(i) < Math.floor(k))
class B {
g) the numbers 5 through 9 to the if (Math.abs(i) == m)
B() { standard output
System.out.println(i);
System.out.println(x); h) the number 10 to the standard
output else
}
System.out.println(j);
} Question 52: What appears in the
standard output when the else
} method named testing is
invoked?
Select the one right answer. void testing() { System.out.println(Math.abs(m
) + 1);
one:
a) Class B tries to access a
private variable defined in its two:
ouer class.
for (int i = 0; i < 3; i++) { Select the one right answer.
b) Class A attempts to create an
instance of B when there is no three: a) 3
current instance of class A.
for (int j = 10; j < 30; j+=10) { b) 0
c) Class B’s constructor must be
public. System.out.println(i + j);
c) -3
if (i > 2)
question 51: Analyze the d) 4
following code.
continue one;
void looper() { e) none of these
}
int x = 0;
}
one:
}
while (x < 10) {
Select all valid answers.
two:

System.out.println(++x); a) 10 and 20

if (x > 3) b) 11 and 21

break two; c) 12 and 22


}
d) 13 and 23
}
e) 30, 31, 32, 33
Select all valid answers.

a) This code compiles


104
Question 54: The ISO code for c) c Question 58: What will
the language you are happen if you try to
interested in is 8859- d) d compile and execute
5. Assume you have a B’s main() method?
stream in a variable class A {
Question 56: What will the user
named mystream
interface look like in an
that’s associated with int i;
applet given the following
a file generated in this
init() method?
8-bit character set. If A(int i) {
the default conversion public void init() {
to Unicode in your this.i = i * 2;
environment is for the setLayout(new BorderLayout());
encoding 8859-1, how }
can you create a new add(new Button("hello"));
instance of }
InputStreamReader }
that will perform the
conversion from ISO Select the one right answer.
8859-5 to Unicode, class B extends A {
automatically? (Start a) Nothing will appear in the applet
by writing the public static void
keyword new and do main(String[] args) {
not add a semicolon at b) A button will appear in the applet
the end.) set in the exact center
B b = new B(2);

ill in the blank. c) A button will appear in the applet }


along the top and centered
horizontally B(int i) {
Question 55: What is written
to the standard output
as the result of d) A button will appear in the top left System.out.println(i);
executing the corner
following statements? }
Boolean b1 = new Boolean(true); e) A button will fill the entire applet
}
Boolean b2 = new Boolean(true); Question 57: What expressions
are true concerning the Select the one right answer.
Object obj1 = (Object)b1; following lines of code?
int[] arr = {1, 2, 3}; a) The instance variable i is set
Object obj2 = (Object)b2; to 4
for (int i=0; i < 2; i++)
b) The instance variable i is set
arr[i] = 0; to 2
if (obj1 == obj2)
Select all valid answers. c) The instance variable i is set
if (obj1.equals(obj2))
to 0
System.out.println("a"); a) arr[0] == 0
d) This code will not compile
else
Question 59: Which best
System.out.println("b"); b) arr[0] == 1 describes the user
interface of an
else applet given the
following init()
if (obj1.equals(obj2)) c) arr[1] == 1 method:
public void init() {
System.out.println("c");

d) arr[2] == 0 setLayout(new
else BorderLayout());
System.out.println("d"); add("North", new
e) arr[3] == 0 TextField(10));
Select the one right answer.
add("Center", new
a) a Button("help"));

}
b) b
105
Select all valid answers. Question 2. SDK in versions prior to 1.2.
Do I want the Java Development Kit This "myth" has unfortunately
a) The TextField object will be (SDK) or the Java Runtime carried over to later versions of
placed at the top of the applet Environment (JRE) ? Java and confusion has
and will be 10 columns wide resulted. A good rule of thumb
Answer. is, "If you don't know how to
The SDK is the Software set the CLASSPATH (since you
b) The Button object will be
Development Kit. This will allow you are relatively new to Java),
centered in the applet and will be
to develop Java software don't set the CLASSPATH at
just large enough to contain the
applications. The SDK includes the all". More information on the
text "help"
JRE as well as other tools that are CLASSPATH environment
suitable for software development. variable can be found at
c) The Button object will be
The JRE is the Java Runtime
centered in the applet and will
Environment. This will allow you to Question 6.
start at the left edge of the
run Java software applications, but What/Where is Java API
applet, fit just under the
does not include the tools to develop Documentation ?
TextField object above it, and
Java software applications.
extend to the right and bottom
In conclusion, if you wish to develop Answer.
edge of the applet
and run Java applications, you want API is an acronym for
the SDK. "Application Programming
d) The TextField object will be If you wish to simply run Java Interface." Therefore, the Java
placed along the top of the applications, but not develop them, API Documentation is a listing
applet and will stretch from the you want the JRE. of all the possible uses of the
left edge to the right edge
current core Java API. This
includes packages, classes,
e) The placement of the Button methods, fields and more. Note
object and the TextField object that Java API Documentation
Question 3.
depends on the overall size of changes as the API changes for
How do I install the Java
the applet. each incremental version of the
Development Kit ?
Java Development Kit.
Question 60: Which of the However, the API (generally)
Answer.
following statements remains reverse compatible
This process is documented at
about try, catch, and and if API becomes outdated, it
finally are true? often becomes "deprecated."
Question 4. The Java API Documentation is
How do I set the PATH environment considered the "bible" of any
Select all valid answers.
variable for the Java Development Java programmer. An example
Kit ? of the use of the API
a) A try block must always be Documentation: the
followed by a catch block java.lang.String class has a
Answer.
The PATH environment variable is set method called length() which
b) A try block can be followed that that it additionally contains the returns an int value indicating
either by a catch block or a bin directory of the installed SDK. the length of a String. This can
finally block, or both Question 5. be confirmed by looking at the
How do I set the CLASSPATH following part of the Java API
c) A catch block must always be variable for the Java Development Documentation
associated with a try block Kit ? http://java.sun.com/j2se/1.4.2
/docs/api/java/lang/String.htm
l#length().
d) A finally can never stand on
its own (that is, without being
associated with try block) Answer. Question 7.
Generally, you do not set the What does this mean
CLASSPATH environment variable for "Exception in thread "main"
e) None of these are true
a standard SDK or JRE installation. java.lang.NullPointerException"
The CLASSPATH environment ?
Back to questions
variable is set for other reasons,
usually the installation of third-party Answer.
Question 1. libraries. Some people (including Often called a
Where can I download the Sun myself) argue that setting the NullPointerException or NPE,
Java Development Kit (SDK) / CLASSPATH environment variable at this is caused by dereferencing
Java Runtime Environment all is bad practice; it should be set an object reference to null.
(JRE) ? dynamically at each build. This keeps That is, you have an object
the build machine clean from reference and you are trying to
Answer. potential "contamination" from dereference it (usually by
At the time of this writing, the libraries in the CLASSPATH. Setting calling a method or accessing a
latest released version is 1.4.2. the CLASSPATH environment variable field/member) while the
This can be downloaded from was required for installation of the reference isn't referring to an
106
object instance. The next line of A common error is to append the
the output will give the location .class file extension to the class System.out.println("x = " + x);
(file name and line number) of name when invoking the JVM; this // using x with a value
the violation. The following code will result in an error similar to the ...
produces a NullPointerException: following:
Exception in thread "main"
... java.lang.NoClassDefFoundError: Question 11.
String s = null; // s is MyClass/class What does this mean
referring to null (no object Fix this problem by removing the "unreported exception
instance) .class file extension from your <something>; must be caught
int len = s.length(); // command. or declared to be thrown" ?
dereferencing a reference to null
- will result in a Wrong Answer.
java.lang.NullPointerException at > java MyClass.class This is caused by a
this line misunderstanding of the
... Right concepts of exception handling
> java MyClass in Java. Generally, Java has
The following fixes the problem: three types of errors that can
occur, a runtime "Error", a
... non-checked "Exception" or a
String s = "blah"; // checked "Exception." A runtime
Question 9.
make sure that s is referring to Error is usually fatal and
What does this mean "non-static
an object instance. should not be handled at all in
variable (or method) <something>
int len = s.length(); // your code. A non-checked
cannot be referenced from a static
dereferencing a reference to a Exception is recognizable
context" ?
String instance - ok. because it is of type
... java.lang.RuntimeException (or
Answer. a subclass) and usually
Well simply put, you are referencing indicates a programming error,
Question 8. something that is non-static from a thus, it probably should not be
What does this mean "Exception static context, which is not handled (of course, there are
in Thread "main" permitted. Elaborating on this always exceptions (no pun
java.lang.NoClassDefFoundError concept in this document may be intended) to this rule).
<something> " ? misleading, so it is best to read the Checked Exceptions are usually
relevant tutorial on Understanding recoverable and it is enforced
Answer. Instance and Class Members. by the compiler that you (the
This means that the Java Virtual developer) handle them,
Machine (JVM) cannot find the hence, the compile error when
class that you are referring to. you don't. Question 12.
The error is followed by the class What does this mean "Note:
Question 10.
name that the JVM was asked to <something> uses or overrides
What does this mean "variable
load. The directory that contains a deprecated API. Note:
<something> might not have been
this class must be in your Recompile with -deprecation
initialized" ?
CLASSPATH environment for details."?
variable. If your CLASSPATH is
not set to anything, then the Answer.
This is caused by using a variable Answer.
class must be located in the
that doesn't have a value. For You might have heard of the
same directory from which the
example, declaring an int without term "self-deprecating humor."
JVM is invoked (package
initializing it's value, then using it It describes humor that
relative). The JVM is generally
somehow (without a value). Note minimizes one's own
(but not always) invoked by
that class data members are importance.
executing the java executable
initialized implicitly. The following Similarly, when a class or
followed by the class name at a
code produces the compiler error: method is deprecated, it
command line.
means that the class or
method is no longer considered
One common problem arises important. It is so
when executing a jar file (using ... unimportant, in fact, that it
the -jar switch), which ignores all int x; // x doesn't have a should no longer be used at all,
CLASSPATH settings, except for value "hasn't been initialized"; as it might well cease to exist
that specified in the Java ARchive System.out.println("x = " in the future.
manifest file. This may be + x); // attempting to use x before
contrary to general intuition, but giving it a value
... The need for deprecation
it makes perfect sense when you
To fix this problem, the value x must comes about because as a
think about it. This is outlined in
be given a value before using it: class evolves, its API changes.
The JAR File Specification.
... Methods are renamed for
int x = 0; // x now has a consistency. New and better
value methods are added. Attributes
107
change. But making such classes, class data members and
changes introduces a problem: class methods. These access
You need to keep the old API modifiers describe what type of Question 15.
around until people make the scope or visibility they have. All What is "inheritance",
transition to the new one, but classes, class data members and "polymorphism (run-time
you don't want developers to class methods have some type of binding)", "an interface" ?
continue programming to the old access level (even if one isn't
API. specified).
Answer.
These concepts are not trival.
The ability to mark a class or These access modifiers are : A good understanding of these
method as "deprecated" solves public (and other) concepts is
the problem. Existing classes protected essential to make good use of
that use the old API continue to package-protected (also called the Java programming
work, but the compiler can issue default) language.
a warning when it finds private
references to deprecated items.
Question 16.
Meanwhile, API documentation To specify a class, data member or What is method overloading ?
can warn the user against using method as having access scope of
the deprecated item and tell the type default is to not explicitly
user how to avoid doing so. To Answer.
declare any access modifier at all.
mark API as deprecated, the Method overloading is distinct
A description of the access modifiers
implementer of the API uses a from method overriding - they
follows, in order of least restrictive to
special tag in doc comments: are two separate concepts.
most restrictive:
@deprecated. Method overloading is where a
class provides a method which
public has the same name but
Note: "Deprecated" and A public class, data member, different type and/or order of
"depreciated" are not the same. constructor or method has scope to parameters. Method
"Depreciated" is a financial term all other classes. All classes can see overloading is generally used
that means "lowered value." each others' public classes, data where a class can perform the
Although the meanings are members, constructors and methods. same operation on more than
similar, classes and methods are
one type of data. Note that a
deprecated, not depreciated.
protected class cannot contain two
Question 13.
A protected class, data member, methods with the same
How do I generate a random
constructor or method has scope to "signature." A method
number between x and y ?
itself, it's subclasses and classes signature is defined by it's
within the same package. A class can name and type/order of it's
Answer. see the protected classes, data parameters. The method return
The java.lang.Math class members, constructors and methods type and modifiers have no
provides a method called of its' superclass and classes within effect on the method
random() that returns a double the same package. Top level classes signature. The following is an
value that is "greater than or cannot be declared as protected. example of method
equal to 0.0 and less than 1.0." overloading:
Therefore, using some simple
package-protected (or default)
mathematics, you can generate a
A package-protected class, data class AddNumbers
value between any range with
member or method has no access {
the following piece of code:
modifier explicitly specified. A class, public double
data member or method which is add(double a, double b)
double num = declared as package-protected has {
Math.random() * (y - x) + x; scope only within its' package. return a +
Classes that are declared to be in the b;
This will generate a random same package can see each others' }
number between x (inclusive) package-protected classes, data
and y (exclusive). members and methods. Classes that public int add(int a,
are declared with package-protected int b)
Question 14. access scope are available to classes {
What are access modifiers within the same package. The return a +
(public, protected, private, package-protected access modifier is b;
default) ? also referred to as default scope or }
package-friendly.
/*
private public long add(int
A private data member or method a, int b) // illegal, a method
Answer. with the same signature
has scope only within itself. A class
In the Java programming already exists
can see only its' own private clases,
language, there are four different {
members, constructors and methods.
types of access modifier. An return a +
Top level classes cannot be declared
access modifier is applied to b;
private.
108
} immutable objects. These rules
*/ super.method2(); follow:
}
- A class is instantiated and all
Question 17. of its properties are set
What is method overriding ? System.out.println("Subclass.method through the constructor(s).
2()"); When the arguments are
} passed at creation, it
Answer.
} eliminates any need for setter
Method overriding is distinct
from method overloading - they methods on the class that
are two separate concepts. might be called later.
Method overriding is where a - The class is declared final.
class provides a method with the Question 18. This prevents another
same signature as a method that Can static methods be overridden ? developer from extending your
is declared in it's superclass. The class and implementing code
subclass' method does not inherit that supports mutability.
Answer.
the functionality of it's - The properties of the class
No. A static method of a subclass
superclass' method unless it is are private. This prevents
that has the same signature as a
done expicitly using the "super" other objects from modifying
static method of a superclass does
keyword. The following code the attributes directly, and
not actually override it. The subclass
demonstrates method overriding: adds another layer of
method cannot call on the superclass
protection from subclassed
methods functionality with the
code over making the class
class Superclass "super" keyword..
final (with one very exceptional
{
rule).
void Question 19. - Other than the
method1() Can private methods be overridden ? constructor(s), there is no code
{
in the class that changes the
Answer. properties of the object. Any
No. A private method of a subclass methods or events for the class
System.out.println("Superclass.
that has the same signature as a must treat the private
method1()");
private method of a superclass does attributes as read-only. In this
}
not actually override it. This is way, the final state of the
because the two methods work object is determined when it is
void
independantly of each other due to constructed, and no
method2()
their access scope. The private opportunity exists to change it
{
subclass method cannot call on the for its lifetime.
private superclass method with the - If methods are implemented
"super" keyword since this is a that perform operations on the
System.out.println("Superclass.
violation of the private access scope. data abstracted by the class,
method2()");
the result of those operations
}
are another instance of the
}
class containing the modified
data.
class Subclass extends Question 20. - If the class is sufficiently
Superclass What does "immutable" mean ? general purpose in scope, it
{
may be packaged with a
// Overrides Answer. companion object that is
method1() and loses the The term immutable simply means mutable. This is the case with
functionality of the superclass unchangeable. Immutable objects do the String and StringBuffer
method1() not change once their constructor classes.
void has executed. You may already know
method1() that the java.lang.String class is
{ immutable, despite the appearance
that it is not, due to its convenient
concatenation operator. You may Question 21.
System.out.println("Subclass.me also know that if you need to write Does Java pass parameters by
thod1()"); code that constructs a single String reference, by value, both or
} object over a number of separate neither ?
statements, it is more efficient to use
// Overrides the java.lang.StringBuffer object. Answer.
method2() and explicitly calls the Java pass all parameters
functionality of the superclass strictly by value. This may be
method2() Immutability is implemented as a
design pattern that the programmer contrary to advice that you
void receive from both (claimed)
method2() builds into the class. There are some
general characteristics that are experienced and inexperienced
{ people. I can assure you that
usually found in all intentionally
they need a walloping; Java is
109
purely pass by value. To clarify, The model in memory now looks like public
there is some deeper this: boolean leak = false;
understanding that is essential.
This understanding is not trivial public
or useless but it is necessary to Stack(int initialCapacity)
understanding how to use the {
Java Programming Language
effectively. elements = new
Java has two basic data types; Object[initialCapacity];
primitive values and object }
references. Java does not permit
direct access to objects (as in public void
.NET), but allows the developer push(Object e)
to declare a reference to an {
object type. There are 8
primitive data types (long, int, ensureCapacity();
short, char, byte, boolean, float
and double). Consider the elements[size++] =
following piece of code: e;
}
...
Object o = new public
Object(); // declares an object Object pop()
The "greyed out" areas represent {
reference called 'o' that refers to
variables that method2 does not
an object of type
have access to. Notice that method2 if(size == 0)
java.lang.Object
can still "see" the object instances, {
String s = "blah"; //
but not the original caller's object
declares an object reference
references. Therefore, if an object throw new
called 's' that refers to an object
instance is altered through one of EmptyStackException();
of type java.lang.String (a literal
method2's object references, the }
String)
change to the instance will be
int x; // declares a
reflected in the original caller's object
primitive type called 'x' of type
references. This will give the false if(leak)
int
impression that the object was {
...
passed by reference. In fact, the
object reference was passed by return elements[--size];
In memory, the above code value. If method2 had changed the }
looks like this: value of the references, the change
would not have been reflected to the else
caller in any way. The primitive data {
type was passed by value and the
effect was not seen at all in the Object result = elements[--
original caller. To reiterate, size];
understanding this concept is not
trivial or academic. It is fundamental elements[size] = null;
to the use of the Java Programming
Language. Java is strictly pass by return result;
value. }
}

private
Now calling a method and void ensureCapacity()
Question 22.
passing these three parameters {
Can Java applications leak memory ?
(by value) with the following
code: if(elements.length
Answer. == size)
Yes. Consider the following code: {
...
method(o, s, x);
... import java.util.*; Object[] oldElements =
elements;
void method(Object
o2, String s2, int x2) public class Stack elements = new Object[2 *
{ { elements.length + 1];
// What does private Object[]
memory look like now ? elements; System.arraycopy(oldElements
} private int size = , 0, elements, 0, size);
0; }
110
} Question 23.
} Can I invoke the garbage collector ?
The following code is likely to private
cause a Answer. SingletonExample()
java.lang.OutOfMemoryError No. Both the java.lang.System and {
caused by a memory leak in the java.lang.Runtime classes provides a
Stack class: gc() method that "suggests that the
class Foo Java Virtual Machine expend effort }
{ toward recycling unused objects in
private int[] order to make the memory they public
vals = new int[10000]; currently occupy available for quick static SingletonExample
} reuse." It is not guaranteed when or getInstance()
if the garbage collector will run by {
class Bar making this call. The common
{ misconception that this method if(instance == null)
public static invokes the garbage collector is a {
void main(String[] args) source of many subtle errors in Java
{ applications. instance = new
SingletonExample();
final int size = 1600; }

Stack s = new
Stack(size); Question 24. return instance;
Can I convert my Java application }
s.leak = true; into a Windows executable (.exe) ? }

Answer.
for(int i = 0; i < size; What you want to do is possible, but
i++) it is not recommended. Java is
Question 26.
{ designed to be a platform
How do I convert a .class file
independent language. Compiling a
back to a .java source file ?
s.push(new Foo()); Java application into a platform-
} specific executable defeats Java's
design intent. Also, using native Answer.
compilers does not offer the Converting a compiled Java
for(int i = 0; i < size; significant performance class file to its original source
i++) improvements over the Java Runtime may be a violation of the
{ Environment with JIT (Just-In-Time) licence to use the software.
enabled. If you want do distribute Typically, there is seldom a
s.pop(); your Java application, distribute it legitimate reason for doing
} with Sun's Java Runtime such a thing. It is important to
Environment. realise the unethical nature of
violating the terms of use of
code that does not belong to
System.out.println("Pushed and you before performing this
popped " + size + " objects"); operation.
Question 25.
What is a "Singleton" class ?
In order to "decompile" a Java
for(int i = 0; i < size; class file to a Java source file,
i++) Answer. you will require the use of a
{ A singleton class is a class where Java decompiler. Some
there only exists at most, one searching around on a web
s.push(new Foo()); instance during runtime. This can be search engine for a "Java
} enforced by giving all constructors decompiler" will likely yield the
private access and providing a public desired results.
static method that returns the only
for(int i = 0; i < size; existing instance. The following is an
i++) example of a Singleton class BUT
{ only if a single thread accesses the
instance. Achieving thread-safe Question 27.
s.pop(); access to singleton classes is a very How do I clear the console
} interesting topic, but is beyond the screen ?
} scope of this document.
} Answer.
class SingletonExample You can't without making a
{ native call using JNI or
private static executing a system command,
SingletonExample instance; and, in both cases, losing
111
platform independance. You can String formatted = Question 32.
"kind of" clear the screen by df.format(d); // "12345.68" Can I reference the subclass
printing a series of new lines. from a superclass ?
Question 29.
... Does Java support multiple Answer
for(int i = 0; i < 100; inheritance ? No. Wanting to do such a thing
i++) generally indicates a design
{ Answer. flaw. It is not possible to
No. Classes may inherit from one explain where the design flaw
System.out.println(); and only one (not zero, implicitly or is, since this question is too
} explicitly) class and may implement general. Therefore, I will
... zero or many interfaces. Interfaces propose some questions that
may inherit from zero or more will hopefully assist you to
The reason for this is that Java interfaces - this is not (and is not understand why this a design
doesn't assume that it's even close to) multiple inheritance. flaw. Firstly, what is "the"
operating environment has a The only exception to this rule is subclass ? A superclass can
console screen. You don't have a java.lang.Object which does not have have more than one (or even
screen for servlets, EJB and a superclass. none) subclasses - this rules
various other environments, so it out the concept of "the"
makes sense not to assume the subclass. A subclass is
existance of one. Generally, dependant on its superclass,
clearing a console screen means and this dependancy is
Question 30. unidirectional - a superclass
one of the following:
How do I make a cannot have a dependancy on
- You are a university student
javax.swing.JTextArea scroll to the a subclass (unless of course, it
trying to "pretty up" your
end ? is some other relationship
assignment, in which case, it's
not worth writing bad code in besides inheritance, but that is
order to do something that Java Answer. beside the point). How can a
was not designed to do. First, the JTextArea must be within a developer design a superclass
- You are using a command line javax.swing.JScrollPane. Then set that knows about ALL of its
interface where you should be the caret position of the JTextArea to subclasses ? Deriving from a
using a windowing interface be at the end. Assuming the class provides you with the
(such as swing) if you want to JTextArea has a reference called 'ta': same functionality as the
perform operations such as superclass - how does the
clearing a screen. ta.setCaretPosition(ta.getText().lengt superclass know about the
- You have too much time on h() - 1); subclass, since it is added at a
your hands (Go and read a good later date (due to the
book on Java, instead of writing unidirectional dependancy) ?
poor code). Perhaps what it is in the
subclass actually belongs in the
superclass ? Perhaps you need
Question 28. Question 31. to use the Template Method
How do I create a String that Can I execute an external Design Pattern ? This is clearly
represents a double (or float) command ? speculation and a more
value with only 2 decimal
concrete solution can only be
places ?
Answer arrived at with some more
Yes you can. Be aware of the thought on your behalf.
Answer. consequences of doing such a thing.
By using the Your application then becomes Question 33.
java.text.DecimalFormat class. dependant on the platform which the Is it possible to prevent a
The following is an example: external command runs on. It may thread of execution from
(or may not) be worthwhile allowing executing for a specified period
double d = 12345.678; the user of your application to of time ?
DecimalFormat df = configure the external command,
new DecimalFormat(); since it changes under so many Answer
different operating environments. It is only possible to prevent
df.setMinimumFractionDigits(2);
the current thread from
You can achieve this by calling one of executing for a specified period
df.setMaximumFractionDigits(2); the exec methods of the of time, but not any arbitrary
String formatted = java.lang.Runtime class, which will thread. This is achieved by
df.format(d); // "12345.68" fork a process from the JVM. A putting the thread into a
handle to this process is returned "sleep" state. It is important to
Alternatively: from the method as a realise the after the specified
java.lang.Process. period of time, the thread
double d = 12345.678; enters the "ready for
DecimalFormat df = execution" state, NOT the
new DecimalFormat("#.00"); "execution" state. The time at
112
which the thread enters the  Recognise the error made after  The IDE writes my code for
"execution" state after sleeping determining the meaning of that me, so that I don't have to
(and then entering "ready" state) error type
is completely indeterminate and  Fix the error The IDE is writing code for
is the responsibility of the thread  Continue development you that you don't
scheduler. It can be said that understand. What happens
"sleeping a thread prevents the In contrast, a user who is learning when the IDE isn't capable
current thread of execution from Java, and is using an IDE might of producing the code
executing for AT LEAST the perform the following actions: exactly as you want ? Are
specified period of time". you capable of editing it ?
Therefore, causing a thread to
 Encounter a
sleep should not be relied upon Learning the intricacies of Java
java.lang.NoClassDefFoundError
as an accurate timer, as is very important for anyone
 Being unable to determine what
accuracy is not guaranteed, and who intends on developing
this message means, consults the
in practice, it seldoms occurs. seriously. This may be contrary
help for the IDE, which clearly, won't
reveal any clues to the belief of the untrained
The java.lang.Thread class  Consult a newsgroup or some user, and I can certainly see
exposes two static sleep internet group for assistance, where why. It is difficult to accept
methods: any explanation that is given, is well that the tools that you are
java.lang.Thread#sleep(long) beyond the understanding of the using are actually a hindrance,
java.lang.Thread#sleep(long, user while they are disguising
int)  Search for the error message on themselves as helpful tools.
the internet, which reveals ad hoc This opinion is not just my
Considering the lack of accuracy advice that is unrelated to the actual own, but that of several very
when putting a thread into the problem (instead of the more likely, competent developers who
sleep state, there doesn't seem IDE setting) have all learnt The Hard Way
to be a good reason why anyone  Continues searching for answers But The Right Way.
would want to call the method to what is generally a trivial problem,
that takes the number of which takes several hours, while the Question 35.
nanoseconds as an argument. competent user resolved the issue in When should I use
less than one minute. java.util.Vector/java.util.Hasht
able ?
This example is one of the many
Question 34. thousands of possibilities that an IDE Answer
Why shouldn't an Integrated can present to a user who is well out
Development Environment (IDE) of their depth of understanding. The classes java.util.Vector
be used for learning Java ? Some people have a hard time and java.util.Hashtable are
recognising their shortcomings, remnants of JDK 1.1 that have
swallowing their pride, and learning been kept in the core API to
Answer
with the appropriate material and maintain reverse compatibility
It is an unfortunate fact that
tools. The best way to learn Java is with older code. These classes
those who have a fundamental
with a text editor (even Notepad or were "retrofitted" in JDK 1.2 to
understanding of Java know the
vim will do!) and the Java 2 SDK. As fit into the new Java
answer to this question, while
a university teacher, I see this Collections Framework. Newer
those who are still learning, often
mistake all too often. Some of the classes/interfaces were
choose to ignore it. An IDE hides
excuses I hear are outrageous: introduced in JDK 1.2 that
the details of the inner workings
of Java, and at times, the user is achieve the same function as
abstracted away so much, that  I don't have time to learn Java Vector and Hashtable, and do
when a problem is encountered, properly not have to maintain any
the user consults the IDE for ... but you have time to fix the backward compatibility.
resolution, rather than infinite number of possible Lessons that were learnt from
understanding that "underneath" problems that are well beyond previous versions of the JDK
the abstractions given by the the scope of your could be applied to these new
IDE, the problem is lurking. understanding ? classes without fear of
breaking earlier code. The
 But it hasn't given me any same functionality of Vector
For example, a user who has an
problems (yet) can be achieved by using
understanding of Java and is
Oh it will. Like I said, I've seen it java.util.ArrayList and the
using an IDE might perform the
far too many times. If it doesn't, functionality of Hashtable can
following actions:
it is purely coincidental (video be achieved by using
tape it - it's a rarity!). java.util.HashMap (there is a
 Encounter a minor difference in that
java.lang.NoClassDefFoundError  The IDE makes it easier for me HashMap permits nulls). If you
 Recognise the message as a The IDE is doing things that you require thread safety on these
type of Throwable and consult don't understand and as soon as types, you can use
the API documentation for that something "breaks", you will be java.util.Collections to
type in big trouble. synchronize them, since Vector
113
and Hashtable are already "efficiency" is defined as the running within the JVM, and
thread-safe, and often times, "efficiency of a code maintainer to the JVM itself. This may cause
unnecessarily. read and maintain the code", the undesirable results, leaving
answer is "yes". data which is external to your
In general, you only need to use application (or any other
a Vector or Hashtable if you are application under the JVM) in
supporting Java Runtime an inconsistent state.
Environment versions that are Question 37.
older than 1.2. More often that Can I start my java.lang.Thread Seldom in an application is
not, the newer classes/interfaces more than once ? there a need to forcefully
should be used in order to take shutdown the JVM. A well
advantage of performance and designed application will have
Answer
maintenance benefits if this is taken into consideration issues
not the case. regarding flow control, and
No. A thread that has been run and application logic will be
completed (by finishing the run() implemented such that the
If you insist on using a Vector or
method) cannot be restarted. application exits cleanly
Hashtable for some unforeseen
Attempting to restart a thread that (usually by exiting the main
reason, you should always use
has completed execution (or is method) when it is time to do
(at least) a java.util.Map
already running) results in a so. It is important to ensure
reference to refer to a Hashtable
java.lang.IllegalStateException. that all non-daemon threads
and/or (at least) a java.util.List
However, you can create and start that your application creates
reference to refer to a Vector.
more than one thread with an are no longer executing when a
This same guideline applies to
instance of java.lang.Runnable clean exit is intended. Also,
using HashMap and ArrayList.
(which defines what the thread does consider that an application
The reasoning for this, and many
during execution in its run() that has more than one exit
other good practices for the Java
method). point is difficult to maintain.
Collections Framework are
detailed in the tutorial.
Question 38.
What's the difference between
Question 36.
javaw.exe and java.exe ?
Can I increase efficiency by using Question 40.
less import statements ? Why is my GUI application
Answer broken if I set the layout to
Answer null ?
Both of these executables start up a
JVM, however, only javaw.exe is Answer
First the term "efficiency" must
available on the Microsoft Windows
be defined.
platform. The javaw.exe executable
Quite often, developers of
allows the user to start the JVM
The quantity and type (wildcard Swing applications will set the
without the need for a command
or fully qualified) of import layout of a java.awt.Container
console from which to launch it from.
statements does not affect to null, in order to avoid the
This is useful for applications that do
runtime performance of an complexities involved is using
not require the user to view the
application, so in terms of Layout Managers. This
command console on the Microsoft
"efficiency of runtime approach is fraught with many
Windows platform, such as graphical
performance", the answer is pitfalls that the developer may
applications.
"no". not be aware of. For instance,
the application may not run
correctly on a system with:
The quantity and type of import
statements does affect compile-
Question 39.  different installed fonts to
time performance - that is, less
How do I exit my application ? the development system.
import statements generally
means your application will  different screen resolution
compile faster; also, using fully Answer to the development system.
qualified import statements  different locale settings to
rather than wildcard import Some developers will immediately the development system.
statements generally means your jump at this question claiming
application will compile faster. If "System.exit" is the answer. Setting a layout to null is
the term "efficiency" is defined However, naively calling this method generally considered poor
as the "efficiency of the compiler can cause potential problems, albeit form, and applications that
to compile my application", the the fact that it occurs often. violate this rule should be
answer is "yes". System.exit(int) forces a JVM considered defective, since it is
shutdown and returns with the exit not guaranteed to run on any
Source code becomes more code given as the parameter. It is system correctly, except for
maintainable when full qualified important to realise that it is not just the system on which it was
imports are used, and unused your application that will cease developed.
imports are absent. If the term running, but any other applications
114
Question 41. and it is this language that this web Question 44.
Why shouldn't I use floating- page is dedicated to. What is the newline character ?
point types for representing
monetary values (or any value J++ is (was) a programming Answer
that demands accuracy) ? language designed my Microsoft
Corporation to compete against Java. A lot of misinformed
Answer It consists of a very similar syntax developers will quickly reply to
and API specification to Java, this question with an answer of
Java floating-point types (float however, it is not compliant with the '\n'. The correct answer is that
and double) are represented in specifications for Java set out by Sun there isn't one. If you consult a
IEEE 754 (Institute of Electrical Microsystems, and this fact was the Unicode table (how Java
and Electronics Engineers) basis for a successful lawsuit filed by characters are represented),
format as per Java Language Sun Microsystems Inc. against you'll find that there is no
Specification 4.2.3. IEEE 754 Microsoft Corporation in 2001. character designated as the
format for floating-point types is line terminator. So where did
a detailed specification, suffice to J# is the successor to J++ developed '\n' come from ? The End Of
say that a floating-point type is by Microsoft as part of their .NET Line (EOL) terminating
"an inexact representation of an initiative and again, is not compliant character on UNIX platforms is
ideal real number" and with the specifications for Java set the Line Feed character '\n'
operations performed on them out by Sun Microsystems. (0x000A). This does NOT apply
are inexact. You can witness to all platforms. For example,
these inaccuracies by performing Javascript is a scripted loosely-typed the Microsoft Windows platform
an operation as simple as (Java is strongly-typed) language uses two characters, Carriage
System.out.println(2.4 * developed by Netscape, which Return and Line Feed to
1.111111); You will immediately unfortunately inherited a similar represent an EOL terminator
notice that the output is not the name to Java that now results in "\r\n" (0x000D 0x000A); the
otherwise expected 2.6666664. confusion. Javascript is the language Macintosh platform uses the
This is due to the internal interpreted by web browsers to Carriage Return to represent
representation of the floating- perform certain browser-specific the EOL terminator "\r"
point type. behaviour along with HTML. It has no (0x000D). Other platforms
relationship to the Java 2 may use other character
The correct approach for storing Programming Language, except for a sequences to represent an EOL
monetary values would be to use similar name. terminator. When you see code
an integral type (such as int, or that is written in a fashion
long) that represents the number similar to this:
of cents guaranteeing accuracy.
Storing other data where
Question 43.
accuracy is required should also System.out.print("hello
How do I access an outer class
use some approach that involves world\n");
member/method from an inner
integral types, and not floating-
class ?
point types. it is important to realize that
you are seeing the string "hello
Answer
If you happen to encounter an world" followed by the Line
application where monetary Feed character, NOT an EOL
values have been represented <OuterClassName>.this.<member/m terminator as some would
using an IEEE 754 floating-point ethodname> suggest. If this code was
type, please contact me such executed on a UNIX platform,
that I can arrange for the Here is an example: you'd have that character
"missing bits" of money to be expressed as an EOL
deposited into my bank account. public class Outer terminator (UNIX platform-
{ specific behaviour), but this is
Question 42. private int x; not the same as writing an EOL
What's the difference between terminator in Java. Some
Java and J++ and J# and Microsoft Windows applications
Javascript ? public class Inner take into account that a lot of
{ developers erroneously insist
void on using '\n' as an EOL
Answer
method() terminator and act accordingly
{ (so that you won't see the
First and foremost, these four consequences). So what if you
technologies are distinct. That it wanted an EOL terminator in a
Outer.this.x = 42;
to say "Java is not J++ is not J# Java environment ? Since Java
}
is not Javascript". is platform-independant, there
}
} needs to be a way of
Java is a programming language representing the EOL
designed by Sun Microsystems terminator on all the different
platforms. You can obtain the
115
EOL terminator by accessing the // Iterate the
System property called "inner" array.
"line.separator". Alternatively, // Length is not
when you write to streams, you constant for all elements.
can use a java.io.BufferedWriter for(int j = 0; j <
to write a new line or a element.length; j++)
java.io.PrintStream to println. {
Doing this will take care of // Get
writing out the correct, and often an element of an "inner" array.
intended, EOL terminator (by String
accessing the line.separator s = element[j];
System property internally). In }
the code sample above, if the }
intention is to print "hello world"
followed by an EOL terminator It is important to realise, that in the
(instead of a Line Feed character above code sample, there is no "2
as it does now), you can simply dimensional" array. There is an array
use the println method, since whose elements are String arrays. A
System.out is a PrintStream. To language such as COBOL supports
reiterate in conclusion, the true multi-dimensional arrays
following statement is NOT (known as "tables"). To understand
equivalent to the statement this distinction is important to use
given above. arrays effectively in Java (and
COBOL too!).

System.out.println("hello
world");

Question 45.
How do I use a multi-dimensional
array ?

Answer

A common misconception is that


Java supports the use of multi-
dimensional 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];

Você também pode gostar