Welcome to your Test - 1 Unique Test Code - 819

Name
Email
Phone
1.

Question:

A developer has written the following code snippet:

        Console c = System.console(); //1
        String line = c.readLine("Please enter your name:"); //2
        System.out.println("Hello, "+line); //3


Which of the following statements are true about this code if it is run in the background by a scheduler?

Select 1 option(s):
2.

Question:

Identify the correct statements about Java Stream API.

Select 1 option(s):
3.

Question:

Given:

List letters = Arrays.asList("j", "a", "v","a");


Which of the following code snippets will print JAVA?

Select 3 option(s):
4.

Question:

Which of the following correctly defines a method named stringProcessor that can be called by other programmers as follows: stringProcessor(str1) or stringProcessor(str1, str2) or stringProcessor(str1, str2, str3), where str1str2, and str3 are references to Strings.

Select 1 option(s):
5.

Question: What is wrong with the following code?

class MyException extends Exception {}
public class TestClass{
public static void main(String[] args){
TestClass tc = new TestClass();
try{
tc.m1();
}
catch (MyException e){
tc.m1();
}
finally{
tc.m2();
}
}
public void m1() throws MyException{
throw new MyException();
}
public void m2() throws RuntimeException{
throw new NullPointerException();
}
}

Select 1 option(s):

6.

Question:

Given:

public class Item{
        private String name;
        private String category;
        private double price;
        
        public Item(String name, String category, double price){
            this.name = name;
            this.category = category;
            this.price = price;
        }

       //accessors not shown
}

What will the following code print?

List<Item> items = Arrays.asList(
        new Item("Pen", "Stationery", 3.0),
        new Item("Pencil", "Stationery", 2.0),
        new Item("Eraser", "Stationery", 1.0),
        new Item("Milk", "Food", 2.0),
        new Item("Eggs", "Food", 3.0)
);

ToDoubleFunction<Item> priceF = Item::getPrice; //1

items.stream()
        .collect(Collectors.groupingBy(Item::getCategory)) //2
        .forEach((a, b)->{
            double av = b.stream().collect(Collectors.averagingDouble(priceF)); //3
            System.out.println(a+" : "+av);
        });


Select 1 option(s):
7.

Question: Which of the statements regarding the following code are correct?

public class TestClass{
   static int a;
   int b;
   public TestClass(){
      int c;
      c = a;
      a++;
      b += c;
   }
   public static void main(String args[]) {   new TestClass();   }
}

Select 1 option(s):
8.

Question: What will the following code print when compiled and run?

var numA = new Integer[]{1, 2};
var list1 = new ArrayList<Integer>(List.of(numA));
list1.add(null);
var list2 = Collections.unmodifiableList(list1);
list1.set(2, 3);
List<List<Integer>> list3 = List.of(list1, list2);
System.out.println(list3);

Select 1 option(s):
9.

Question:

Given the following module definitions:

module m${
   requires _n;
   exports o;
}

module _n{
   requires m$;
   exports p;
}

Identify the correct statements.

Select 1 option(s):
10.

Question: Which is the first line that will cause compilation to fail in the following program?

// Filename: A.java
class A{
public static void main(String args[]){
A a = new A();
B b = new B();
a = b; // 1
b = a; // 2
a = (B) b; // 3
b = (B) a; // 4
}
}
class B extends A { }

Select 1 option(s):

11.

Question: Which of the following are valid declarations inside the FooI interface?

interface AI{
   void moo();
}
interface FooI extends AI{
   //INSERT CODE HERE
}

Select 2 option(s):
12.

Question: What will the following code print when compiled and run?

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

    String s = "blooper";
    StringBuilder sb = new StringBuilder(s);
    s.append("whopper");
    sb.append("shopper");
    
    System.out.println(s);
    System.out.println(sb);
  }
}

Select 1 option(s):
13.

Question: Which of the following class definitions is/are legal definition(s) of a class that cannot be instantiated?

class Automobile{
abstract void honk(); //(1)
}
abstract class Automobile{
void honk(); //(2)
}
abstract class Automobile{
void honk(){}; //(3)
}
abstract class Automobile{
abstract void honk(){} //(4)
}
abstract class Automobile{
abstract void honk(); //(5)
}

