Welcome to your Test - 2 Unique Test Code - 819

Name
Email
Phone
1.

Question:

You are creating an acme.db module. This module contains a com.acme.DB class that will be used by other modules of your application. Which of the following files correctly defines the acme.db module?

Select 1 option(s):
2.

Question: Which of the following code fragments is/are appropriate usage(s) of generics?

Select 2 option(s):
3.

Question: Which of the following options correctly create an ExecutorService instance?

Select 1 option(s):
4.

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

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

        System.out.println(getMsg((char)10));

    }

    public static String getMsg(char x){
        String msg = "Input value must be ";
        msg = msg.concat("smaller than X");
        msg.replace('X', x);
        String rest = " and larger than 0";
        msg.concat(rest);
        return msg;
    }
}

Select 1 option(s):
5.

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

class Game{
public void play() throws Exception{
System.out.println("Playing...");
}
}
public class Soccer extends Game{
public void play(){
System.out.println("Playing Soccer...");
}
public static void main(String[] args){
Game g = new Soccer();
g.play();
}
}

Select 1 option(s):

6.

Question:

How will you initialize a SimpleDateFormat object so that the following code will print the full text time zone of the given date?

    System.out.println(sdf.format(new Date()));


Select 1 option(s):
7.

Question:

A java source file contains the following code:

interface I {
int getI(int a, int b);
}
interface J{
int getJ(int a, int b, int c);
}
abstract class MyIJ implements J , I { }
class MyI{
int getI(int x, int y){ return x+y; }
}
interface K extends J{
int getJ(int a, int b, int c, int d);
}

Identify the correct statements:

Select 1 option(s):
8.

Question: Which of the following commands can be used to run a class named com.foo.Bar, which is part of a module named foo.bar packaged in foobar.jar

(Assume that the jar file is located in the current directory.)

Select 1 option(s):
9.

Question:

Checked exceptions are meant for...

Select 1 option(s):
10.

Question: Which of the given statements are correct for a method that overrides the following method:

public Set getSet(int a) {...}

Assume that Set is an interface and HashSet is a class that implements Set.

Select 3 option(s):
11.

Question: What will the following code print?

public class Test{
    public static void stringTest(String s){
        s.replace('h', 's');
    }
    public static void stringBuilderTest(StringBuilder s){
        s.append("o");
    }
    public static void main(String[] args){
        String s = "hell";
        StringBuilder sb = new StringBuilder("well");
        stringTest(s);
        stringBuilderTest(sb);
        System.out.println(s + sb);
    }
}

Select 1 option(s):
12.

Question:

Given :

//1
public class TestClass {
//2
   public static void main(String... args) throws Exception{
        List al = new ArrayList();
        printElements(al);
   }

//3
    static void printElements(List... la) {
       for(List l : la){
           System.out.println(l);
       }
    }
}


Which option will get rid of compilation warnings for the above code?

Select 1 option(s):
13.

Question:

Consider the following program :

class Test{
  public static void main(String[] args){
    short s = 10;   // 1
    char c = s;     // 2
    s = c;          // 3
  }
}


Identify the correct statements.

Select 2 option(s):
14.

Question:

Identify correct statements regarding Java module system.

Select 1 option(s):
15.

Question: What can be inserted in the code below so that it will print true when run?

public class TestClass{

   public static boolean checkList(List list, Predicate<List> p){
      return p.test(list);
   }
  
   public static void main(String[] args) {
      boolean b = //WRITE CODE HERE
      System.out.println(b);
   }
}


Select 2 option(s):
16.

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

public class TestClass{
  public static void main(String args[ ] ){
    Object a, b, c ;
    a = new String("A");
    b = new String("B");
    c = a;
    a = b;
    System.out.println(""+c);
  }
}

Select 1 option(s):
17.

Question:

Given the following class:

public class SpecialPicker<K>{
   public K pickOne(K k1, K k2){
     return k1.hashCode()>k2.hashCode()?k1:k2;
   }    
}

what will be the result of running the following lines of code:

  SpecialPicker<Integer> sp = new SpecialPicker<>(); //1
  System.out.println(sp.pickOne(1, 2).intValue()+1); //2


Select 1 option(s):
18.

Question:

Given the following class:

public class Food{  // LINE 1
  String name;
  int caloriesPerServing;
  public Food(String name, int calories){
    this.name = name; this.caloriesPerServing = calories;
  }
  //accessors not shown

  //LINE 2
}

This class is used in an application as follows -

ArrayList<Food> al = new ArrayList<>();
//code that adds Food objects to al not shown
Collections.sort(al);

