do it for scjp
TRANSCRIPT
-
8/6/2019 do it for scjp
1/83
http://www.javagenious.com/forum/index.php?PHPSESSID=67ddee677841675f48643995dfeb79fc&topi
c=2.0
SCJP 1.6(CX-310-065) Exam Pattern :Exam type: Exam type: Multiple choice and drag anddropNumber of questions: 72Pass score: 65% (47 of 72 questions)Time limit: 210 minutes
Section 1: Declarations, Initialization and ScopingSection 2: Flow ControlSection 3: API ContentsSection 4: ConcurrencySection 5: OO ConceptsSection 6: Collections / Generics
Section 7: Fundamentals
Section 1: Declarations, Initialization and Scoping---------------------------------------------------------------------------------------------------------------------------------------------------------------------
y Develop code that declares classes(including abstractand all types of nested classes), interfaces, enums, andincludes the appropriate use of package and importstatements (including static imports).
y Develop code that declares an interface and thatimplements or extends one or more interfaces.
Develop code that declares an abstract class. Developcode that extends an abstract class.y Develop code that declares, initializes, and uses
primitives, arrays, enums, and objects as static,instance, and local variables. Also, use legal identifiersfor variable names.
y Given a code example, determine if a method iscorrectly overriding or overloading another method,and identify legal return values (including covariantreturns), for the method.
Given a set of classes and superclasses, develop constructorsfor one or more of the classes. Given a class declaration,
determine if a default constructor will be created, and if so,determine the behavior of that constructor. Given a nested ornon-nested class listing, write code to instantiate the class.
Section 2: Flow Control
y Develop code that implements an if or switch
Vinsys IT Services1st main
BTM layout 100ft Ringroad,
Near Friends resturant,
Bangalore 5600068
Karnataka
Call Us:080-41550745.
Mobile : +91 9986074882.
Email us at:
Website :www.vinsys.in
SureSuccess3rd Floor, Siteno.
8/2 (OldNo9)
Brook Field Main Road,
Near HDFC Bank,HyperCity
Mall
Bangalore 560037
Karnataka
Call Us:080 4227 4295.
Mobile : +91 8105820111.
Email us at:[email protected].
Website
:www.getsuresuccess.com
CMS Institute JayanagarCMS
Info Systems Pvt Ltd.
# 610 Vandna Arcade , 3rd
Flore
10th A main Road Jayanagar
4th Block
Bangalore 560011
(Near to Masjid)
Ph: 9986690134
Mail:
-
8/6/2019 do it for scjp
2/83
statement; and identify legal argument types for thesestatements.
y Develop code that implements all forms of loops anditerators, including the use of for, the enhanced forloop (for-each), do, while, labels, break, and continue;and explain the values taken by loop counter variables
during and after loop execution.y Develop code that makes use of assertions, and
distinguish appropriate from inappropriate uses ofassertions.
y Develop code that makes use of exceptions andexception handling clauses (try, catch, finally), anddeclares methods and overriding methods that throwexceptions.
y Recognize the effect of an exception arising at aspecified point in a code fragment. Note that theexception may be a runtime exception, a checkedexception, or an error.
y Recognize situations that will result in any of thefollowing being thrown:ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException,NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError,StackOverflowError or NoClassDefFoundError.Understand which of these are thrown by the virtualmachine and recognize situations in which othersshould be thrown programatically.
Section 3: API Contents
y Develop code that uses the primitive wrapper classes(such as Boolean, Character, Double, Integer, etc.),and/or autoboxing & unboxing. Discuss thedifferences between the String, StringBuilder, andStringBuffer classes.
y Given a scenario involving navigating file systems,reading from files, writing to files, or interacting withthe user, develop the correct solution using thefollowing classes (sometimes in combination), fromjava.io: BufferedReader, BufferedWriter, File,FileReader, FileWriter, PrintWriter, and Console.
y Use standard J2SE APIs in the java.text package tocorrectly format or parse dates, numbers, andcurrency values for a specific locale; and, given ascenario, determine the appropriate methods to use ifyou want to use the default locale or a specific locale.Describe the purpose and use of the java.util.Localeclass.
y Write code that uses standard J2SE APIs in thejava.util and java.util.regex packages to format orparse strings or streams. For strings, write code that
1) Asna Institute ofHardware Technology
Pvt. Ltd.#346/36, 1st
Florr, H.M.T Main
Road,Opps.Subbaiah
Hospital, Mathikere,
Bangalore-560054
Phone: 080-23378342
site code: II127
2)NAISSANCE INFOTECH
307 ,GROUND FLOOR,
18TH CROSS
6TH MAIN,
MALLESWARAM
BANGALORE, Karnataka560055
Phone: 080-2344 9427/28
Site Code: II66
3) NIIT LTD Vijayanagar
Address : No. 2934/E &
2935/E,
III Floor,Magadi Rd,
Vijayanagar II Stage,
Bangalore - 560 040
Landline : 080-30582764Mobile : +91 99641 44096
4) MICRO ACADEMY (I)
PVT. LTD. #72, Keonics
Electronics City
Hosur Main Road
BANGALORE, Karnataka
560100
Phone: 080-51381749
Site Code: IID68
5) IIHT LIMITED-INFANTRY
ROAD-BANGALORE63,
OPP. SALEEH AHMED
INFANTRY ROAD
BANGALORE, Karnataka
560001
Phone: 080-25598351
-
8/6/2019 do it for scjp
3/83
uses the Pattern and Matcher classes and theString.split method. Recognize and use regularexpression patterns for matching (limited to: . (dot), *(star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and? will be limited to greedy quantifiers, and theparenthesis operator will only be used as a grouping
mechanism, not for capturing content duringmatching. For streams, write code using the Formatterand Scanner classes and thePrintWriter.format/printf methods. Recognize anduse formatting parameters (limited to: %b, %c, %d, %f,%s) in format strings.
Section 4: Concurrency
y Write code to define, instantiate, and start newthreads using both java.lang.Thread andjava.lang.Runnable.
y Recognize the states in which a thread can exist, andidentify ways in which a thread can transition fromone state to another.
y Given a scenario, write code that makes appropriateuse of object locking to protect static or instancevariables from concurrent access problems.
Section 5: OO Concepts
y Develop code that implements tight encapsulation,loose coupling, and high cohesion in classes, anddescribe the benefits.
y Given a scenario, develop code that demonstrates theuse of polymorphism. Further, determine whencasting will be necessary and recognize compiler vs.runtime errors related to object reference casting.
y Explain the effect of modifiers on inheritance withrespect to constructors, instance or static variables,and instance or static methods.
y Given a scenario, develop code that declares and/orinvokes overridden or overloaded methods and code
that declares and/or invokes superclass, oroverloaded constructors.y Develop code that implements "is-a" and/or "has-a"
relationships.
Section 6: Collections / Generics
Site Code: IIF23
6) R.C.S. EDUCATION PVT
LTD 127, 4TH FLOOR
ANCHORAGE COURTOPP BRIGADE TOWERS
BRIGADE ROAD
BANGALORE, Karnataka
560025
Phone: 080-25361911
Site Code: IIF16
7) Q-SOFT Systems &
Solutions (P) Ltd. 252, First
Floor
Kanakapura RoadJaya Nagar 7th Block
Bangalore, Karnataka 560
082
Phone:
26340507/26639207
Site Code: IIF51
8) NCT TRAINING PVT LTD
NO 2 2ND FLOOR
MUNISWAMAPPA RDNEXT TO POLICE STATION
J. C. NAGAR
BANGALORE, Karnataka
560006
Phone: 080-41285393
Site Code: IIF79
9) NEWHORIZON INDIA
LIMITED-DICKENSEN
ROAD-BANGALOREN-101,
NORTH BLOCK, MANIPAL
CENTER
47 DICKENSEN ROAD
BANGALORE, Karnataka
560041
Phone: 25595380
Site Code: IIG19
-
8/6/2019 do it for scjp
4/83
y Given a design scenario, determine which collectionclasses and/or interfaces should be used to properlyimplement that design, including the use of theComparable interface.
y Distinguish between correct and incorrect overrides ofcorresponding hashCode and equals methods, andexplain the difference between == and the equalsmethod.
y Write code that uses the generic versions of theCollections API, in particular, the Set, List, and Mapinterfaces and implementation classes. Recognize thelimitations of the non-generic Collections API and howto refactor code to use the generic versions. Writecode that uses the NavigableSet and NavigableMapinterfaces.
y Develop code that makes proper use of typeparameters in class/interface declarations, instancevariables, method arguments, and return types; and
write generic methods or methods that make use ofwildcard types and understand the similarities anddifferences between these two approaches.
y Use capabilities in the java.util package to write codeto manipulate a list by sorting, performing a binarysearch, or converting the list to an array. Usecapabilities in the java.util package to write code tomanipulate an array by sorting, performing a binarysearch, or converting the array to a list. Use thejava.util.Comparator and java.lang.Comparableinterfaces to affect the sorting of lists and arrays.Furthermore, recognize the effect of the "naturalordering" of primitive wrapper classes andjava.lang.String on sorting.
Section 7: Fundamentals
y Given a code example and a scenario, write code thatuses the appropriate access modifiers, packagedeclarations, and import statements to interact with(through access or inheritance) the code in theexample.
y Given an example of a class and a command-line,determine the expected runtime behavior.
y Determine the effect upon object references andprimitive values when they are passed into methodsthat perform assignments or other modifyingoperations on the parameters.
y Given a code example, recognize the point at which anobject becomes eligible for garbage collection,determine what is and is not guaranteed by thegarbage collection system, and recognize thebehaviors of the Object.finalize() method.
10) NEW HORIZON INDIA
LIMITED-DICKENSEN
ROAD-BANGALOREUNIT
#401, MONEY POINT
4TH FLOOR, #59KH ROAD (DOUBLE ROAD)
EMERALD SYSTEMS
BANGALORE, Karnataka
560027
Phone: 080-22483919
Site Code: IIG2
11) iDOMAINS
TECHNOLOGIES No.65,
First Floor,KHB Colony,
2nd A Cross,5th Block,
Koramangala,BehindWipro K1
Building,Near JyotiNivas
Coleg
BANGALORE, Karnataka
560095
Phone:
4121613041102030
Site Code: IIG24
12) INFOSYS
TECHNOLOGIES LTD( Onlyfor Infosys Employees)
ELECTRONICS CITY
HOSUR ROAD
BANGALORE, Karnataka
Phone: 080-28520261
Site Code: IIG4
13) GALAXY
INFORMATION
TECHNOLOGIES
#3346/A,1-FLOOR,13TH
CROSS
BANASHANKARI
2ND STAGE
BANGALORE, Karnataka
560070
Phone: 80-55333187
Site Code: IIG60
-
8/6/2019 do it for scjp
5/83
y Given the fully-qualified name of a class that isdeployed inside and/or outside a JARfile, constructthe appropriate directory structure for that class.Given a code example and a classpath, determinewhether the classpath will allow the code to compilesuccessfully.
y Write code that correctly applies the appropriateoperators including assignment operators (limited to:=, +=, -=), arithmetic operators (limited to: +, -, *, /, %,++, --), relational operators (limited to: =,==, !=), the instanceof operator, logical operators(limited to: &, |, ^, !, &&, ||), and the conditionaloperator ( ? : ), to produce a desired result. Write codethat determines the equality of two objects or twoprimitives.
14) DAKSHIN
TECHNOLOGIES GVS
COMPLEX ,NO 296 2ND
FLOOR
22ND CROSS,10TH
MAIN,3
RD BLOCK(OPP.TO COSMOPOLITAN
CLUB)
JAYANAGAR
BANGALORE, Karnataka
560011
Phone: 080-30934868
Site Code: IIG80
15) IIHT LTD -
JAYANAGAR-BANGALORE
-(FRANCHISEE)
SOLUTIONS INTEGRATED-FRANCHISE
#74,1-FLOOR,KESHAVA
KRUPA.10-M
30TH CROSS,4TH BLOCK
JAYANAGAR
BANGALORE, Karnataka
560011
Phone: 22457577
Site Code: IIG95
16) IIHT-BANGALORE-(FRANCHISE) IT HARBOUR
SOLUTIN LTD
# 101, ESTEEM PLAZA
ABOVE COFFEE DAY
SADASHIVNAGAR,
BANGALORE, Karnataka
560080
Phone: 41137700/01/02
Site Code: IIG98
17) LEARNING LABS PVT
LIMITED LEARNING LABS
PVT LIMITED
# 1, HIRANYA COMPLEX,
AIRPORT ROAD, DOMLUR
(ABOVE HAIKU HONDA
SHOWROOM)
BANGALORE, Karnataka
-
8/6/2019 do it for scjp
6/83
What is new in SCJP 1.6?
There is few minor changes from the previous version 5.0.
Objectives are very similar to SCJP 5.0 exam except that fewminor updates. In the following section bolded topics areupdated in SCJP 6.0.
y Section : 3-1.6: Given a scenario involving navigating filesystems, reading from files, writing to files, or interacting
with the user, develop the correct solution using the
following classes (sometimes in combination), from java.io:
BufferedReader, BufferedWriter, File, FileReader, FileWriter,
PrintWriter, and Console ( mock exams for console ).
y Section : 5-1.5: Given a scenario, develop code that declaresand/or invokes overridden or overloaded methods and code
that declares and/or invokes superclass or overloaded
constructors.
y Section : 6-1.6: Write code that uses the generic versions ofthe Collections API, in particular, the Set, List, and Map
interfaces and implementation classes. Recognize the
limitations of the non-generic Collections API and how to
refactor code to use the generic versions. Write code that
uses the NavigableSet ( mock exams ) and NavigableMap (
mock exams ) interfaces.
y Section : 7-1.5: Given a code example, recognize the point atwhich an object becomes eligible for garbage collection, and
determine what is and is not guaranteed by the garbagecollection system. Recognize the behaviors of System.gc and
finalization ( mock exams for garbage collection in scjp 1.6 ).
1.6: Given a code example, recognize the point at
which an object becomes eligible for garbage
collection, determine what is and is not guaranteed by
the garbage collection system, and recognize thebehaviorsofthe Object.finalize() method.
560071
Phone:
41262390/41265144
Site Code: IIH7
18) NIIT LTD.JAYANAGAR-BANGALORENIIT LTD
75, 8TH E-MAIN, 4TH-
BLOCK
JAYNAGAR
BANGALORE, Karnataka
560011
Phone: 51211090
Site Code: IIN32
19) NIIT LTD -
KORAMANGALA NIIT LTD -
KORAMANGALA143-B,1ST FLOOR, 60 FEET
ROAD
5TH BLOCK, NEAR ANAND
SWEETS
KORAMANGALA
BANGALORE, Karnataka
560095
Phone: 080-41303291
Site Code: IIN40
20) SQL STARINTERNATIONL LTD-
BANGALORE40/4, 3rd
FLOOR,
LAVELLE ROAD
BANGALORE, Karnataka
560001
Phone: 2227781
Site Code: IIU2
21) CARTEL NETWORK
SOLUTIONS (P) LTD.
986,41 ST CROSS3RD
BLOCK
RAJAJINAGAR
Opp ESI Hospital
BANGALORE, Karnataka
560010
Phone: 9845023146
-
8/6/2019 do it for scjp
7/83
1. Kathy Sierra & Bert Bates is the best book for this exam.
2. Read the book 2 or 3 times & Clearly understand the topic
and do all the questions given in this book at end of each
chapter.
3. Clearly understand the rules for overloading andoverriding.
4. Get familiar with the API for Date, Calender, Locale,
DateFormat, String, StringBUffer & StringBuilder.
5. Write Simple programs to make it clear for Regular
expressions & Static imports.
6. For I/o, Serialization follow the steps. Like creation &
working with directories, Storing and reading data to and
from file, etc.
7. Clearly Understand how the boxing & unboxing is
working.
8. Familier the API for Array & Collections classes.9. Make it clear in var args and Conversions (Wrapper to
primitive & vice versa)
10. In Collections Clearly understand how we can override
hashCode and Equals methods. Familar the differences
between all the Collection interfaces and Classes.
11. Threading, good book is ks&B one only. Read 2 or 3 times
and do all questions given.
If You want to pass, that book is sufficient. For Generics &
Collections, Enums & Var-args I followed the mock questions
fromjava-beat. They are very good. Especillay for all newtopics which are introduced for 5.0 they covered vey well.
Mocks exams done by me:
y 1. Kathy Sierra & Bert Bates book questions + 2 mock exams(They are tough compared to real exam)
y 2. Mocks exam question fromjava-beat.y 3. http://www.danchisholm.net/ (for all old topics).y 4. http://faq.javaranch.com/view?ScjpMockTests (You can
get some question from that).
Site Code: IIH23
22) ROOMAN
TECHNOLOGIES 130 1ST
BLOCK
RAJKUMAR ROADRAJAJINAGAR
BANGALORE, Karnataka
560010
Phone: 23127771
Site Code: IIH37
23) NIIT LTD-VIJAYA
NAGAR-BANGALORE
2934/E-II FLOOR
MAGADI CHORD ROAD
ABOVE FOOD WORLD
VIJAYANAGAR II STAGEBANGALORE, Karnataka
560040
Phone:
41270768/41270769
Site Code: IIN34 24)
APTECH COMPUTER
EDUCATION6TH FLOOR C
WING
MITTAL TOWERS
MG ROAD
BANGALORE, Karnataka560001
Phone: 80-25585542
Site Code: IIO19
1.6 Dump
February 2, 2011 By admin44 Comments
-
8/6/2019 do it for scjp
8/83
FormoreSCJP 1.6 dumpspleasecontact :[email protected]
Question 1
What is the output for the below code ?
1. public class A {
2. int add(int i, int j){
3. return i+j;
4. }
5. }
6. public class B extends A{
7. public static void main(String argv[]){
8. short s = 9;
9. System.out.println(add(s,6));
10. }
11. }
Options are
A. Compilefail due toerroron lineno 2
B. Compilefail due toerroron lineno 9
C. Compilefail due toerroron lineno 8
D. 15
Answer:
B is thecorrect answer.
Cannot make a staticreference to thenon-static method add(int, int)from the type A. Theshort sis autoboxedcorrectly, but the add() methodcannot be invoked from a static method because
-
8/6/2019 do it for scjp
9/83
add() methodisnot static.
Question 2
What is the output for the below code ?
public class A {
int k;
boolean istrue;
static int p;
public void printValue() {
System.out.print(k);
System.out.print(istrue);
System.out.print(p);
}
}
public class Test{
public static void main(String argv[]){
A a = new A();
a.printValue();
}
}
Options are
A.0 false 0
B.0 true 0
C.0 0 0
-
8/6/2019 do it for scjp
10/83
D.Compileerrorstatic variable must beinitialized beforeuse.
Answer:
A is thecorrect answer.
Global andstatic variableneednot beinitialized beforeuse. Default valueofglobal andstaticintvariableiszero. Default valueofboolean variableisfalse. Remember local variable must beinitialized beforeuse.
Question 3
What is the output for the below code ?
public class Test{
int _$;
int $7;
int do;
public static void main(String argv[]){
Test test = new Test();
test.$7=7;
test.do=9;
System.out.println(test.$7);
System.out.println(test.do);
System.out.println(test._$);
}
}
Options are
A.7 9 0
B.7 0 0
-
8/6/2019 do it for scjp
11/83
C.Compileerror $7 isnot valididentifier.
D.Compileerrordoisnot valididentifier.
Answer:
D is thecorrect answer.
$7 is valididentifier. Identifiers must start with a letter, a currency character($), orunderscore(_). Identifierscannot start with a number. Youcant use a Java keyword as anidentifier. dois aJava keyword.
Question 4
What is the output for the below code ?
package com;
class Animal {
public void printName(){
System.out.println(Animal);
}
}
package exam;
import com.Animal;
public class Cat extends Animal {
public void printName(){
System.out.println(Cat);
}
}
package exam;
import com.Animal;
-
8/6/2019 do it for scjp
12/83
public class Test {
public static void main(String[] args){
Animal a = new Cat();
a.printName();
}
}
Options are
A.Animal
B.Cat
C.Animal Cat
D.Compile Error
Answer:
D is thecorrect answer.
Cat classwont compile becauseitssuperclass, Animal, hasdefault access andisin a different
package. Only publicsuperclasscan be accessiblefordifferent package.
Question 5
What is the output for the below code ?
public class A {
int i = 10;
public void printValue() {
System.out.println(Value-A);
}
}
-
8/6/2019 do it for scjp
13/83
public class B extends A{
int i = 12;
public void printValue() {
System.out.print(Value-B);
}
}
public class Test{
public static void main(String argv[]){
A a = new B();
a.printValue();
System.out.println(a.i);
}
}
Options are
A.Value-B 11
B.Value-B 10
C.Value-A 10
D.Value-A 11
Answer:
B is thecorrect answer.
Ifyoucreateobject ofsubclasswith referenceofsuperclass like( A a = new B();) thensubclassmethod andsuperclass variablewill beexecuted.
Question 6
-
8/6/2019 do it for scjp
14/83
What is the output for the below code ?
public enum Test {
BREAKFAST(7, 30), LUNCH(12, 15), DINNER(19, 45);
private int hh;
private int mm;
Test(int hh, int mm) {
assert (hh >= 0 && hh = 0 && mm
-
8/6/2019 do it for scjp
15/83
public class A {
static{System.out.println(static);}
{ System.out.println(block);}
public A(){
System.out.println(A);
}
public static void main(String[] args){
A a = new A();
}
Options are
A.A blockstatic
B.static block A
C.static A
D.A
Answer:
B is thecorrect answer.
First executestatic block, thenstatement block thenconstructor.
}
Options are
A.7:30
B.Compile Error anenum cannot beinstantiatedusing thenewoperator.
C.12:30
D.19:45
-
8/6/2019 do it for scjp
16/83
Answer:
B is thecorrect answer.
As anenum cannot beinstantiatedusing thenewoperator, theconstructorscannot becalled
explicitly. You have todo like Test t = BREAKFAST;
Question 8
What is the output for the below code ?
1. public class Test {
2. public static void main(String[] args){
3. int i = 010;
4. int j = 07;
5. System.out.println(i);
6. System.out.println(j);
7. }
8. }
Options are
A.8 7
B.10 7
C.Compilationfailswith anerrorat line 3
D.Compilationfailswith anerrorat line 5
Answer:
A is thecorrect answer.
By placing a zeroinfront ofthenumberis anintegerinoctal form. 010 isinoctal form .soitsvalueis 8.
Question 9
-
8/6/2019 do it for scjp
17/83
What is the output for the below code ?
1. public class Test {
2. public static void main(String[] args){
3. byte b = 6;
4. b+=8;
5. System.out.println(b);
6. b = b+7;
7. System.out.println(b);
8. }
9. }
Options are
A.14 21
B.14 13
C.Compilationfailswith anerrorat line 6
D.Compilationfailswith anerrorat line 4
Answer:
C is thecorrect answer.
int orsmallerexpressions alwaysresultingin anint. Socompilercomplain about Type
mismatch: cannot convert from int to byteforb = b+7; But b += 7; // No problem
because +=, -=, *=, and /= will all put in animplicit cast. b += 7 issame as b = (byte)b+7
socompilernot complain.
Question 10
What is the output for the below code ?
-
8/6/2019 do it for scjp
18/83
public class Test {
public static void main(String[] args){
String value = abc;
changeValue(value);
System.out.println(value);
}
public static void changeValue(String a){
a = xyz;
}
}
Options are
A.abc
B.xyz
C.Compilationfails
D.Compilationclean but nooutput
Answer:
A is thecorrect answer.
Java passreference as value. passing theobject reference, andnot the actual object itself.
Simply reassigning to the parameterused to pass the valueinto the methodwill do
nothing, because the parameterisessentially a local variable.
Question 11
What is the output for the below code ?
public class Test {
-
8/6/2019 do it for scjp
19/83
public static void printValue(int i, int j, int k){
System.out.println(int);
}
public static void printValue(byteb){
System.out.println(long);
}
public static void main(String args) {
byte b = 9;
printValue(b,b,b);
}
}
Options are
A.long
B.int
C.Compilationfails
D.Compilationclean but throws RuntimeException
Answer:
B is thecorrect answer.
Primitivewideninguses thesmallest method argument possible. (ForExampleifyou passshortvalue to a method but methodwith short argument isnot available thencompilerchoose method
with int argument). But in thiscasecompilerwill prefertheolderstyle beforeit chooses thenewerstyle, to keep existingcode morerobust. var-args methodis looserthanwiden.
Question 12
You have a java file name Test.java inside src folder of javaproject
-
8/6/2019 do it for scjp
20/83
directory. You have also classes folder inside javaproject directory.
you have issued below command from command prompt.
cd javaproject
Which of the below command puts Test.class file inside classes folder ?
Options are
A.javac-dclassessrc/Test.java
B.javac Test.java
C.javacsrc/Test.java
D.javacclassessrc/Test.java
Answer:
A is thecorrect answer.
The-doption lets you tell thecompilerinwhich directory to put the .classfileit
generates(dfordestination)
Question 13
You have two class files name Test.class and Test1.class inside javaproject directory.
Test.java source code is :
public class Test{
public static void main (String[] args){
System.out.println(Hello Test);
}
}
Test1.java source code is :
public class Test1{
-
8/6/2019 do it for scjp
21/83
public static void main (String[] args){
System.out.println(Hello Test1);
}
}
you have issued below commands from command prompt.
cd javaproject
java Test Test1
What is the output ?
Options are
A.Hello Test
B.Hello Test Hello Test1
C.Hello Test1
D.Runfails classnot found
Answer:
A is thecorrect answer.
You must specify exactly oneclassfile toexecute. Ifmore thanone thenfirst onewill beexecuted.
Question 14
You have a java file name Test.java .
Test.java needs access to a class contained in app.jar in exam
directory.
Which of the follwing command set classpath to compile clean?
Options are
-
8/6/2019 do it for scjp
22/83
A.javac-classpath exam/app.jarTest.java
B.javac-classpath app.jarTest.java
C.javac-classpath exam Test.java
D.Noneofthe above
Answer:
A is thecorrect answer.
javac-classpath exam/app.jarTest.java is thecorrect command toset exam/app.jarinclasspath.
Question 15
What will be the result of compiling the following code:
public class SuperClass {
public int doIt(String str, Integer data)throws Exception{
String signature = (String, Integer[]);
System.out.println(str + + signature);
return 1;
}
}
public class SubClass extends SuperClass{
public int doIt(String str, Integer data)
{
String signature = (String, Integer[]);
System.out.println(Overridden: + str + +
signature);
return 0;
-
8/6/2019 do it for scjp
23/83
}
public static void main(String args)
{
SuperClass sb = new SubClass();
sb.doIt(hello, 3);
}
}
Options are
A.Overridden: hello(String, Integer[])
B.hello(String, Integer[])
C.Complilationfails
D.Noneofthe above
Answer:
C is thecorrect answer.
Unhandledexception type Exception.
Question 16
What happens when the following code is compiled and run.
Select the one correct answer.
for(int i = 2; i < 4; i++)
for(int j = 2; j < 4; j++)
if(i < j)
assert i!=j : i;
Options are
-
8/6/2019 do it for scjp
24/83
A.Theclasscompiles andruns, but doesnot print anything.
B.Thenumber2 gets printedwith AssertionError
C.compileerror
D.Thenumber3 gets printedwith AssertionError
Answer:
A is thecorrect answer.
Whenifconditionreturns true, the assert statement alsoreturns true. Hence AssertionErrordoesnot get generated.
Question 17
What happens when the following code is compiled and run.
Select the one correct answer.
for(int i = 2; i < 4; i++)
for(int j = 2; j < 4; j++)
assert i!=j : i;
Options are
A.Theclasscompiles andruns, but doesnot print anything.
B.Thenumber2 gets printedwith AssertionError
C.compileerror
D.Thenumber3 gets printedwith AssertionError
Answer:
B is thecorrect answer.
Wheni and j are both 2, assert conditionisfalse, and AssertionErrorgetsgenerated. .
Question 18
-
8/6/2019 do it for scjp
25/83
try{
File f = new File(a.txt);
}catch(Exception e){
}catch(IOException io){
}
Is this code create new file name a.txt ?
Options are
A.True
B.False
C.Compilation Error
D.None
Answer:
C is thecorrect answer.
IOExceptionisunreachable tocompilerbecause all exceptionisgoing tocatch by Exception
block.
Question 19
class A {
A(String s) {
}
A() {
}
}
1. class B extends A {
-
8/6/2019 do it for scjp
26/83
2. B() { }
3. B(String s) {
4. super(s);
5. }
6. void test() {
7. // insert code here
8. }
9. }
Which of the below code can be insert at line 7 to make clean
compilation ?
Options are
A.A a = new B();
B.A a = new B(5);
C.A a = new A(Strings);
D.All of the above
Answer:
A is thecorrect answer.
A a = new B();iscorrect because anonymousinnerclasses arenodifferent from any otherclasswhenit comes to polymorphism.
Question 20
What is the output for the below code ?
interface A {
public void printValue();
-
8/6/2019 do it for scjp
27/83
-
8/6/2019 do it for scjp
28/83
void printValue(){
System.out.println(A.A1);
}
}
}
1. public class Test{
2. public static void main (String[] args){
3. A a = new A();
4. // INSERT CODE
5. a1.printValue();
6. }
7. }
Which of the below code inserted at line 4, compile and produce the
output A.A1?
Options are
A.A.A1 a1 = new A.A1();
B.A.A1 a1 = a.new A1();
C.A a1 = new A.A1();
D.All of the above
Answer:
B is thecorrect answer.
correct innerclassinstantiationsyntaxis A a = new A(); A.A1 a1 = a.new A1();
Question 22
-
8/6/2019 do it for scjp
29/83
What is the output for the below code ?
public class A {
public void printValue(){
System.out.println(Value-A);
}
}
public class B extends A{
public void printNameB(){
System.out.println(Name-B);
}
}
public class C extends A{
public void printNameC(){
System.out.println(Name-C);
}
}
1. public class Test{
2. public static void main (String[] args) {
3. B b = new B();
4. C c = new C();
5. newPrint(b);
6. newPrint(c);
7. }
-
8/6/2019 do it for scjp
30/83
8. public static void newPrint(A a){
9. a.printValue();
10. }
11. }
Options are
A.Value-A Name-B
B.Value-A Value-A
C.Value-A Name-C
D.Name-B Name-C
Answer:
B is thecorrect answer.
Class B extended Class A therefore all methodsofClass A will be available toclass B exceptprivate methods. Class C extended Class A therefore all methodsofClass A will be available toclass C except private methods.
Question 23
What is the output for the below code ?
public class A {
public void printName(){
System.out.println(Value-A);
}
}
public class B extends A{
public void printName(){
System.out.println(Name-B);
-
8/6/2019 do it for scjp
31/83
}
}
public class C extends A{
public void printName(){
System.out.println(Name-C);
}
}
1. public class Test{
2. public static void main (String[] args) {
3. B b = new B();
4. C c = new C();
5. b = c;
6. newPrint(b);
7. }
8. public static void newPrint(A a){
9. a.printName();
10. }
11. }
Options are
A.Name-B
B.Name-C
C.Compilationfailsdue to anerroron lines 5
D.Compilationfailsdue to anerroron lines 9
-
8/6/2019 do it for scjp
32/83
Answer:
C is thecorrect answer.
Reference variablecan refer to any object of the same type as thedeclared reference ORcan
referto any subtypeof thedeclared type. Reference variable b is typeofclass B andreferencevariable c is a typeofclass C. So Compilationfails.
Question 24
What is the output for the below code ?
public class C {
}
public class D extends C{
}
public class A {
public C getOBJ(){
System.out.println(class A return C);
return new C();
}
}
public class B extends A{
public D getOBJ(){
System.out.println(class B return D);
return new D();
}
}
public class Test {
-
8/6/2019 do it for scjp
33/83
public static void main(String args) {
A a = new B();
a.getOBJ();
}
}
Options are
A.class A return C
B.class B return D
C.Compilationfails
D.Compilationsucceed but nooutput
Answer:
B is thecorrect answer.
From J2SE 5.0 onwards. return type in theoverriding method can be sameor subtypeof thedeclaredreturn typeoftheoverridden(superclass) method.
Question 25
What is the output for the below code ?
public class A {
private void printName(){
System.out.println(Value-A);
}
}
public class B extends A{
public void printName(){
-
8/6/2019 do it for scjp
34/83
System.out.println(Name-B);
}
}
public class Test{
public static void main (String[] args) {
B b = new B();
b.printName();
}
}
Options are
A.Value-A
B.Name-B
C.Value-A Name-B
D.Compilationfails private methodscant beoverride
Answer:
B is thecorrect answer.
Youcannot override private method , private methodisnot availabeinsubclass . In this
case printName() method a class A isnot overriding by printName() methodofclass B.
printName() methodofclass B different method. So youcancall printName() methodofclass B.
Question 26
What is the output for the below code ?
import java.io.FileNotFoundException;
public class A {
-
8/6/2019 do it for scjp
35/83
public void printName() throws FileNotFoundException {
System.out.println(Value-A);
}
}
public class B extends A{
public void printName() throws NullPointerException{
System.out.println(Name-B);
}
}
public class Test{
public static void main (String[] args) throws Exception{
A a = new B();
a.printName();
}
}
Options are
A.Value-A
B.Compilationfails-Exception NullPointerExceptionisnot compatiblewith throws
clausein A.printName()
C.Name-B
D.Compilationsucceed but nooutput
Answer:
C is thecorrect answer.
-
8/6/2019 do it for scjp
36/83
Theoverriding methodcan throw any unchecked(runtime)exception, regardlessofexceptionthrown by overridden method. NullPointerExceptionis RuntimeExceptionsocompilernotcomplain.
Question 27
What is the output for the below code ?
public class A {
public A(){
System.out.println(A);
}
public A(int i){
this();
System.out.println(i);
}
}
public class B extends A{
public B (){
System.out.println(B);
}
public B (int i){
this();
System.out.println(i+3);
}
}
public class Test{
-
8/6/2019 do it for scjp
37/83
public static void main (String[] args){
new B(5);
}
}
Options are
A.A B 8
B.A 5 B 8
C.A B 5
D.B 8 A 5
Answer:
A is thecorrect answer.
Constructorofclass B call theirsuperclassconstructorofclass A (public A()) , which executefirst, and that constructorscan beoverloaded. Thencome toconstructorofclass B (public B (inti)).
Question 28
What is the output for the below code ?
1. public interface InfA {
2. protected String getName();
3. }
public class Test implements InfA{
public String getName(){
return test-name;
}
public static void main (String[] args){
-
8/6/2019 do it for scjp
38/83
Test t = new Test();
System.out.println(t.getName());
}
}
Options are
A.test-name
B.Compilationfailsdue to anerroron lines 2
C.Compilationfailsdue to anerroron lines 1
D.Compilationsucceed but Runtime Exception
Answer:
B is thecorrect answer.
Illegal modifierfortheinterface method InfA.getName();only public and abstract are Permitted
Question 29
What is the output for the below code ?
public class D {
int i;
int j;
public D(int i,int j){
this.i=i;
this.j=j;
}
public void printName() {
System.out.println(Name-D);
-
8/6/2019 do it for scjp
39/83
}
}
1. public class Test{
2. public static void main (String[] args){
3. D d = new D();
4. d.printName();
5.
6. }
7. }
Options are
A.Name-D
B.Compilationfailsdue to anerroron lines 3
C.Compilationfailsdue to anerroron lines 4
D.Compilationsucceed but nooutput
Answer:
B is thecorrect answer.
Since thereis already a constructorin thisclass(public D(int i,int j)), thecompilerwont supplya default constructor. If youwant a no-argument constructor to overload thewith argumentsversion you already have, you have todefine it by yourself. TheconstructorD()isundefined inclass D. If youdefine explicit constructor then default constructorwill not be available. Youhave todefineexplicitly like public D(){ } then the abovecodewill work. Ifnoconstructorintoyourclass , a default constructorwill be automatically generated by thecompiler.
Question 30
public class A {
public void test1(){
-
8/6/2019 do it for scjp
40/83
System.out.println(test1);
}
}
public class B extends A{
public void test2(){
System.out.println(test2);
}
}
1. public class Test{
2. public static void main (String[] args){
3. A a = new A();
4. A b = new B();
5. B b1 = new B();
6. // insert code here
7. }
8. }
Which of the following , inserted at line 6, will compile and print
test2?
Options are
A.((B)b).test2();
B.(B)b.test2();
C.b.test2();
D.a.test2();
-
8/6/2019 do it for scjp
41/83
Answer:
A is thecorrect answer.
((B)b).test2(); is propercast. test2() method is inclass B soneed tocast b thenonly test2() is
accessible. (B)b.test2(); is not proper cast without the second set of parentheses,the compilerthinksit is anincompletestatement.
Question 31
What is the output for the below code ?
1. public class Test {
2. public static void main(String args) {
3. int x =5;
4. x *= 3 + 7;
5. System.out.println(x);
6. }
7. }
Options are
A.22
B.50
C.10
D.Compilationfailswith anerrorat line 4
Answer:
B is thecorrect answer.
x *= 3 + 7;issame asx = x * (3 +7) = 5 * (10) = 50 becauseexpressionon theright is alwaysplacedinside parentheses.
Question 32
-
8/6/2019 do it for scjp
42/83
What is the output for the below code ?
1. public class Test {
2. enum Month { JAN, FEB, MAR };
3. public static void main(String args) {
4. Month m1 = Month.JAN;
5. Month m2 = Month.JAN;
6. Month m3 = Month.FEB;
7. System.out.println(m1 == m2);
8. System.out.println(m1.equals(m2));
9. System.out.println(m1 == m3);
10. System.out.println(m1.equals(m3));
11. }
12. }
Options are
A.true true truefalse
B.true truefalsefalse
C.falsefalse true true
D.Compilationfailswith anerrorat line 10
Answer:
B is thecorrect answer.
m1 and m2 refer to thesameenum constant So m1 == m2 returns true BUT m1 and m3 refer todifferent enum constant So m1 == m3 returns false. m1.equals(m2) returns true becauseenumconstant value is same (JAN and JAN). m1.equals(m3) return false because enum constantsvalues aredifferent (JAN andFEB).
-
8/6/2019 do it for scjp
43/83
Question 33
What is the output for the below code ?
1. public class Test {
2. public static void main(String args) {
3. int [] index = new int[5];
4. System.out.println(index instanceof Object);
5. }
6. }
Options are
A.true
B.false
C.Compilationfailswith anerrorat line 3
D.Compilationfailswith anerrorat line 4
Answer:
A is thecorrect answer.
An array is always aninstanceofObject
Question 34
What is the output for the below code ?
public class Test {
public static void main(String args) {
int a =5 , b=6, c =7;
System.out.println(Value is + b +c);
System.out.println(a + b +c);
-
8/6/2019 do it for scjp
44/83
System.out.println(String +(b+c));
}
}
Options are
A.Valueis 67 18 String 13
B.Valueis 13 18 String 13
C.Valueis 13 18 String
D.Compilationfails
Answer:
A is thecorrect answer.
Ifthe left handoperandisnot a String then + operatortreat as plus BUT ifleft handoperandis aString then + perform Stringconcatenation.
Question 35
What is the output for the below code?
public class A {
public A() {
System.out.println(A);
}
}
public class B extends A implements Serializable {
public B() {
System.out.println(B);
}
-
8/6/2019 do it for scjp
45/83
}
public class Test {
public static void main(String args) throws Exception {
B b = new B();
ObjectOutputStream save = new ObjectOutputStream(new
FileOutputStream(datafile));
save.writeObject(b);
save.flush();
ObjectInputStream restore = new ObjectInputStream(new
FileInputStream(datafile));
B z = (B) restore.readObject();
}
}
Options are
A.A B A
B.A B A B
C.B B
D.B
Answer:
A is thecorrect answer.
On the timeofdeserialization , the Serializableobject not createnewobject. Soconstructorofclass B doesnot called. A isnot Serializableobject soconstructoriscalled.
Question 36
-
8/6/2019 do it for scjp
46/83
What is the output for the below code?
public class A {
public A() {
System.out.println(A);
}
}
public class Test {
public static void main(String args) throws Exception {
A a = new A();
ObjectOutputStream save = new ObjectOutputStream(new
FileOutputStream(datafile));
save.writeObject(a);
save.flush();
ObjectInputStream restore = new ObjectInputStream(new
FileInputStream(datafile));
A z = (A) restore.readObject();
}
}
Options are
A.A A
B.A
C.java.io.NotSerializableException
D.Noneofthe above
-
8/6/2019 do it for scjp
47/83
Answer:
C is thecorrect answer.
Class A doesnot implements Serializableinterface. So throws NotSerializableExceptionon
trying to Serialize a non Serializableobject.
Question 37
What will be the result of compiling and run the following code:
public class Test {
public static void main(String args) throws Exception {
Integer i = 34;
int l = 34;
if(i.equals(l)){
System.out.println(true);
}else{
System.out.println(false);
}
}
}
Options are
A.true
B.false
C.Compileerror
D.Noneofthe above
Answer:
-
8/6/2019 do it for scjp
48/83
A is thecorrect answer.
equals() methodfortheintegerwrapperswill only return trueifthe two primitive types and thetwo values areequal.
Question 38
What will be the result of compiling and run the following code:
public class Test {
public static void main(String args) throws Exception {
File file = new File(test.txt);
System.out.println(file.exists());
file.createNewFile();
System.out.println(file.exists());
}
}
Options are
A.true true
B.false true
C.false true
D.Noneofthe above
Answer:
B is thecorrect answer.
creating a newinstanceoftheclassFile, yourenot yet making an actual file, youre just creatinga filename. Sofile.exists()returnfalse. createNewFile() methodcreated an actual file.sofile.exists()return true.
Question 39
-
8/6/2019 do it for scjp
49/83
-
8/6/2019 do it for scjp
50/83
Answer:
C is thecorrect answer.
No java.io.NotSerializableException, Becauseclass A variableisstatic. static variables arenot
Serializable.
Question 40
What will happen when you attempt to compile and run the following code
?
1. public class Test extends Thread{
2. public static void main(String argv[]){
3. Test t = new Test();
4. t.run();
5. t.start();
6. }
7. public void run(){
8. System.out.println(run-test);
9. }
10. }
Options are
A.run-test run-test
B.run-test
C.Compilationfailsdue to anerroron line 4
D.Compilationfailsdue to anerroron line 7
Answer:
-
8/6/2019 do it for scjp
51/83
A is thecorrect answer.
t.run() Legal, but doesnot start a new thread , it is like a methodcall ofclass Test BUT t.start()create a thread andcall run() method.
Question 41
What is the output for the below code ?
class A implements Runnable{
public void run(){
System.out.println(run-a);
}
}
1. public class Test {
2. public static void main(String args) {
3. A a = new A();
4. Thread t = new Thread(a);
5. t.start();
6. t.start();
7. }
8. }
Options are
A.run-a
B.run-a run-a
C.Compilationfailswith anerrorat line 6
D.Compilationsucceed but Runtime Exception
-
8/6/2019 do it for scjp
52/83
Answer:
D is thecorrect answer.
Once a thread has beenstarted, it canneverbestarted again. 2nd time t.start() throws
java.lang.IllegalThreadStateException.
Question 42
What is the output for the below code ?
class A implements Runnable{
public void run(){
try{
for(int i=0;i
-
8/6/2019 do it for scjp
53/83
t.join();
t1.start();
}
}
Options are
A.A A A A B B B B
B.A B A B A B A B
C.Output orderisnot guaranteed
D.Compilationsucceed but Runtime Exception
Answer:
A is thecorrect answer.
t.join(); means Threat t must finish before Thread t1 start.
Question 43
What is the output for the below code ?
public class B {
public synchronized void printName(){
try{
System.out.println(printName);
Thread.sleep(5*1000);
}catch(InterruptedException e){
}
}
public synchronized void printValue(){
-
8/6/2019 do it for scjp
54/83
System.out.println(printValue);
}
}
public class Test extends Thread{
B b = new B();
public static void main(String argv[]) throws Exception{
Test t = new Test();
Thread t1 = new Thread(t,t1);
Thread t2 = new Thread(t,t2);
t1.start();
t2.start();
}
public void run(){
if(Thread.currentThread().getName().equals(t1)){
b.printName();
}else{
b.printValue();
}
}
}
Options are
A.print : printName , thenwait for5 seconds then print : printValue
B.print : printName then print : printValue
-
8/6/2019 do it for scjp
55/83
C.print : printName thenwait for5 minutes then print : printValue
D.Compilationsucceed but Runtime Exception
Answer:
A is thecorrect answer.
Thereisonly one lock perobject, ifone thread has pickedup the lock, nootherthreadcan pickup the lockuntil thefirst threadreleases the lock. printName() method acquire the lockfor5seconds, Sootherthreadscannot access theobject. Ifonesynchronized methodofaninstanceisexecuting thenothersynchronized methodofthesameinstanceshouldwait.
Question 44
What is the output for the below code ?
public class B {
public static synchronized void printName(){
try{
System.out.println(printName);
Thread.sleep(5*1000);
}catch(InterruptedException e){
}
}
public synchronized void printValue(){
System.out.println(printValue);
}
}
public class Test extends Thread{
B b = new B();
-
8/6/2019 do it for scjp
56/83
public static void main(String argv[]) throws Exception{
Test t = new Test();
Thread t1 = new Thread(t,t1);
Thread t2 = new Thread(t,t2);
t1.start();
t2.start();
}
public void run(){
if(Thread.currentThread().getName().equals(t1)){
b.printName();
}else{
b.printValue();
}
}
}
Options are
A.print : printName , thenwait for5 seconds then print : printValue
B.print : printName then print : printValue
C.print : printName thenwait for5 minutes then print : printValue
D.Compilationsucceed but Runtime Exception
Answer:
B is thecorrect answer.
Thereisonly one lock perobject, ifone thread has pickedup the lock, nootherthreadcan pickup the lockuntil thefirst threadreleases the lock. In thiscase printName()isstatic , So lockisin
-
8/6/2019 do it for scjp
57/83
class B not instance b, both method(onestatic andotherno-static)canrunsimultaneously. Astaticsynchronized method and a nonstaticsynchronized methodwill not blockeach other.
Question 45
What is the output for the below code ?
class A extends Thread{
int count = 0;
public void run(){
System.out.println(run);
synchronized (this) {
for(int i =0; i < 50 ; i++){
count = count + i;
}
notify();
}
}
}
public class Test{
public static void main(String argv[]) {
A a = new A();
a.start();
synchronized (a) {
System.out.println(waiting);
try{
-
8/6/2019 do it for scjp
58/83
a.wait();
}catch(InterruptedException e){
}
System.out.println(a.count);
}
}
}
Options are
A.waitingrun 1225
B.waitingrun 0
C.waitingrun andcount can be anything
D.Compilationfails
Answer:
A is thecorrect answer.
a.wait(); put threadonwait until not get notifed. A threadgetson thiswaiting list by executingthewait() methodofthe target object. It doesnt execute any furtherinstructionsuntil thenotify()methodofthe target object iscalled. A thread tocall wait()ornotify(), the thread has to be theownerofthe lockforthat object.
Question 46
Which of the following statements about this code are true?
class A extends Thread{
public void run(){
for(int i =0; i < 2; i++){
System.out.println(i);
-
8/6/2019 do it for scjp
59/83
}
}
}
public class Test{
public static void main(String argv[]){
Test t = new Test();
t.check(new A(){});
}
public void check(A a){
a.start();
}
}
Options are
A.0 0
B.Compilationerror, class A hasnostart method
C.0 1
D.Compilationsucceed but runtimeexception
Answer:
C is thecorrect answer.
class A extends Thread means the anonymousinstance that is passed tocheck() method has astart methodwhich thencalls therun method.
Question 47
HashMap can be synchronized by _______ ?
-
8/6/2019 do it for scjp
60/83
Options are
A.Map m = Collections.synchronizeMap(hashMap);
B.Map m = hashMap.synchronizeMap();
C.Map m = Collection.synchronizeMap(hashMap);
D.Noneofthe above
Answer:
A is thecorrect answer.
HashMap can besynchronized by Map m = Collections.synchronizeMap(hashMap);
Question 48
What is the output for the below code?
import java.util.LinkedList;
import java.util.Queue;
public class Test {
public static void main(String args) {
Queue q = new LinkedList();
q.add(newyork);
q.add(ca);
q.add(texas);
show(q);
}
public static void show(Queue q) {
q.add(new Integer(11));
while (!q.isEmpty ( ) )
-
8/6/2019 do it for scjp
61/83
System.out.print(q.poll() + );
}
}
Options are
A.Compileerror: Integercant add
B.newyorkca texas 11
C.newyorkca texas
D.Noneofthe above
Answer:
B is thecorrect answer.
qwasoriginally declared as Queue, But inshow() methodit is passed as anuntypedQueue. nothingin thecompilerorJVM preventsusfrom adding an Integerafterthat. Iftheshowmethodsignatureis publicstatic voidshow(Queueq) than youcant add Integer, OnlyString allowed. But publicstatic voidshow(Queueq)isuntyped Queueso youcan add Integer.Ypoll() Retrieves andremoves the headofthisqueue, orreturnsnull ifthisqueueisempty.
Question 49
What is the output for the bellow code?
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Test {
public static void main(String args) {
Set s = new TreeSet();
s.add(7);
s.add(9);
-
8/6/2019 do it for scjp
62/83
-
8/6/2019 do it for scjp
63/83
-
8/6/2019 do it for scjp
64/83
Options are
A.10
B.8
C.15
D.12
Answer:
A is thecorrect answer.
/** * Constructs anempty list with aninitial capacity of ten. */ public ArrayList()
{ this(10); }
Question 52
What is the output for the below code ?
package bean;
public class Abc {
public static int index_val = 10;
}
package com;
import static bean.Abc.index_val;
public class Test1 {
public static void main(String args) {
System.out.println(index_val);
}
}
Options are
-
8/6/2019 do it for scjp
65/83
A.10
B.compileerror, index_val not defined
C.Compileerrorat import static bean.Abc.index_val;
D.Noneofthe above
Answer:
A is thecorrect answer.
Thestaticimport construct allowsunqualified access tostatic memberswithout inheriting
from the typecontaining thestatic members. J2SE 5.0 onwardsit allowsstaticimport like
import static bean.Abc.index_val; andcan beusedirectly System.out.println(index_val);
Question 53
Which of the following statement is true about jar command?
Options are
A.The jarcommandcreates the META-INFdirectory implicitly.
B.The jarcommandcreates the MANIFEST.MFfileimplicitly.
C.The jarcommandwouldnot place any ofyourfilesin META-INFdirectory.
D.All of the above are true
Answer:
A is thecorrect answer.
All statements are true.
Question 54
You have a class file name Test.class inside javaproject directory.
Test.java source code is :
import java.util.Properties;
-
8/6/2019 do it for scjp
66/83
-
8/6/2019 do it for scjp
67/83
public void printValue(){
System.out.println(A);
}
}
public class B extends A {
public void printValue(){
System.out.println(B);
}
}
1. public class Test {
2. public static void main(String args) {
3. A b = new B();
4. newValue(b);
5. }
6. public static void newValue(A a){
7. if(a instanceof B){
8. ((B)a).printValue();
9. }
10. }
11. }
Options are
A.A
B.B
-
8/6/2019 do it for scjp
68/83
C.Compilationfailswith anerrorat line 4
D.Compilationfailswith anerrorat line 8
Answer:
B is thecorrect answer.
instanceofoperatorisusedforobject reference variables tocheckwhetheranobject isof
a particulartype. InnewValue(b); b isinstanceofB Soworks properly.\
Question 56
What is the output for the below code ?
1. public class Test {
2. static int i =5;
3. public static void main(String args) {
4. System.out.println(i++);
5. System.out.println(i);
6. System.out.println(++i);
7. System.out.println(++i+i++);
8.
9. }
10. }
Options are
A.5 6 7 16
B.6 6 6 16
C.6 6 7 16
D.5 6 6 16
-
8/6/2019 do it for scjp
69/83
Answer:
A is thecorrect answer.
i++ : print value thenincrement (postfix increment happens afterthe valueofthe
variableisused) ++i : increment the print (prefix increment happens before the valueof
the variableisused)
Question 57
What is the output for the below code ?
1. public class Test {
2. public static void main(String args) {
3. Integer i = 34;
4. String str = (i
-
8/6/2019 do it for scjp
70/83
Question 58
What is the output ?
public class Test {
public static void main(String args) {
Pattern p = Pattern.compile(a+b?c*);
Matcher m = p.matcher(ab);
boolean b = m.matches();
System.out.println(b);
}
}
Options are
A.true
B.false
C.Compileerror
D.Noneofthe above
Answer:
A is thecorrect answer.
X? X, onceornot at all X* X, zeroormore times X+ X, oneormore times
Question 59
What is the output for the below code ?
1. public class Test {
2. public static void main(String[] args){
3. byte i = 128;
-
8/6/2019 do it for scjp
71/83
-
8/6/2019 do it for scjp
72/83
11. }
Options are
A.17
B.0
C.Compilationfailswith anerrorat line 5
D.Compilationfailswith anerrorat line 8
Answer:
D is thecorrect answer.
i and j areinstance variable and attempting to access aninstance variablefrom a static method.So Compilationfails .
Question 61
Which collection class grows or shrinks its size and provides indexed
access to its elements, but methods are not synchronized?
Options are
A.java.util.ArrayList
B.java.util.List
C.java.util.HashSet
D.java.util.Vector
Answer:
A is thecorrect answer.
| ArrayList provides anindex toitselements and methods arenot synchronized.
Question 62
What is the output of bellow code ?
-
8/6/2019 do it for scjp
73/83
public class Bean{
private String str;
Bean(String str ){
this.str = str;
}
public String getStr() {
return str;
}
public boolean equals(Object o){
if (!(o instanceof Bean)) {
return false;
}
return ((Bean) o).getStr().equals(str);
}
public int hashCode() {
return 12345;
}
public String toString() {
return str;
}
}
import java.util.HashSet;
public class Test {
-
8/6/2019 do it for scjp
74/83
public static void main(String sss) {
HashSet myMap = new HashSet();
String s1 = new String(das);
String s2 = new String(das);
Bean s3 = new Bean(abcdef);
Bean s4 = new Bean(abcdef);
myMap.add(s1);
myMap.add(s2);
myMap.add(s3);
myMap.add(s4);
System.out.println(myMap);
}
}
Options are
A.das abcdef
B.das abcdefdas abcdef
C.dasdas abcdefabcdef
D.das
Answer:
A is thecorrect answer.
implemented equals and hashCode methods toget uniqueresult in Set.
Question 63
What will happen when you attempt to compile and run the following code
-
8/6/2019 do it for scjp
75/83
?
class A implements Runnable{
public void run(){
System.out.println(run-A);
}
}
1. public class Test {
2. public static void main(String argv[]){
3. A a = new A();
4. Thread t = new Thread(a);
5. System.out.println(t.isAlive());
6. t.start();
7. System.out.println(t.isAlive());
8. }
9. }
Options are
A.falserun-A true
B.falserun-A false
C.truerun-A true
D.Compilationfailsdue to anerroron line 7
Answer:
A is thecorrect answer.
Once thestart() methodiscalled, the threadisconsidered to be alive.
-
8/6/2019 do it for scjp
76/83
Question 64
What will happen when you attempt to compile and run the following code
?
1. public class Test extends Thread{
2. public static void main(String argv[]){
3. Test t = new Test();
4. t.run();
5. t.start();
6. }
7. public void run(){
8. System.out.println(run-test);
9. }
10. }
Options are
A.run-test run-test
B.run-test
C.Compilationfailsdue to anerroron line 4
D.Compilationfailsdue to anerroron line 7
Answer:
A is thecorrect answer.
t.run() Legal, but doesnot start a new thread , it is like a methodcall ofclass Test BUT
t.start()create a thread andcall run() method.
Question 65
-
8/6/2019 do it for scjp
77/83
Which of the following are methods of the Thread class?
1) yield()
2) sleep(long msec)
3) go()
4) stop()
Options are
A.1 , 2 and 4
B.1 and 3
C.3 only
D.Noneofthe above
Answer:
A is thecorrect answer.
Checkout the Java2 Docsforanexplanation
Question 66
What notifyAll() method do?
Options are
A.Wakesup all threads that arewaitingon thisobjects monitor
B.Wakesup one threads that arewaitingon thisobjects monitor
C.Wakesup all threads that arenot waitingon thisobjects monitor
D.Noneofthe above
Answer:
A is thecorrect answer.
notifyAll() : Wakesup all threads that arewaitingon thisobjects monitor.A threadwaits
-
8/6/2019 do it for scjp
78/83
on anobjects monitorby callingoneofthewait methods.
Question 67
What is the output for the below code?
import java.util.NavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class Test {
public static void main(String args) {
NavigableMap navMap = new
ConcurrentSkipListMap();
navMap.put(4, April);
navMap.put(5, May);
navMap.put(6, June);
navMap.put(1, January);
navMap.put(2, February);
navMap.put(3, March);
navMap.pollFirstEntry();
navMap.pollLastEntry();
navMap.pollFirstEntry();
System.out.println(navMap.size());
}
}
Options are
A.Compileerror: No methodname like pollFirstEntry()orpollLastEntry()
-
8/6/2019 do it for scjp
79/83
B.3
C.6
D.Noneofthe above
Answer:
B is thecorrect answer.
Y pollFirstEntry() Removes andreturns a key-value mapping associatedwith the least
key in this map, ornull ifthe map isempty.
Y pollLastEntry() Removes andreturns a key-value mapping associatedwith thegreatest key inthis map, ornull ifthe map isempty.
Question 68
What is the output for the bellow code?
import java.io.Console;
public class Test {
public static void main(String args) {
Console con = System.console();
boolean auth = false;
if (con != null)
{
int count = 0;
do
{
String uname = con.readLine(null);
char[] pwd = con.readPassword(Enter %ss
-
8/6/2019 do it for scjp
80/83
password: , uname);
con.writer().write(\n\n);
} while (!auth && ++count < 3);
}
}
}
Options are
A.NullPointerException
B.It works properly
C.Compile Error: NoreadPassword() methodin Consoleclass.
D.Noneofthe above
Answer:
A is thecorrect answer.
$ passing a null argument to any methodin Consoleclasswill cause a
NullPointerException to be thrown.
Question 69
What is the output for the below code?
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;
public class Test {
-
8/6/2019 do it for scjp
81/83
public static void main(String args) {
List lst = new ArrayList ();
lst.add(34);
lst.add(6);
lst.add(2);
lst.add(8);
lst.add(7);
lst.add(10);
NavigableSet nvset = new TreeSet(lst);
System.out.println(nvset.headSet(10,true));
}
}
Options are
A.Compileerror: No methodname like headSet()
B.2, 6, 7, 8, 10
C.2, 6, 7, 8
D.Noneofthe above
Answer:
B is thecorrect answer.
headSet(10) Returns theelementselements arestrictly less than 10.
q headSet(10,false) Returns theelementselements arestrictly less than 10.
- headSet(10,true) Returns theelementselements arestrictly less thanorequal to 10.
Question 70
-
8/6/2019 do it for scjp
82/83
What is the output?
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;
public class Test {
public static void main(String args) {
List lst = new ArrayList();
lst.add(34);
lst.add(6);
lst.add(2);
lst.add(8);
lst.add(7);
lst.add(10);
NavigableSet nvset = new TreeSet(lst);
System.out.println(nvset.lower(6)+ +nvset.higher(6)+
+ nvset.lower(2));
}
}
Options are
A.1 2 7 10 34 null
B.2 7 null
C.2 7 34
-
8/6/2019 do it for scjp
83/83
D.1 2 7 10 34
Answer:
B is thecorrect answer.
lower() Returns thegreatest element in thisset strictly less than thegivenelement, or
null ifthereisnosuch element.
higher() Returns the least element in thisset strictly greaterthan thegivenelement, or
null ifthereisnosuch element.