Whizbang Practice Exam 4 Missed Flashcards Preview

Custom Java OCA 8 > Whizbang Practice Exam 4 Missed > Flashcards

Flashcards in Whizbang Practice Exam 4 Missed Deck (23)
Loading flashcards...
1
Q

What will be the output of this program?

       public class Whizlab{
           public static void main(String[] args) {
                   double []dbls;
                   dbls = {1.0,2.1,3.5};

                   dbls[1] = 10.5;
                   System.out.print(dbls[1] + dbls[2]);
      }    }             
Please select :
A. 14
B. 11.6
C. A  NullPointerException is thrown.
D. An ArrayIndexOutOfBoundsException is thrown. 
E. Compilation fails.
A

Option E is the correct answer.

The code fails to compile as we tried to use Array constants to initialize the array after declaring the array which is illegal. Array constants can only be used in initializers. Hence, option E is correct.

2
Q

Which of the following statement(s) is/are false about the arrays?

Please select :
A. We can create anonymous arrays.
B. The number of elements an array can hold is fixed.
C. An array is an object.
D. If an array length is 10, then the last index position is 9.
E. None of the above.

A

Option E is the correct answer.

An array is considered as an object; also their number of elements that can hold is fixed. Since the array indexes start from zero, last element position in the array is one less than the array length. It is perfectly legal to create anonymous arrays, hence option E is correct.

3
Q

Given

       class Whizlab{
       public static void main(String args[]){
                       new Whizlab().meth();                
                       }
   public void meth()throws Exception{
                   for(int x=0;x>5;x++)
                                   System.out.print(x);
                   }    } What is the output? 
Please select :
A. 01234
B. An exception is thrown at runtime.
C. Code will cause a never ending loop.
D. Compilation fails.
E. No output
A

Option D is the correct answer.

‘meth’ method has declared a checked exception. When we are calling a method which declares or throwing a checked exception, the calling method should declare or handle that checked exception otherwise compilation fails. ‘main’ doesn’t declared or handled an Exception . It causes compile time error. Hence Option D is Correct. Remaining options are incorrect as explained above.

4
Q

What will be the output while running the program with args as the array [“0”, “2”]?

    public class Whizlab {
             public static void main(String[ ] args) {
                      try {
                                 int x = args.length;
                                 int  v = 10 / x;
                                 System.out.print(x);
                                 try {
                                         if (x == 1)
                                          x = x / x - x;
                                          if (x == 2) {
                                                 int [ ] c = {2};
                                                 c[3] = 3;
                                          }
                                 }
                                 catch (ArrayIndexOutOfBoundsException e) {
                                           System.out.println("out of bounds.");
                                  }
                                  catch (ArithmeticException e) {
                                           System.out.println("Arithmetic");
                                   }
                        }
               }
     }
Please select :
A. 2
B. 2out of bounds. 
C. out of bounds.
D. Arithmetic
E. Compilation fails.
A

Option E is the correct answer.

The two catch blocks are associated with the inner try on line 7. Since the outer try on line 3 has no catch or finally blocks, compilation will fail.

5
Q

What happens when the following code compiles and executes ?

            public class Whizlab{

                            public static void main(String[] args){

                                            try {

                                                            int a[] = new int[4];

                                            a[3] = (a[0]+a[1])/a[2];

                                            System.out.println(a[3]);

                                            }catch(ArithmeticException e){

                                                            System.out.println(“A”);

                                            }catch(Exception ex){

                                                            System.out.println(“E”);

                                            }

                            }
                }
A. 0
B. The program cannot compile because all the elements in the array “a” are not initialized. 
C. A
D. E
E. AE
A

Option C is the correct answer.

While initializing the array, all the elements in the array are set to 0. Hence when divided by 0, an Arithmeticexception is thrown, it is caught by the first “catch” block hence A will be printed.

6
Q

Which of the following is a valid top level class declaration?

Please select :
A. class switch{ }
B. public static class Test{} 
C. protected class Test{ }
D. private class Test{ }
E. None of the above
A

Explanation:

Option E is the correct answer.

Option E is correct because all given top level classes are incorrect.

