Welcome to your Test - 2 Code - 819

Name
Email
Phone
1.

Question:

Given:

abstract class AmazingClass{
    void amazingMethod(Collection c){
        System.out.println("Got collection");
    };
}

public class SpecialAmazingClass extends AmazingClass{
    void amazingMethod(List l){
        System.out.println("Got list");
    };
    
    public static void main(String[] args) {
        List<String> al = new ArrayList<String>();
        Collection<String> c = al;
        AmazingClass ac = new SpecialAmazingClass();
        ac.amazingMethod(c);
    }
}


What is the output?

Select 1 option(s):
2.

Question: What will the following code print?

        String examName = "OCP Java 11";
        String uniqueExamName = new String(examName);
        String internedExamName = uniqueExamName.intern();
        System.out.println(
                (examName==uniqueExamName)+" "+
                (examName == internedExamName)+" "+
                (uniqueExamName == internedExamName) );

Select 1 option(s):
3.

Question:

How will you initialize a DateTimeFormatter object so that the following code will print the number of the month (i.e. 02 for Feb, 12 for Dec, and so on) and a two digit calendar year of any given date?

    System.out.println(dtf.format(LocalDate.now()));\

Select 1 option(s):
4.

Question:

Consider the following class:

public class Student implements Serializable{
    public static final long serialVersionUID = 1;
    public String name;
    public String grade;
    public String toString(){ return "["+name+", "+grade+"]"; }
}


An object of this class was created as follows and was serialized to a file c:\temp\bob.ser:
        Student s = new Student();
        s.name = "bob";
        s.grade = "10";

After some time the Student class was changed as follows:
public class Student implements Serializable{
    public static final long serialVersionUID = 1;
    public String id="S111";
    public String name;
    public String grade;
    public int age=15;
    public String toString(){ return "["+id+", "+name+", "+grade+", "+age+"]"; }
}

Now, the serialized file is read back as follows:
   FileInputStream fis = new FileInputStream("c:\\temp\\bob.ser");
   ObjectInputStream is = new ObjectInputStream(fis);
   s = (Student) is.readObject();
   is.close();            
   System.out.println("Loaded "+s);


What will it print?

Select 1 option(s):
5.

Question:

Given the following contents of module-info.java,

module enthu.finance{
  exports com.enthu.Reports to com.enthu.tax;
  requires transitive enthu.utils;
}


Select 1 option(s):
6.

Question: Which of the following are benefits of ArrayList over an array?

Select 1 option(s):
7.

Question: What will the following code print?

var a = new int[]{ 1, 2, 3, 4, 5};
var b = new int[]{ 1, 2, 3, 4, 5, 3};
var c = new int[]{ 1, 2, 3, 4, 5, 6};
        
int x = Arrays.compare(a, c);
int y = Arrays.compare(b, c);
System.out.println(x+" "+y);


Select 1 option(s):
8.

Question: What changes can be done to the following code so that it will compile and run without an exception?

List<String> keys = List.of("a");  //1
keys.add("b"); //2

Map<String, String> map = Map.of(); //3

int i = 0;
for(var key : keys){
    map.put(key, "----");
}
System.out.println(keys+" "+map.size());

Select 1 option(s):
9.

Question:

Identify correct statements about Java platform module system.

Select 2 option(s):
10.

Question:

Which of the given options if put at //1 will correctly instantiate objects of various classes defined in the following code?


public class TestClass
{
   public class A{
   }
   public static class B {
   }
   public static void main(String args[]){
      class C{
      }
      //1
   }
}


Select 2 option(s):
11.

Question:

Given:

@Retention(value=RUNTIME)
@Target(value={TYPE_USE,TYPE_PARAMETER})
public @interface NonNull{    
}


Identify correct usages.

Select 2 option(s):
12.

Question: Which of the following are valid code snippets appearing in a method:

Select 3 option(s):
13.

Question:

Consider the following code snippet:

XXXX m ;
//other code that initializes m
  switch( m ){
     case 32  : System.out.println("32");   break;
     case 64  : System.out.println("64");   break;
     case 128 : System.out.println("128");  break;
  }


What type can 'm' be of so that the above code compiles and runs as expected ?

Select 3 option(s):
14.

Question: What will be the result of compiling and running the following code:

float foo = 2, bar = 3, baz = 4;    //1
float mod1 = foo % baz, mod2 = baz % foo;  //2
float val = mod1>mod2? bar : baz; //3
System.out.println(val);

Select 1 option(s):
15.

Question:

Consider the following code appearing in a module-info.java

module com.amazing.movies{ //1
   exports com.amazing.movies; //2
   exports com.amazing.movies to com.amazing.rentals;//3
   requires transitive com.amazing.customer;//4
}

Identify correct statements.

Select 1 option(s):
16.

Question:

