Welcome to your Test - 5 Code - 819

Name
Email
Phone
1.

Question:

Assuming that the following method will always be called with a phone number in the format ddd-ddd-dddd (where d stands for a digit), what can be inserted at //1 so that it will return a String containing the same number except its last four digits will be masked with xxxx?

public static String hidePhone(String fullPhoneNumber){
  //1 Insert code here
}

Select 3 option(s):
2.

Question:

Consider the following classes:

class Boo {
    public Boo(){ System.out.println("In Boo"); }
}
class BooBoo extends Boo {
    public BooBoo(){ System.out.println("In BooBoo"); }
}

class Moo extends BooBoo implements Serializable {
    int moo = 10; { System.out.println("moo set to 10"); }
    public Moo(){ System.out.println("In Moo"); }
}


First, the following code was executed and the file moo1.ser was created successfully:

  Moo moo = new Moo();
  moo.moo = 20;
  FileOutputStream fos = new FileOutputStream("c:\\temp\\moo1.ser");
  ObjectOutputStream os = new ObjectOutputStream(fos);
  os.writeObject(moo);
  os.close();


Next, the following code was executed.

  FileInputStream fis = new FileInputStream("c:\\temp\\moo1.ser");
  ObjectInputStream is = new ObjectInputStream(fis);
  Moo moo = (Moo) is.readObject();
  is.close();
  System.out.println(moo.moo);


Which of the following will be a part of the output of the second piece of code?

Select 3 option(s):
3.

Question: Which of these array declarations and instantiations are legal?

Select 4 option(s):
4.

Question:

Given the following code:

       List<Integer> aList = List.of(40, 30, 20);  //1
       List<Integer> bList = List.copyOf(aList); //2
       
       bList.sort((Integer::compare)); //3
       System.out.println( bList ); //4

       aList.sort((Integer::compare)); //5
       System.out.println( aList ); //6

Identify correct statement.

Select 1 option(s):
5.

Question: 

Given:

DoubleStream ds =  DoubleStream.of(1.0, 2.0, 3.0);
//INSERT CODE HERE
ds.map(doubleF.apply(5.0)).forEach(System.out::println);


Which of the following statements can be inserted in the above code?

Select 1 option(s):
6.

Question

Your group has an existing application (reports.jar) that uses a library (analytics.jar) from another group in your company. Both - the application and the library - use a JDBC driver packaged in ojdbc8.jar.

Which of the following options describes the steps that will be required to modularize your application?

Select 1 option(s):
7.

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

public class TrimTest{
   public static void main(String args[]){
      String blank  = " ";  // one space
      String line = blank + "hello" + blank + blank;
      line.concat("world");
      String newLine  =  line.trim();
      System.out.println((int)(line.length() + newLine.length()));
   }
}

Select 1 option(s):
8.

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

interface Pow{
    static void wow(){
        System.out.println("In Pow.wow");    
    }
}

abstract class Wow{
   
   static void wow(){  // LINE 9
       System.out.println("In Wow.wow");    
  }    
}

public class Powwow extends Wow implements Pow {
    public static void main(String[] args) {
        Powwow f = new Powwow();
        f.wow();
    }
}

Select 2 option(s):
9.

Question:

Consider the following code:

public class FileCopier {
    public static void copy(String records1, String records2)  {
        try (
                InputStream is = new FileInputStream(records1);
                OutputStream os = new FileOutputStream(records2);  ) {  //1

            if(os == null) os = new FileOutputStream("c:\\default.txt");  //2

            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = is.read(buffer)) != -1) {  //3
                os.write(buffer, 0, bytesRead);
                System.out.println("Read and written bytes " + bytesRead);
            }
        } catch (IOException e) { //4
            e.printStackTrace();
        }
    }

    public static void main(String[] args)  {
        copy("c:\\temp\\test1.txt", "c:\\temp\\test2.txt");
    }
}


Assuming appropriate import statements and the existence of both the files, what will happen when the program is compiled and run?

