224 question explain at ions
TRANSCRIPT
-
8/9/2019 224 Question Explain at Ions
1/46
Abhijit.A.Nayak KCT,Coimbatore
1
Sun Certified Programmer for the Java 2Platform, StandardExam 310-055
Edition 5.0
Explanation Abhijit.A.Nayak [email protected]
Question 1
All constants in an interface are declared public,static,final
Page 22
Question 2
Option A is wrong because the syntax is wrong.Option C is wrong because only collections can be checked forhasnext() and next()
Question 3
On line 17,the short circuit operator && evaluates itself to befalse. if((x==4) && !b2) , here once x==4 is evaluated to befalse then other condition is not checked. So option D is right.Refer page 294
Question 4
Finally surely executes even if there is an exception or not.Refer page 347
Question 5
When attempting to cast a reference variable to a type thatfails the I S-A test, a ClassCastException is Throw n.Refer page 370
Question 6
Locale.getDefault(); is the right method to create an instanceof the Locale. Refer Page 471. In option D,
-
8/9/2019 224 Question Explain at Ions
2/46
Abhijit.A.Nayak KCT,Coimbatore
2
df.setDateFormat(d) is wrong because the question asked isabout the output not to set the date. Hence Option B is theright answer.
Question 7
In Encapsulation all instance variables in a class should bemarked as Private. Refer page 83 for the rules.
Question 8
In the line 25,Constructor call to the private variable of theMoney class is w rong. Hence there is a compilation error.Eventhough the argument passed to public StringgetCountry(String timeZone) ie String timeZone is irre levant ,
it follows the correct syntax in accessing the instance variablevia a method which has been marked as public.
Question 9
Has a Relationship is based on usage.Refer page 92.Man has a bestfriend instance variable or class member ofMan is bestfriend. Bestfriend is a (type of)Dog.
Question 10
Option C is wrong cause in a Hashset no dulicates areallowed.Second Entry is not allowed inside the set.Option D Hashset is a Set , not a map.Option B is w rongbecause in a map when we delete an object first we check ifthe hashcode() is equal then we check the equals() methodto see if both the instances are the same.
Question 11
The format of the question is correct. But in arrays andcollections the elements inside the collection/ array must bemutually comparable. This w ill be known as an error onlyduring the runtime, because the complier does not know w hatis inside the array until it runs.Refer page 556.
Question 12
This is postfix increment operator inside the dostuff method.But the variable inside the method is always a local and thescope of it dies after it leaves the method.hence dostuff=5.
-
8/9/2019 224 Question Explain at Ions
3/46
Abhijit.A.Nayak KCT,Coimbatore
3
Once it reaches the main, it realizes that x is a local to themain() and x was initialized as 5. so main=5. for incrementoperator refer page 290.
Question 13
A is correct since we are importing the class in a usual wayand accessing the staticvariable using the class name.C is correct since we are importing the class using the staticimports and accessing thestatic variable w ithout class name.Refer page no 776 for information on static imports
Question 14
To use an enum constant from out side of the class the onlyway is to use fully qualified name i.e option D.Refer page no 60 and 61 for similar examples
Question 15
It is an Argument-Defined Anonymous Inner class.Option D isthe wrong syntax because of class.Option A is wrong becausea new keyword is not there.Option B is w rong because of the
absence of the () after foo.Refer page number 653 for an example.
Question 16
Read the question carefully cause it is tricky & perplex.Once new Beta.testfoo() is invoked, line number 28System.out.println( fubar( new A())); is invoked.Theinvocation then calls the method fubar on line number 20.Infubar the foo.bar(); takes the version which was inside the
testfoo() as it was overridden ie on the line 24,25,26(optionB). If these 3 lines were deleted then the call goes to Betaversion s bar() method on line numbers 16,17,18 (Option E).Similarly for option F.
Question 17
From the Code we know that for like 4 to work properly we afully qualified name for sure. So in option EImport static sun.scjp.Color.GREENTells us that this is the right option.
-
8/9/2019 224 Question Explain at Ions
4/46
Abhijit.A.Nayak KCT,Coimbatore
4
Then out of the other options. We first need to import thepackage which must contain the enum, so we eliminate Abecause there is no static import. Remember static import isused for accessing static members. So here inside the enumall 3 colors are static.But we also need to access the color
enum so w e must have import sun.scjp.color.*;Option C is the right answer.
Question 18
This is straight forward and easy. Interface can only extendanother interface. so option A is right
Question 19
Method to be called depends on the actual object type,not onthe 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 optionsA and B are invalid.There is no operator such as -> in java so D is invalid, Wecannot use both object andclass for calling a method so E is invalid.Option C is the correct way to call the method of Circle bycreating a reference on the abstract class Shape.
Question 22
Rules for overridingClass members cant have an access modifier which isnarrower than what is declared.But it can be broader.protected abstract double getSalesAmount(); so proctectedand public are allowed to override but not private and defaultas its narrower than w hat has been declared in Employeeclass.
Question 23
-
8/9/2019 224 Question Explain at Ions
5/46
-
8/9/2019 224 Question Explain at Ions
6/46
Abhijit.A.Nayak KCT,Coimbatore
6
Only option C is there with this order. Then Go in Goban isprinted.
Question 27
Since f is declared in try block its scope is in try block only itcannot be accessed fromout side of the try block i.e finally block also. So the compilercomplains that the symbol fcannot be resolved in line 17.
Question 28
This is too easy. Anyw ays, when x+=x is invoked then x=x+xtakes place. Hence x =5+5 and x =10
Question 29
This is also too easy. We are creating an array of integers x[]and adding elements. Now integer array y[] is assigned to x[]and so y[2] is 3 because all arrays have a zero based index.
Question 30
Identifier can begin only w ith a letter,an underscore, or a
currency character.Refer two minute drill first point on page 68.
Question 31
A is a simple w ay to create an static array (in C style). B isway whichfollows Java rules i.e, declaring, constructing and initializing.
option C looks like an Anonymous array, but its not.the intshould not have a number between the brackets [].If it w as an Anonymous Array it should look likestatic final int[] a;a= new int[]{100,200};
Question 32This is an example to iterate through the enum elementsusing the enhanced for loop. Color.values() is the type whichhas to be passed in for the enum Color.
-
8/9/2019 224 Question Explain at Ions
7/46
Abhijit.A.Nayak KCT,Coimbatore
7
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 pub lic int getRGB() { return rgb; }
In order for the enum to work properly we need to make anenum instance. For that the proper syntax isOption B Color treeColor = Color.GREEN;Option A is wrong because the syntax for the enum which isenumname.enumvalueOption C is w rong because w e cant add new values to theenum after its declaration.
Now for the 2nd pickOption D is wrong because of w rong syntax like option Aenumname.enumvalueOption E is wrong again because purple cant be added or beassigned as its invalid.So option E is right.
Question 34
As soon as line 20 has been invoked,the format uses theoverridden method of the enum Title.But first the constructor runs and then the format methodruns.
Question 35
It is a straight forward question for the new For Each for loop.Here Anonymous Array has been used to initialize the objectobj[] 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 classname, it can be invokedusing reference variableB) Since alpha is static it can be invoked using the class namedirectly
-
8/9/2019 224 Question Explain at Ions
8/46
Abhijit.A.Nayak KCT,Coimbatore
8
C) static method (alpha) can be called from non static methoddirectly in thesame class (beta)D) non static method (beta) cannot be referenced from thestatic method
alpha)Refer page no 144 and 145 for more information on staticmethods.
Question 37
It is a straight forward question for variable arguments.
Question 38
JavaBeans P roperty Naming rules refer page 8,9Question 39
Static Method should access the Static instance variables. Sothe code does not compile.Since the static method getInstanceCount cannot referencethe non static variablecounter the compiler fails to compile in line 6 saying that Anon static variables cannot
be referenced by static method . So option A is correct.Refer page 142,143
Question 40
If the property is Boolean, the getter methods prefix is eitherget or is. Refer page 9.The setter method should be void andthe getter method must consists the Boolean.Hence option A and C are the right answers.
Question 41
The question here is about legal return types.Refer page 123.When option C has been used we know that Two I S-A One. Soit is allowed.(Co variant Return Type).Option D is overriding the super classes foo() method so it isallowed as well.
-
8/9/2019 224 Question Explain at Ions
9/46
Abhijit.A.Nayak KCT,Coimbatore
9
Question 42
A is invalid since the return type changes. D is invalid sincethe modifier can be lessrestrictive but it should not be more restrictive, so public and
protected is allowedbut private is not allowed. So B,C and E are correct.
Question 43
When overriding the overridden method can return the sameor sub type but not thesuper type. Since in line6 of class C it is returning the supertype the compiler throws anerror.
Refe r pages 122 , 123 and 124 for information oncovariant return types.
Question 44
Refer page 239 and 240.The complier w ill always choose tothe older style than the never one to keep the code morerobust.So option A.
Question 45
The option here is C. If w e are overriding then the rules are nochanging the return type and the arguments .But If itsoverloading then w e have to change the Arguments as well asthe return type.
Question 46
This is inner class question.Refer page 641,642.
But the option B should be like this Line.Point p = newLine().Point(); Guess there was a typing error.
To instantiate an inner classMyOuter.MyInner myinner= new MyOuter().MyInner();
OrIf you already have an instance of the outer class thenMyOuter outterObjRef=new MyOuter();MyOuter.MyInner myinner= MyOuter.new MyInner();
Question 47
-
8/9/2019 224 Question Explain at Ions
10/46
Abhijit.A.Nayak KCT,Coimbatore
10
The return type should be Line.Point because that correctlyretrieves a local instance of a Point object.so option A and Care wrong.we should instantiate line inorder to get a newinstance and from that instance we invoke getpoint() method.So option D is right.
Question 48
When Three is instantiated. calls the super constructors areinvoked because it in a built in call.So option C.
Question 49
Simple but tricky flow since the subclass invokes the superclass default or no-args constructor but
there is no such constructor in class Person it fails to compile(it fails to invoke the superclass constructor in line 18). So option D is correct.
Question 50
Since the subclass constructor invokes the base class defaultor no-args constructor and there is no such constructor itthrows compilation error so to stop this we need to insert
the statement given in option D. B,C and E are invalid becausesince w e cannot call constructor using the class name, we caninvoke the constructor using the this() or super() only.
Question 51
Follow the flow to know the out put . Remember that this() isused to invoke the current class constructors this. is used toaccess the current object variables.
Question 52
The answer is Compilation fails since the syntax for defaultcase is " default" not "casedefault".Refer page no 327 for valid example.
Question 53
Since there is no break statement, after the case collie theflow of control goes to the next line and produces the outputas collie harrier
-
8/9/2019 224 Question Explain at Ions
11/46
Abhijit.A.Nayak KCT,Coimbatore
11
Question 54
The output is really simple,In line 12 , there is a methodinvocation to line 18 which returns true.so the output is A.
Question 55
This is a Wrapper class example so its simple and easy. Boththe Wrapper class objects are converted to integers andadded.
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:8After the th ird i teration x:3 y:7After the fourth iteration x:4 y:6During the 5th iterationFirst y5 x5Then x value is checked and it exits the loop.
Question 59
The while loop never executes even once.hence the option isC.
Question 60
This is an infinite loop.as its a do while loop, the source codeinside the loop executes once which makes x=9 from then onit goes on looping.so the option here is D.
Question 61
To sort in reverse order it is not the correct way ,
-
8/9/2019 224 Question Explain at Ions
12/46
Abhijit.A.Nayak KCT,Coimbatore
12
to sort in reverse order we first need to applyreverse method followed by sort method.Refer page no 624 for correct syntax.
Question 62
LinkedList keeps the elements in the order of the index i.ew ith insertion positions so the elements are displayed as inthe insertion order itself. (Dont confuse w ith the objectname sorted, it is just a trick but the LinkedList w ont keepthe elements in sorted order)Note: we can keep the elements in sorted order using TreeSetand TreeMapRefer page no 542 and 560 to know abt LinkedList and Lists
Question 63
Since i is declared inside the for loop it can be accessed insidethe for loop only, it is not visible outside the for block so thecompilation w ill fail in line 15. when accessing i the compilersays that cannot resolve symbol i.
Question 64
To use to assertions first we need to enable assertions , forthis we need to use the ea or enableassertions so options Aand C are invalid. If w e use C and F the condition w ill be trueso it wont throw any Error, If we use B and E the assertionsare enabled and the condition w ill be false (length!=1) so itthrow AssertionError.Option D is the correct syntax it wontproduce and error.Option F enables assertions only for thetest class and two strings test , file1 are passed as commandline argument.
Question 65
This is a simple assertion example. During java AssertStuffthe assert is skipped and the output is passed. During java -eaAssertStuff since the value of the assertion is false ,AssertionError is thrown.Refer page 373.
Question 66
-
8/9/2019 224 Question Explain at Ions
13/46
Abhijit.A.Nayak KCT,Coimbatore
13
javac -source 1.3 Test.java makes sure that if assert is anidentifier.Refer pages 375,376,377.Due to this when we use source 1.3 it complies fine but showswarnings.anything above java1.3 the compilation fails.
Question 67
Assertions cannot be used to validate the public methodargumentsSo line 26 ( assert (x>0)) is not legal because we cant useassertions to validate arguments of a public method andassert (dostuff4()) is also not valid because it can cause aside effect as in it should leave the program as it is. A methodcall inside the assert keyword is wrong syntax.Refer page no 380for usage information of assertions
Question 68
When overriding a method the overriding method cannotthrow any checked exceptions or user defined exceptions(user defined exceptions are also treated as checkedexceptions) that is not throw n by super class method. So thecompilation in line 2 of class B will fails.Refer page no 99 for overriding rules.
Question 69
The option is D and E because when a.sayHello(john ) isinvoked,it throws an exception which either has to be handledby a try/ catchOption E and or has to be declared in thecalled method option D.handle or declare rule.
Question 70
If a null pointer exception takes place then the exception iscaught and then a is printed and the finally block executes.Hence option D.
Question 71
In line 14 w e are overriding the process() method.when weoverride exceptions only narrower exceptions can bedeclared.In class As process() method there is noexception.hence compilation error on line 14.
-
8/9/2019 224 Question Explain at Ions
14/46
Abhijit.A.Nayak KCT,Coimbatore
14
Question 72
This is a Runtime Exception,it is an unchecked exception andtherefore 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 bedeclared or handled as it is an unchecked exception.In theIf(true) condition an exception is thrown w hich propagates toto the process methods which rethrow s it to the callingmethod where it is handled and hence Exception is printed.Question 73
Again the compilation error on line 19 because the callingmethod should e ither handle or declare the exception. On line12, 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 amethod which does not throw any exception in class B thevoid process method is overridden w ithout any exception.Thisis a valid rule of overriding.Exception can be anything broaderor it simply not exist but is should not be narrow er.
Question 75
The connection is made on line 85. On line 86 the exceptionoccurs which is handled via a catch loop. So the lines after 86,dont execute.Which leaves the resource connection openstill.so option C is the right answer.
Question 76The question is tricky once the a.method1(); is called and thenb.method2(); is called from there and c.method3() ; is called
from there.Remember NullPointerException is a RuntimeException.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.sooption E is right. The exception is caught by it and the linesinside the catch executes. So option B is correct too.
Question 77
Dont be tricked because the exception thrown by thecatch (TestException te) {throw new RuntimeException(te);
-
8/9/2019 224 Question Explain at Ions
15/46
Abhijit.A.Nayak KCT,Coimbatore
15
} is a run time exception it need not be handled or declaredby the calling method.so option b.Remember runtimeexceptions are unchecked exceptions.
Question 78
When handling exception the subclass type catch block shouldbe first then the super class type should be last. (hereNullPointerException is subclass of Exception class) Soit wont compile, to compile it correctly we need to exchangethe lines 16 and 18Refer page no 557 for more information.
Question 79
Remember Errors are like unchecked exception. It need not bedeclare or handled. Refer page 363.Errors and Exceptionsshare a common super class called throwable.here on the line12. if (true) throw new AssertionError(); an error is thrown tothe calling code w hich is the main function. So the next line13 in test() and the exception is not caught in main. Hencenothing is printed.
Question 80
Exception is caught on line 14. But every time the finally runsfirst and then the exception propagates to main and is caughtthere.
Question 81
The flow is simple it is a runtime error which is an unchecked
exception. try { test(); } calls test()prints test and throwsnew runtime exception which is caught exception is printedbecause it is a superclass exception and runtime exceptionsneed not be caught so it is handled here only. Thenend isprinted in main as it is already been caught and cause its aruntime exception.
For ques t ion 82 - p lease re fe r page 370 in t he K&B tex t book .
Question 82
-
8/9/2019 224 Question Explain at Ions
16/46
Abhijit.A.Nayak KCT,Coimbatore
16
IllegalArgumentException is thrown w hen a method receivesan argument formatted differently than the methodexpects.Hence option D.
Question 83
This is a NullPointerException.Null pointer exception is thrownwhen attempting to access an object with a reference variablewhose current value is null. classB.getValue(); is a null value.Because class Bs getvalue() method has to access class csgetvalue() method inorder to get a string.hence it is a runtimeexception.
Question 84
java.lang.ExceptionlnlnitializerErrorThrown whenattempting to initialize a static variable or an initializationblock.
Question 85
StackOverflowError thrown w hen a method recourses toodeeply. 3 is passed in and the method is a recursive method it
calls itself and hence option A is right cause it count(); keepscalling itself.
Question 86
Wrapper class Integer i is never initialized to zeroautomatically. Hence we get a runtime exception of 0.whereas 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 Integerit throwsNumberFormatExceptin when assigning a String to Integer.The correct way to use is:Integer i=(Integer)args[0]; orint i= Integer.parseInt(args[0]);
-
8/9/2019 224 Question Explain at Ions
17/46
Abhijit.A.Nayak KCT,Coimbatore
17
Question 89
Option D:Since StringBuffer and StringBuilder methods aresame we can replace with no other changes.Option A:Since StringBuffer is thread safe A is wrongOption C:Since + is not overridden in StringBuffer ( and also inStringBuilder) it is not possible.Option B:Since StringBuilder methods are not thread safe itincreases the performance
Question 90
If w e use string buffer instead of string builder we wont getcomplete synchronized data. To get proper sync we shouldmake the method log synchronized.Option A is correct.
Question 91
Fred this is appended w ith 47.Fred is also lost because it isappended w ith 47.47 is lostS=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 outputsb) 123456789.delete(0,3) results in 456789 ( observe thesecond parameter of delete method is not zero based index, itis 1 based w here as the first param is zerobased) Now456789 .replace(1,3,24) = 424789 (same as above).Now424789 .delete(4,6)= 4247 (here also same thing first
param zero based n secondparam 1 based)e)123456789.delete(0,3)=456789.replace(1,3,7)=47789.delete(2,5)=47.insert(1,24)=4247Refer 425,426 and 427 for the methods explanation
Question 93
When invoking method the matching is the priority is directmapping w idening autoboxing varargs.So go(y) invokesthe int method by w idening short to int since the direct
-
8/9/2019 224 Question Explain at Ions
18/46
Abhijit.A.Nayak KCT,Coimbatore
18
mapping is not available.go(z) invokes the Long version byauto boxing to Long since the direct mapping and w idening isnot available.Refer page no 238 for w idening , auto boxing and varargsrules.
Question 94
Here the methods go(short s) ans go(Short s) both are samein the sense of compiler so the compiler fails to compilesaying multiple declarations.
Question 95
This is quiet simple.Unless you carefully look into the question
you might not spot it.The directory object is created but notthe actual directory in the hard disk becausedirectory.mkdir(); was not called and hence this causes anIOException during runtime.Refer page 440 for an example.
Question 96
Refer page 436. writing a line separator to the stream is theonly extra thing in buffered writer when compared tofilewriter.
Question 97
As per the Serialization rules the classes that are involving inserialization also should implement Serializable interface buthere the class Tree is not implementing the Serializableinterface, so it throws an Exception when it is trying toserialize the Forest class.Refer page no 450 for similar example.
Question 98
When overriding w riteobject() and readobject() we shouldmake sure than we should read the data in the same order aswe wrote it.Refer page 451.
Question 99
-
8/9/2019 224 Question Explain at Ions
19/46
Abhijit.A.Nayak KCT,Coimbatore
19
For option E refer to page 453.For option D refer to page 449.
Question 100Since there is no problem in code and no complex flow , it is a
general flow . So the corresponding values w ill be printed.Refer page no 444 for similar example
Question 101
If the super class in not implementing Serializable interfacewhen deserializing the class the super class constructor willrun.So the execution in object creation is lines 19,14,16 output 12.When serializing no output.
When deserializing the Food constructor wi ll run so output is1A the line 22 output is restored and size 42So the complete output is 121restored42.Refer page no 452, 453 and 454 for same example
Question 102
Refer page 451.
s.defaultWriteObject(); is used to normalize all the data in anormal way.
Question 103
This is very easy. Refer pages 469,470.(3.1415926); is rounded off to 4 decimal points
Question 104
Parse(input) is wrong parse(numbers only) same w ithoption DSo equals is wrong cause it does not make sense in formattingproblems.So option B is correct.Parse() method takes a String formatted in the style of TheDateFormat instance.it coverts the string to dateRefer page 465
Question 105
-
8/9/2019 224 Question Explain at Ions
20/46
Abhijit.A.Nayak KCT,Coimbatore
20
This is simple .Refer page 471 and look at the valid instancecreation options.
Question 106
There is not method such like that setLocale. To set the localewe need to create aLocale object using the following syntaxLocal locItaly=new Local(it ,I T) and format() method isavailable inDateFormat 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 aninstance 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 TheDateFormat instance.it coverts the string to date
Refer page 465.Parse() must be placed inside a try/ catchblock.Refer page 470.
Question 109
Sorry I dont know why the compilation fails, here test.splitand tokens.length both are correct but may be problem w ith\ 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 w ith 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 w hite space character s .
-
8/9/2019 224 Question Explain at Ions
21/46
Abhijit.A.Nayak KCT,Coimbatore
21
Question 112
% d is printing integer values but Math.PI returns double so itthrows NumberFormatException.
Refer page no 489, 490 and 491 for information on formatting
Question 113
For retrieving the next integer first we need to test w ithhasNextInt and then retrieve using the nextInt. If w e are notchecking w ith the hasNextInt it refers to the string only andthrows parsing exception.Refer page no.s 477 and 489 for explanation on Scanner class.
Question 114
A separate thread w ill be created only when we call startmethod on a thread object. So in the given options we arecalling the start methods in D and F on ly.
Question 115
Calling run method wont start a new thread and w ont throwany error or exception, since calling run() is similar to calling
any other method so it is treated as just calling run( )method tw o times but it doesnt start the thread.Callingstart() method makes the t.run(); t.run(); run . and then startcalls run();So the run() method w ill be executed three times and out putis runnungrunningrunning.Re fer p a g e n o 6 8 2 f o r t h e ex p l a n at i o n o n ru n ( ) m e th o d .
Question 116
Exception is created because t.start(); is called tw ice.So aruntime Exception is created. Refer Page 730 3rd point in thetwo minute drill(objective 4.1)
Question 117
It is an example for anonymous inner class and it is follow ingall the rules for a thread implementation that is creating a
-
8/9/2019 224 Question Explain at Ions
22/46
Abhijit.A.Nayak KCT,Coimbatore
22
thread object by passing Runnable reference, overriding therun() method and invoking the start method on the threadobject. So the output is bar.
Question 118
Run() method in the Thread t s anonymous class creation getsoverridden and so Dog is the Right answer.
Question 119
In the main method x which is initialized is not shownbecause it is a non static variable.As soon as new Starter().makeItSo(); is called. First theconstructor is called.
Here x=5;From here the start(); is made which calls the run();Here x *= 2;Hence x=10 inside runOnly now the method makeitso is called after the constructorand run(from start) method calls are completed.Here the x is x=x-1So the answer is 9.
Question 120
Here the target for the thread t is a new instance of the classthread2 w hich implements runnable.When t.start(); is invokedrun is printed for sure and Runtime exception is caught andthen End of method is also definitely printed.the order isdecided by the JVM.
Question 121
Since we are declared main as the throws Exception it w ontcreate any problem it compiles and runs successfully, so theout put is sleep after minimum of 3000 secs.If the main is not declared as throws Exception we need a trycatch block since sleep method throws InterruptedExceptionotherw ise the compilation fails.Refer page no 693 and 694 for more information.
Question 122
The possible results are
-
8/9/2019 224 Question Explain at Ions
23/46
Abhijit.A.Nayak KCT,Coimbatore
23
Started0123Completed and 0123StartedCompleted(Ofcourse other possibilities areStarted123Completed,01StartedCompleted,012StartedCompleted)First output: Main thread (the thread w hich is executing the
current program) executes first and prints Started but bcoz ofjoin method it waits till thread completes so thread tw ill be executed and prints 0123 after t completed it joinsw ith main thread now main thread continues and printsCompleted.
Second Output: t thread starts and prints 0123 and mainthread prints Started and since Thread t is already completed,main thread continues and prints Completed.But theCompleted will not be executed until t thread is completed
bcoz of join.
Refer page no 698 and 699 for explanation.
Question 123
Main Thread Thread1 Thread2
First StartMain is called in the main threadThread1 is executed start1 is printed.In Thread1 Delay(6000) is executed.Then first delay(1000) in the main thread is executed.Then 2nd delay(1000) in the main thread is executed.Then 3rd delay(1000) in the main thread is executed.Then EndMain from thread1 is executedEnd1 is printed from Thread1.Then Thread2 is executedstart2 is printed.In Thread2 Delay(2000) is executed.Then thread2 is interrupted in main(); t2.interrupt();
So Exception is created in Delay(2000) and caught and Erroris printed.End2 is printed from Thread2.
This took me one hour to decode properly with lot ofmodifications to trace the Thread.This is the way it should betraced.Hopefully I am right :-) .
Question 124
-
8/9/2019 224 Question Explain at Ions
24/46
Abhijit.A.Nayak KCT,Coimbatore
24
The rule for synchronizing threads are keep instance variablesprivate and method accessing them should be named publicand synchronized keyword should be present.
Question 125
The option is A & C.Compilers give different output mine gave me 0,0,2,2,4,4,6,6,
What we have to figure out is 0, 2, 4, 4, 6, 8, 10, 6,In option A . Say one thread executes the loop and prints is0, 2, 4, and pre-empts and then second thread uses that value4 which was the latest and prints 4, 6, 8, 10. remember in thissum what we have to realize is only 8 numbers are printed
and only in the ascending order. Then 6 is printed by the firstthread.
Option B: 0, 2, 4, 6, 8, 10, 12, 14.This is w hen the x value isbeing increment until the loop is completed by thread one 0,2, 4, 6 and then it continued to increment by 2nd threads loop8, 10, 12, 14
Question 126
This is a tricky one.Option E is correct Because A,B,C shouldrun thrice each once.Dont know about option G
Question 127
Unless a synchronized on the (This) is not made there wont
be a lock on the current object accessed by the thread.Whichmeans X can be changed randomly.So Option D is a must.Option A is a must because if we place the X inside asynchronized method it w ill be better to get the lock on theobject.
Question 128
The synchronized keyw ord can be applied in two ways..i.e formethod and block. When it is applied to method there is noneed to pass object and when it is applied to block wemust pass the object on which object we want to get lock
-
8/9/2019 224 Question Explain at Ions
25/46
Abhijit.A.Nayak KCT,Coimbatore
25
A)Incorrect bcoz we cannot apply synchronized keyword forany variablesB)Incorrect bcoz we are not passing the object for thesynchronized blockD)Incorrect bcoz there is no need to pass object when we are
applying it to method
Question 129
Static variables should be accessed from static methods inorder to be thread safe.option E is right.
Question 130
doTransfer(r1, r2, 5 ) ; r 1 = 5,r2=15
doTransfer(r2, r1, 2);r1= 7 r2= 13doTransfer(r1, r2, 1); r1=6,r2=14These are the 3 options which are the possible outputs butThe code may deadlock (w ithout completing) w ith no outputis also correcting as a can be waiting for b and b can bewaiting for a
Question 131
No syntax errors and exceptions, so follow the code to knowthe output
Question 132
Wait and Notify should be applied for locking the object butnot thread.Here w e are passing the Thread but not the object .Correct examples are synchronized( this ) locks on the currentobject,synchronized(MyClass.class) locks on the MyClassobject. 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
-
8/9/2019 224 Question Explain at Ions
26/46
Abhijit.A.Nayak KCT,Coimbatore
26
wait is applied on bar object so notify or notifyAll should beinvoked on bar object, but there are so many threads so thebetter way is to use the notifyAll . So bar.notifyAll() is correct.
Question 134
As the encapsulation rules A & D are correct.Refer page no.s: 82, 83 and 84 for encapsulation rules.
Question 135
Here the string is public but the class is default . Since theclass has package level access u can access the String only inthe same package.
Question 136
A is invalid since i++ is different from ++i so it changesthe output.
B is invalid since i=1; differs w ith i=0; when initializationand in output
C is invalid since if it is private it cannot be accessed inClient class.
D is the correct way which uses the autoboxing Integeri=0;In ++i it is unboxed and incremented.
Refer page no.s 234 and 236 for information.Question 137
Base is having public modifier but the class is having defaultmodifier, so the class can be accessed only w ithin the packagehence the variable base can be accessed in the same package.
Refer Q. No : 21 for same example
Question 138
A It is correct because p0=p1, Class B extends Class A.All that is in Class A can be accessed by Class B. BIt is w rong because Class C and Class B extend Class
A.So there will be methods that are different in Class B &Class C which cannot be the same. CThe Return type of p4 is Class A but Return Type of p2
is Class C. They cannot be assigned together. DIt is w rong because p1 cant be cast to the type ClassB Ep1 can be assigned to a variable which is cast to
ClassB because both can access only the Class Bs data.
-
8/9/2019 224 Question Explain at Ions
27/46
Abhijit.A.Nayak KCT,Coimbatore
27
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 objectoriginally.
Question 140
This is a simple but tricky overriding problem, All three areRaceCar() objects but refer to each of the classes. Hence allthe 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 canaccess Cs method.Dont know why it is markedwrong.probably because the question was different.All the other Examples are correct because of Simpleoverriding 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 variablethe method should be declared in super class otherwise it w illbe failed to compiles. ( Even though at run time it invokes thesubclass method).Since here y method declared in B but it is not declared ininterface A, so the compilers checks for that and the
compilation fails. (I f y() is declared in A then at runtime itinvokes the y() method of class B only but at compile time itchecks in A since we are used the reference variable of typeA)Refer page no 100 (last para) for explanation.
Question 144
Class E overrides bMethod{} even though a return cast typeof Class D is present only the Overridden version of the ClassE is exectuted.
-
8/9/2019 224 Question Explain at Ions
28/46
Abhijit.A.Nayak KCT,Coimbatore
28
This is an Example of UpCasting Refer page114.Dog,Beagle,Pet example on 115.
Question 145
Option A,E it is wrong because Class C does not Implementthe InterfaceA.Other Options are correct Because Either ClassB or InterfaceAhave declared/ implemented the method public int getValue();
Question 146
It is a call from Subclasses constructor to SuperclassesOverriden Construction(Anything w hich is other than No-
Argument Constructor is Overridden).
Question 147
Based on the class name the output: Base.FOO = foo (since it is static Base.FOO works) Sub.FOO = bar (same as above) b.FOO = Base.FOO = foo s.FOO = Sub.FOO = bar
((Base)s).FOO) = (Base).FOO = foo
(I f the FOO is not static then the last result is barsince the object is of type Sub).
Question 148
A) final and abstract keywords cannot be applied at a time amethod, since the abstract method must be overridden whereas final not allows to overrideB) Since protected method is visible in any subclass of X it canbe overridden in any subclass
c) Static variables can be accessed from static as w ell asinstance methods there is no such restrictionD) A final method cannot be overridden in any subclasswhether it is static or non static or publicE)Since static variables are class variables we call a staticmethod without creating an instance for that, just we can callit using the class name itselfF) Once it is declared as private it is not visible in any of thesubclasses so if we override the method it is not actuallyoverriding, it is simply just new declaration.
-
8/9/2019 224 Question Explain at Ions
29/46
Abhijit.A.Nayak KCT,Coimbatore
29
G)Protected Member can be accessed through inheritance by asubclass even if the sub class is in a different package.so it iswrong.only default should be in the same package.
Re fer p a g e n o 9 9 f o r m o re i n f o rm a t i o n o n O v er r i d i n g
Question 149
Are you confused w ith a long code dont worry just observethe addTopping method inline 3. It is final so it can be overridden in sub lass i.e inPepperon1. So the compilationfails in line 8.Re fer p a g e n o 4 0 f o r i n f o rm a t i o n o n f i n a l m e th o d s .
Question 150
The variable a is private in class Super so it is not accessiblein class Sub and there is no default constructor in class Super.So we need to make the changes accordingly and they mustbe done independently.Options C and D are correct to changethe code independently (if it is togetherthere are otheroptions also correct).Refe r quest ions 28 and 122 f o r s im i la r exam p le .
Question 151
Since the methods are overridden , the execution of themethod depends on the currentobject but not on the reference type and super.methodinvokes the super class method.So the execution of the statements is..
MultiCalc Line 8
MultiCalc Line 9 MultiCalc Line 10
MultiCalc Line 3 now multiply = 2 MultiCalc Line 4 MultiCalc Line 2 now value= 0 - 3 = -3 MultiCalc Line 5 SimpleCalc Line 3 value= -3 + 7 = 4 MultiCalc Line 6 value= 4*2 = 8 MultiCalc Line 11 Output value is 8
Question 152
-
8/9/2019 224 Question Explain at Ions
30/46
Abhijit.A.Nayak KCT,Coimbatore
30
To call or invoke other constructor in the same class we needto use the this() but not the class name. So the compilationfails.
Question 153
This() calls the no argument constructor of the same class.So option a,b is ruled out.Super() w ithout argument is wrong cause in superclassconstructor has been overridden w ith an argument.So option C is wrong.Option F is wrong because w heelcount is private it is notinherited.
Question 154
This is a simple question . Super() constructor and assigningthe variable with this operator.
Question 155
AoverridingBinvalid overridingCOverloading (long argument)Dinvalid override return type cant be changed.EOverloading ( long argument)FOverloadingGOverloadingQuestion156
this.a +=5 makes class Bar integer a to be incremented to 13Foo foo = new Bar(); is an object of type Bar but which refers
to Foo. So in the print statement foo.a returns the Foos awhich is 3.
Question 157
super.mult iply(a, b); here is w rong. Super(); orsuper(arguments) are correct superclass constructor calls .we cannot call the super classes methods using a constructorcall method super() ; so compilation error.
Question 158
-
8/9/2019 224 Question Explain at Ions
31/46
Abhijit.A.Nayak KCT,Coimbatore
31
The code w ith compile because there is no error in the syntax.It is not a proper design of is-a Relationship cause we areextending from java.util.Linkedlist w e are not overriding andcannot override any of the linkedlist methods,we are justusing them.add(p);
There no has-a relationship .Refer page number 92.By default inheritining java.util.Linkedlist also allow s us toremove from the list.
Question 159
Option ahas-a can be encapsulated.Option b has-a can be implemented using interfacesIndirectlyOption Factress is not a movie
Question 160
Option CInterfaces can be used , not a mustOption Dinheritance represents extends,implements which isis-a relationsh ip
Question 161
BCat implements JumperCDog extends AnimalFTail tail; this is default access so Beagle can access the tailSo Beagle has a tail
GBeagle implements Jumper is aQuestion 162
A treeset is a sorted set by nature. Its output will be inascending order.Order or insertion or latest access is notconsidered.
Question 163
Poll() retrieves the head element and removes it from thequeue.Peek() retrieves the element at the head of the queuebut doesnt delete it .
-
8/9/2019 224 Question Explain at Ions
32/46
Abhijit.A.Nayak KCT,Coimbatore
32
Question 164
Since ws1 ans w s2 are user defined objects they refer to thedifferent objects. But after creating s1, s1 w ill be placed in
String pool, when s2 is created the JVM sees that sameobject is existing so s2 also refers to the s1 So s1 and s2 bothare fully equal. As per the HasSet rules only one object w ill betaken the duplicate object w ill not be added. So intotal 3 objects will exist in the list ws1,ws2,s1
Refer page no 562 for more information
Question 165
The set variable contains only three elements from the coilcollection, but the order is NOT guaranteed to bepreserved.set s dont take in duplicates and the elements
which are added inside are not in the same order.they arerandomly inserted.
Question 166
public int compareTo(Score other) {/ *more code here*/ } iscorrect because Comparable we should take anargument of the type youre sorting.Refer page 552.
Question 167
add(0,object), is used by the list interface method Refer page569.Random Access is used by Vector and ArrayList types oflist.
So option D is correct.
Question 168
hashCode(), hashCode()/ 2 and hashCode()/ 2-age*3 all
return same value for few of the
-
8/9/2019 224 Question Explain at Ions
33/46
Abhijit.A.Nayak KCT,Coimbatore
33
elements, but hashCode()+age*7 returns diff values sooptions B is correct.Try with example values for clarifications.Refe r page no 53 3 fo r exp lana t ion on hashCode legal re t u rn
va lues
Question 169
Hashcode and equals should be overridden.Equals must takein an argument of type Object.
Question 170
To the hashset during compilation wat matters is there shouldnot be any duplicates.creating an different objects of type
person and adding it to the set is allowed regardless ofchecking if the name is the same or not. The equals methoddoes NOT properly override the Object.equals method.
Question 171
The equals method does NOT properly override the Object.equalsmethod. The syntax of equals method is w rong, since equalstakes Object as param but not theuser defined object, so it throws compilation error. The correctsyntax is public Boolean equals(Object o)Re f er p a g e n o 5 2 6 f o r m o r e i n f o r m a t i o n o n e q u a l s m e t h o d
Question 172
Options C and E are correct as per the hashCode implications.Refe r page no 53 4 and 530 fo r hashCode im p l i ca t ions .
Question 173
Option A is correct since both are always equals since it enum
by default implementsComparableRe fer p a g e n o 6 0 - 6 3 t o k n o w m o re ab o u t e n u m s
Question 174
Set cant take duplicates, so only one set.add(k1); set.add(k2);works.The size of the set now is 2k2.i = 1;
nothing affects the set cause k2 is not used in the next printstatement
-
8/9/2019 224 Question Explain at Ions
34/46
Abhijit.A.Nayak KCT,Coimbatore
34
output is again 2k1 is removed now k1 w hich is stored has a value of i=1 soit is checked using equals and also hashcode. And successfullyremovedoutput is one
k2.i=1 makes sure that k2s i is not removed from the setcollection because while equals method and hashcode methodchecks it equals return false and hashcode returns i=2 fork2. hence output is one.
Option F is correct.
Question 175
Option AGet(index) is used only by listOption Biterator is used by list and set.Option Cit is an method which returns an array containingthe elements of the collection.but the return type is object nota collection.Object[] toArray(); (note there are no arguments intoArray();)
Option D iterator is used by list and set.Option E it is an method which returns an array containingthe 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 w ecant add anything to the collection.it means anytype.referpage 595.what we are looking for here is of type object.C is not valid since the method return type is Object but weare receiving it to String w ithout castingA is valid since we are passing legacy list to list and returntypes are same.D is valid since Specific type to legacy is allowed and returntypes are matching.E is valid since Specific type to legacy type is allowed and weare type casting
-
8/9/2019 224 Question Explain at Ions
35/46
Abhijit.A.Nayak KCT,Coimbatore
35
the return value.
Re fer p a g e n o 5 7 6 f o r m o re i n f o rm a t i o n o n
m ix ing gene r i cs and legacy code .
Question 177
This is a simple example.inputs 0042 and retrives and printsit.If you don t know this please read Colletions again.Makesure you know
add() method is used by set,list
remove() used by all put() by map get() by list and map contains()list,set
ContainsKey or ContainsValue() Map Iterator() Set,List
These are the important interface methods refer to page 569.
Question 178
Since with the generics implementation there is no need ofexplicit type conversion fromwrappers to primitives line 14
And to make the code easywe can remove the complex for loop and can be replaced withthe enhanced version.List intList makes sure only Integer List is created.
options A,C,F are enough to use generics.
Question 179
Option A it is wrong because any list cant be assignedto The type List
Option BList cant be assigned to List cause might have methods which A doesnt. it shouldalways be List a = b; where b = List
Option CList and List when equatedmeans the same.
Option D Class D extends B so it can be assigned. Option EList cant be assigned to anything like
List
-
8/9/2019 224 Question Explain at Ions
36/46
Abhijit.A.Nayak KCT,Coimbatore
36
Option FWrong it should be assigned only toList
Option GList
-
8/9/2019 224 Question Explain at Ions
37/46
Abhijit.A.Nayak KCT,Coimbatore
37
Put is used to add elements to the collections and the returntype may be normal.but look at the instance variables E min . That is wrong . it should be of the form E min .Refer pages 598-602 for making our own generic class.
Question 184
one.name= Coffee;two.name= Tea;these two lines makes sure that when they are added to theset what happens is compare(object o) return a zero w ith itand all the objects which are of type Drink are assumed to bethe same so while iterating over the collection we get Coffeeagain n again.
Question 185
reverseOrder(); method returns a Comparator that sorts thereverse of the collectionss current sort sequence.Its synyax is static Comparator reverseOrder(Comparator)Refer page 568 for the syntax.So the sort method takes the syntax which is shown belowStatic void sort(List, Comparator);So option D is correct.
Question 186
Option B is correct because asList(T [] ) is the correctsyntax.there must be an argument of the list.Refer page 568.
Question 187
Searching an array or collection that is not sorted is a biggotcha.We can also use the comparator in either the sort orthe search.Refer page 558.
Question 188
The code is correct and when sorting spaces w ill come firstthen caps and then smallsso the output is C.Re fer p a g e n o 5 5 6 a n d 5 5 7 f o r s or t i n g i n f o rm a t i o n
Question 189
C is right because Comparator when not used insidebinarySearch() method we get an undefined answer.
-
8/9/2019 224 Question Explain at Ions
38/46
Abhijit.A.Nayak KCT,Coimbatore
38
For other rules refer to question above this.
Question 190
Keyset() returns the keeps in a Map.
In order to sort this we use option B because sort method inoption A and C are used only with lists.not with maps.Option D is wrong because there is nothing called theSortedset.TreeSet() by default is a sorted set. So that is the correctanswer.
Question 191
If ur not importing the package which u w ant to use for amethod or a class the only way is to use the full name in thisexample the full name ispackagename.classname.methodname i.eUtils.BitUtils.process(bytes); The option E seems to be correctbut in the given question u can not use the import statementin the middle of the program.Refer Page no 7 69
Question 192
private static void process(byte[] b) { } in the BitUtil class sowe cant access the process In the other package.so option F
Question 193
String getText() is got a default access, so it cannot beinherited to other packages.only protected and public throughinheritance.
Question 194
Only if we make the consume() method public in salomon.javawe can access it is griskly bear.option A is correct
We need not use fully qualified name look at the code weare making an instance of the Saloman class so option D iscorrect.if we didnt make an instance we should ve pickedoption E
Question 195
-
8/9/2019 224 Question Explain at Ions
39/46
Abhijit.A.Nayak KCT,Coimbatore
39
Static import is used here to use Tw ice method .Twice methodis static and when we use the fully qualified name it can beaccessed easily without typing much code.Refer static imports in chapter 10.
Question 196
The line in 20 is treated as s= s+ (EASY++ + s);Since EASY is final it can not be incremented so it fails tocompile.
Question 197
The flow is correct. So option A
Question 198
Args is an array. Arrays have the variable length.but stringshave a method lenth();So option B is correct
Question 199
The current directory is / foo/ and we ve have used a fully
qualified name henceforth w e dont need a classpath.Hence option B
Question 200
This question looks very deceptive and correct. Lookcarefully.dostuffX is not in main. We get an exception
Exception in thread "main" java.lang.NoSuchMethodError:main
Thrown if an application tries to call a specified method of aclass (either static or instance), and that class no longer has adefinition of that method.Normally, this error is caught by the compiler; this error canonly occur at run time if the def inition of a class hasincompatibly changed.
Question 201
java Yippee
-
8/9/2019 224 Question Explain at Ions
40/46
Abhijit.A.Nayak KCT,Coimbatore
40
no arguments passed nothing is printed.
java Yippee 1234for( int x = 1; x < args.length; x++)
see this x starts w ith 1 args[] is zero based. So234 is correct.
Question 202
Same explanation as the previous one
java Yippee a b cfor( int x = 1; x < args.length; x++)
see this x starts with 1 args[] is zero basedso b , c
Question 203
D,E follow the correct syntax.See page 764.
Question 204
A is correct because it follows the current syntax.
Question 205
It is a general flow for the program. It seems the modifyDescis modifying the desc of it (in lines 6,7,8) but actually it iscreating a new object which is local to that method andassigning the desc to the item desc. So the output isGobStopper FizzyLifting.
Question 206
When the object is created the constructor assigns the value42 to id.But in line 14 using the method w e are trying tomodify the value so it throws fails to compile since finalvariable cannot be modified. this.id in line 13 and id in lineboth refers to the id declared in line 12, (since we are havingone more local variable in the constructor w ith the same namewe are referredit using this in line 13).
-
8/9/2019 224 Question Explain at Ions
41/46
Abhijit.A.Nayak KCT,Coimbatore
41
Question 207
Substitute the options in the questions and write dow n theflow u w ill get the correct options as B,C,F.
Question 208
The flow is
Foo foo = new Foo( 300); 300Foo fooFoo = fooBar( foo); 100foo = fooBar( fooFoo);100Question 209
Since intObj is added to the numbers objects, it is in use bythe numbers object till line 18. So it is becomes candidate forgarbage collection in line 19 only ( it is not used byany thing) ( See the numbers object is declared inside themethod the scope of thatobject is inside that method only sooutside the method it is not accessible, and intObj life is insidethe for loop only but it is in use wi th numbers object so it is
not eligible for garbage collection there in line 17th or 18th )
Refe r page no 248 fo r s im i la r exam p le
Question 210
This is the direct way to request garbage collector for garbagecollection .For garbage collection w e can use System.gc() orRuntime rt = Runtime.getRuntime(); rt.gc();Re fer p a g e n o 2 5 1 a n d 2 5 2 f o r m o re i n f o rm a t i o n
Question 211
On line 22,snooch and booch are created w ith the help ofsnoog.when snoog is referenced to null,the snooch and boochare useless here after.They are not referenced by snoog andthey left on the heap w ithout any purpose.so they are eligiblefor the garbage collection.
Question 212
5 . Object o = new Object();
-
8/9/2019 224 Question Explain at Ions
42/46
Abhijit.A.Nayak KCT,Coimbatore
42
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 ooftype Object .
8. doSomethingElse(null) ;Now when null is passed through then the object o on line5 w ill be refered to null. Not the new object created on line 7.Hence on line 8,object o on line 5 becomes available forgarbage collection.
Question 213
Refe r page 253 on f i na l i ze( ) m e thod .
For any given object,finalize() w ill be called only once
(atmost) by the garbage collector.Calling finalise() can actually result in saving an object fromdeletion.
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
SEE THE IMAGE IN THE NEXT PAGE.
Now we have to move the Poker.jar to the stuff/ java onlythen we can access like
java cp / stuff/ java games.cards.Poker.
This is the correct way to do it.Option is C.
-
8/9/2019 224 Question Explain at Ions
43/46
Abhijit.A.Nayak KCT,Coimbatore
43
Question 215
This question is very easy.just jolt down the path names and
the fully qualified names to classes and draw directories , theoption is jar A.
Question 216
By default the compiler w ill search for the directory treenamed jre/ lib/ ext.The jar files hold all the locations to the fileand Book can access paper from the jar file.So option B is correct.Option D is correct because it follows the correct commandwhich includes the classpath environmentvariable/ foo/ myLib.jar.
-
8/9/2019 224 Question Explain at Ions
44/46
Abhijit.A.Nayak KCT,Coimbatore
44
Option E is wrong because syntax for using jar file inclasspath is w rong.Option C is wrong because environment variable is placedwrongly.
Option A is wrong because the complier does not search thereby default.Option F is wrong because d is used w hich is originally usedfor telling the compiler to put the class files in a particulardirectory.Option G is correct becauseJar file is placed in / foo/ myLib.jar this has access toPaper.javaClasspath environment variable is also / foo/ myLib.jar and thefile to be compiled is Book.java.
Question 217
OptionAIt is wrong because
-
8/9/2019 224 Question Explain at Ions
45/46
Abhijit.A.Nayak KCT,Coimbatore
45
If w e run mainclass from apps/It cant access the mainclass
Option B is correct becausecom.company.application.MainClass can be accessed from
apps
Option C is correct because java -classpath / appscom.company.application.MainClass if runfrom any directory,we are directly accessing the mainclass.
Option D is wrong because it can search for directories insideapplication as well if that has a MainClass then there w ill bename collision.
Option E is wrong because we are searching from/ apps/ com/ company/ application and t he current directorywhich is / apps.
Option F is wrong becausecom.company.application.MainClass doesn t exist fromapplication directory . check the figure above.
Question 218
The class file chess must be either in the subdirectories of thetest orJar file inside test:/ home/ bob/ downloads/ *.jar games.Chess
When the classpath environment variable in the command hasbeen invoked nothing shows up .so it should be in the test foldersomew here.so test folder is in either option A or option C .
After that even I dont know the logic sorry.Question 219
Since str is receiving the value null and we are applying thelength() method on the null object it throwNullPointerException..
Question 220
In line 13 usage of if condition is w rong (it is correct inc/ c++). In java if condition takes only boolean expression it
may be boolean value or an expression which results in
-
8/9/2019 224 Question Explain at Ions
46/46
Abhijit.A.Nayak KCT,Coimbatore
Boolean. So the compilation fails.Refe r page no 320 321 and 3 2 2 f o r m o r e in f o r m a t i o n
Question 221
I2 is a type Integer(w rapper class). but startingI is anprimitive integer.so the == test failsTheir values are equal because equals classes take only objectinside. So it is true.
Question 222
It refers to a cup but it is an object of poison cupCup cup = new P oisonCup(); see this.
Question 223
Simple example for conditional operator. Sinceelements.length >0, the Condition becomes true and theelements[0] is assigned to first.
Question 224
if (value || (setting && title == Hello)) is wrong . value is
an integer ,title is a string .
ALL THE BEST !