Consider the following

public class TestClass {
public static void main(String[] args) {
TestClass tc = new TestClass();
tc.myMethod();
}
public void myMethod() {
yourMethod();
}
public void yourMethod() {
throw new Exception();
}
}

What changes can be done to make the above code compile?

Select 1 option(s):
17.

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

var nameList = new ArrayList<String>();
nameList.add("Ally");
nameList.add("Billy");
nameList.add("Cally");
nameList.add("Billy");
nameList.add("Ally");

var nameSet1 = new HashSet<String>();
for(var name:nameList) nameSet1.add(name);
var nameSet2 = new HashSet<String>(nameList);
System.out.println(nameList.size()+" "+nameSet1.size()+" "+nameSet2.size());

Select 1 option(s):
18.

Question: What, if anything, is wrong with the following code?

interface T1{
}
interface T2{
   int VALUE = 10;
   void m1();
}

interface T3 extends T1, T2{
   public void m1();
   public void m1(int x);
}

Select 1 option(s):
19.

Question:

Your application is packaged in myapp.jar and depends on a jar named datalayer.jar, which in turn depends on mysql-connector-java-8.0.11.jar. The following packages exist in these jars:

myapp.jar:   com.abc.myapp
datalayer.jar: com.abc.datalayer
mysql-connector-java-8.0.11.jar:  com.mysql.jdbc


You want to use bottom up approach for migrating your app to a modular app. Which of the following is required before you can do this?

Select 1 option(s):
20.

Question: Which of the following statements are correct regarding the module system of Java.

Select 2 option(s):
21.

Question:

Given:

public class FunWithArgs {
    public static void main(String[][] args) {
        System.out.println(args[0][1]);
    }
    public static void main(String[] args) {
        var fwa = new FunWithArgs();
        String[][] newargs = {args};
        fwa.main(newargs);
    }
}


The above program is compiled with the command line:
javac FunWithArgs.java
and then run with:
java FunWithArgs a b c

What will be the output?

Select 1 option(s):
22.

Question: Which of the following lines of code that, when inserted at line 1, will make the overriding method in SubClass invoke the overridden method in BaseClass on the current object with the same parameter.

class BaseClass{
public void print(String s) { System.out.println("BaseClass :"+s); }
}
class SubClass extends BaseClass{
public void print(String s){
System.out.println("SubClass :"+s);
// Line 1
}
public static void main(String args[]){
SubClass sc = new SubClass();
sc.print("location");
}
}

Select 1 option(s):

23.

Question:

Identify correct statements.

Select 3 option(s):
24.

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

public class TestClass{
public static void main(String args[ ] ){
int i = 1;
int[] iArr = {1};
incr(i) ; incr(iArr) ;
System.out.println( "i = " + i + " iArr[0] = " + iArr [ 0 ] ) ;
}
public static void incr(int n ) { n++ ; }
public static void incr(int[ ] n ) { n [ 0 ]++ ;
}
}

Select 1 option(s):

25.

Question:

Identify correct statements about the modular JDK.

Select 3 option(s):
26.

Question:

Given:

public static void main(String[] args){
        try(FileInputStream fis = new FileInputStream("c:\\temp\\test.text")){
            System.out.println(fis);            
        }
        //line 1
}

Which of the following options can be inserted at //1 independent of each other to make the above code compile?

Select 2 option(s):
27.

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

public class TestClass{
   public static void main(String args[ ] ){
      int i = 0 ;
      boolean bool1 = true ;
      boolean bool2 = false;
      boolean bool  = false;
      bool = ( bool2 &  method1(i++) ); //1
      bool = ( bool2 && method1(i++) ); //2
      bool = ( bool1 |  method1(i++) ); //3
      bool = ( bool1 || method1(i++) ); //4
      System.out.println(i);
   }
   public static boolean method1(int i){
       return i>0 ? true : false;
   }
}

Select 1 option(s):
28.

Question: What can be inserted in the code below so that it will print 1 2 3?

class MyProcessor{
    Integer value;
    public MyProcessor(Integer value){
        this.value = value;
    }
    public void process(){
        System.out.println(value+" ");
    }
}
public class TestClass {
    
    public static void main(String[] args) {
        List<Integer> ls = Arrays.asList(1, 2, 3);
        
        INSERT CODE HERE
    }
}

Select 1 option(s):
29.

Question:

Given:

public class Student {
    private String name;
    private int marks;

    //constructor and getters and setters not shown

    public void addMarks(int m){
        this.marks += m;
    }
    public void debug(){
        System.out.println(name+":"+marks);
    }
}

What will the following code print when compiled and run?

List<Student> slist = Arrays.asList(new Student("S1", 40), new Student("S2", 35), new Student("S3", 30));
Consumer<Student> increaseMarks = s->s.addMarks(10);
slist.forEach(increaseMarks);
slist.stream().forEach(Student::debug);