Select 1 option(s):
10.

Question:

Given the following code, which of these statements are true?

class TestClass{
public static void main(String args[]){
int k = 0;
int m = 0;
for ( var i = 0; i <= 3; i++){
k++;
if ( i == 2){
// line 1 }
m++;
}
System.out.println( k + ", " + m );
}
}

Select 3 option(s):

11.

Question: What will be the contents of d at the end of the following code?

        Deque<Integer> d = new ArrayDeque<>();
        d.push(1);
        d.offerLast(2);
        d.push(3);
        d.peekFirst();
        d.removeLast();
        d.pop();
        System.out.println(d);

Select 1 option(s):
12.

Question:

Given that java.lang.String has two overloaded toUpperCase methods - toUpperCase() and toUpperCase(Locale ), consider the following code:

String name = "bob";
String val = null;
//Insert code here
System.out.print(val);


Which of the following code fragments can be inserted in the above code so that it will print BOB?

Select 2 option(s):
13.

Question:

Identify correct statements about the modular JDK.

Select 3 option(s):
14.

Question:

Identify the valid for loop constructs assuming the following declarations:

Object o = null;
Collection c = //valid collection object.
int[][] ia = //valid array

Select 2 option(s):

15.

Question:

Given the following code fragment:


        var raf = new RandomAccessFile("c:\\temp\\test.txt", "rwd");

        //INSERT CODE HERE

        raf.close();
        
        var dis = new DataInputStream(new FileInputStream("c:\\temp\\test.txt"));
        String value = dis.readUTF();
        System.out.print(value);
        dis.close();

Which of the following options can be inserted in the above code so that it will print hello world?

Select 1 option(s):
16.

Question: What will the following code print?

public class Test{
    public static void testInts(Integer obj, int var){
        obj = var++;
        obj++;
    }
    public static void main(String[] args) {
        Integer val1 = new Integer(5);
        int val2 = 9;
        testInts(val1++, ++val2);
        System.out.println(val1+" "+val2);
    }
}

Select 1 option(s):
17.

Question:

Consider the following code...

class MyException extends Exception {}

public class TestClass{
     public void myMethod() throws XXXX{
         throw new MyException();
     }
}


What can replace XXXX?

Select 3 option(s):
18.

Question: What will the following class print ?

class Test{
public static void main(String[] args){
int[][] a = { { 00, 01 }, { 10, 11 } };
int i = 99;
try {
a[val()][i = 1]++;
} catch (Exception e) {
System.out.println( i+", "+a[1][1]);
}
}
static int val() throws Exception {
throw new Exception("unimplemented");
}
}

Select 1 option(s):

19.

Question:

Identify the correct statements about the following code:

import java.util.*;
import java.util.function.*
class Account {
    private String id;
    public Account(String id){ this.id = id; }
    //accessors not shown
}
public class BankAccount extends Account{
    private double balance;
    public BankAccount(String id, double balance){ super(id); this.balance = balance;}

    //accessors not shown