Select 2 option(s):

14.

Question: What will the following class print when run?

public class Sample{
public static void main(String[] args) {
String s1 = new String("java");
StringBuilder s2 = new StringBuilder("java");
replaceString(s1);
replaceStringBuilder(s2);
System.out.println(s1 + s2);
}
static void replaceString(String s) {
s = s.replace('j', 'l');
}
static void replaceStringBuilder(StringBuilder s) {
s.append("c");
}
}

Select 1 option(s):

15.

Question:

Identify correct statements about java.io.Console class?

Select 1 option(s):
16.

Question: What will the following code print when run?

public class Test {

    static String s = "";

    public static void m0(int a, int b) {
        s += a;
        m2();
        m1(b);
    }

    public static void m1(int i) {
        s += i;
    }

    public static void m2() {
        throw new NullPointerException("aa");
    }

    public static void m() {
        m0(1, 2);
        m1(3);
    }

    public static void main(String args[]) {
        try {
            m();
        } catch (Exception e) {
        }
        System.out.println(s);
    }
}

Select 1 option(s):
17.

Question:

Identify the valid enum declarations.

Select 2 option(s):
18.

Question:

Consider following classes:

//In File Other.java
package other;
public class Other { public static String hello = "Hello"; }
//In File Test.java
package testPackage;
import other.*;
class Test{
public static void main(String[] args){
String hello = "Hello", lo = "lo";
System.out.print((testPackage.Other.hello == hello) + " "); //line 1 System.out.print((other.Other.hello == hello) + " "); //line 2
System.out.print((hello == ("Hel"+"lo")) + " "); //line 3
System.out.print((hello == ("Hel"+lo)) + " "); //line 4
System.out.println(hello == ("Hel"+lo).intern()); //line 5
}
}
class Other { static String hello = "Hello"; }

What will be the output of running class Test?

Select 1 option(s):
19.

Question:

Given the following code :

public class TestClass {
int[][] matrix = new int[2][3];
var a = new int[]{1, 2, 3};
var b = new int[]{4, 5, 6};
public int compute(int x, int y){ //
1 : Insert Line of Code here
}
public void loadMatrix(){
for(int x=0; x<matrix.length; x++){
for(int y=0; y<matrix[x].length; y++){
//2: Insert Line of Code here
}
}
}
}

What can be inserted at //1 and //2?

Select 1 option(s):
20.

Question:

For what command line arguments will the following program print true?

class TestClass{
public static void main(String[] args){
Integer i = Integer.parseInt(args[0]);
Integer j = i;
i--;
i++;
System.out.println((i==j));
}
}

Select 3 option(s):

21.

Question: What will the following program print when compiled and run:

public class TestClass {
    public static void main(String[] args) {
            someMethod();
    }
    
    static void someMethod(Object parameter)  {
          System.out.println("Value is "+parameter);
    }
}

Select 1 option(s):
22.

Question: What will the following code print when compiled and run?

        String val1 = "hello";
        StringBuilder val2 = new StringBuilder("world");
        UnaryOperator<String> uo1 = s1->s1.concat(val1); //1
        UnaryOperator<String> uo2 = s->s.toUpperCase(); //2
        System.out.println(uo1.apply(uo2.apply(val2))); //3

Select 1 option(s):
23.

Question:

Given:

   Character[] ca = { 'b', 'c', 'a', 'e', 'd' };
   List<Character> l = Arrays.asList(ca);
   l.parallelStream().peek(System.out::print).forEachOrdered(System.out::print);

Identify the correct statement about the above code.

Select 1 option(s):
24.

Question:

Assuming that the directory /works/ocpjp/code exists but /works/ocpjp/code/sample does not exist, what will the following code output?

        Path d1 = Paths.get("/works");
        Path d2 = d1.resolve("ocpjp/code"); //1
        d1.resolve("ocpjp/code/sample");  //2
        d1.toAbsolutePath(); //3
        System.out.println(d1);
        System.out.println(d2);


Select 1 option(s):
25.

Question:

Consider the following code :

import java.util.*;
class Request { }
class RequestCollector{
    //1 : Insert declaration here
    
    public synchronized void addRequest(Request r){
    container.add(r);
    }
    public synchronized Request getRequestToProcess(){
    return container.poll();
    }
}