What changes must be done to Food class so that the call to Collections.sort(al) will work as expected?

Select 2 option(s):
19.

Question: What will the following code print?

   var flag = true;
   if(flag = false){
      System.out.println("1");
   }else if(flag){
      System.out.println("2");
   }else if(!flag){
      System.out.println("3");
   }else    System.out.println("4");

Select 1 option(s):
20.

Question; What will the following code print?

List s1 = new ArrayList( );
s1.add("a");
s1.add("b");
s1.add("c");
s1.add("a");
if(s1.remove("a")){
    if(s1.remove("a")){
        s1.remove("b");
    }else{
        s1.remove("c");
    }
}
System.out.println(s1);

Select 1 option(s):
21.

Question:

You are writing a class named Bandwidth for an internet service provider that keeps track of number of bytes consumed by a user. The following code illustrates the expected usage of this class -

class User{
    Bandwidth bw = new Bandwidth();
    
    public void consume(int bytesUsed){
        bw.addUsage(bytesUsed);
    }
   ... other irrelevant code    
}

class Bandwidth{
    private int totalUsage;
    private double totalBill;
    private double costPerByte;
    
   
    //add your code here

    ...other irrelevant code
}

Your goal is to implement a method addUsage (and other methods, if required) in Bandwidth class such that all the bandwidth used by a User is reflected by the totalUsage field and totalBill is always equal to totalUsage*costPerByte. Further, that a User should not be able to tamper with the totalBill value and is also not able to reduce it.

Which of the following implementation(s) accomplishes the above?

Select 1 option(s):
22.

Question:

Assuming that STOCK table exists and is empty, what will the following code snippet print?

String qr = "insert into STOCK ( ID, TICKER, LTP, EXCHANGE ) values( ?, ?, ?, ?)";
try(PreparedStatement ps =  c.prepareStatement(qr);)
{
    ps.setInt(1, 111);
    ps.setString(2, "APPL");
    ps.setDouble(3, 0.0);
    ps.setString(4, "NYSE");
    int i = ps.executeUpdate();  //1
    System.out.println(i);
}


Select 1 option(s):
23.

Question:

Given the following code, which of the constructors shown in the options can be added to class B without causing a compilation to fail (independent of each other)?

class A{
int i;
public A(int x) { this.i = x; }
}
class B extends A{
int j;
public B(int x, int y) { super(x); this.j = y; }
}

Select 2 option(s):

24.

Question:

Given the following code:

interface Movable{
   int offset = 100;
   public void move(int dx);
}
interface Growable{
  public void grow(int dy);
}

class Animal implements Movable, Growable{
   public void move(int dx){ }
   public void grow(int dy){ }
}


Select 1 option(s):
25.

Question: What will the following program print?

class Test{
public static void main(String args[]){
int var = 20, i=0;
do{
while(true){
if( i++ > var) break;
}
}while(i<var--);
System.out.println(var);
}
}

Select 1 option(s):

26.

Question:

A novice java programmer is unable to get a file named Coffee.java compiled. It contains the following enum definition:

public enum Coffee  //1
{
    ESPRESSO("Very Strong"), MOCHA, LATTE; //2
    public String strength; //3
    Coffee(String strength) //4
    {
         this.strength = strength; //5
    }
    public String toString(){   return strength; } //6
}


Which line is causing the problem?

Select 1 option(s):
27.

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

public class TestClass{
   public static void main(String args[ ] ){
      A o1 = new C( );
      B o2 = (B) o1;
      System.out.println(o1.m1( ) );
      System.out.println(o2.i );
   }
}
class A { int i = 10;  int m1( ) { return i; } }
class B extends A { int i = 20;  int m1() { return i; } }
class C extends B { int i = 30;  int m1() { return i; } }

Select 1 option(s):
28.

Question: What will be the result of compilation and execution of the following code ?

IntStream is1 = IntStream.range(0, 5); //1
OptionalDouble x = is1.average(); //2
System.out.println(x); //3

Select 1 option(s):
29.

Question:

Given :

PERSON table in the database with the following data:

ID(int)  NAME(varchar)   TAXID(varchar)
--------------------
1   Ally   111
2   Bob  222

and the following code:

        Connection c = ds.getConnection(); //assume that ds refers to a DataSource
        Statement stmt = c.createStatement();
        String qr = "select * from PERSON";
        try(ResultSet rs = stmt.executeQuery(qr);
            PreparedStatement ps1 = c.prepareStatement("update PERSON set taxid = 'NNNN' where id=?");
           )
        {
            while(rs.next()){
                int id = rs.getInt(1);
                ps1.setInt(1, id);
                ps1.executeUpdate(); //1
                System.out.println("Updated "+rs.getString(3)); //2
            }
        }