    public static void main(String[] args) {
        Map<String, Account> myAccts = new HashMap<>();
        myAccts.put("111", new Account("111"));
        myAccts.put("222", new BankAccount("111", 200.0));
        
        BiFunction<String, Account, Account> bif =
  (a1, a2)-> a2 instanceof BankAccount?new BankAccount(a1, 300.0):new Account(a1); //1
        
        myAccts.computeIfPresent("222", bif);//2
        BankAccount ba = (BankAccount) myAccts.get("222");
        System.out.println(ba.getBalance());
    }
}


Select 1 option(s):
20.

Question:

You are designing a class that will cache objects. It should be able to store and retrieve an object when supplied with an object identifier.
Further, this class should work by tracking the "last accessed times" of the objects. Thus, if its capacity is full, it should remove only the object that hasn't been accessed the longest.

Which collection class would you use to store the objects?

Select 1 option(s):
21.

Question:

Given:

List<Double> dList = Arrays.asList(10.0, 12.0);
dList.stream().forEach(x->{ x = x+10; });
dList.stream().forEach(d->System.out.println(d));

What will it print when compiled and run?

Select 1 option(s):
22.

Question:

Assume that dt refers to a valid java.util.Date object and that df is a reference variable of class DateFormat.
Which of the following code fragments will print the country and the date in the correct local format?

Select 1 option(s):
23.

Question: Which of the following code fragments will successfully initialize a two-dimensional array of chars named cA with a size such that cA[2][3] refers to a valid element?

1.
  char[][] cA = {  { 'a', 'b', 'c' },  { 'a', 'b', 'c' }   };
2.
  char cA[][] = new char[3][];
  for (int i=0; i<cA.length; i++) cA[i] = new char[4];
3.
  char cA[][] = { new char[ ]{ 'a', 'b', 'c' }  ,   new char[ ]{ 'a', 'b', 'c' }  };
4
  char cA[3][2] = new char[][] {  { 'a', 'b', 'c' },   { 'a', 'b', 'c' }   };
5.
  char[][] cA = { "1234", "1234",  "1234"  };

6.
   var cA[][] = new char[3][];
   for (var i=0; i<cA.length; i++) cA[i] = new char[4];

Select 1 option(s):
24.

Question:

Consider the contents of following two files:

//In file A.java
package a;
public class A{
   A(){ }
   public void  print(){ System.out.println("A"); }
}

//In file B.java
package b;
import a.*;
public class B extends A{
   B(){ }
   public void  print(){ System.out.println("B"); }
   public static void main(String[] args){
      new B();
   }
}


What will be printed when you try to compile and run class B?

Select 1 option(s):
25.

Question:

Consider the following class...

class TestClass{
   int i;
   public TestClass(int i) { this.i = i;  }
   public String toString(){
       if(i == 0) return null;
       else return ""+i;
   }
   public static void main(String[ ] args){
      TestClass t1 = new TestClass(0);
      TestClass t2 = new TestClass(2);
      System.out.println(t2);
      System.out.println(""+t1);
   }
}


What will be the output when the above program is run?

Select 1 option(s):
26.

Question:

Consider the following classes...

class Teacher{
void teach(String student){
/* lots of code */
}
}
class Prof extends Teacher{
//1
}

Which of the following methods can be inserted at line //1 ?

Select 4 option(s):
27.

Question: Which exact exception class will the following class throw when compiled and run?

class Test{
   public static void main(String[] args) throws Exception{
      int[] a = null;
      int i = a [ m1() ];
   }
   public static int m1() throws Exception{
      throw new Exception("Some Exception");
   }
}

Select 1 option(s):
28.

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

class AX{
  static int[] x = new int[0];
  static{
   x[0] = 10;
  }
  public static void main(String[] args){
    var ax = new AX();
  }
}

Select 1 option(s):
29.

Question:

Given:
        List<String> l1 = Arrays.asList("a", "b");
        List<String> l2 = Arrays.asList("1", "2");

Which of the following lines of code will print the following output?
a
b
1
2


Select 1 option(s):
30.

Question:

Consider the following code:

//Assume appropriate imports
public class FileCopier {