What can be inserted at //1?

Select 1 option(s):
26.

Question: What will the following code print when compiled and run?

public class Data{
    int value;
    Data(int value){
        this.value = value;
    }
    public String toString(){ return ""+value; }
    
    public static void main(String[] args) {
        Data[] dataArr = new Data[]{ new Data(1), new Data(2), new Data(3), new Data(4) };

        List<Data> dataList = Arrays.asList(dataArr); //1

        for(Data element :  dataList){

            dataList.removeIf( (Data d) -> { return d.value%2 ==  0; } );  //2

            System.out.println("Removed "+d+", "); //3
        }
   }      
}

Select 1 option(s):
27.

Question:

Identify the correct statement(s).

Select 2 option(s):
28.

Question: Java's Exception mechanism helps in which of the following ways?

Select 2 option(s):
29.

Question: What can be inserted in the following code so that it will print exactly 2345 when compiled and run?

public class FlowTest {

    static int[] data = {1, 2, 3, 4, 5};

    public static void main(String[] args) {
        for (var i : data) {
            if (i < 2) {
                //insert code1 here
            }
            System.out.print(i);
            if (i == 3) {
                //insert code2 here
            }
        }
    }
}

Select 2 option(s):
30.

Question:

You want to invoke the overridden method (the method in the base class) from the overriding method (the method in the derived class) named m().

Which of the following constructs which will let you do that?

Select 1 option(s):
31.

Question: Which lines contain a valid constructor in the following code?

public class TestClass{
public TestClass(int a, int b) { } // 1
public void TestClass(int a) { } // 2
public TestClass(String s); // 3
private TestClass(String s, int a) { } //4
public TestClass(String s1, String s2) { }; //5
}

Select 3 option(s):

32.

Question:

Identify correct statements about the module system of Java.

Select 3 option(s):
33.

Question: Which of the following declarations is equivalent to var  b = 10>11;.

Select 2 option(s):
34.

Question;

Given:

public class PlaceHolder<K, V> { //1
    private K k;
    private V v;
    public PlaceHolder(K k, V v){ //2
        this.k = k;
        this.v = v;
    }
    public K getK() { return k; }
    public static <X> PlaceHolder<X, X> getDuplicateHolder(X x){ //3
        return new PlaceHolder<X, X>(x, x); //4
    }
}

Which line will cause compilation failure?

Select 1 option(s):
35.

Question:

Given:

package strings;
public class StringFromChar {
    
    public static void main(String[] args) {
        String myStr = "good";
        char[] myCharArr = {'g', 'o', 'o', 'd' };
        
        String newStr = "";
        for(char ch : myCharArr){
            newStr = newStr + ch;
        }
        boolean b1 = newStr == myStr;
        boolean b2 = newStr.equals(myStr);
        
        System.out.println(b1+ " " + b2);
        
    }
}


What will it print when compiled and run?

Select 1 option(s):
36.

Question:

Identify the correct statements about the following code:

import java.util.*;
class Person {
    private static int count = 0;
    private String id = "0"; private String interest;
    public Person(String interest){ this.interest = interest; this.id = "" + ++count; }
    public String getInterest(){ return interest;     }
    public void setInterest(String interest){ this.interest = interest; }
    public String toString(){ return id; }
}

public class StudyGroup
{
    String name = "MATH";
    TreeSet<Person> set = new TreeSet<Person>();
    public void add(Person p) {
      if(name.equals(p.getInterest())) set.add(p);
    }

    public static void main(String[] args) {
      StudyGroup mathGroup = new StudyGroup();
      mathGroup.add(new Person("MATH"));
      System.out.println("A");
      mathGroup.add(new Person("MATH"));
      System.out.println("B");
      System.out.println(mathGroup.set);
    }
}


Select 1 option(s):
37.

Question:

Given:

class Base{
    public <T> List<T> transform(List<T> list)
    {
        return new ArrayList<T>();
    }
}

class Derived extends Base{
      *INSERT CODE HERE*
}


What can be inserted in the above code?

Select 2 option(s):
38.

Question: Which of the following method(s) of java.util.stream.Stream interface is/are used for reduction?

Select 2 option(s):
39.

