Whizbang Practice Exam 3 Missed Flashcards

1
Q

What will be the output of this program code?

class Whiz {
                public static void main(String[] args) {
                                int a[ ][ ] = new int[3][];
                                 a[1] = new int[]{1,2,3};
                                 a[2] = new int[]{4,5};
                                System.out.print(a[1][2]);
                }
}             

Please select :
A. 2
B. 3
C. Exception will be thrown at runtime.
D. Compilation fails due to an error at line 3.
E. Compilation fails due to an error at line 4.

A

Option B is the correct answer.

At line 3, we created a two-dimensional array with the first dimension as 3 so there can be three rows, then at lines 4 and 5, we assigned two anonymous one-dimensional arrays to last two rows of the two-dimensional array. At line 6, we tried to print the second-row third element which is 3. Note here we haven’t given any value to the first row of the two-dimensional array. So, option B is correct.

Reference : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

The correct answer is: 3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What will be the output of this program code?

  1. import java.util.Arrays;
  2. public class Whiz{
  3. public static void main(String[] args) {
  4. int[ ] ints = {3,6,1,4,0};
  5. Arrays.sort(ints,0,4);
  6. for(int i : ints) {
  7. System.out.print(i);
  8. }
  9. }
  10. }
Please select :
A. 01436
B. 01346
C. 13460
D. An Exception is thrown.
E. Compilation fails.
A

Option C is the correct answer.

One version of the sort method of Arrays class sorts the specified range of the array into ascending order. The range to be sorted extends from the index fromIndex, inclusive, to the index toIndex, exclusive.

public static void sort(int[] a,int fromIndex,int toIndex)

Here we have passed range 0 to 4, which means elements from first element (inclusive) to 4th element. So only they will be sorted i.e. 3,6,1,4 will be sorted and the final output is 13460. Hence, option C is correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Which of the following error/exception is typically thrown by JVM?

Please select :
A. IllegalStateException
B. AssertionError 
C. StackOverflowError   
D. ArrayIndexOutOfBoundsException
E. All of the above.
A

Option C and D are the correct answer.

StackOverflowError, ArrayIndexOutOfBoundsException will be thrown by JVM. Hence Options C, D are correct. Options A, B are incorrect because IllegalStateException, AssertionError can be thrown programmatically.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Which of the following is checked exception?

Please select :
A. ClassCastException
B. NullPointerException
C. ExceptionInInitializerError 
D. IllegalArgumentException
E. None of the above.
A

Option E is the correct answer.

There are three kinds of exceptions in Java.

  1. checked exception
  2. error
  3. runtime exception
  4. Checked exception:
    These are exceptional conditions that a well-written application should anticipate and recover from.
    All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
  5. Error:
    These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. All direct or indirect subclasses of Error are errors. Ex : ExceptionInInitializerError etc
  6. Runtime exception:
    These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from.All direct or indirect subclasses of RuntimeException are the runtime exceptions.
    Ex : ClassCastException, NullPointerException, IllegalArgumentException, etc.

Errors and runtime exceptions are collectively known as unchecked exceptions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which will compile successfully when inserted at line 3?

abstract interface Movable{
                int x = 10;
                  //insert code here
                void run();
 }
Please select :
A. private int x = 10;
B. abstract int i = 5;
C. final static float  c = 6.0;
D. final short s=10;
E. None of the above.
A

Option D is the correct answer.

Option A is incorrect since at line 2 we already defined a variable calls ‘x’ so we can’t have another variable with the same name in the same scope. Also, the private variables are not allowed in interfaces.

Option B is incorrect as an abstract modifier is not valid for a variable.

Option C is incorrect since float literal should be ended with ‘f’ when it has decimal points.

Option D is correct as we can assign int literal within the range of -32768 – 32767 to a short.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Which of the following uses a fully qualified name in java?

Please select :
A. class MyDate extends java.util.Date{
//statement; 
}
B. import java.util.*;
class MyDate extends Date{
//statement; 
}
C. import java.util.Date.*;
class MyDate extends Date{
//statement; 
}
D. None of the above.
A

Option A is the correct answer