    public static void copy(String records1, String records2) throws IOException {
        try (
                InputStream is = new FileInputStream(records1);
                OutputStream os = new FileOutputStream(records2);) {
            var buffer = new byte[1024];
            var bytesRead = 0;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }

        } catch (FileNotFoundException | java.io.InvalidClassException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        copy("c:\\temp\\test1.txt", "c:\\temp\\test2.txt");
    }
}


Given that test1.txt exists but test2.txt does not exist, what will happen when the above program is compiled and run?

Select 1 option(s):
31.

Question:

Given:

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

and the following code:

var books = new ArrayList<Book>(List.of(new Book("The Outsider", "fiction"),
        new Book("Becoming", "non-fiction"),new Book("Uri", "non-fiction")));

books.sort(Comparator.comparing(Book::getGenre).thenComparing(Book::getTitle).reversed());
System.out.println(books);


What will be the result?

Select 1 option(s):
32.

Question:

Given:

List<String> strList = Arrays.asList("a", "aa", "aaa");
Function<String, Integer> f = x->x.length();
Consumer<Integer> c = x->System.out.print("Len:"+x+" ");
Predicate<String> p = x->"".equals(x);
strList.forEach(  *INSERT CODE HERE*  );


What can be inserted in the code above?

Select 1 option(s):
33.

Question:

Given:

HashMap<Integer, String> hm = new HashMap<>();
hm.put(1, "a"); hm.put(2, "b"); hm.put(3, "c");

Which of the following statements will print the keys as well as values contained in the map?

Select 1 option(s):
34.

Question:

Given the follow two module definitions:

module author{
  requires serviceapi;
  uses api.BloggerService;
}

and

module abc.blogger{
  requires serviceapi;
  provides api.BloggerService with abc.SimpleBlogger;
}


Identify correct statement(s).

Select 2 option(s):
35.

Question: You want to use a third party JDBC driver for a database. Which of the following actions must you take to retrieve a Connection using that driver in your JDBC program?

Select 2 option(s):
36.

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

//imports not shown
class Movie{
    static enum Genre  {DRAMA, THRILLER, HORROR, ACTION };
    private Genre genre;
    private String name;
    private char rating = 'R';
    Movie(String name, Genre genre, char rating){
        this.name = name; this.genre = genre; this.rating = rating;
    }
    //accessors not shown
}
public class FilteringStuff {
    public static void main(String[] args) {
        List<Movie> movies = Arrays.asList(
                new Movie("Titanic", Movie.Genre.DRAMA, 'U'),
                new Movie("Psycho", Movie.Genre.THRILLER, 'U'),
                new Movie("Oldboy", Movie.Genre.THRILLER, 'R'),
                new Movie("Shining", Movie.Genre.HORROR, 'U')
                );
        
        movies.stream()
                .filter(mov->mov.getRating()=='R')
                .peek(mov->System.out.println(mov.getName()))
                .map(mov->mov.getName());
    }
    
}

Select 1 option(s):
37.

Question:

Given:

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

   //assume appropriate implementations of equals and hashCode based on isbn property
}


and the following code snippet:

List<Book> books = getBooksByAuthor("Ludlum");
books.stream().sorted().forEach(b->System.out.println(b.getIsbn())); //1

Assuming that getBooksByAuthor is a valid method that returns a List of Books, which of the following statements is/are true?

Select 1 option(s):
38.

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

class TestClass{
public static void main(String args[]){
var b = false;
var i = 1;
do{
i++ ;
} while (b = !b);
System.out.println( i );
}
}

Select 1 option(s):

39.

Question:

Consider the following code:

class Bond
{
    String ticker; double coupon; java.time.LocalDate maturity;
}

class Portfolio implements Serializable
{
    String accountName;
    Bond[] bonds;
}

public class TestClass {
  public static void main(String[] args) throws Exception{
     Portfolio portfolio = // get portfolio somehow
     // serialize portfolio
  }
}


Which of the following approaches can be taken independent of each other so that a Portfolio object can be serialized while preserving the state of the Bond objects contained in Portfolio?

Select 2 option(s):
40.

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

(Assume that MySpecialException is an unchecked exception.)

1. public class ExceptionTest {
2.    public static void main(String[] args) {
3.        try {
4.            doSomething();
5.        } catch (MySpecialException e) {
6.            System.out.println(e);
7.        }
8.    }
9.
10.    static void doSomething() {
11.        int[] array = new int[4];
12.        array[4] = 4;
13.        doSomethingElse();
14.    }
15.
16.    static void doSomethingElse() {
17.        throw new MySpecialException("Sorry, can't do something else");
18.    }
}

Select 1 option(s):
41.

Question:

Given:

List ls = Arrays.asList(11, 11, 22, 33, 33, 55, 66);