Identify correct statements.

Select 2 option(s):
30.

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

class TestClass{
public static void main(String args[]){
int i = 0;
loop : // 1
{
System.out.println("Loop Lable line");
try{
for ( ; true ; i++ ){
if( i >5) break loop;
// 2
}
}
catch(Exception e){
System.out.println("Exception in loop.");
}
finally{
System.out.println("In Finally"); // 3
}
}
}
}

Select 1 option(s):

31.

Question:

Given the class

// Filename: Test.java
public class Test{
public static void main(String args[]){
for(int i = 0; i< args.length; i++){
System.out.print(" "+args[i]);
}
}
}

Now consider the following 3 options for running the program:

a: java Test
b: java Test param1
c: java Test param1 param2

Which of the following statements are true?

Select 2 option(s):
32.

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

package trywithresources;

import java.io.IOException;

public class Device{
    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.read();
            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):
33.

Question: What two changes can you do, independent of each other, to make the following code compile:

//assume appropriate imports
class PortConnector {

    public PortConnector(int port) {
        if (Math.random() > 0.5) { //assume that random() returns a random value between 0.0 and 1.0)
            throw new IOException();
        }

        throw new RuntimeException();
    }
}


public class TestClass {

    public static void main(String[] args) {
        try {
            PortConnector pc = new PortConnector(10);
        } catch (RuntimeException re) {
            re.printStackTrace();
        }
    }
}

Select 2 option(s):
34.

Question: What will the following code print?


List<String> names = Arrays.asList("Peter", "Paul", "Pascal");
Optional<String> ops = names.stream()
                .parallel()
                .allMatch(name->name!=null)
                .filter(name->name.length()>6)
                .findAny();
System.out.println(ops);

Select 1 option(s):
35.

Question: Which of the following statements will compile without any error?

Select 4 option(s):
36.

Question: What will the following program print?

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

Select 1 option(s):

37.

Question:

Identify valid methods:

Assume that Shape is a valid non-final class.

Select 2 option(s):
38.

Question: What will be the output when the following program is run?

package exceptions;
public class TestClass{
public static void main(String[] args) {
try{
hello();
}
catch(MyException me){
System.out.println(me);
}
}
static void hello() throws MyException{
int[] dear = new int[7];
dear[0] = 747;
foo();
}
static void foo() throws MyException{
throw new MyException("Exception from foo");
}
}
class MyException extends Exception {
public MyException(String msg){
super(msg);
}
}

(Assume that line numbers printed in the messages given below are correct.)

Select 1 option(s):
39.

Question: What is the effect of compiling and running the code shown in exhibit?

public class TestClass{
public static void main (String args []){
var sum = 0;
for (int i = 0, j = 10; sum > 20; ++i, --j) // 1
{
sum = sum+ i + j;
}
System.out.println("Sum = " + sum);
}
}

Select 1 option(s):

40.

Question: What will the following program print?

public class TestClass{
static boolean b;
static int[] ia = new int[1];
static char ch;
static boolean[] ba = new boolean[1];
public static void main(String args[]) throws Exception{
var x = false;
if( b ){
x = ( ch == ia[ch]);
}
else x = ( ba[ch] = b );
System.out.println(x+" "+ba[ch]);
}
}

Select 1 option(s):

41.

Question:

Given that a class named mywids.Widget is part of a module named mod.wids packaged in mywidgets.jar, which of the following commands can be used to execute this class?

(Assume that the jar file is located in the current directory and the jar file does not have any entry in its manifest.)

Select 1 option(s):
42.

Question: What will be the output of the following lines ?

System.out.println("" +5 + 6);   //1
System.out.println(5 + "" +6);   // 2
System.out.println(5 + 6 +"");   // 3
System.out.println(5 + 6);       // 4

Select 1 option(s):
43.

Question:

Given:

interface Carnivore{
    default int calories(List<String> food){
        return food.size()*100;
    }
    int eat(List<String> foods);
}
class Tiger implements Carnivore{
    public int eat(List<String> foods){
        System.out.println("Eating "+foods);
        return foods.size()*200;
    }
}
public class TestClass {
    public static int size(List<String> names){
        return names.size()*2;
    }
    public static void process(List<String> names, Carnivore c){
        c.eat(names);
    }
    
    public static void main(String[] args) {
        List<String> fnames = Arrays.asList("a", "b", "c");
        Tiger t = new Tiger();

        INSERT CODE HERE

   }
}