Option A is incorrect as class name “switch” is a keyword in java.

Option B is incorrect as it is illegal to use static with top level class declarations.

Options C and D are incorrect as both protected and private access levels are not allowed with top level class declarations.

7
Q

Given

public class Whizlab{
    public static void main(String [ ] args) {
                int ar[][] = {{1,11},{1},{1,11}};
                for(int x = 0;x < ar.length;x++){
                                //insert here
                }
     }
}

Which of the following can be inserted at line 5, will print all elements of the array?

Please select :
A. for(x : ar[x]) System.out.print(x);
B. for(int y : ar) System.out.print(y);
C. for(int y : ar[x]) System.out.print(y);
D. System.out.print(ar[x]); 
E. None of above
A

Option C is the correct answer.

To print all elements in the array we have to iterate trough each one dimensional array, for that we can use enhanced for loop, for that we need to get each one dimensional array by using “ar[x]” and then we can use enhanced for loop to iterate each element easily as follows

            for(int y : ar[x])

So option C is correct since it will print all elements as required.

8
Q

Which of the following will compile successfully and produce output A when inserted independently at line 5?(Choose 3 options)

class Whizlab{
          public static void main(String [] args) {
                    int x = -10;
                    int y =  10;
                    //insert here
                   System.out.print("A");
          }
}
Please select :
A. if(y++>10 | x%(-3)==1) 
B. if(y>=10 &amp; x%(-3)==-1)
C. if(y>10 |  x%(3)==-1) 
D. if(++y>10 &amp;  x%(-3)==1)
E. if( ++y>10 | x%(-3)==1) 
F. if(y++>=10 ^  x%(-3)==-1)
A

Options B, C, and E are the correct answers.

x%(-3) will produce -1 because x is marked as minus (-).Post increment will do anything in the executing moment so y++ will be still same(y=10). But pre-increment makes it 11 before check it with value 10.

9
Q

Given

       class Whizlab{
           public static void main(String[] args){
                      int y = -10;          
                       int x = -3;
                       System.out.println(y%x);
           }
       }
What is the output?
Please select :
A. -1
B. 1 
C. 3
D. -3
E. Compilation fails
A

Option A is the correct answer.

When using the % operator, no matter from what value (negative or positive) we use to divider Remainder takes numerator sign. So here the numerator is negative and so reminder will stay negative. So remainder value will be -1. Hence option A is correct.

10
Q

Which of the following will override the go method of Parent class when inserted independently at line 8?

class Parent {
          protected void go() throws java.io.FileNotFoundException {
                  System.out.print("Parent");     
           }
}
class Child extends Parent{
           // override go method here
}

Please select :
A. private void go() throws IndexOutOfBoundsException{ System.out.print(“Child”); }
B. void go() throws IOException{ System.out.print(“”); }
C. public void go (String s)throws IndexOutOfBoundsException{ System.out.print(s); }
D. protected void go() throws RuntimeException{ System.out.print(“Child”); }
E. None of above.

A

Option D is the correct answer.

While overriding methods, we can’t throw new or broader checked exceptions, but we can throw new or broader unchecked exceptions. So here option D is correct since it throws a new unchecked exception than the original method and it is legal.
Also, we should use the same or less restrictive access level than the original method. In the option D and in the original method we have used protected access level modifier, which is correct.

Option A is incorrect since private is more restrictive than protected level.

Option B is incorrect since we can’t throw a new checked exception when overriding method.

Option C is incorrect since when overriding method we can’t change argument list if we do then it is overloading not overriding.

11
Q

In which of the following situations, you will choose interface inheritance over class inheritance?

       You are asked to create two classes(A,B) which should have some behaviors in common and class B is already a subclass of class C
        You are asked to create two classes (A,B) which should have some behaviors in common and class A is already implements another interface C .
        You are asked to create two classes (A,B) which should have some behaviors in common and both classes (A,B) are already sub classes of other classes (C,D) . Please select : A. All  B. Only I C. Only II and III D. Only I and III E. None
A

Option D is the correct answer.

Statement I is correct as one class already extend an another class we won’t able to give it the same behavior by extending another class. So, in this case, we have to create an interface and then implements it.