Select 1 option(s):
30.

Question:

Consider the following code:

import java.util.concurrent.*;

public class ThreadPoolTest {
    public static void main(String[] args) {
        Runnable r = ()-> System.out.println("In Runnable");
        Callable<Integer> c = ()-> { System.out.println("In Callable"); return 0; };
        var es = Executors.newCachedThreadPool();

        //INSERT CODE HERE

        es.shutdown();

    }

}

What can be inserted in the above code so that both - Runnable r and Callable c - will be executed?

Select 1 option(s):
31.

Question:

Given that c:\temp\pathtest is a directory that contains several directories. Each sub directory contains several files but there is exactly one regular file named test.txt within the whole directory structure.

Which of the given options can be inserted in the code below so that it will print complete path of test.txt?

try{
    Stream<Path> s = null;

    INSERT CODE HERE

    s.forEach(System.out::println);
}catch(IOException ioe){
    ioe.printStackTrace();
}

Select 1 option(s):
32.

Question: What will the following program print when run without any command line argument?

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

        var hasParams = (args == null ? false : true);
        if(hasParams){
            System.out.println("has params");
        }{
            System.out.println("no params");
        }
    }
}

Select 1 option(s):
33.

Question: What will the following code print when run?

import java.nio.file.Path;
import java.nio.file.Paths;

public class PathTest {
    static Path p1 = Paths.get("c:\\finance\\data\\reports\\daily\\pnl.txt");
    
    public static void main(String[] args) {
        System.out.println(p1.subpath(0, 2));
    }
}

Select 1 option(s):
34.

Question: What will the following code print when run?

public class TestClass {
public void switchString(String input){
switch(input){
case "a" : System.out.println( "apple" );
case "b" : System.out.println( "bat" );
break;
case "B" : System.out.println( "big bat" );
default : System.out.println( "none" );
}
}
public static void main(String[] args) throws Exception {
var tc = new TestClass();
tc.switchString("B");
}
}

Select 1 option(s):

35.

Question:

The following code was written for Java 7:

Map<String, List<Double>> groupedValues = new HashMap<>();

public void process(String name, Double value){
    List<Double> values = groupedValues.get(name);
    if(values == null){
        values = new ArrayList<Double>();
        groupedValues.put(name, values);
    }
    values.add(value);
}

Which of the following implementations correctly makes use of the functional interfaces available in the Java standard library to achieve the same?

Select 1 option(s):
36.

Question: 

Identify correct statement(s) regarding the benefit of using PreparedStatement over Statement.

Select 2 option(s):
37.

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

public class StringArrayTest{
   public static void main(String args[]){
      String[][][] arr  = {{ { "a", "b" , "c"}, { "d", "e", null } },{ {"x"}, null },{{"y"}},{ { "z","p"}, {} }
      };
      System.out.println(arr[0][1][2]);
   }
}

Select 1 option(s):
38.

Question: What will the following code print when run?

class MyCallable implements Callable<String>{
    public String call() throws Exception {
        Thread.sleep(50000);
        return "DONE";
    }
}
public class TestClass {

    public static void main(String[] args) throws Exception {
       var es =  Executors.newSingleThreadExecutor();
       var future = es.submit(new MyCallable());
       System.out.println(future.get()); //1
       es.shutdownNow(); //2
    }
}

Select 1 option(s):
39.

Question: What will the following code print?

Object v1 = IntStream.rangeClosed(10, 15)
        .boxed()
        .filter(x->x>12)
        .parallel()
        .findAny();

Object v2 = IntStream.rangeClosed(10, 15)
        .boxed()
        .filter(x->x>12)
        .sequential()
        .findAny();

System.out.println(v1+":"+v2);

(Note: < and > in the options below denote the possible output and not the sign themselves.)

Select 1 option(s):
40.

Question: What will the following program print when run?

public class ChangeTest {
private int myValue = 0;
public void showOne(int myValue){
myValue = myValue;
}
public void showTwo(int myValue){
this.myValue = myValue;
}
public static void main(String[] args) {
var ct = new ChangeTest();
ct.showTwo(200);
System.out.println(ct.myValue);
ct.showOne(100);
System.out.println(ct.myValue);
}
}

Select 1 option(s):

41.

Question: Which of the following are valid declarations inside an interface independent of each other?

Select 2 option(s):
42.

Question: What will the following code print?

void crazyLoop(){
var c = 0;
JACK: while (c < 8){
JILL: System.out.println(c);
if (c > 3) break JILL; else c++;
}
}

Select 1 option(s):

43.

Question:

Given:

  Connection con = DriverManager.getConnection(dbURL);
  String updateString =
        "update SALES " +
        "set T_AMOUNT = 100 where T_NAME = 'BOB'";
  Statement stmt = con.createStatement();
  stmt.executeUpdate(updateString);
  //INSERT CODE HERE