Which of the following options can be inserted independent of each other in the code above without any compilation error?

Select 3 option(s):
44.

Question:

Identify valid for loop constructs:

Select 3 option(s):
45.

Question:

Given:

class A{
  public List<? super Integer> getList(){
      //valid code
  };
}
class B extends A{
  @Override
  *INSERT CODE HERE*
      //valid code
  };
}

What can be inserted in the above code?

Select 3 option(s):
46.

Question:

Given the following classes and declarations, which of these statements about //1 and //2 are true?

class A{
private int i = 10;
public void f(){}
public void g(){}
}
class B extends A{
public int i = 20;
public void g(){}
}
public class C{
A a = new A();//1
A b = new B();//2
}

Select 1 option(s):

47.

Question:

Given:

class Book{
    private String title;
    private double price;
    public Book(String title, double price){
        this.title = title;
        this.price = price;
    }
    //getters/setters not shown
}

What will the following code print?

List<Book> books = Arrays.asList(new Book("Thinking in Java", 30.0),
                                 new Book("Java in 24 hrs", 20.0),
                                 new Book("Java Recipies", 10.0));
double averagePrice = books.stream().filter(b->b.getPrice()>10)
        .mapToDouble(b->b.getPrice())
        .average().getAsDouble();
System.out.println(averagePrice);


Select 1 option(s):
48.

Question:

Given:

var data = new ArrayList<>();
data.add("A");
data.add(100); //1
data.add("C");
data.set(0, 200); //2
data.remove(2); //3
data.set(2, 101L);//4
System.out.println(data);

What will be the output?

Select 1 option(s):
49.

Question:

You have created a module named mycompany.smartschool packaged in smartschool.jar. This module uses a third party non-modular java library packaged as utils.jar.

How will you execute your module's main class named mycompany.smartschool.Main?

(Assume that the jar files are located in the current directory.)

Select 1 option(s):
50.

Question:

Consider these two interfaces:

interface I1
{
   void m1() throws java.io.IOException;
}
interface I2
{
   void m1() throws java.sql.SQLException;
}


What methods have to be implemented by a class that says it implements I1 and I2 ?

Select 1 option(s):
51.

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

public class TestClass {
    
    public static void main(String[] args){
        while(var k = 5; k<7){
            System.out.println(k++);
        }
    }
}

Select 1 option(s):
52.

Question:

Given:

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

        List<Integer> list = new CopyOnWriteArrayList<>();
        ExecutorService es = Executors.newFixedThreadPool(5);
        CyclicBarrier cb = new CyclicBarrier(2, ()->System.out.print("All Done"));

        IntStream.range(0, 5).forEach(n->es.execute(
                ()->{
                    try{
                        list.add(n);
                        cb.await();
                    }catch(InterruptedException|BrokenBarrierException e){
                        System.out.println("Exception");
                    }
                }
        ));
        es.shutdown();
   }
}

What will the above program print?

Select 2 option(s):
53.

Question:

NOTE: Although CallableStatement is not mentioned explicitly in the exam objectives, some candidates has reported getting a question on it.

What should be inserted in the following code so that it works as expected?


String token = "xyz";
String output = null;
String processedValueCall = "{call reconciler(?,?)}";
CallableStatement callableStatement = dbConnection.prepareCall(processedValueCall);

*INSERT CODE HERE*

callableStatement.executeUpdate();
String value = callableStatement.getString(2);

Assume that the token variable is the first parameter to be passed.

Select 1 option(s):
54.

Question: Which of the following is illegal ?

Select 1 option(s):
55.

Question:

Complete the following code by filling the two blanks -

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

Select 1 option(s):
56.

Question:

Given:

//using title, price constructor to create Book instances
var books = List.of(new Book("The Outsider", 2.99), new Book("Where the Crawdads Sing", 4.99 ),
        new Book("Elevation", 2.99), new Book("Coffin from Hong Kong", 1.99) );
Stream<Book> bkStrm = books.stream();//

double total = bkStrm.map(b->b.getPrice()).reduce(0.0, (a, b)->{ return a+b;}); //1

Assuming appropriate constructor and methods, which of the following options are equivalent to the statement at //1 of the above code?

Select 1 option(s):
57.

Question:

Given the following code:

class TestClass{
   public static void main(String args[]){
      java.sql.Timestamp ts = new java.sql.Timestamp(1);
      java.awt.Label lb = new java.awt.Label("Time is "+ts);
      System.out.println(lb);
   }
}

and the following commands:

javac TestClass.java
jdeps -summary TestClass.java

What will be the output?

Select 1 option(s):