Professional Documents
Culture Documents
224 Questions - Explaination Sun Certified Programmer For The Java 2 Platform, Standard Exam PDF
224 Questions - Explaination Sun Certified Programmer For The Java 2 Platform, Standard Exam PDF
Nayak
KCT,Coimbatore
Question 6
Locale.getDefault(); is the right method to create an instance
of the Locale. Refer Page 471. In option D,
1
Abhijit.A.Nayak
KCT,Coimbatore
Abhijit.A.Nayak
KCT,Coimbatore
Abhijit.A.Nayak
KCT,Coimbatore
Question 18
This is straight forward and easy. Interface can only extend
another interface. so option A is right
Question 19
Method to be called depends on the actual object type,not on
the return type.
Question 20
It is an simple argument - defined inner anonymous class
.refer page 653 for an example
Question 21
Since we can not create an instance for abstract class options
A and B are invalid.
There is no operator such as -> in java so D is invalid, We
cannot use both object and
class for calling a method so E is invalid.
Option C is the correct way to call the method of Circle by
creating a reference on the abstract class Shape.
Question 22
Rules for overriding
Class members cant have an access modifier which is
narrower than what is declared.But it can be broader.
protected abstract double getSalesAmount(); so proctected
and public are allowed to override but not private and default
as its narrower than what has been declared in Employee
class.
Question 23
Abhijit.A.Nayak
KCT,Coimbatore
Abhijit.A.Nayak
KCT,Coimbatore
Question 31
A is a simple way to create an static array (in C style). B is
way which
follows Java rules i.e, declaring, constructing and initializing.
option C looks like an Anonymous array, but its not.the int
should not have a number between the brackets [].
If it was an Anonymous Array it should look like
static final int[] a;
a= new int[]{100,200};
Question 32
This is an example to iterate through the enum elements
using the enhanced for loop. Color.values() is the type which
has to be passed in for the enum Color.
Abhijit.A.Nayak
KCT,Coimbatore
Question 33
This is an example of a method,constructor inside an enum.
The instance variable is private final int rgb;
The constructor is Color( int rgb) { this.rgb = rgb; }
The method is public int getRGB() { return rgb; }
In order for the enum to work properly we need to make an
enum instance. For that the proper syntax is
Option B Color treeColor = Color.GREEN;
Option A is wrong because the syntax for the enum which is
enumname.enumvalue
Option C is wrong because we cant add new values to the
enum after its declaration.
Now for the 2nd pick
Option D is wrong because of wrong syntax like option A
enumname.enumvalue
Option E is wrong again because purple cant be added or be
assigned as its invalid.
So option E is right.
Question 34
As soon as line 20 has been invoked,the format uses the
overridden method of the enum Title.
But first the constructor runs and then the format method
runs.
Question 35
It is a straight forward question for the new For Each for loop.
Here Anonymous Array has been used to initialize the object
obj[] array. Somearray takes only integers as obj[] array has
been casted with (int[]) type.
Question 36
A) Since beta is not static it cannot be invoked using class
name, it can be invoked
using reference variable
B) Since alpha is static it can be invoked using the class name
directly
Abhijit.A.Nayak
KCT,Coimbatore
Question 41
The question here is about legal return types.
Refer page 123.
When option C has been used we know that Two IS-A One. So
it is allowed.(Co variant Return Type).
Option D is overriding the super classes foo() method so it is
allowed as well.
Abhijit.A.Nayak
KCT,Coimbatore
Question 42
A is invalid since the return type changes. D is invalid since
the modifier can be less
restrictive but it should not be more restrictive, so public and
protected is allowed
but private is not allowed. So B,C and E are correct.
Question 43
When overriding the overridden method can return the same
or sub type but not the
super type. Since in line6 of class C it is returning the super
type the compiler throws an
error.
Refer pages 122, 123 and 124 for information on
covariant return types.
Question 44
Refer page 239 and 240.The complier will always choose to
the older style than the never one to keep the code more
robust.
So option A.
Question 45
The option here is C. If we are overriding then the rules are no
changing the return type and the arguments .But If its
overloading then we have to change the Arguments as well as
the return type.
Question 46
This is inner class question.Refer page 641,642.
But the option B should be like this Line.Point p = new
Line().Point(); Guess there was a typing error.
To instantiate an inner class
MyOuter.MyInner myinner= new MyOuter().MyInner();
Or
If you already have an instance of the outer class then
MyOuter outterObjRef=new MyOuter();
MyOuter.MyInner myinner= MyOuter.new MyInner();
Question 47
Abhijit.A.Nayak
KCT,Coimbatore
10
Abhijit.A.Nayak
KCT,Coimbatore
Question 54
The output is really simple,In line 12 , there is a method
invocation to line 18 which returns true.so the output is A.
Question 55
This is a Wrapper class example so its simple and easy. Both
the Wrapper class objects are converted to integers and
added.
Question 56
The format for if is if(---){ } elseif(---){}else{}
So compilation error.
Question 57
There cant be a finally if there is no try/catch.
Question 58
After the first iteration
x:1 y:9
After the second iteration x:2 y:8
After the third iteration
x:3 y:7
After the fourth iteration x:4 y:6
During the 5th iteration
First y5 x5
Then x value is checked and it exits the loop.
Question 59
The while loop never executes even once.hence the option is
C.
Question 60
This is an infinite loop.as its a do while loop, the source code
inside the loop executes once which makes x=9 from then on
it goes on looping.so the option here is D.
Question 61
To sort in reverse order it is not the correct way ,
11
Abhijit.A.Nayak
KCT,Coimbatore
12
Abhijit.A.Nayak
KCT,Coimbatore
13
Abhijit.A.Nayak
KCT,Coimbatore
Question 72
This is a Runtime Exception,it is an unchecked exception and
therefore need not be handled or declared unless you wish.
Therefore when ((A)new B()).process(); is called then
super.process(); is called in class A the exception need not be
declared or handled as it is an unchecked exception.In the
If(true) condition an exception is thrown which propagates to
to the process methods which rethrows it to the calling
method where it is handled and hence Exception is printed.
Question 73
Again the compilation error on line 19 because the calling
method should either handle or declare the exception. On line
12, throw new Exception(); is called which has to be handled
or declared in the calling method.
Question 74
Here the option is B because the calling method calls a
method which does not throw any exception in class B the
void process method is overridden without any exception.This
is a valid rule of overriding.Exception can be anything broader
or it simply not exist but is should not be narrower.
Question 75
The connection is made on line 85. On line 86 the exception
occurs which is handled via a catch loop. So the lines after 86,
dont execute.Which leaves the resource connection open
still.so option C is the right answer.
Question 76
The question is tricky once the a.method1(); is called and then
b.method2(); is called from there and c.method3(); is called
from there.Remember NullPointerException is a Runtime
Exception.So all three methods need not handle/declare it.
c.method3(); propagates to b.method2();a.method1();
which is the calling code and it handles the exception.so
option E is right. The exception is caught by it and the lines
inside the catch executes. So option B is correct too.
Question 77
Dont be tricked because the exception thrown by the
catch (TestException te) {
throw new RuntimeException(te);
14
Abhijit.A.Nayak
KCT,Coimbatore
Question 78
When handling exception the subclass type catch block should
be first then the super class type should be last. (here
NullPointerException is subclass of Exception class) So
it wont compile, to compile it correctly we need to exchange
the lines 16 and 18
Refer page no 557 for more information.
Question 79
Remember Errors are like unchecked exception. It need not be
declare or handled. Refer page 363.Errors and Exceptions
share a common super class called throwable.here on the line
12. if (true) throw new AssertionError(); an error is thrown to
the calling code which is the main function. So the next line
13 in test() and the exception is not caught in main. Hence
nothing is printed.
Question 80
Exception is caught on line 14. But every time the finally runs
first and then the exception propagates to main and is caught
there.
Question 81
The flow is simple it is a runtime error which is an unchecked
exception. try { test(); } calls test()prints test and throws
new runtime exception which is caught exception is printed
because it is a superclass exception and runtime exceptions
need not be caught so it is handled here only. Thenend is
printed in main as it is already been caught and cause its a
runtime exception.
For question 82- please refer page 370 in the K&B text book.
Question 82
15
Abhijit.A.Nayak
KCT,Coimbatore
Question 83
This is a NullPointerException.Null pointer exception is thrown
when attempting to access an object with a reference variable
whose current value is null. classB.getValue(); is a null value.
Because class Bs getvalue() method has to access class cs
getvalue() method inorder to get a string.hence it is a runtime
exception.
Question 84
java.lang.ExceptionlnlnitializerErrorThrown when
attempting to initialize a static variable or an initialization
block.
Question 85
StackOverflowError thrown when a method recourses too
deeply. 3 is passed in and the method is a recursive method it
calls itself and hence option A is right cause it count(); keeps
calling itself.
Question 86
Wrapper class Integer i is never initialized to zero
automatically. Hence we get a runtime exception of 0.where
as int x initializes itself to zero after compiling.
Question 87
This is simple.str+=42 means str=str+42;
Question 88
args[0] represents a String bur we are assigning it to Integer
it throws
NumberFormatExceptin when assigning a String to Integer.
The correct way to use is:
Integer i=(Integer)args[0]; or
int i= Integer.parseInt(args[0]);
16
Abhijit.A.Nayak
KCT,Coimbatore
Question 89
Option D:Since StringBuffer and StringBuilder methods are
same we can replace with no other changes.
Option A:Since StringBuffer is thread safe A is wrong
Option C:Since + is not overridden in StringBuffer ( and also in
StringBuilder) it is not possible.
Option B:Since StringBuilder methods are not thread safe it
increases the performance
Question 90
If we use string buffer instead of string builder we wont get
complete synchronized data. To get proper sync we should
make the method log synchronized.Option A is correct.
Question 91
Fred this is appended with 47.Fred is also lost because it is
appended with 47.47 is lost
S=Fred47 (1st one,this is also lost)
ed47
(2nd one,this is also lost)
ED47
(final one)
Question 92
Observe the following output sequence for both the outputs
b) 123456789.delete(0,3) results in 456789 ( observe the
second parameter of delete method is not zero based index, it
is 1 based where as the first param is zerobased) Now
456789.replace(1,3,24) = 424789 (same as above).
Now424789.delete(4,6)= 4247 (here also same thing first
param zero based n second
param 1 based)
e)
123456789.delete(0,3)=456789.replace(1,3,7)=47789
.delete(2,5)=47.insert(1,24)=4247
Refer 425,426 and 427 for the methods explanation
Question 93
When invoking method the matching is the priority is direct
mapping widening autoboxing varargs.So go(y) invokes
the int method by widening short to int since the direct
17
Abhijit.A.Nayak
KCT,Coimbatore
Question 99
18
Abhijit.A.Nayak
KCT,Coimbatore
19
Abhijit.A.Nayak
KCT,Coimbatore
This is simple .Refer page 471 and look at the valid instance
creation options.
Question 106
There is not method such like that setLocale. To set the locale
we need to create a
Locale object using the following syntax
Local locItaly=new Local(it,IT) and format() method is
available in
DateFormat class and it is not available in the Date class.
Refer page no 466,467 and 468
Question 107
getLocalTime() and setLocaltime() are invalid . so option C &
D are wrong . getTime() & setTime() are correct.
Option B is right because the static method used to get an
instance of date format is getDateInstance();
Refer page 461 for date and Refer 471 for DateFormat.
Question 108
Parse() method takes a String formatted in the style of The
DateFormat instance.it coverts the string to date
Refer page 465.Parse() must be placed inside a try/catch
block.Refer page 470.
Question 109
Sorry I dont know why the compilation fails, here test.split
and tokens.length both are correct but may be problem with
\s may be it should be \\s.
Refer page no 475 and 486 for some information.
Question 110
split(\\d ) splits the string by separating with the a digit.
So the tokens array becomes tokens={a,b,c}
Refer page no.s 475 and 486 for tokenizing the Strings.
Question 111
String regex = \\.\\s*; means the regular expression is .
Followed by a white space character s.
20
Abhijit.A.Nayak
KCT,Coimbatore
Question 112
%d is printing integer values but Math.PI returns double so it
throws NumberFormatException.
Refer page no 489, 490 and 491 for information on formatting
Question 113
For retrieving the next integer first we need to test with
hasNextInt and then retrieve using the nextInt. If we are not
checking with the hasNextInt it refers to the string only and
throws parsing exception.
Refer page no.s 477 and 489 for explanation on Scanner class.
Question 114
A separate thread will be created only when we call start
method on a thread object. So in the given options we are
calling the start methods in D and F only.
Question 115
Calling run method wont start a new thread and wont throw
any error or exception, since calling run() is similar to calling
any other method so it is treated as just calling run()
method two times but it doesnt start the thread.Calling
start() method makes the t.run(); t.run(); run . and then start
calls run();
So the run() method will be executed three times and out put
is runnungrunningrunning.
Refer page no 682 for the explanation on run() method.
Question 116
Exception is created because t.start(); is called twice.So a
runtime Exception is created. Refer Page 730 3rd point in the
two minute drill(objective 4.1)
Question 117
It is an example for anonymous inner class and it is following
all the rules for a thread implementation that is creating a
21
Abhijit.A.Nayak
KCT,Coimbatore
Question 121
Since we are declared main as the throws Exception it wont
create any problem it compiles and runs successfully, so the
out put is sleep after minimum of 3000 secs.
If the main is not declared as throws Exception we need a try
catch block since sleep method throws InterruptedException
otherwise the compilation fails.
Refer page no 693 and 694 for more information.
Question 122
The possible results are
22
Abhijit.A.Nayak
KCT,Coimbatore
23
Abhijit.A.Nayak
KCT,Coimbatore
Question 127
Unless a synchronized on the (This) is not made there wont
be a lock on the current object accessed by the thread.Which
means X can be changed randomly.So Option D is a must.
Option A is a must because if we place the X inside a
synchronized method it will be better to get the lock on the
object.
Question 128
The synchronized keyword can be applied in two ways..i.e for
method and block. When it is applied to method there is no
need to pass object and when it is applied to block we
must pass the object on which object we want to get lock
24
Abhijit.A.Nayak
KCT,Coimbatore
Question 131
No syntax errors and exceptions, so follow the code to know
the output
Question 132
Wait and Notify should be applied for locking the object but
not thread.Here we are passing the Thread but not the object .
Correct examples are synchronized( this ) locks on the current
object,synchronized(MyClass.class) locks on the MyClass
object. But in this we are passing the Thread object.
Note: A thread acquires the lock on object.
Refer page nos 707,708,709
Question 133
25
Abhijit.A.Nayak
KCT,Coimbatore
26
Abhijit.A.Nayak
KCT,Coimbatore
FSame as option E.
Question 139
Animal animal = new Dog(); is a dog object which is of the
type Animal.It can only access the Animal Methods,
cat.makenoise(); cant be accessed because it is a dog object
originally.
Question 140
This is a simple but tricky overriding problem, All three are
RaceCar() objects but refer to each of the classes. Hence all
the methods have been overridden successfully.
Refer Page 100,101 for examples
Question 141
z.c1(); Class A does not have c1() method.
y.c1(); technically it is correct. Y instance of class C can
access Cs method.Dont know why it is marked
wrong.probably because the question was different.
All the other Examples are correct because of Simple
overriding rules,Inheritence and Abstract methods,Classes.
void y(); should have been declared in the interface.
Question 143
[lines 24 and 25 are a.x(); a.y() ]
When invoking a method with super class reference variable
the method should be declared in super class otherwise it will
be failed to compiles. ( Even though at run time it invokes the
subclass method).
Since here y method declared in B but it is not declared in
interface A, so the compilers checks for that and the
compilation fails. (If y() is declared in A then at runtime it
invokes the y() method of class B only but at compile time it
checks in A since we are used the reference variable of type
A)
Refer page no 100 (last para) for explanation.
Question 144
Class E overrides bMethod{} even though a return cast type
of Class D is present only the Overridden version of the Class
E is exectuted.
27
Abhijit.A.Nayak
KCT,Coimbatore
28
Abhijit.A.Nayak
KCT,Coimbatore
29
Abhijit.A.Nayak
KCT,Coimbatore
Question 155
Aoverriding
Binvalid overriding
COverloading (long argument)
Dinvalid override return type cant be changed.
EOverloading ( long argument)
FOverloading
GOverloading
Question156
this.a +=5 makes class Bar integer a to be incremented to 13
Foo foo = new Bar(); is an object of type Bar but which refers
to Foo. So in the print statement foo.a returns the Foos a
which is 3.
Question 157
super.multiply(a, b); here is wrong. Super(); or
super(arguments) are correct superclass constructor calls .
we cannot call the super classes methods using a constructor
call method super(); so compilation error.
Question 158
30
Abhijit.A.Nayak
KCT,Coimbatore
Question 160
Option CInterfaces can be used , not a must
Option Dinheritance represents extends,implements which is
is-a relationship
Question 161
BCat implements Jumper
CDog extends Animal
FTail tail; this is default access so Beagle can access the tail
So Beagle has a tail
GBeagle implements Jumper is a
Question 162
A treeset is a sorted set by nature. Its output will be in
ascending order.Order or insertion or latest access is not
considered.
Question 163
Poll() retrieves the head element and removes it from the
queue.Peek() retrieves the element at the head of the queue
but doesnt delete it .
31
Abhijit.A.Nayak
KCT,Coimbatore
Question 164
Since ws1 ans ws2 are user defined objects they refer to the
different objects. But after creating s1, s1 will be placed in
String pool, when s2 is created the JVM sees that same
object is existing so s2 also refers to the s1 So s1 and s2 both
are fully equal. As per the HasSet rules only one object will be
taken the duplicate object will not be added. So in
total 3 objects will exist in the list ws1,ws2,s1
32
Abhijit.A.Nayak
KCT,Coimbatore
33
Abhijit.A.Nayak
KCT,Coimbatore
output is again 2
k1 is removed now k1 which is stored has a value of i=1 so
it is checked using equals and also hashcode. And successfully
removed
output is one
k2.i=1 makes sure that k2s i is not removed from the set
collection because while equals method and hashcode method
checks it equals return false and hashcode returns i=2 for
k2. hence output is one.
Option F is correct.
Question 175
Option AGet(index) is used only by list
Option Biterator is used by list and set.
Option Cit is an method which returns an array containing
the elements of the collection.but the return type is object not
a collection.
Object[] toArray(); (note there are no arguments in
toArray();)
Option D iterator is used by list and set.
Option E it is an method which returns an array containing
the elements of the collection.but the return type is collection.
T[] toArray(T[])
Option Fiterator syntax wrong. Should be only
(Iterator(return type)) iterator();
Question 176
B is not valid since the type is not specified.<?> means we
cant add anything to the collection.it means anytype.refer
page 595.what we are looking for here is of type object.
C is not valid since the method return type is Object but we
are receiving it to String without casting
A is valid since we are passing legacy list to list and return
types are same.
D is valid since Specific type to legacy is allowed and return
types are matching.
E is valid since Specific type to legacy type is allowed and we
are type casting
34
Abhijit.A.Nayak
KCT,Coimbatore
35
Abhijit.A.Nayak
KCT,Coimbatore
Question 180
D is correct because List<? super String> means any type
that is a super class of String or of Type String. So it
accepts objects too.
Question 181
Double forms 123.000 for option D and C .but for option A
and C integer types are only passed in.Option A it is passed in
as a string but it is mutually comparable as the collections
dont see what has been stored it , it just checks if it follows
the syntax.
Question 182
If we use the "?" place holder it takes any type object but it
not allows to add the objects to the list so the options A,B and
E are wrong (since we are having add method).
If we use C it allows all types of objects so it also not valid.
If we use D it allows only the numeric type objects i.e Integer,
Float, Double, Short ,Long
and Byte (these are all the subclasses of Number class)
If we use the F option it allows the Integer types i.e Integer,
Short Long and Byte.
Refer page no 592, 596 and 610 for more information on ? and
? extends
Question 183
Hint 1 :generic class MinMax so all options are possible
Hint 2:Type parameter of MinMAx
all options are possible because type is E
it should implement Comparable . Comparable is a Class not
an interface that means E extends Comparable<E>
so option B,D is ruled out
From Option A & C
36
Abhijit.A.Nayak
KCT,Coimbatore
37
Abhijit.A.Nayak
KCT,Coimbatore
38
Abhijit.A.Nayak
KCT,Coimbatore
39
Abhijit.A.Nayak
KCT,Coimbatore
40
Abhijit.A.Nayak
KCT,Coimbatore
Question 207
Substitute the options in the questions and write down the
flow u will get the correct options as B,C,F.
Question 208
The flow is
Foo foo = new Foo( 300); 300
Foo fooFoo = fooBar( foo); 100
foo = fooBar( fooFoo); 100
Question 209
Since intObj is added to the numbers objects, it is in use by
the numbers object till line 18. So it is becomes candidate for
garbage collection in line 19 only ( it is not used by
any thing) ( See the numbers object is declared inside the
method the scope of thatobject is inside that method only so
outside the method it is not accessible, and intObj life is inside
the for loop only but it is in use with numbers object so it is
not eligible for garbage collection there in line 17th or 18th )
Refer page no 248 for similar example
Question 210
This is the direct way to request garbage collector for garbage
collection .For garbage collection we can use System.gc() or
Runtime rt = Runtime.getRuntime(); rt.gc();
Refer page no 251 and 252 for more information
Question 211
On line 22,snooch and booch are created with the help of
snoog.when snoog is referenced to null,the snooch and booch
are useless here after.They are not referenced by snoog and
they left on the heap without any purpose.so they are eligible
for the garbage collection.
Question 212
5. Object o = new Object();
41
Abhijit.A.Nayak
KCT,Coimbatore
6. doSomethingElse(o);
Here new object is created and passed to the line 6.
7.o = new Object();
here again new object is created and refered to variable oof
type Object .
8. doSomethingElse(null);
Now when null is passed through then the object o on line
5 will be refered to null. Not the new object created on line 7.
Hence on line 8,object o on line 5 becomes available for
garbage collection.
Question 213
Refer page 253 on finalize() method.
For any given object,finalize() will be called only once
(atmost) by the garbage collector.
Calling finalise() can actually result in saving an object from
deletion.
Question 214
The correct syntax for using jar file with class path is
java/javaC -cp JarName.jar ClassName.java
so from this we get option C & F to be correct.
And inorder to type the command :java games.cards.Poker
42
Abhijit.A.Nayak
KCT,Coimbatore
Question 215
This question is very easy.just jolt down the path names and
the fully qualified names to classes and draw directories , the
option is jar A.
Question 216
By default the compiler will search for the directory tree
named jre/lib/ext.The jar files hold all the locations to the file
and Book can access paper from the jar file.
So option B is correct.
Option D is correct because it follows the correct command
which includes the classpath environment
variable/foo/myLib.jar.
43
Abhijit.A.Nayak
KCT,Coimbatore
44
Abhijit.A.Nayak
KCT,Coimbatore
Question 219
Since str is receiving the value null and we are applying the
length() method on the null object it throw
NullPointerException..
Question 220
In line 13 usage of if condition is wrong (it is correct in
c/c++). In java if condition takes only boolean expression it
may be boolean value or an expression which results in
45
Abhijit.A.Nayak
KCT,Coimbatore
46