Question: What should be placed in the two blanks so that the following code will compile without errors:

class XXX{
    public void m() {
        throw new RuntimeException();
    }
}
class YYY extends XXX{
    public void m() throws Exception{
      throw new Exception();
    }
}
public class TestClass {
    public static void main(String[] args) {
        ______ obj = new ______();
        obj.m();
    }
}

Select 1 option(s):
40.

Question" What will the following code print?

List<Integer> ls = Arrays.asList(1, 2, 3);

Function<Integer, Integer> func = a->a*a; //1

ls.stream().map(func).peek(System.out::print); //2

Select 1 option(s):
41.

Question:

Identify the correct statements about ArrayList?

Select 3 option(s):
42.

Question: What is wrong with the following code written in a single file named TestClass.java?

class SomeThrowable extends Throwable { }
class MyThrowable extends SomeThrowable { }
public class TestClass{
   public static void main(String args[]) throws SomeThrowable{
      try{
         m1();
      }catch(SomeThrowable e){
         throw e;
      }finally{
         System.out.println("Done");
      }
   }
   public static void m1() throws MyThrowable{
      throw new MyThrowable();
   }
}

Select 1 option(s):
43.

Question: Which of the following statements regarding java.util.HashSet is correct?

Select 1 option(s):
44.

Question: What will be the result of attempting to compile and run the following code?

class SwitchTest{
   public static void main(String args[]){
      for ( var i = 0 ; i < 3 ; i++){ //1
         var flag  = false;
         switch (i){ //2
            flag  = true; //3
         }
         if ( flag )  System.out.println( i );
      }
   }
}

Select 1 option(s):
45.

Question: What will the following code print?

        int[] ia1 = { 0, 1, 4, 5};
        int[] ia2 = { 0, 1, 1, 5, 6};
        
        int x = Arrays.compare(ia1, ia2);
        int y = Arrays.mismatch(ia1, ia2);
        System.out.println(x+" "+y);

Select 1 option(s):
46.

Question:

Given:

public class Book {
   private String title;
   private String genre;
   public Book(String title, String genre){
        this.title = title; this.genre = genre;
   }
   //accessors not shown
}

and the following code:

List<Book> books = Arrays.asList(
        new Book("Gone with the wind", "Fiction"),
        new Book("Bourne Ultimatum", "Thriller"),
        new Book("The Client", "Thriller")
);

Reader r = b->{
    System.out.println("Reading book "+b.getTitle());  
};
books.forEach(x->r.read(x));

What would be a valid definition of Reader for the above code to compile and run without any error or exception?

Select 2 option(s):
47.

Question: What will the following code print?

AtomicInteger ai = new AtomicInteger();
Stream<Integer> stream = Stream.of(11, 11, 22, 33).parallel();
stream.filter( e->{
    ai.incrementAndGet();
    return e%2==0;
});
System.out.println(ai);

Select 1 option(s):
48.

Question: What will be printed when the following code is compiled and run?

package trywithresources;

import java.io.IOException;

public class Device implements AutoCloseable{
    String header = null;
    public void open(){
        header = "OPENED";
        System.out.println("Device Opened");
    }
    public String read() throws IOException{
        throw new IOException("Unknown");
    }
    
    public void writeHeader(String str) throws IOException{
        System.out.println("Writing : "+str);
        header = str;
    }
    public void close(){
        header = null;
        System.out.println("Device closed");
    }
    
    public static void testDevice(){
        try(Device d = new Device()){
            d.open();
            d.writeHeader("TEST");
            d.close();
        }catch(IOException e){
            System.out.println("Got Exception");
        }
    }
    public static void main(String[] args) {
        Device.testDevice();
    }
    
}

Select 1 option(s):
49.

Question:

Consider the following class...

public class ParamTest {
  public static void printSum(int a, int b){
      System.out.println("In int "+(a+b));
  }
  
  public static void printSum(Integer a, Integer b){
      System.out.println("In Integer "+(a+b));
  }
  
  public static void printSum(double a, double b){
      System.out.println("In double "+(a+b));
  }
  
  public static void main(String[] args) {
      printSum(1, 2);
  }
}

What will be printed?

Select 1 option(s):
50.

Question:

Consider the following method:

    static int mx(int s){
        for(int i=0; i<3; i++){
            s = s + i;
        }
        return s;
    }


and the following code snippet:

   int s = 5;
        s += s + mx(s) + ++s;
        System.out.println(s);


What will it print?

Select 1 option(s):
51.

Question:

A user thread of a GUI application needs to perform certain security sensitve operations upon receiving system events. For this purpose, a call back handler has been registered with the system by the user thread based upon inputs from the GUI. The operations should be executed only if the user has appropriate permissions as per the security policy.

The following code shows the call back handler:

public class ProtectedCallbackHandler implements Runnable{
    final String action;
    public ProtectedCallbackHandler(String action){
        this.action = action;
    }
    public void run(){
    AccessController.doPrivileged(
        new PrivilegedAction<Void>() {
            public Void run() {
                //Do sensitive operations based upon action value
                return null;
            }
        });            
    }
}


Identify correct statements.

Select 1 option(s):
52.

Question: What will the following code print when run?

  LocalDate d = LocalDate.now();
  DateFormat df = new DateFormat(DateFormat.LONG);
  System.out.println(df.format(d));

Select 1 option(s):
53.

Question:

Consider the following code:

class MyClass { }
public class TestClass{
   MyClass getMyClassObject(){
      MyClass mc = new MyClass(); //1
         return mc; //2
   }
   public static void main(String[] args){
      TestClass tc = new TestClass(); //3
      MyClass x = tc.getMyClassObject(); //4
      System.out.println("got myclass object"); //5
      x = new MyClass(); //6
      System.out.println("done"); //7
   }
}


After what line the MyClass object created at line 1 will be eligible for garbage collection?

Select 1 option(s):
54.

Question:

Given:

Locale locale = new Locale("en", "US");
ResourceBundle rb = ResourceBundle.getBundle("test.MyBundle", locale);


Which of the following are valid lines of code?

(Assume that the ResourceBundle has the values for the given keys.)

Select 2 option(s):
55.

Question:

Consider the following code:

public class Student {
private Map<String, Integer> marksObtained = new HashMap<String, Integer>();
private ReadWriteLock lock = new ReentrantReadWriteLock();
public void setMarksInSubject(String subject, Integer marks){
// valid code to set marks for a given subject
}
public double getAverageMarks(){
//1 - INSERT CODE HERE
var sum = 0.0;
try{
for(Integer mark : marksObtained.values()){
sum = sum + mark;
}
return sum/marksObtained.size();
}
finally{
//2 - INSERT CODE HERE
}
}
}

What should be inserted at //1 and //2?

Select 1 option(s):
56.

Question:

Given:

public class Book {
   private String title;
   private LocalDate releaseDate;
   public Book(String title, LocalDate releaseDate){
        this.title = title; this.releaseDate = releaseDate;
   }
   //accessors not shown
}

and the following code:

var books = new ArrayList<Book>(List.of(new Book("The Outsider", LocalDate.of(2019, 1, 1)),
        new Book("Becoming", LocalDate.of(2018, 1, 1)),new Book("Uri", LocalDate.of(2017, 1, 1))));

Predicate<Book> p = b->b.getReleaseDate().isAfter(IsoChronology.INSTANCE.date(2018, 1, 1));

Set<String> newBooks = books.stream().
     INSERT CODE HERE

What can be inserted in the code above so that newBooks will be assigned a set of books that were released after the date indicated by the predicate p?

Select 3 option(s):
57.

Question: What will the following code print when compiled and run?

var tickers = List.of("A", "D", "E", "C", "A");
var ratio = List.of(1.0, 1.2, 1.5, 1.8, 2.0);
var map1 = IntStream.range(0, tickers.size())
        .boxed()
        .collect(Collectors.toMap(
                i -> tickers.get(i),
                i -> 1.0/ratio.get(i), (x, y) -> x+y)) ;  //<<----- LINE 1

var map2 = map1.entrySet().stream().sorted(Map.Entry.comparingByKey())
        .collect(
            Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (x, y) -> x-y,
                LinkedHashMap::new)
        );  //<<----- LINE 2

map2.forEach((var k, var v)->System.out.printf("%s = %.2f\n",k, v));

Select 1 option(s):