Statement III is correct as both classes already extend other classes we won’t able to give it the same behavior by extending another class. So, in this case, we have to create an interface and then implements it.

Statement II is incorrect as even one class already implements an interface, it can still extend a class, so in this case, it is optional to implements interface.

As explained above, D is correct.

12
Q

What will be the output of this program?

  class Whizlab {
             int i;
             public static void main(String [] args) {
                      Float F = 1.03f;
                      new Whizlab().devide(F);
             }
             void devide(Double D) {
                      System.out.print(D/i);
              }
}
Please select :
A. 0
B. Infinity 
C. Compilation fails.
D. An exception is thrown at runtime.
A

Option C is the correct answer.

Option C is correct as at line 6, we try to pass Float wrapper to a method which expects Double wrapper. Not like primitives, none of the wrapper classes will widen from one to another. As an example following code fragment will cause the whole code fail from compiling.

Ex: Long L = 10;

You may feel like, first 10 will be converted to an Integer and then widen to a Long. But it will never happen and its illegal.

Options A, B, and D are incorrect as code fails to compile. If we used primitives then the code would run fine and would give us the output as infinity as dividing float value from zero returns infinity as the output.

13
Q

What will be the output of this program?

       public class Whizlab{
                       static int x = 1;
                   Whizlab( ){x++;}
                   public static void main(String args[]){
                                   System.out.print(x + check(2));
                  }             
                       static int check(int i){
                                   return new Whizlab().x*i;
                   }
   }                             
Please select :
A. 1
B. 2 
C. 4
D. 5
E. Compilation fails.
A

Option D is the correct answer.

In Java, primitives are passed by their value but not the reference. At line 6, we are calling check method by passing value 2. Inside check method creating an instance will increase the value of x by one, and then multiplying it by 2 will return 4. Finally, 1+4 will result in output 5. Hence, option D is correct.

14
Q

Which of the following is a valid statement about this interface?

interface Movable{
static int speed = 12;
String s = “speed: “;
}

Please select :
A. new Movable().s;
B. Movable.speed  = 10; 
C. System.out.println(Movable.s);
D. Given interface is invalid.
E.  None of the above.
A

Option C is the correct answer.

Interface variables are implicitly public, static and final. So, even we haven’t declared without them, they can be considered as implicitly public, static and final.

Option A is incorrect since we can’t instantiate an interface.

Option B is incorrect since we can’t change the value of final fields.

Option C is correct since field is static we can refer it using class or interface name.

15
Q

What will be the output of this program?

       public class Whizlab{
       int _ = $;
       static int $ = 5;
               public static void main(String[] args) {
                               System.out.print($ +_);
               }
       }

Please select :
A. 5
B. 10
C. Compilation fails due to an error at line 2.
D. Compilation fails due to an error at line 5.
E. Compilation fails due to multiple errors.

A

Option D is the correct answer.

In given code, we have used _ and $ as field names. It is perfectly legal since we can use _ and $ for variable names and also can use them to start variable name. Hence, there is no compile-time error because of line 2.

However it is illegal to access a non-static variable in a static content, so at line 5 trying to access instance variable _ at line 5 result a compile-time error. So, option D is correct.

16
Q

What will be the output of this program?

import java.time.Period;

public class Whizlab{

public static void main(String [ ] args){
Period p1 = Period.ofYears(1);
Period p2 = Period.of(0, 1, 0);
Period p3 = p1.plus(p2);
System.out.println(p3.getDays());
}
}

Please select :
A. 397
B. 396 
C. 0
D. An Exception will be thrown.
E. Compilation fails.
A

Option C is the correct answer.

Period models a quantity or amount of time in terms of years, months and days. The getDays method returns only the amount which is in the day portion of the Period. Here first we created Period with one year and then added 1 month to it, so at the end, period contained one year and one month but zero days, hence option C is correct.

17
Q

What will be the output of this program?