A fully qualified means using the complete package details when accessing a Java class. For example, if you are using java.lang.String is a fully qualified name for the class String. Here “java.lang” is the package where String class is declared and implemented. Other options are using the wild card “*” to import the classes and not using the fully qualified name to access the classes.

So, in this case, option A uses fully qualified name for the date class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What will be the output of this program code?

import java.util.*;
    class Whiz {
              public static void main(String args[]){
                       System.out.println(new Date());
              }
    }
Please select :
A. Prints today date
B. An Exception
C. Compile Error at line 1
D. Compile Error at line 5.
A

Option A is the correct answer

A fully qualified means using the complete package details when accessing a Java class. For example, if you are using java.lang.String is a fully qualified name for the class String. Here “java.lang” is the package where String class is declared and implemented. Other options are using the wild card “*” to import the classes and not using the fully qualified name to access the classes.

So, in this case, option A uses fully qualified name for the date class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What will be the output of this program code?

import java.util.*;
    class Whiz {
              public static void main(String args[]){
                       System.out.println(new Date());
              }
    }
Please select :
A. Prints today date
B. An Exception
C. Compile Error at line 1
D. Compile Error at line 5.
A

Option A is the correct answer.

Date class is present in Java since JDK 1.0. It is present in java.util package. It will contain current date, time, day name, time, and zone information. So, at line 5, statement prints current date, time, day name, time, and zone information.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Which of the following import statement will be inserted at line 1?

  // insert here
      public class Whiz {
               public static void main(String args[ ]) {   
                        System.out.println(pow(5,5));
               }
      }             
Please select :
A. import java.lang.Math.*; 
B. import static java.Math.*;
C. import static java.lang.Math.pow;
D. import java.Math.pow;
E. No import statement is needed.
A

Option C is the correct answer.

In given code, we have used the static pow method of Math class directly, so we have to import statically that method or all static members of the class. Correct syntax to import pow method statically is;

            import static java.lang.Math.pow;

So, option C is correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What will be the output of this program?

class Whiz {

      static int i;          
      int j;
      Whiz() { j=i++; }
          public static void main(String args[]) {
                    Whiz s = new Whiz();
                    Whiz s1= new Whiz();
                     Whiz s2= new Whiz();
                    System.out.print( "i = "+s.i);
                    System.out.print( ", j = "+s.j);
          }
}
What is the result?
Please select :
A. i = 3, j = 3 
B. i = 1, j = 0
C. i = 3, j = 0
D. An Exception is thrown.
E. Compilation fails.
A

Option C is the correct answer.

In the above snippet, the variable i is static and j is in non-static variables. A static variable is associated with the class has only one copy per class but not for each object, Whereas a Non-static variable will have one copy each per object. Each instance of a class will have one copy of non-static variables. Since the variable i is common for every instance it will get increment each time instance is created so the values of i is 3 and j is 0. (While creating an instance, i is incremented and retains its value)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What will be the output of this program?

class Whiz{

final int i;

                public static void main(String args[]){
                                Whiz s= new Whiz();
                                System.out.println( "i = "+s.i);
                }
}
Please select :
A. Prints i = 0 
B. Prints i = 1
C. Prints i = Null
D. Runtime Exception is thrown.
E. Compile-time Error.
A

Option E is the correct answer.

The compiler complains “variable i has not been initialized in the default constructor”. A final variable is equivalent to a constant entity in java. Once it is initialized it may not be changed. But, it has to be initialized at the time of declaration. It can be initialized in 3 ways.

A final variable is initialized at the time of declaration

final int i=100;

It can be initialized in the constructor

Whiz(){i=100;}

It can be initialized in instance block of initialization.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What will be the output of this program?

public class Whiz {
          public static void main(String [ ] args) {          
                   do {
                             int i = 3;
                             System.out.print(i++);
                         } while (i <= 6);
          }
}
Please select :
A. 333
B. 3456
C. 333333
D. Infinite loop of 3 
E. Compilation fails
A

Option E is the correct answer.

The variable i is declared within the body of the do-while statement, so it is out of scope on line 6. Line 6 generates a compiler error, so option E is correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What will be the output of this program?

public class Whiz {

     public static void main(String [ ] args) {  
              String out = "";
               z: for (int i = 3; i< 8; i++) {                            
                         if (i == 3)
                             continue;
                          if (i== 3)
                               break z;
                          out += i;
                 }
                 System. out .println(out);
      } }
