OCPJP 6 Free Mock Exam Practice Questions

download OCPJP 6 Free Mock Exam Practice Questions

of 40

Transcript of OCPJP 6 Free Mock Exam Practice Questions

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    1/40

    OCPJP 6 Free Mock Exam Practice Questions

    Questions no -1What is the output for the below code ?

    class A implements Runnable{public void run(){

    System.out.println(Thread.currentThread().getName());}

    }

    public class Test {public static void main(String... args) {

    A a = new A();Thread t = new Thread(a);Thread t1 = new Thread(a);

    t.setName("t");t1.setName("t1");t.setPriority(10);t1.setPriority(-3);t.start();t1.start();

    }}

    Options are

    A.t t1B.t1 t

    C.t t

    D.Compilation succeed but Runtime Exception

    Answer :

    D is the correct answer.

    Thread priorities are set using a positive integer, usually between 1 and 10.

    t1.setPriority(-3); throws java.lang.IllegalArgumentException.

    ads

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    2/40

    Questions no -2What is the output for the below code ?

    class A implements Runnable{public void run(){

    System.out.println(Thread.currentThread().getName());}

    }

    1. public class Test {2. public static void main(String... args) {3. A a = new A();4. Thread t = new Thread(a);5. t.setName("good");6. t.start();

    7. }8. }

    Options are

    A.goodB.null

    C.Compilation fails with an error at line 5D.Compilation succeed but Runtime Exception

    Answer :

    A is the correct answer.

    Thread.currentThread().getName() return name of the current thread.

    Questions no -3

    https://play.google.com/store/apps/details?id=com.bricksbay.exam.ocpjp6f
  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    3/40

    What is the output for the below code ?

    public class Test {

    public static void main(String[] args) {

    Boolean expr = true;if (expr) {System.out.println("true");

    } else {System.out.println("false");

    }

    }

    }

    optionsA)trueB)Compile Error - can't use Boolean object in if().C)falseD)Compile Properly but Runtime Exception.

    Correct answer is : A

    Explanations : In the if statement, condition can be Boolean objectin jdk1.5 and jdk1.6.In the previous version only boolean is allowed.

    Questions no -4What is the output for the below code ?

    public class Test {

    public static void main(String[] args) {List list = new ArrayList();list.add(0, 59);int total = list.get(0);System.out.println(total);

    }

    }

    options

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    4/40

    A)59B)Compile time error, because you have to do int total =((Integer)(list.get(0))).intValue();C)Compile time error, because can't add primitive type in List.D)Compile Properly but Runtime Exception.

    Correct answer is : A

    Explanations :Manual conversion between primitive types (such as anint) and wrapper classes

    (such as Integer) is necessary when adding a primitive data type to acollection in jdk1.4 but

    The new autoboxing/unboxing feature eliminates this manual conversionin jdk 1.5 and jdk 1.6.

    Questions no -3What is the output for the below code ?

    public class Test {

    public static void main(String[] args) {Integer i = null;int j = i;System.out.println(j);

    }

    }

    optionsA)0B)Compile with errorC)nullD)NullPointerException

    Correct answer is : D

    Explanations :An Integer expression can have a null value. If yourprogram tries to autounbox null,

    it will throw a NullPointerException.Questions no -4What is the output for the below code ?

    public class Outer {private int a = 7;

    class Inner {public void displayValue() {

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    5/40

    System.out.println("Value of a is " + a);}

    }}

    public class Test {

    public static void main(String... args) throws Exception {Outer mo = new Outer();Outer.Inner inner = mo.new Inner();inner.displayValue();

    }

    }

    optionsA)Value of a is 7B)Compile Error - not able to access private member.C)Runtime ExceptionD)Value of a is 8

    Correct answer is : A

    Explanations : An inner class instance can never stand alone withouta direct relationship to an instance of the outer class.

    you can access the inner class is through a live instance of the

    outer class.

    Inner class can access private member of the outer class.

    Questions no -5What is the output for the below code ?

    public class B {

    public String getCountryName(){return "USA";

    }

    public StringBuffer getCountryName(){StringBuffer sb = new StringBuffer();sb.append("UK");return sb;

    }

    public static void main(String[] args){B b = new B();

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    6/40

    System.out.println(b.getCountryName().toString());}

    }

    optionsA)Compile with errorB)USAC)UKD) Runtime Exception

    Correct answer is : A

    Explanations : You cannot have two methods in the same class withsignatures that only differ by return type.Questions no -6What 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 {

    public static void main(String... args) {A a = new B();a.getOBJ();

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    7/40

    }}

    options

    A)Compile with error - Not allowed to override the return type of amethod with a subtype of the original type.B)class A - return CC)class B - return DD) Runtime Exception

    Correct answer is : C

    Explanations : From J2SE 5.0 onwards. You are now allowed to overridethe return type of a method with a subtype of the original type.Questions no -7What is the output for the below code ?

    public class A {

    public String getName() throws ArrayIndexOutOfBoundsException{return "Name-A";

    }

    }

    public class C extends A{

    public String getName() throws Exception{return "Name-C";

    }

    }

    public class Test {public static void main(String... args) {

    A a = new C();a.getName();

    }

    }

    optionsA)Compile with errorB)Name-AC)Name-CD)Runtime Exception

    Correct answer is : A

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    8/40

    Explanations : Exception Exception is not compatible with throwsclause in A.getName().

    Overridden method should throw only same or sub class of theexception thrown by super class method.Questions no -8

    What is the output for the below code ?

    import java.util.regex.Matcher;import java.util.regex.Pattern;

    public class Test {

    public static void main(String... args) {

    Pattern p = Pattern.compile("a*b");Matcher m = p.matcher("b");boolean b = m.matches();System.out.println(b);

    }}

    optionsA)trueB)Compile ErrorC)false

    D)b

    Correct answer is : A

    Explanations : a*b means "a" may present zero or more time and "b"should be present once.Questions no -9What is the output for the below code ?

    public class Test {

    public static void main(String... args) {

    String input = "1 fish 2 fish red fish blue fish";Scanner s = new

    Scanner(input).useDelimiter("\\s*fish\\s*");System.out.println(s.nextInt());System.out.println(s.nextInt());System.out.println(s.next());System.out.println(s.next());s.close();

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    9/40

    }}

    optionsA)1 2 red blueB)Compile Error - because Scanner is not defind in java.C)1 fish 2 fish red fish blue fishD)1 fish 2 fish red blue fish

    Correct answer is : A

    Explanations : java.util.Scanner is a simple text scanner which canparse primitive types and strings using regular expressions.Questions no -10

    What is the output for the below code ?

    public class Test {

    public static void main(String... args) {

    Pattern p = Pattern.compile("a{3}b?c*");Matcher m = p.matcher("aaab");boolean b = m.matches();System.out.println(b);

    }}

    optionsA)trueB)Compile ErrorC)falseD)NullPointerException

    Correct answer is : A

    Explanations :X? X, once or not at allX* X, zero or more timesX+ X, one or more timesX{n} X, exactly n timesX{n,} X, at least n timesX{n,m} X, at least n but not more than m timesQuestions no -11

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    10/40

    What is the output for the below code ?

    public class Test {

    public static void main(String... args) {

    Pattern p = Pattern.compile("a{1,3}b?c*");Matcher m = p.matcher("aaab");boolean b = m.matches();System.out.println(b);

    }}

    optionsA)trueB)Compile ErrorC)falseD)NullPointerException

    Correct answer is : A

    Explanations :X? X, once or not at allX* X, zero or more timesX+ X, one or more timesX{n} X, exactly n times

    X{n,} X, at least n timesX{n,m} X, at least n but not more than m timesQuestions no -12What 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");}

    }

    public class Test {

    public static void main(String... args) throws Exception {B b = new B();

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    11/40

    ObjectOutputStream save = new ObjectOutputStream(new

    FileOutputStream("datafile"));save.writeObject(b);save.flush();

    ObjectInputStream restore = new ObjectInputStream(newFileInputStream("datafile"));

    B z = (B) restore.readObject();

    }

    }

    optionsA)A B AB)A B A BC)B BD)A B

    Correct answer is : A

    Explanations :On the time of deserialization , the Serializableobject not create new object. So constructor of class B does notcalled.

    A is not Serializable object so constructor is called.Questions no -13What is the output for the below code ?

    public class A {}

    public class B implements Serializable {A a = new A();public static void main(String... args){

    B b = new B();try{

    FileOutputStream fs = newFileOutputStream("b.ser");

    ObjectOutputStream os = newObjectOutputStream(fs);

    os.writeObject(b);os.close();

    }catch(Exception e){e.printStackTrace();

    }

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    12/40

    }

    }

    optionsA)Compilation FailB)java.io.NotSerializableException: Because class A is notSerializable.C)Run properlyD)Compilation Fail : Because class A is not Serializable.

    Correct answer is : B

    Explanations :It throws java.io.NotSerializableException:A Becauseclass A is not Serializable.

    When JVM tries to serialize object B it will try to serialize A alsobecause (A a = new A()) is instance variable of Class B.

    So thows NotSerializableException.

    Questions no -14What is the output for the below code running in the same JVM?

    public class A implements Serializable {transient int a = 7;static int b = 9;

    }

    public class B implements Serializable {

    public static void main(String... args){A a = new A();try {

    ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("test.ser"));

    os.writeObject(a);os. close();System.out.print( + + a.b + " ");

    ObjectInputStream is = new ObjectInputStream(new

    FileInputStream("test.ser"));A s2 = (A)is.readObject();is.close();System.out.println(s2.a + " " + s2.b);

    } catch (Exception x){

    x.printStackTrace();}

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    13/40

    }

    }

    optionsA)9 0 9B)9 7 9C)0 0 0D)0 7 0

    Correct answer is : A

    Explanations :transient variables are not serialized when an objectis serialized.

    In the case of static variable you can get the values in the same

    JVM.

    Questions no -15What 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/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    14/40

    optionsA)7:30B)Compile Error - an enum cannot be instantiated using the newoperator.C)12:50

    D)19:45

    Correct answer is : B

    Explanations : As an enum cannot be instantiated using the newoperator, the constructors cannot be called explicitly.You have to do likeTest t = BREAKFAST;Questions no -16What is the output for the below code ?

    public class Test {enum Day {

    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,SUNDAY}enum Month {

    JAN, FEB}

    public static void main(String[] args) {

    int[] freqArray = { 12, 34, 56, 23, 5, 13, 78 };

    // Create a Map of frequenciesMap ordinaryMap = new HashMap();for (Day day : Day.values()) {

    ordinaryMap.put(day, freqArray[day.ordinal()]);}

    // Create an EnumMap of frequenciesEnumMap frequencyEnumMap = new

    EnumMap(ordinaryMap);

    // Change some frequenciesfrequencyEnumMap.put(null, 100);

    System.out.println("Frequency EnumMap: " +frequencyEnumMap);

    }

    }

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    15/40

    optionsA)Frequency EnumMap: {MONDAY=12, TUESDAY=34, WEDNESDAY=56,THURSDAY=23, FRIDAY=5, SATURDAY=13, SUNDAY=78}B)Compile ErrorC)NullPointerExceptionD)Frequency EnumMap: {MONDAY=100, TUESDAY=34, WEDNESDAY=56,

    THURSDAY=23, FRIDAY=5, SATURDAY=13, SUNDAY=123}

    Correct answer is : C

    Explanations : The null reference as a key is NOT permitted.Questions no -17public class EnumTypeDeclarations {

    public void foo() {

    enum SimpleMeal {BREAKFAST, LUNCH, DINNER

    }

    }}

    Is the above code Compile without error ?

    optionsA)Compile without errorB)Compile with errorC)Compile without error but Runtime ExceptionD)Compile without error but Enum Exception

    Correct answer is : B

    Explanations :An enum declaration is a special kind of class declaration:

    a) It can be declared at the top-level and as static enumdeclaration.

    b) It is implicitly static, i.e. no outer object is associated withan enum constant.

    c) It is implicitly final unless it contains constant-specific classbodies, but it can implement interfaces.

    d) It cannot be declared abstract unless each abstract method isoverridden in the constant-specific class body of every enumconstant.

    e) Local (inner) enum declaration is NOT OK!

    Here inpublic void foo() {

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    16/40

    enum SimpleMeal {BREAKFAST, LUNCH, DINNER

    }}

    enum declaration is local within method so compile time error.

    Questions no -18What is the output for the below code ?

    public enum Test {int t;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/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    17/40

    Questions no -19What is the output for the below code ?

    public class B extends Thread{public static void main(String argv[]){

    B b = new B();b.run();}public void start(){for (int i = 0; i < 10; i++){System.out.println("Value of i = " + i);}}}

    optionsA)A compile time error indicating that no run method is defined forthe Thread classB)A run time error indicating that no run method is defined for theThread classC)Clean compile and at run time the values 0 to 9 are printed outD)Clean compile but no output at runtime

    Correct answer is : D

    Explanations : This is a bit of a sneaky one as I have swapped aroundthe names of the methods you need to define and call when running athread.

    If the for loop were defined in a method called public void run()and the call in the main method had been to b.start() The list ofvalues from 0 to 9would have been output.Questions no -20

    What is the output for the below code ?

    public class Test extends Thread{

    static String sName = "good";public static void main(String argv[]){

    Test t = new Test();

    t.nameTest(sName);System.out.println(sName);

    }public void nameTest(String sName){

    sName = sName + " idea ";start();

    }public void run(){

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    18/40

    for(int i=0;i < 4; i++){

    sName = sName + " " + i;

    }}

    }

    optionsA)goodB)good ideaC)good idea good ideaD)good 0 good 0 1

    Correct answer is : A

    Explanations : Change value in local methods wouldnt change inglobal in case of String ( because String object is immutable).Questions no -21What is the output for the below code ?

    public class Test{public static void main(String argv[]){Test1 pm1 = new Test1("One");pm1.run();Test1 pm2 = new Test1("Two");pm2.run();

    }}

    class Test1 extends Thread{private String sTname="";Test1(String s){

    sTname = s;

    }public void run(){

    for(int i =0; i < 2 ; i++){try{sleep(1000);

    }catch(InterruptedException e){}

    yield();System.out.println(sTname);}

    }}

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    19/40

    optionsA)Compile errorB)One One Two Two

    C)One Two One TwoD)One Two

    Correct answer is : B

    Explanations : If you call the run method directly it just acts asany other method and does not return to the calling code until it hasfinished. executingQuestions no -22What is the output for the below code ?

    public class Test extends Thread{public static void main(String argv[]){

    Test b = new Test();b.start();}public void run(){

    System.out.println("Running");}

    }

    optionsA)Compilation clean and run but no output

    B)Compilation and run with the output "Running"C)Compile time error with complaint of no Thread importD)Compile time error with complaint of no access to Thread package

    Correct answer is : B

    Explanations :The Thread class is part of the core java.lang package and does notneed any explicit import statement.Questions no -23What is the output for the below code ?

    public class Tech {

    public void tech() {System.out.println("Tech");

    }

    }

    public class Atech {

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    20/40

    Tech a = new Tech() {public void tech() {

    System.out.println("anonymous tech");}

    };

    public void dothis() {a.tech();

    }

    public static void main(String... args){Atech atech = new Atech();atech.dothis();

    }

    optionsA)anonymous techB)Compile ErrorC)TechD)anonymous tech Tech

    Correct answer is : A

    Explanations : This is anonymous subclass of the specified classtype.

    Anonymous inner class ( anonymous subclass ) overriden the Tech superclass of tech() method.

    Therefore Subclass method will get called.Questions no -24What is the output for the below code ?

    public class Outer {private String x = "Outer variable";void doStuff() {String z = "local variable";class Inner {public void seeOuter() {System.out.println("Outer x is " + x);System.out.println("Local variable z is " + z);

    }}

    }

    }

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    21/40

    optionsA)Outer x is Outer variable.B)Compile ErrorC)Local variable z is local variable.D)Outer x is Outer variable Local variable z is local variable

    Correct answer is : B

    Explanations : Cannot refer to a non-final variable z inside an innerclass defined in a different method.Questions no -25

    What is the output for the below code ?

    public class Test {

    public static void main(String... args) {for(int i = 2; i < 4; i++)

    for(int j = 2; j < 4; j++)assert i!=j : i;

    }}

    optionsA)The class compiles and runs, but does not print anything.B)The number 2 gets printed with AssertionErrorC)The number 3 gets printed with AssertionErrorD)compile error

    Correct answer is : B

    Explanations : When i and j are both 2, assert condition is false,and AssertionError gets generated.Questions no -26

    What is the output for the below code ?

    public class Test {

    public static void main(String... args) {for(int i = 2; i < 4; i++)

    for(int j = 2; j < 4; j++)

    if(i < j)assert i!=j : i;

    }}

    optionsA)The class compiles and runs, but does not print anything.

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    22/40

    B)The number 2 gets printed with AssertionErrorC)The number 3 gets printed with AssertionErrorD)compile error

    Correct answer is : A

    Explanations : When if condition returns true, the assert statementalso returns true.Hence AssertionError not generated.Questions no -26What is the output for the below code ?

    public class NameBean {private String str;

    NameBean(String str ){this.str = str;

    }

    public String toString() {return str;}

    }

    import java.util.HashSet;

    public class CollClient {

    public static void main(String ... sss) {HashSet myMap = new HashSet();String s1 = new String("das");String s2 = new String("das");

    NameBean s3 = new NameBean("abcdef");NameBean s4 = new NameBean("abcdef");

    myMap.add(s1);myMap.add(s2);myMap.add(s3);myMap.add(s4);

    System.out.println(myMap);}

    }

    optionsA)das abcdef abcdefB)das das abcdef abcdefC)das abcdefD)abcdef abcdef

    Correct answer is : A

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    23/40

    Explanations : Need to implement 'equals' and 'hashCode' methods toget unique Set for user defind objects(NameBean).

    String object internally implements 'equals' and 'hashCode' methodstherefore Set only stored one value.

    Questions no -27Synchronized resizable-array implementation of the List interface is_____________?

    optionsA)VectorB)ArrayListC)HashtableD)HashMap

    Correct answer is : A

    Explanations : Vector implements List, RandomAccess - Synchronizedresizable-array implementation of the List interface with additional"legacy methods."Questions no -28What is the output for the below code ?public class Test {

    public static void main(String argv[]){

    ArrayList list = new ArrayList();

    ArrayList listStr = list;ArrayList listBuf = list;listStr.add(0, "Hello");StringBuffer buff = listBuf.get(0);System.out.println(buff.toString());

    }

    }

    options

    A)HelloB)Compile errorC)java.lang.ClassCastExceptionD)null

    Correct answer is : C

    Explanations : java.lang.String cannot be cast tojava.lang.StringBuffer at the code StringBuffer buff =

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    24/40

    listBuf.get(0);So thows java.lang.ClassCastException.Questions no -29What 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 ( ) )

    System.out.print(q.poll() + " ");}

    }

    optionsA)Compile error : Integer can't addB)newyork ca texas 11C)newyork ca texasD)newyork ca

    Correct answer is : B

    Explanations :

    q was originally declared as Queue, But in show() methodit is passed as an untyped Queue. nothing in the compiler or JVMprevents us from adding an Integer after that.

    If the show method signature is public static voidshow(Queue q) than you can't add Integer, Only Stringallowed. But public static void show(Queue q) is untyped Queue so youcan add Integer.

    poll() Retrieves and removes the head of this queue, or returnsnull if this queue is empty.Questions no -30What is the output for the below code ?

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    25/40

    public interface TestInf {int i =10;}

    public class Test {public static void main(String... args) {

    TestInf.i=12;System.out.println(TestInf.i);

    }

    }

    optionsA)Compile with error

    B)10C)12D) Runtime Exception

    Correct answer is : A

    Explanations : All the variables declared in interface is Implicitlystatic and final , therefore can't change the value.Questions no -31What is the output for the below code ?

    public class Test {static { int a = 5; }

    public static void main(String[] args){System.out.println(a);}

    }

    optionsA)Compile with errorB)5C)0D) Runtime Exception

    Correct answer is : A

    Explanations : A variable declared in a static initialiser is notaccessible outside its enclosing block.Questions no -32What is the output for the below code ?

    class A {{ System.out.print("b1 "); }

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    26/40

    public A() { System.out.print("b2 "); }}class B extends A {static { System.out.print("r1 "); }public B() { System.out.print("r2 "); }{ System.out.print("r3 "); }

    static { System.out.print("r4 "); }}class C extends B {public static void main(String[] args) {System.out.print("pre ");new C();System.out.println("post ");

    }}

    options

    A)r1 r4 pre b1 b2 r3 r2 postB)r1 r4 pre b1 b2 postC)r1 r4 pre b1 b2 post r3 r2D)pre r1 r4 b1 b2 r2 r3 post

    Correct answer is : A

    Explanations : All static blocks execute first then blocks andconstructor.

    Blocks and constructor executes (super class block then super classconstructor, sub class block then sub class constructor).

    Sequence for static blocks is super class first then sub class.

    Sequence for blocks is super class first then sub class.

    Questions no -33What is the output for the below 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);

    }

    }

    }

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    27/40

    optionsA)trueB)false

    C)Compile ErrorD) Runtime Exception

    Correct answer is : A

    Explanations : equals() method for the integer wrappers will onlyreturn true if the two primitive types and the two values are equal.Questions no -34Which statement is true about outer class?

    options

    A)outer class can only declare public , abstract and finalB)outer class may be privateC)outer class can't be abstractD)outer class can be static

    Correct answer is : A

    Explanations : outer class can only declare public , abstract andfinal.Questions no -35

    What is the output for the below code ?

    static public class Test {public static void main(String[] args) {

    char c = 'a';

    switch(c){case 65:

    System.out.println("one");break;case 'a':

    System.out.println("two");break;case 3:

    System.out.println("three");}

    }

    }

    optionsA)one

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    28/40

    B)twoC)Compile error - char can't be permitted in switch statementD)Compile error - Illegal modifier for the class Test; only public,abstract & final are permitted.

    Correct answer is : D

    Explanations : outer class can only declare public , abstract andfinal.Illegal modifier for the class Test; only public, abstract & finalare permittedQuestions no -36

    What is the output for the below code ?

    public class Test {

    public static void main(String... args) {

    ArrayList list = new ArrayList();list.add(1);list.add(2);list.add(3);

    for(int i:list)System.out.println(i);

    }}

    options

    A)1 2 3B)Compile error , can't add primitive type in ArrayListC)Compile error on for(int i:list) , Incorrect SyntaxD)0 0 0

    Correct answer is : A

    Explanations : JDK 1.5, 1.6 allows add primitive type in ArrayListand for(int i:list) syntax is also correct.for(int i:list) is same asfor(int i=0; i < list.size();i++){

    int a = list.get(i);

    }Questions no -37What is the output for the below code ?

    public class SuperClass {public int doIt(String str, Integer... data)throws

    ArrayIndexOutOfBoundsException{String signature = "(String, Integer[])";System.out.println(str + " " + signature);

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    29/40

    return 1;}

    }

    public class SubClass extends SuperClass{

    public int doIt(String str, Integer... data) throws Exception{

    String signature = "(String, Integer[])";System.out.println("Overridden: " + str + " " +

    signature);return 0;

    }

    public static void main(String... args){

    SuperClass sb = new SubClass();

    try{ sb.doIt("hello", 3);}catch(Exception e){

    }

    }

    }

    options

    A)Overridden: hello (String, Integer[])B)hello (String, Integer[])C)This code throws an Exception at RuntimeD)Compile with error

    Correct answer is : D

    Explanations : Exception Exception is not compatible with throwsclause in SuperClass.doIt(String, Integer[]).The same exception or subclass of that exception is allowed.

    Questions no -38What is the result of executing the following code, using the

    parameters 0 and 3 ?

    public void divide(int a, int b) {try {

    int c = a / b;} catch (Exception e) {

    System.out.print("Exception ");} finally {

    System.out.println("Finally");

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    30/40

    }

    optionsA)Prints out: Exception Finally

    B)Prints out: FinallyC)Prints out: ExceptionD)Compile with error

    Correct answer is : B

    Explanations : finally block always executed whether exception occursor not.

    0/3 = 0 Does not throws exception.Questions no -39Which of the below statement is true about Error?

    optionsA)An Error is a subclass of ThrowableB)An Error is a subclass of ExceptionC)Error indicates serious problems that a reasonable applicationshould not try to catch.D)An Error is a subclass of IOException

    Correct answer is : A and C

    Explanations : An Error is a subclass of Throwable that indicatesserious problems that a reasonable application should not try tocatch.

    Questions no -40Which of the following is type of RuntimeException?

    optionsA)IOExceptionB)ArrayIndexOutOfBoundsExceptionC)ExceptionD)Error

    Correct answer is : B

    Explanations : Below is the tree.java.lang.Objectjava.lang.Throwable

    java.lang.Exceptionjava.lang.RuntimeException

    java.lang.IndexOutOfBoundsExceptionjava.lang.ArrayIndexOutOfBoundsException

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    31/40

    Questions no -41What is the output for the below code ?

    public class Test {

    public static void main(String... args) throws Exception {

    File file = new File("test.txt");System.out.println(file.exists());FileWriter fw = new FileWriter(file);System.out.println(file.exists());

    }

    }

    optionsA)true true

    B)false falseC)false trueD)true false

    Correct answer is : C

    Explanations :Creating a new instance of the class File, you're notyet making an actual file, you're just creating a filename.

    So file.exists() return false.

    FileWriter fw = new FileWriter(file) do three things:

    It created a FileWriter reference variable fw.

    It created a FileWriter object, and assigned it to fw.

    It created an actual empty file out on the disk.

    So file.exists() return true.Questions no -42When comparing java.io.BufferedWriter and java.io.FileWriter, whichcapability exist as a method in only one of two ?

    optionsA)closing the streamB)flushing the streamC)writting to the streamD)writting a line separator to the stream

    Correct answer is : D

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    32/40

    Explanations :A newLine() method is provided in BufferedWriter whichis not in FileWriter.Questions no -43What is the output for the below code ?public class Test{

    public static void main(String[] args) {int i1=1;switch(i1){

    case 1:System.out.println("one");

    case 2:System.out.println("two");

    case 3:System.out.println("three");

    }}}

    optionsA)one two threeB)oneC)one twoD)Compile error.

    Correct answer is : A

    Explanations : There is no break statement in case 1 so it causes thebelow case statements to execute regardless of their values.Questions no -44What is the output for the below code ?

    public class Test {public static void main(String[] args) {

    char c = 'a';

    switch(c){case 65:

    System.out.println("one");break;case 'a':

    System.out.println("two");break;case 3:

    System.out.println("three");}

    }

    }

    optionsA)one two threeB)one

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    33/40

    C)twoD)Compile error - char can't be in switch statement.

    Correct answer is : C

    Explanations : Compile properly and print two.

    Questions no -45What 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 = newConcurrentSkipListMap();

    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());

    }}

    optionsA)Compile error : No method name like pollFirstEntry() orpollLastEntry()B)3C)6

    D)4

    Correct answer is : B

    Explanations :

    pollFirstEntry() Removes and returns a key-value mappingassociated with the least key in this map, or null if the map isempty.

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    34/40

    pollLastEntry() Removes and returns a key-value mapping associatedwith the greatest key in this map, or null if the map is empty.Questions no -46What 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 = newConcurrentSkipListMap();

    System.out.print(navMap.lastEntry());

    }}

    optionsA)Compile error : No method name like lastEntry()B)nullC)NullPointerExceptionD)0

    Correct answer is : B

    Explanations : lastEntry() Returns a key-value mapping associatedwith the greatest key in this map, or null if the map is empty.Questions no -47What 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) {

    NavigableMapnavMap = newConcurrentSkipListMap();

    navMap.put(4, "April");navMap.put(5, "May");navMap.put(6, "June");navMap.put(1, "January");navMap.put(2, "February");

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    35/40

    System.out.print(navMap.ceilingKey(3));

    }}

    optionsA)Compile error : No method name like ceilingKey()B)nullC)NullPointerExceptionD)4

    Correct answer is : D

    Explanations : Returns the least key greater than or equal to thegiven key, or null if there is no such key.

    In the above case : 3 is not a key so return 4 (least key greaterthan or equal to the given key).Questions no -48What 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) {

    NavigableMapnavMap = newConcurrentSkipListMap();

    navMap.put(4, "April");navMap.put(5, "May");navMap.put(6, "June");navMap.put(1, "January");navMap.put(2, "February");

    System.out.print(navMap.floorKey(3));

    }}

    options

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    36/40

    A)Compile error : No method name like floorKey()B)nullC)NullPointerExceptionD)2

    Correct answer is : D

    Explanations : Returns the greatest key less than or equal to thegiven key, or null if there is no such key.

    In the above case : 3 is not a key so return 2 (greatest key lessthan or equal to the given key).Questions no -49What is the output for the below code ?

    public class Test {public static void main(String... args) {

    List lst = new ArrayList();lst.add(34);lst.add(6);lst.add(6);lst.add(6);lst.add(6);lst.add(5);

    NavigableSet nvset = new TreeSet(lst);System.out.println(nvset.tailSet(6));

    }}

    optionsA)Compile error : No method name like tailSet()B)6 34C)5D)5 6 34

    Correct answer is : B

    Explanations : tailSet(6) Returns elements are greater than or equal

    to 6.Questions no -50What is the output for the below code ?

    import java.util.ArrayList;import java.util.List;import java.util.NavigableSet;import java.util.TreeSet;

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    37/40

    public class Test {public static void main(String... args) {

    List lst = new ArrayList();lst.add(34);lst.add(6);lst.add(6);lst.add(6);lst.add(6);

    NavigableSet nvset = new TreeSet(lst);nvset.pollFirst();nvset.pollLast();

    System.out.println(nvset.size());

    }}

    optionsA)Compile error : No method name like pollFirst() or pollLast()B)0C)3D)5

    Correct answer is : B

    Explanations :

    pollFirst() Retrieves and removes the first (lowest) element, orreturns null if this set is empty.

    pollLast() Retrieves and removes the last (highest) element, orreturns null if this set is empty.

    Questions no -51What is the output for the below code ?

    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) {

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    38/40

    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

    A)1 2 7 10 34 nullB)2 7 nullC)2 7 34D)1 2 7 10 34

    Correct answer is : B

    Explanations :

    lower() Returns the greatest element in this set strictly lessthan the given element, or null if there is no such element.

    higher() Returns the least element in this set strictly greaterthan the given element, or null if there is no such element.

    Questions no -52What 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 {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);

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    39/40

    NavigableSet nvset = new TreeSet(lst);System.out.println(nvset.headSet(10));

    }

    }

    optionsA)Compile error : No method name like headSet()B)2, 6, 7, 8, 10C)2, 6, 7, 8D)34

    Correct answer is : C

    Explanations : headSet(10) Returns the elements elements are strictly less than10.

    headSet(10,false) Returns the elements elements are strictly lessthan 10.

    headSet(10,true) Returns the elements elements are strictly lessthan or equal to 10.

    Questions no -53What is the output for the below 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 %s's

    password: ", uname);

    con.writer().write("\n\n");} while (!auth && ++count < 3);

    }

  • 8/11/2019 OCPJP 6 Free Mock Exam Practice Questions

    40/40

    }}

    optionsA)NullPointerExceptionB)It works properlyC)Compile Error : No readPassword() method in Console class.D)null

    Correct answer is : A

    Explanations : passing a null argument to any method in Console classwill cause a NullPointerException to be thrown.