What statement should be added to the above code so that the update is committed to the database?

Select 1 option(s):
44.

Question:

Given:

public class Book {
private int id;
private String title;
private String genre;
private String author;
private double price;

//constructors and accessors not shown
}


Assuming that books is a List of Book objects, what can be inserted in the code below at DECLARATION and EXPRESSION so that it will classify the books by genre and then also by author?

DECLARATION classified = null;
classified = books.stream().collect(Collectors.groupingBy(
        EXPRESSION
));
System.out.println(classified);


Select 1 option(s):
45.

Question:

Consider the following code:

    public static boolean isValid(Path p){
        
        return p.startsWith("temp") && p.endsWith("clients.dat");
    }
    
    public static void writeData() {
        var p1 = Paths.get("\\temp\\records");
        var p2 = p1.resolve("clients.dat");
        System.out.println(p2+" "+isValid(p2));
        
    }


What will be printed when the method writeData() is executed?

Select 1 option(s):
46.

Question: What is the result of executing the following fragment of code:

var b1 = false;
var b2  = false;
if (b2 = b1 == false){
   System.out.println("true");
} else{
   System.out.println("false");
}

Select 1 option(s):
47.

Question:

Identify correct statements about the following method that is used internally by a class:

private byte[] allocateNew(int additional, byte[] existing){
        byte[] newarray = new byte[existing.length+additional];
        System.arraycopy(existing, 0, newarray, 0, existing.length);
        return newarray;
}

Select 2 option(s):
48.

Question: While working on a code cleaup project for a library that you make available to your users, you observe the following customer visible method:

public void setApprovedUsers(final List<String> userids) {
                return AccessController.doPrivileged(
                    (PrivilegedAction<Void>)() -> {
                         this.userManager.setApprovedUsers(userids);
                         return null;
                    }
                );
       }
}

What change should you make to this method so that it satisfies the requirements for a customer visible method?

Select 1 option(s):
49.

Question:

Consider the following interface definition:

interface Bozo{
         int type = 0;
         public void jump();
}


Now consider the following class:

public class Type1Bozo implements Bozo{
         public Type1Bozo(){
            type = 1;
         }

         public void jump(){
            System.out.println("jumping..."+type);
         }

         public static void main(String[] args){
            Bozo b = new Type1Bozo();
            b.jump();
         }
}

What will the program print when compiled and run?

Select 1 option(s):
50.

Question: What is the result of executing the following code when the value of i is 5:

switch (i){
    default:
    case 1:
        System.out.println(1);
    case 0:
        System.out.println(0);
    case 2:
        System.out.println(2);
        break;
    case 3:
        System.out.println(3);
}

Select 1 option(s):
51.

Question:

Given:

class Base{
   public <T extends CharSequence> Collection<String> transform(Collection<T> list)
   {
      return new ArrayList<String>();
   }
    
}

class Derived extends Base{
   //public  Collection<String> transform(Collection<String> list) { return new HashSet<String>(); }; //1
   
   //public <T extends String> Collection<T> transform(Collection<T> list) { return new HashSet<T>();}; //2
   
   //public <T extends CharSequence> List<T> transform(Collection<T> list) { return new ArrayList<T>(); }; //3
   
   //public <T extends CharSequence> Collection<T> transform(List<T> list) { return new HashSet<T>(); }; //4
    
   //public <T super String> Collection<T> transform(List<String> list) { return new HashSet<T>(); };//5
   
   //public  Collection<CharSequence> transform(Collection<CharSequence> list) { return new HashSet<CharSequence>();}; //6
}


Identify correct statements about the methods defined in Derived assuming they are uncommented one at a time individually.

Select 1 option(s):
52.

Question:

Given :

TEACHER table in the database with the following data:

ID(int)  NAME(varchar)   SUBJECT(varchar)
--------------------
1   Ally   MATH
2   Bob  MATH
1   Ally  SCIENCE

and the following code:

try(
        Connection c = ds.getConnection(); //assume that ds refers to a DataSource
        PreparedStatement selectPS = c.prepareStatement("select ID, SUBJECT from TEACHER where NAME = ?");
        PreparedStatement insertPS = c.prepareStatement("insert into SUBJECT (NAME, TEACHERID) VALUES (?, ?)");
    )
    {
         selectPS.setString(1, "Ally");
         ResultSet rs = selectPS.executeQuery();
         while(rs.next()){
                insertPS.setObject(1, rs.getObject(2, JDBCType.VARCHAR));
                insertPS.setObject(1, rs.getObject(1, JDBCType.INTEGER));
                insertPS.execute(); //1
         }
    }


Identify correct statements.

Select 2 option(s):