J2EE FAQ Collection
J2EE FAQ Collection
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
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)
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.
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.
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)
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;
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);
} 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?
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?
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
// 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.
two: a) 3 else
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
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
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; };
t.start();
c) This class is a top-level class:
Select all valid answers.
}
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';
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;
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 {
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
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