Whizbang Practice Final Missed Flashcards

1
Q

What will be the output of this program code?

public class Whiz {

      public static void main(String[] args) {

               String [][]strs = new String[5][];
               strs[1] = new String[2];
               System.out.print(strs.length + strs[1].length);
      }  }                             
Please select :
A. 2
B. 4
C. 7
D. A NullPointerException is thrown
E. Compilation fails
A

Option C is the correct answer.

When we are using a two-dimensional array, the length variable of that array will represent the number of rows in a two-dimensional array so here at line 7 length field of the strs array will be 5, then accessing the length of a one-dimensional array in index position 1 will return 2 so total will be 7. Hence, option C is correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
public class Whiz {
          static Integer i;
          public static void main(String[] args) {
                    try {
                           System.out.print(i.toString());
                    }catch(RuntimeException ex) {
                           throw ex;
                    }catch(Exception e) {
                           System.out.print("e");
                    }finally {
                           System.out.print("fin");
                    }
          }
 }
A

Option D is the correct answer.

Here at line 5, a null pointer exception will be thrown and it will be caught from the first catch box since null pointer exception is a subtype of Runtime exception. But again in the catch box throwing new exception will result in an uncaught exception, since the finally will execute at the end result will be fin, followed by an exception. Hence, option D is correct.

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

What will be the output of this program code?

public class Whiz {

       public static void main(String[] args) {

                 int ints[] = get(-1);
                 System.out.println(ints.length);
       }

      public static int[] get(int x) {
               return new int[x];
      }  }
Please select :
A. 0
B. -1
C. NegativeArraySizeException
D. IllegalArgumentException 
E. NullPointerException
A

Option C is the correct answer.

This code throws a NegativeArraySizeException at line 10 as when we are using negative array size to initialize an array NegativeArraySizeException is thrown. So, option C is correct.

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

Which of the following exception will be thrown by the JVM when we try to access a char of a string using the length of the string?

Please select :
A. NullPointerException
B. StringIndexOutOfBoundsException
C. NumberFormatException
D. ArrayIndexOutOfBoundsException 
E. There will be no exception
A

Option B is the correct answer.

Option B is correct since the StringIndexOutOfBoundsException is thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string. The NullPointerException is thrown by the JVM when there is a null reference where an object is required. So, option A is incorrect.

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

Which of the following can be inserted at line 2, to make this code compile?

  public void exc() throws FileNotFoundException{
          // INSERT CODE HERE
  }
Please select :
A. throw new java.io.IOException();
B. throw new RuntimeException();
C. throw new Exception();
D. throw new IOException();
E. All of the above
A

Option B is the correct answer.

A method that declares an exception isn’t required to throw one, and runtime exceptions can be thrown in any method, making option B correct.

Options A, C, and D are incorrect because a broader exception is not allowed.

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

Which of the following is platform independent?

Please select :
A. JRE
B. JDK
C. JVM 
D. byte code
E. None of the above
A

Option D is the correct answer.

The Java bytecode works on all Java virtual machines is that a rather strict standard has been written for how Java virtual machines work. This means that no matter what physical platform you are using, the part where the Java bytecode interfaces with the JVM is guaranteed to work only one way. Since all the JVMs work exactly the same, the same code works exactly the same everywhere without recompiling. So, option D is correct.

Other options are incorrect since the component of java are not platform independent but they provide the capability for bytecode to be platform independent.

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?

public class Whiz {

       public static void main(String[] args) {

                String[ ] sts = {“A”,”B”,”C”};

                 for (String i : sts) {
                         continue;
                         System.out.print(i);
                 }
       }  }
A

Your answer is incorrect.

Explanation:
Option E is the correct answer.

Here at line 8, we have used continue because of that for each iteration of for each loop, line 9 can’t be reached. Hence, the compiler complains that line 9 is unreachable. So, option E is correct.

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

Which of the following has higher operator precedence than instanceof operator?

Please select :
A. ==
B. !=
C. new
D. +=
E. There is no such operator called instanceof.
A

Option C is the correct answer.

According to java operator precedence, only the relational operator ‘new’ has higher precedence than the instance operator from given options.

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

What will be the output of this code fragment?

public class Whiz {
         public static void main(String[] args) {
                   long in = 3;
                    final byte b = 0;
                switch(in) {                                         
                                   case b : System.out.print(0);
                                   case b+1 : System.out.print(1);break;
                                   case b+3 : System.out.print(3);
                                   case b+2 : System.out.print(2);break;
                                   default :System.out.print("?");
                }             
      }  }
Please select :
A. 32 
B. 32?
C. 132
D. 01
E. Compilation fails
A