Please select :
A. 4
B. 4567
C. 34567
D. No output will be produced.
E. Compilation fails due to multiple errors.
A

Option B is the correct answer.

For loop at line 5 iterates till the value of i reaches 8, so the value of i will be increased 1 by 1 from 3 to 8. When the value of the variable i is 3, first “if” test will execute and skip concatenating the value of i to the String out. Since the first if statement, second if statement does not execute so loop won’t break there. So, the String out will consist of concatenated values from 4 to 7 i.e. “4567”. Hence, option B is correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Which of the following will compile and produce BC when inserted at line 4?

  class Whiz {
             public static void main(String [ ] args) {
                       final int s = 2;
                       // insert code here
                       switch(s) {
                               case 1       : System.out.print("A");break;
                               case x-1    :System.out.print("B");
                               case x       : System.out.print("C");break;
                               case x+1   : System.out.print("D");break;
                               default      : System.out.print("F");
                      }
           }
  }
Please select :
A. int x=2;
B. final int x=2;
C. int x=3;
D. private final int x = 3; 
E. None of the above.
A

Option E is the correct answer.

The case constant has to be a compile-time constant, so we can’t use option A and C. Option D is incorrect since we can’t use private access modifier inside the local scope.

Option B is incorrect since it will produce two cases with same value 1 which is illegal. Hence, option E is correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What will be the output of this program?

   class Whiz {
              public static void main(String[ ] args) {
                       int i = 3, j = 2;     
                       System.out.println(i-- + --j + ++i);
               }
    }
Please select :
A. 8 
B. 7
C. 6
D. 5
E. Compilation fails.
A

Your answer is incorrect.

Explanation:
Option B is the correct answer.

The increment/decrement operators can be applied before or after the operand. At Line 4 i– and –j will end in i and j being decremented by one respectively. Now, i is 2 and j is 1. ++i will increment the value of i by one. Now, i is 3 and j is 1. So, the statement at line 4 becomes as follows

System.out.println(3 + 1 + 3);

Hence output will be 7, option B is correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Which of the following statement is true?

Please select :
A. The up casting doesn’t limit the capabilities of the object.
B. The down casting can’t be occurred implicitly.
C. Casting subclass object to superclass object is known as down casting.
D. With up casting, a ClassCastException is possible.
E. None of the above.

A

Option B is correct as down casting should be done explicitly.

Option A is incorrect as the when we casting the object becomes more general so it will remove object’s unique actions. Therefore, object capabilities are reduced.

Option C is incorrect as the casting subclass object to super class object is known as up casting.

Option D is incorrect as with down casting, a ClassCastException is possible but not with up casting.

17
Q

What will be the output of this program?

class Whiz{
                int i = 10;
                public static void main(String args[]){
                                int i;
                                if(new Whiz().go(10))   i = 5;
                                                System.out.print(i);
                }
                boolean go(int y){
                                if(y>5) return true;
                                else return false;
                }
}

Please select :
A. 5
B. 10
C. An exception will be thrown at runtime.
D. Compilation fails due to an error at line 4.
E. Compilation fails due to an error at line 6.

A

Option E is the correct answer.

Local variables must be initialized before using them, here we have used if block to initialize the value for variable i. So, the compiler knows that initialization might not happen and produce compile-time error due to line 6.

18
Q

What will be the output of this program?

class Whiz{
        public static void main(String args[]) throws Exception{
                 System.out.print(new Whiz().check(10));
        }
        boolean check(short x){
               if(x<10) return true;
               else return false;
        }
}

Please select :
A. false.
B. true
C. An exception is thrown at runtime
D. Compilation fails due to an error at line 3
E. Compilation fails due to multiple errors

A

Option D is the correct answer.

At line 3, we pass int literal to the method but the check method accepts only short variable so the compilation fails. If we use a cast as (short)10 then the code will work fine. This is because we pass int literal as the parameter to a method, however, if we assign 10 to short value as follows it is legal.

            short s = 10;
19
Q

Which of the following set contains only primitive literals?

Please select :
A. 1, ‘c’, “a”
B. 1, 1.5f, True
C. ‘BF’, 10, “Sure”
D. 1.2D, 1f, ‘c’
E. None of the above.
A