Which of the following expressions will return true?

Select 2 option(s):
42.

Question:

Consider the directory structure and its contents shown in the figure.

(c:\temp is a directory that contains two text files - test1.txt and text2.txt)

What should be inserted at //Line 10 in the following code so that it will write "hello" to text2.txt?

    public static void writeData() throws Exception{
        var p1 = Paths.get("c:\\temp\\test1.txt");
        var p2 =  //LINE 10 - INSERT CODE HERE
        var bw = new BufferedWriter(new FileWriter(p2.toFile()));
        bw.write("hello");
        bw.close();
    }


Select 1 option(s):
43.

Question:

This following code appears in a file named VehicleType.java. Why would it not compile?

//In file VehicleType
package objective1;
public enum VehicleType
{
    
    SUV, SEDAN, VAN, SPORTSCAR;

    public VehicleType()
    {
    
    }
    
}

Select 1 option(s):
44.

Question:

Consider the following program:

class Game {
public void play() throws Exception {
System.out.println("Playing...");
}
}
class Soccer extends Game {
public void play(String ball) {
System.out.println("Playing Soccer with "+ball);
}
}
public class TestClass {
public static void main(String[] args) throws Exception {
Game g = new Soccer();
// 1
Soccer s = (Soccer) g;
// 2
}
}

Which of the given options can be inserted at //1 and //2?

Select 2 option(s):
45.

Question:

Given:

public @interface Authors {
    Author[] value();
    String team() default "enthuware";
}

@Repeatable(Authors.class)
public @interface Author {
    int id() default 0;
    String[] value();
}

Identify correct usages of the above annotations.

Select 2 option(s):
46.

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

public class TestClass{
   public static void main(String args[ ] ){
      StringBuilder sb = new StringBuilder("12345678");
      sb.setLength(5);
      sb.setLength(10);
      System.out.println(sb.length());
   }
}

Select 1 option(s):
47.

Question:

Given:

public class Book{
    private String title;
    private Double price;
    public Book(String title, Double price){
        this.title = title;
        this.price = price;
    }
    //accessor methods not shown
}

What will the following code print when compiled and run?

Book b1 = new Book("Java in 24 hrs", 30.0);
Book b2 = new Book("Thinking in Java", null);
Supplier s1 = b1::getPrice;
System.out.println(b1.getTitle()+" "+s1.get());
Supplier s2 = b2::getPrice;
System.out.println(b2.getTitle()+" "+s2.getAsDouble());


Select 1 option(s):
48.

Question:

Given:
    public static void copy1(Path p1, Path p2) throws Exception {
        Files.copy(p1, p2, StandardCopyOption.REPLACE_EXISTING);
    }


Identify correct statements.

Select 2 option(s):
49.

Question:

Given the following code:

   Transaction<Number, Integer> t1 = new Transaction<>(1, 2); //1

   Transaction<Number, String> t2 = new Transaction<>(1, "2"); //2

It is required that //1 must compile and //2 must NOT compile. Which of the following declarations of class Transaction will satisfy the requirement?

Select 1 option(s):
50.

Question:

Given:

import java.util.*;
public class EventProcessor{
   public void processEvents(Collection c){
      c.forEach(o -> System.out.println(o));
   }
}

class MapEventProcessor extends EventProcessor{
   public void processEvents(Map events){
      *INSERT CODE HERE*
   }
}

Which of the following options can be inserted in the above code without compilation error?

Select 2 option(s):
51.

Question:

Your application includes a method that generates a report using Employee data. While generating the report, if this method detects inconsistent payment records, it cannot generate the report. You want to create a new exception class that should be thrown in this situation. Which of the following is a valid implementation for this exception?

Select 1 option(s):
52.

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

Stream<Integer> values = IntStream.rangeClosed(10, 15).boxed(); //1
Object obj = values.collect(Collectors.partitioningBy(x->x%2==0)); //2
System.out.println(obj);

Select 1 option(s):