Option E is the correct answer.

Option E is correct as the code fails to compile due to line 6. The Switch doesn’t allow long, float, double, and boolean values. The Switch works with the byte, short, char, int, Byte, Short, Character, Integer, String and Enum types.

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

The correct answer is: Compilation fails

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 code?

class Whiz {
          public static void main(String args[]) {
                   new Whiz().iterator(new int []{10,12,13});
          }
          void iterator(int []i) {
                    for(int x=0;x
A

Option D is the correct answer.

We have passed the anonymous array to the iterator method which uses a for loop to iterate through array elements and print them. In given for loop, we have used the printing statement in update part and we have done the increment part inside the loop, so in the first iteration, it will increase the value of x and then print the second element. But when it does two iterations, the value of x will become 3, so in the final iteration trying to access element will index position 3, will result in an exception. Hence, option D is correct.

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

What will be the output of this code fragment?

 public class Whiz {
          public static void main(String[] args) {
                   Base bs = new Subclass();
                   bs.display();
          }
 }             
 class Base {
           public static void display() {
                    System.out.println("Base");
           }
 }
 class Subclass extends Base { 
            public static void display() {
                     System.out.println("Subclass");
            }
 }
A

Option B is the correct answer.

We can declare static methods with the same signature in a subclass but it is not considered overriding as there won’t be any run-time polymorphism. If a derived class defines a static method with the same signature as a static method in base class, the method in the derived class hides the method in the base class. As per overriding rules, this should call to class Subclass’s static overridden method. Since a static method cannot be overridden, it calls Base’s display(). Hence, option B is correct.

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

Which of the following has correct method signature for overriding version of this method which is located in an interface?

abstract int calculate()throws IOException;

Please select :
A. int calculate()throws Exception;
B. void calculate()throws IOException;
C. public int calculate();
D. public void calculate()throws IOException; 
E. Given method is invalid
A

Option C is the correct answer

It is given that method is located in an interface so it is implicitly public.

Option A is incorrect since we can’t use more restrictive access level when overriding methods, so using default is incorrect. And also, we can’t throw a boarder checked exception.

Option B is incorrect since we can’t use more restrictive access level when overriding methods so using default is incorrect

Option C is correct since there we have used public as the access level and it is legal to skip throwing an exception for overridden method.

When overriding we can’t change the return type except for covariant types, hence option D is incorrect.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
class Animal {
            public void eat() throws Exception { System.out.print("Animal eats");}
  }
  class Dog extends Animal {
            public void eat() { System.out.print("Dog eats"); }
        public static void main(String [] args) {
                 Animal a = new Dog();
                 Dog d = new Dog();
                 d.eat();
                 a.eat();
        }   }
A

Option E is the correct answer.

If a method is overridden but we use a polymorphic (super type) reference to refer to the subtype object with the overriding method, the compiler assumes we are calling the supertype version of the method. If the supertype version declares a checked exception but the overriding subtype method does not, the compiler still thinks you are calling a method that declares an exception.

So, the above code fails to compile due to line 12, since compiler sees calling the eat method of the superclass and fail to catch or declare the exception.

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

Which of the following is a correct variable declaration?

Please select :
A. int stu count;
B. double null;
C. float 12f;
D. int x_y;
E. None of the above.
A

Your answer is incorrect.

Explanation:
Option D is the correct answer.

Option D is correct since we can use “_” in a variable name.

Option A is incorrect since we cannot use spaces in a variable name.

Option B is incorrect since we cannot use a keyword for a variable name, here ‘null’ is a keyword.

Option C is incorrect since we can’t start a variable name with a digit.

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

How many objects are eligible for GC when line 12 is reached?

class Exam {
           Exam(Integer in){ code = in;}
           String s = “OCAJP”;
           Integer code;
}
public class Whiz {
         public static void main(String [] args) {
                  Integer c = 808;
                  Exam w =new Exam(c);
                  w = null;
         System.out.println(c); }
}
Please select :
A. 1
B. 2
C. 3 
D. 4
E. Compilation fails
A

Option B is the correct answer.

At line 10, we have created an Exam instance by passing a wrapper variable c. At line 11, making w reference null will cause the Exam instance eligible for the GC and also the String reference too. But the Integer code refers to the same place where the variable c refers so it won’t be eligible for the GC. Hence, at line 12, only 2 objects are eligible for the GC.

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

Which of the following will return a Boolean wrapper instance with value true?

Please select :
A. Boolean.TRUE;
B. Boolean.valueOf(“true”); 
C. new Boolean(“True”);
D. All of these.
A

Option D is the correct answer.

All the given statements will return a Boolean with value true. Hence, option D is correct.

17
Q

What will be the output of this program?

class Whiz {
          public static void main(String args[]) {
                    Double d = 10.0;
                    Integer i = 10;
                    System.out.print((d + i).intValue());
         }
  }
Please select :
A. 20.0
B. 20 
C. 10
D. An Exception is thrown
E. Compilation fails
A

Option E is the correct answer.

The code fails to compile due to line 5, as the sum of the Double and Integer wrapper return primitive double so trying to invoke a method on the primitive result in a compile-time error. Hence, the option E is correct.

18
Q

What will be the output of this program?

 class Whiz {
           public static void main(String args[]) {
                    Double d = 10.7;
                    Integer i = Integer.decode("12");
                    Integer ii = Integer.parseInt("011");
                System.out.print(ii+d+i);
       }   }
Please select :
A. 33.7
B. 31.7 
C. An Exception is thrown.
D. Compilation fails due to line 4.
E. Compilation fails due to multiple errors.
A

Option A is the correct answer.

public static int parseInt(String s) throws NumberFormatException

It parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign ‘-‘ (‘\u002D’) to indicate a negative value or an ASCII plus sign ‘+’ (‘\u002B’) to indicate a positive value. If the argument is preceded by zeros, those zeros will be ignored.
If the characters in the string are in binary or hexadecimal format or not contain a parsable integer, you will get NumberFormatException.

Here Integer.parseInt(“011”) gives 11

public static Integer decode(String nm) throws NumberFormatException

It decodes a String into an Integer. Accepts decimal, hexadecimal, and octal numbers. It throws NumberFormatException if the String does not contain a parsable integer.

Here Integer.decode(“12”) gives 12.

Hence, the final output is 33.7

19
Q

What will be the output of this program code?

public class Whiz {
         public static void main(String[] args) {   
                  int i1 = 10;
                  int i2;
                  if (i1 > 2) {
                                    i1 = 1;
                                    i2 = 1;
                                 } else {
                                    i1 = 2;
                                 }
                  System.out.println(i1+i2);
        }
}
Please select :
A. 11
B. 10
C. 2 
D. 1
E. Compilation fails.
A

Option E is the correct answer.

This code fails to compile due to line 11 as the compiler is smart enough to recognize initializations that are more complex. In this example, there are two branches of code. i1 is initialized in both of them, so the compiler is perfectly happy. i2 is only initialized if check happens to be true. The compiler knows there is the possibility for the check to be false, resulting in uninitialized code, and gives a compiler error. Hence, option E is correct.

20
Q

What will be the output of this program code?

public class Whiz {
public static void main(String[] args) {
int i1 = 10;
int i2;
if (i1 > 2) {
i1 = 1;
i2 = 1;
} else {
i1 = 2;
}
System.out.println(i1+i2);
}
}
Please select :
A. 11
B. 10
C. 2
D. 1
E. Compilation fails.

A

Option E is the correct answer.

This code fails to compile due to line 11 as the compiler is smart enough to recognize initializations that are more complex. In this example, there are two branches of code. i1 is initialized in both of them, so the compiler is perfectly happy. i2 is only initialized if check happens to be true. The compiler knows there is the possibility for the check to be false, resulting in uninitialized code, and gives a compiler error. Hence, option E is correct.

21
Q

Which of the following can be considered as widening primitive conversion?

Please select :
A. long to float
B. String to int
C. int to byte
D. char to byte
E. None of the above
A

Option A is the correct answer.

There are 19 specific conversions on primitive types called as the widening primitive conversions:

byte to short, int, long, float, or double

short to int, long, float, or double

char to int, long, float, or double

int to long, float, or double

long to float or double

float to double

22
Q

What will be the output of this program code?

public class Whiz {
         public static void main(String[] args) {
                  type(10);
                  type(10.0f);
         }
     public static void type(int x) {
              System.out.print("int");
      }

     public static void type(double x)throws Exception {
              System.out.print("double");
     }

     public static void type(byte x) {
              System.out.print("byte");
      }

      private static void type(float x) {
              System.out.print("float");
      }   }      
Please select :
A. intdouble
B. intfloat
C. bytefloat
D. bytedouble
E. Compilation fails
A

Option B is the correct answer.

In above code, we have few overloaded versions of the type method. When methods we can throw new exceptions, so line 11 will compile successfully.

In the main method, we have invoked the type method two times. First at line 3 invoking type method by passing int will print “int” as the output, then at line 4 invoking the type method by passing float literal will invoke the float versio,n so “float” will be printed. Hence, the option B is correct.

23
Q

What will be the output of this program code?

class Whiz {
          public static void main(String args[]) {
                   StringBuilder sb = new StringBuilder("A");
                   sb.append(new char[]{'B','C'});
                   sb.append(3);
                   sb.append(true);
                   System.out.print(sb);
          } 
}

Please select :
A. A
B. ABC3true
C. BC3true
D. Compilation fails due to an error at line 4.
E. Compilation fails due to multiple errors.

A

Option B is the correct answer.

The StringBuilder is not immutable so not like strings whatever we do on the string builder is reflected in the instance. So in given code, we have used few overloaded versions of the append method and all of them are legal. They will add “BC”, 3 and true respectively, hence option B is correct.

24
Q

What will be the output of this program code?

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

class Whiz {
          public static void main(String args[ ]) {
                   DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yy/mm/dd");
                   LocalDateTime ldt = LocalDateTime.of(2015, 10,10,11,22);
                  System.out.println(dtf.format(ldt));
          }
}
Please select :
A. 15/22/10
B. 2015/10/10
C. 15/10/10 
D. An Exception is thrown.
E. Compilation fails.
A

Option A is the correct answer.

We can create custom date time formatters using the ofPattern method of the DateTimeFormatter class.

public static DateTimeFormatter ofPattern(String pattern)

Creates a formatter using the specified pattern. This method will create a formatter based on a simple pattern of letters and symbols as described in the class documentation. For example, d MMM uuuu will format 2011-12-03 as ‘3 Dec 2011’.

Here we have used yy - which represents the year in two digits, mm – minutes and then dd for day. So, the output will be 15/22/10. Hence, the option A is correct.

25
Q

What will be the output of this program code?

import java.time.LocalDate;

public class Whiz {
         public static void main(String[] args) {
                  LocalDate l = LocalDate.of(2014, 1, 31).plusMonths(1);
                  System.out.println(l);
         }   
}
Please select :
A. 2014-01-31
B. 2014-03-01 
C. 2014-02-28
D. An Exception is thrown.
E. Compilation fails.
A

Option C is the correct answer.

Here we have added one month to the date of “2014/1/31” and It would not yield “2014/2/31” or not throw any exception instead it will return the last day of the valid month. Hence, here option C is correct as the last date of February 2014.

26
Q

What will be the output of this program code?

import java.time.LocalDate;

public class Whiz {
         public static void main(String[] args) {
                  LocalDate lc = LocalDate.of(2015, 1, 31).now();
                  lc.plusYears(3);
                  System.out.println(lc);
         }   
}

Current Date : 2015-06-28

Please select :
A. 2015-01-31
B. 2015-06-28
C. 2018-06-28 
D. An Exception is thrown.
E. Compilation fails.
A

Option B is the correct answer.

At line 5, first we have created LocalDate with date “2015, 1, 31” then invoking the static method ‘now’ will return a new date with current date. So lc reference will refer to the instance with current date but not to date “2015, 1, 31”. Time package instances are immutable hence adding 3 years att line 6 won’t change original instance, so option B is correct.

27
Q

What will be the output of this program code?

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class Whiz {
         public static void main(String[] args) {
             LocalDateTime l = LocalDateTime.of(LocalDate.of(2015,3,3), LocalTime.of(11,22));
             l = l.withDayOfMonth(12);
            System.out.println(l.getMonth() + " : " + l.getDayOfMonth() + " : " + l.getHour());
     }    }
Please select :
A. MARCH : 12 : 11
B. 3 : 12 : 11 
C. 3 : 1 : 11
D. An Exception is thrown.
E. Compilation fails
A

Option A is the correct answer.

At line 8, we have used following method of the LocalDateTime class to create a LocalDateTime instance.

public static LocalDateTime of(LocalDate date,LocalTime time)

This obtains an instance of LocalDateTime from a date and time. Then invoking the withDayOfMonth by passing 12 will change the day of the above created LocalDateTime instance to 12. So, now the date of the LocalDateTime is 2015-03-12 and time 11:22.

Option A is correct since the getMonth method returns the name of the month but not the int value of the month.

28
Q

Which of the following method/s of the LocalDate class returns LocalDateTime?

Please select :
A. atTime(OffsetTime)
B. plusHours(long)
C. now(Clock)
D. now() 
E. None of the above.
A

Option E is the correct answer.

Option E is correct since none of the given methods return LocalDateTime.

Option A is incorrect since the atTime(OffsetTime) method returns OffsetDateTime.

Option B is incorrect since there is no such a method called as plusHours in the LocalDate.

Options C and D are incorrect since the now method returns a LocalDate.