Option E is the correct answer.

Option D is incorrect since ‘1f’ is invalid

Option A is incorrect as “a” is a String literal.

Option B is incorrect as True is incorrect literal is should be true.

Option C is incorrect as ‘BF’ is illegal; char literal can only have one letter.

20
Q

What will be the output of this program?

class Whiz{
int x = 012;
       public static void main(String [] args){
                  Whiz pr = new Whiz();
                  pr.go(20);
       }
       void go(final int i){
              System.out.print(i/x);
       }
}

Please select :
A. 1
B. 2
C. 0
D. Compilation fails due to an error at line 2.
E. Compilation fails due to an error at line 7.

A

Option B is correct. At line 2, instead of using Decimal literals, we have used octal literals. So, the decimal value of x is 10 and the output is 2.

21
Q
class MainClass{
                MainClass(){    System.out.print("MainClass ");                                }             
}
class SubClass extends MainClass{
                {System.out.print("I ");}
                static{System.out.print("S ");}
                SubClass(int i){
                                this();
                                System.out.print("SubClass ");
                }
                SubClass(){
                                super();
                                System.out.print("SubClass ");
                }
 }
public class SubSubClass extends SubClass{
                SubSubClass(String s){
                                super();
                                System.out.print("SubSubClass ");
                }
                public static void main(String [] args){
                                new SubSubClass("ABC");
                }
 }
Please select :
A. MainClass S I SubClass SubSubClass
B. S MainClass I SubClass SubSubClass
C. S MainClass I SubClass SubClass SubSubClass
D. SubSubClass SubClass S I MainClass
E. Compilation fails
A

Option B is the correct answer.

To get the correct answer, you should know, static initialization blocks run once when the class is first loaded. Instance initialization blocks run every time a new instance is created. They run after all super-constructors and before the constructor’s code have run.

Here first ‘S’ will be printed as the static block executes when the class is loading, then at line 23 when the instance of SubSubClass is created, last super class constructor in the class hierarchy which is MainClass will be executed and print “MainClass”. When it comes to next subclass it will first execute non-static code block and then its constructor, so “I” and “SubClass” will print. Finally, the SubSubclass constructor will execute and print ‘SubSubClass’. Hence, option B is correct.

22
Q

Which of the following statement is invalid?

Please select :
A. Overloaded methods may change the argument list.
B. Overridden methods should not change the argument list.
C. Overloaded methods must change the argument list.
D. Overloaded methods can change return type.
E. In Overridden methods, object type determines which method is selected.

A

Option A is the correct answer.

Only option A is invalid, as we should change the argument list when overloading method. So option C is a valid statement. We can change the return type also; hence option D is a valid statement.

When method overriding methods we should not change the argument list, so option B is valid.

In Overridden methods, object type determines which method selected so option E is valid.

23
Q

What will be the output of this program?

   class Person{
             Person() {
                     System.out.print("CP ");
             }
             static{ System.out.print("SP ");}
    }
    class Student extends Person {
               Student() {
                      System.out.print("CS ");
                }
     }
    class Teacher extends Person {
               Teacher() {
                        System.out.print("CT ");
                }
                private Teacher(String s){
                        System.out.print("OCT ");
                }
     }
     class Whiz {
               public static void main(String [ ] args) {
                        Person p1 = new Teacher(“name”);
                        Student s1 = new Student();
               }
      } 
Please select :
A. SP OCT CP SP CS
B. SP CP IT OCT CP CS
C. SP CP OCT CP CS
D. SP CP OCT CT SP CP CS 
E. Compilation fails.
A

Option E is the correct answer.

Teacher class has a constructor which can take String as an argument but it is marked as private so it can’t be seen by the Whiz class. So, this code fails to compile.

24
Q

Which of the following is the correct method signature of overloaded version of this method?

public void method() { / *codes */}

Please select :
A. public int method()
B. private void method()
C. private int method(String s)
D. public String method()
E. None of the above
A

Option C is the correct answer.

While overloading the method, argument list should be changed. So, option C is correct since it changes the argument list. It is legal to change the return type when we overload methods.

25
Q