1    import java.util.function.*;
2    public class Employee {
3             int id;
4             public static void main(String[] args) {
5                      Employee e = new Employee();
6                      e.id = 3;
7                      check(e, p -> p.id < 10);    
8             }
9             private static void check(Employee e, Predicate pr) {
10                    String result = pr.test(e) ? "match" : "not match";
11                    System.out.print(result);
12           }
13   }
Please select :
A. match
B. not match
C. Compiler error at line 7. 
D. Compiler error at line 10.
E. None of the above.
A

Option A is the correct answer.

This code compiles successfully. Line 7 creates a lambda expression that checks if the “id” is less than 10.
Since there is only one parameter and it does not specify a type, the parentheses around the type parameter are optional in the lambda expression at line 7.

Line 10 uses the Predicate interface, which has a test() method.
p.id<10 => 3<10 => true, so test method returns true.
The condition becomes true at line 10. So, “match” will be stored in the result.

Hence, option A is correct.

18
Q

Which of the following formatting string can be used to format date string to following format?

25 Dec 2015

Please select :
A. d MMM uuuu
B. dd M yy
C. dd MM uuuu
D. d MM yyyy
E. None of the above.
A

Option A is the correct answer.

According to the given format, we need to have a day, a three letter month followed by a full year. So for that, we need to use

uuuu - year (four u’s, we have to use since the year is in 4 digit format)

MMM – to present a month in the three-letter format.

d – for the day

19
Q

What will be the output of this program?

import java.time.LocalDate;
import java.time.temporal.ChronoField;

public class Whizlab{
                  public static void main(String[] args) {
                                LocalDate ld = LocalDate.of(2015, 12, 12);
                                ld = ld.with(ChronoField.DAY_OF_YEAR,30);
                                System.out.println(ld);
                  }   
}
Please select :
A. 2015-12-12
B. 2015-01-30
C. 2015-12-30
D. An Exception will be thrown.
E. Compilation fails
A

Option B is the correct answer.

With the method of the LocalDate class returns a copy of this date with the specified field set to a new value.

public LocalDate with(TemporalField field, long newValue)

So, here this will change the day to 30th day of the year so the month will also be changed since the 1/30 is the 30th day of the year result will be 2015-01-30; hence option B is correct.

20
Q

Given

import java.time.LocalTime;
import java.time.temporal.ChronoField;

public class Whizlab{
                  public static void main(String[] args) {
                                LocalTime lt = LocalTime.of(2,2,15);
                                System.out.println(lt.getLong(ChronoField.valueOf("MINUTE_OF_DAY")));
                  }   
} 

What is the output?

Please select :
A. 122
B. 842
C. 2
D. An Exception. 
E. Compilation fails.
A

Option A is the correct answer.

The getLong method of the LocalTime class returns the value of the specified field from this time as a long.

            public long getLong(TemporalField field)

This queries this time for the value of the specified field. If it is not possible to return the value, because the field is not supported or for some other reason, an exception is thrown.

So in this case it will be 2 hours and 2 minutes form the day started. So it will be converted in to minutes and return hence option A is correct.

21
Q

What will be the output of this program?

import java.util.ArrayList;
import java.util.List;

public class Whizlab{

            public static void main(String[] args){   
                            List list = new ArrayList();
                            list.add(“1”);
                            list.add(“2”);
                            list.add(“3”);
                            list.add(“4”);

                            System.out.println(list.set(3,”3”));
            } }
Please select :
A. 4
B. 3
C. -1
D. An Exception is thrown.
E. Compilation fails.
A

Option A is the correct answer.

We have used ArrayList class set method at line 13,

public E set(int index, E element)

This method replaces the element at the specified position in this list with the specified element and returns the element which is removed. So, in this case 4 will be returned since 4 is located in the position we are going to remove. So, option A is correct.

22
Q

What are the Java runtime (unchecked) exceptions?

A
ArithmeticException
//ArrayStoreException
ClassCastException
//EnumConstantNotPresentException
IllegalArgumentException
//IllegalThreadStateException
NumberFormatException
//IllegalMonitorStateException
IllegalStateException
IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
NegativeArraySizeException
NullPointerException
//SecurityException
//TypeNotPresentException
//UnsupportedOperationException
23
Q

What are checked exceptions used for?

A

represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)