What will be the output of this program?

 class Whiz {
            static {
                     x = 10;
                     y = 5;                      
            }
  int x;
  final static int y ;
  public static void main(String args[ ]) {
            try {
                      Whiz pr =  new Whiz();
                      int c = pr.x/y;
                      System.out.print(c);
             } catch(ArithmeticException E) {
                      System.out.print("Arithmetic Exception");
                       }
            }
  }
Please select :
A. 0 
B. 2
C. An Arithmetic Exception will be thrown.
D. Compilation fails due to an error an line 3.
E. Compilation fails due to multiple errors.
A

Option D is correct since there is an error at line 3, we tried to access the non-static variable x inside a static block is illegal since static content can’t access non-static content.

26
Q

What will be the output of this program?

class Whiz{
        public static void main(String[] args){
                    StringBuilder sb =new StringBuilder("OCAJP");
                    String s = new String(sb.toCharArray());
                    s = s.concat(" 8");
                    System.out.print(s);
         }
}
Please select :
A. OCAJP 8 
B. OCAJP
C. 8
D. An Exception is thrown.
E. Compilation fails.
A

Option E is the correct answer.

String class has a method called toCharArray which returns an array of characters of given string. Also, String class has a constructor which can take a char array and a string but StringBuilder class doesn’t have CharArray method. Hence, code fails to compile because of line 4, so option E is correct.

27
Q

What will be the output of this program?

class Whiz{
        public static void main(String[] args){
                  StringBuilder sb = new StringBuilder("aAaA");
                  sb.insert(sb.lastIndexOf("A"),true);
                  System.out.print(sb);
        }
}
Please select :
A. aAtrueaA
B. aAatrueA
C. atrueAaA
D. A StringIndexOutOfBoundsException is thrown
E. Compilation fails.
A

Option B is the correct answer.

At line 3 we have created StringBuilder instance by passing “aAaA”. Then at line 4, we have used one of the overloaded versions of the insert method of the StringBuilder

public StringBuilder insert(int offset, boolean b)

Inserts the string representation of the boolean argument into this sequence.

The overall effect is exactly as if the second argument were converted to a string by the method String.valueOf(boolean), and the characters of that string were then inserted into this character sequence at the indicated offset.

The offset argument must be greater than or equal to 0, and less than or equal to the length of this sequence.

Here we have passed the index of the last “A” as the so true will be inserted before the last occurrence of “A”, hence option B is correct.

28
Q

Which of the following method of String class has been introduced in java SE 8?

Please select :
A. split
B. replaceFirst
C. append
D. set 
E. join
A

Option E is the correct answer.

Option E is correct since the Java SE 8 only introduced one new method called join in String class.

public static String join(CharSequencedelimiter, CharSequence… elements)

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

For example,

 String message = String.join("-", "Java", "is", "cool");

 // message returned is: "Java-is-cool"
29
Q

Which of the following method was introduced in ArrayList in java SE 8?

Please select :
A. length
B. spliterator
C. retainAll
D. listIterator 
E. None of the above
A

Option B is the correct answer.

All except length which is invalid method are valid methods which are available in the ArrayList, however from them, only the spliterator was introduced in java SE 8, others were available from earlier versions of java.

30
Q

Which of the following statement can be used to declare and instantiate an ArrayList to hold only Book instances with a default capacity of 10 elements?

Please select :
A. ArrayList book=  new ArrayList<>();
B. ArrayList book=  new ArrayList<>(10); 
C. ArrayList book=  new ArrayList(10);
D. ArrayList book=  new ArrayList();
E. All of the above.
A

Option E is the correct answer.

From java SE 7, we can use the diamond operator so we can skip the generic part of the object initializing since the compiler figures out what it should be, for example following are same

ArrayList library = new ArrayList<>();

ArrayList library = new ArrayList();

The default capacity of the Array list is 10, and we can also create ArrayList with the capacity we need, so here all options are correct.

31
Q

Which of the following can be used to get the number of elements in an ArrayList object?

Please select :
A. capacity
B. length 
C. size()
D. length()
E. None of the above.
A

Option C is the correct answer.

All collection classes have a method called size which returns the number of elements in the collection, so option C is correct.

Options A and B are incorrect since there are no such variables. The length method is used with the strings.