Welcome to your Test - 11 Code - 819

Name
Email
Phone
1.

Question:

Given:

package strings;
public class StringFromChar {
    
    public static void main(String[] args) {
        String myStr = "good";
        char[] myCharArr = {'g', 'o', 'o', 'd' };
        
        String newStr = null;
        for(char ch : myCharArr){
            newStr = newStr + ch;
        }

        System.out.println((newStr == myStr)+ " " + (newStr.equals(myStr)));
        
    }
}


What will it print when compiled and run?

Select 1 option(s):
2.

Question:

Given:

class LowBalanceException extends ______{ //1
    public LowBalanceException(String msg){ super(msg);    }
}

class WithdrawalException extends ______{ //2
    public WithdrawalException(String msg){ super(msg);    }
}
class Account{
    double balance;
    public void withdraw(double amount) {
        try{
            throw new LowBalanceException("Not Implemented");
        }catch(WithdrawalException e){
            throw new RuntimeException(e.getMessage());
        }
    }
    public static void main(String[] args) {
        try{
            Account a = new Account();
            a.withdraw(100.0);
        }catch(WithdrawalException e){
            System.out.println(e.getMessage());
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
}


What can be inserted in the above code at //1 and //2 so that it will print "Not Implemented" when run?

Select 1 option(s):
3.

Question:

Assuming that the file module-info.java and the folder out\foo.bar exists, what will happen when the following code is run?


Path p1 = Paths.get("c:\\temp\\src\\foo.bar\\module-info.java");
Path p2  = Paths.get("c:\\temp\\out\\foo.bar");
Files.move(p1, p2);


Select 1 option(s):
4.

Question:

Assume that a method named 'method1' contains code which may raise a non-runtime (checked) Exception.

What is/are the possible way(s) to declare this method so that it indicates that it expects the caller to handle that exception?

Select 2 option(s):
5.

Question: Which of the given options if put at //1 will compile without any error?

public class TestClass
{
   public class A
   {
   }
   public static class B
   {
   }
   public void useClasses()
   {
      //1
   }
}

Select 1 option(s):
6.

Question:

Consider the following code:

class A {
public void doA(int k) throws Exception { // 0
for(int i=0; i< 10; i++) {
if(i == k) throw new Exception("Index of k is "+i); // 1
}
}
public void doB(boolean f) { // 2
if(f) {
doA(15); // 3
}
else return;
}
public static void main(String[] args) { // 4
A a = new A();
a.doB(args.length>0); // 5
}
}

Which of the following statements are correct?

Select 1 option(s):
7.

Question:

Consider the following interface definition:

public interface ConstTest{
public int A = 1; //1
int B = 1; //2
static int C = 1; //3
final int D = 1; //4
public static int E = 1; //5
public final int F = 1; //6
static final int G = 1; //7
public static final int H = 1; //8
}

Which line(s) will cause a compilation error?

Select 1 option(s):
8.

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

List<StringBuilder> messages = Arrays.asList(new StringBuilder(), new StringBuilder());
messages.stream().forEach(s->s.append("helloworld"));
messages.forEach(s->{
    s.insert(5,",");
    System.out.println(s);
});


Select 1 option(s):
9.

Question:

Given the following interface:

interface InputStreamHandler {
    public long read(InputStream in) throws IOException;
}

and the following code in some other class:

public long getTotal(String file) throws IOException{
    long sum = readFileBuffered(file,
            (InputStream in) -> {
            long current = 0;
            for (;;) {
                int b = in.read();
                if (b == -1) {
                    return current;
                }
                current += b;
            }
        });
    return sum;
}

public  long readFileBuffered(String file, InputStreamHandler handler) throws IOException {
    try (final InputStream in = Files.newInputStream(Paths.get(file))) {
        return handler.read(new BufferedInputStream(in));
    }
}


Identify correct statements.

Select 1 option(s):
10.

Question:

Identify valid statements.

Select 3 option(s):
11.

Question: Which of the following interface definitions can use Lambda expressions?

Select 1 option(s):
12.

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

List<String> values = Arrays.asList("Java EE", "C#", "Python");
boolean flag = values.stream().allMatch(str->{
        System.out.println("Testing: "+str);
        return str.equals("Java");
        });
System.out.println(flag);

Select 1 option(s):
13.

Question: What will the following code fragment print?

        Path p1 = Paths.get("c:\\personal\\.\\photos\\..\\readme.txt");
        Path p2 = p1.normalize();
        System.out.println(p2);

Select 1 option(s):
14.

Question:

Given:

import java.time.LocalDate;
import static java.time.DayOfWeek.*;
public class TestClass {
    public static void main(String[] args){
        var day = LocalDate.now().with(FRIDAY).getDayOfWeek();

        switch(day){
            case MONDAY:
            TUESDAY:
            WEDNESDAY:
            THURSDAY:
            FRIDAY:
                System.out.println("working");
            case     SATURDAY:
            SUNDAY:
                System.out.println("off");
        }
    }
}


What is the output?

Select 1 option(s):
15.

Question: Which of the following method would you use to get a JDBC connection while using JDBC 4.0 but not while using a previous version of JDBC?

Select 2 option(s):
16.

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

void test(int x){
   switch(x){
      case 1:
      case 2:
      case 0:
      default :
      case 4:
      case 'a'|'b': System.out.println('c');
   }
}

Select 1 option(s):
17.

Question:

You are the maintainer of a library packaged as bondanalytics.jar, which is used by several groups in your company. It has the following two packages that are used by other applications:
com.abc.bonds
com.abc.bonds.analytics

You want to modularize this jar but some groups have not yet modularized their applications. How will such groups use the modularized jar?

Select 1 option(s):
18.

Question:

Given the following class, which of the given blocks can be inserted at line 1 without errors?

public class InitClass{
private static int loop = 15 ;
static final int INTERVAL = 10 ;
boolean flag ;
//line 1
}

Select 4 option(s):

19.

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

public interface FooI{

}

Select 3 option(s):
20.

Question:

Given the following code (assume appropriate imports):

public class IOTest {
    public static void main(String[] args) {
        var myfile = Paths.get("test.txt");
        try(var bfr = Files.newBufferedReader(myfile, Charset.forName("US-ASCII") )){
            String line = null;
            while( (line = bfr.readLine()) != null){
                System.out.println(line);
            }
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

What will be printed when this code is run if test.txt doesn't exist?

Select 1 option(s):
21.

Question:

Given:

@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD, ElementType.METHOD}) //1
@Target({ElementType.TYPE})//2
@Retention(RetentionPolicy.RUNTIME)//3
public @interface DebugInfo { //4
    String name() default=""; //5
    String[][] params();//6
    java.util.Date entryTime();//7
}

Which line(s) will cause compilation failure?

Select 4 option(s):
22.

Question:

Following is a program to capture words from command line and create two collections. One that keeps only unique words and one that keeps all the words in the order they were entered. What should replace AAA and BBB?

   static Collection unique = new AAA();
   static Collection ordered = new BBB();
   public static void main(String args[]) throws Exception
   {
      BufferedReader bfr = new BufferedReader( new InputStreamReader( System.in ) );
      String s = bfr.readLine();
      while(s != null && s.length() >0)
      {
         unique.add(s);
         ordered.add(s);
         s = bfr.readLine();
      }
      System.out.println(unique);
      System.out.println(ordered);
   }


Select 2 option(s):
23.

Question:

Given:

class Game{ }
class Cricket extends Game{ }
class Instrument{ }
class Guitar extends Instrument{ }

interface Player<E>{ void play(E e); }
interface GamePlayer<E extends Game> extends Player<E>{ }
interface MusicPlayer<E extends Instrument> extends Player{ }


Identify valid declarations.

Select 1 option(s):
24.

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

        Deque<Integer> d = new ArrayDeque<>();
        d.add(1);
        d.addFirst(2);
        d.pop();
        d.offerFirst(3);

(Assume that in the output, front of deque is on the left side and the end is on the right side.)

Select 1 option(s):
25.

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

import java.util.*;

public class TestClass {

    public static void main(String[] args) {

        TreeSet<Integer> s = new TreeSet<Integer>();
        TreeSet<Integer> subs = new TreeSet<Integer>();

        for(int i = 324; i<=328; i++)
        {
            s.add(i);
        }
        subs = (TreeSet) s.subSet(326, true, 328, true );
        subs.add(329);
        System.out.println(s+" "+subs);
        
    }

}

Select 1 option(s):
26.

Question: Which of the following texts can occur in a valid resource bundle file?

Select 2 option(s):
27.

Question:

Given:

ArrayList<Integer> source = new ArrayList<Integer>();
source.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));

List<Integer> destination =
        Collections.synchronizedList(new ArrayList<Integer>());

source
        .parallelStream()  //1
        .peek(item->{destination.add(item); }) //2
        .forEachOrdered(System.out::print);
System.out.println("");
destination
         .stream() //3
         .forEach(System.out::print); //4
System.out.println("");

What changes must be made to the above code so that it will consistently print
123456
123456

?

Select 1 option(s):
28.

Question:

Consider the following code:

public class Logger{
    private StringBuilder sb = new StringBuilder();
    
    public void logMsg(String location, String message){
    sb.append(location);
    sb.append("-");
    sb.append(message);
    }
    
    public void dumpLog(){
    System.out.println(sb.toString());
    //Empty the contents of sb here
    }
    
}


Which of the following options will empty the contents of the StringBuilder referred to by variable sb in method dumpLog()?

Select 1 option(s):
29.

Question: What will the following program print?

public class TestClass{
  public static void main(String[] args){
     Object obj1 = new Object();
     Object obj2 = obj1;
     if( obj1.equals(obj2) ) System.out.println("true");
     else  System.out.println("false");
  }
}

Select 1 option(s):
30.

Question: What will the following code print?

Stream<String> ss = Stream.of("a", "b", "c");
String str = ss.collect(Collectors.joining(",", "-", "+"));
System.out.println(str);

Select 1 option(s):
31.

Question:

Identify correct statements about the modular JDK.

Select 3 option(s):
32.

Question:

Identify the correct statements about the following code:

import java.util.*;
class Person {
    private String name;
    public Person(String name) {  this.name = name;    }
    public String getName() { return name;  }
    public void setName(String name) { this.name = name; }

    public String toString() { return name; }
}

class Helper {

    public void helpPeople(Queue people, Queue helped) {
        do {
            Person p = (Person) people.poll();
            System.out.println("Helped : " + p + " ");
            helped.offer(p.getName());
        } while (!people.isEmpty());
    }

    public static void main(String[] args) {
        Queue<Person> q = new LinkedList<Person>();
        q.offer(new Person("Pope"));
        q.offer(new Person("John"));
        Queue<Person> helpedQ = new LinkedList<Person>();
        Helper h = new Helper();
        h.helpPeople(q, helpedQ);
    }
}


Select 2 option(s):
33.

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

public class TestClass{
    
    public static int operate(IntUnaryOperator iuo){
        return iuo.applyAsInt(5);
    }
    
    public static void main(String[] args) {
        
        IntFunction<IntUnaryOperator> fo = a->b->a-b;  //1
        
        var x = operate(fo.apply(20)); //2
        System.out.println(x);
    }
}

Select 1 option(s):
34.

Question: What will the following lines of code print?

        System.out.println(1 + 5 < 3 + 7);
        System.out.println( (2 + 2) >= 2 + 3);

Select 1 option(s):
35.

Question: What can be done to get the following code to compile and run? (Assume that the options are independent of each other.)

public float parseFloat( String s ){
float f = 0.0f; // 1
try{
f = Float.valueOf( s ).floatValue(); // 2
return f ; // 3
}
catch(NumberFormatException nfe){
f = Float.NaN ; // 4
return f; // 5
}
finally { return f; // 6
}
return f ; // 7
}

Select 4 option(s):

36.

Question:

Given:

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

What can be inserted in the above code?

Select 5 option(s):
37.

Question:

As a part of an application, you have serialized and stored some objects of a class in the database. At another place in the same application, you deserialize those objects.

After a few months you determine that you need to add one new String field in the class.

Which of the following statements are correct regarding the above described situation?

Select 1 option(s):
38.

Question:

Your application consists of two jar files produced by two different teams - accounting-3.2.jar and reporting-5.6.jar. Classes in reporting-5.6.jar uses classes from com.abc.accounts package in accounting-3.2.jar while classes in accounting-3.2.jar do not refer to classes from reporting-5.6.jar.

The application is currently launched using the following command:
java -classpath accounting-3.2.jar;reporting-5.6.jar com.abc.reporting.Main

The accounting team has decided to modularize the new version of their jar but the reporting team hasn't.

Which of the following commands can be used to launch the reporting application using the new version of accounting jar?

Select 2 option(s):
39.

Question:

Consider the following method code:

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

            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
                System.out.println("Read and written bytes " + bytesRead);
            }
        }
        catch (  *INSERT CODE HERE*  e ) { //LINE 100
        }
        
    }


What can be inserted at //LINE 100 to make the method compile?

Select 1 option(s):
40.

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

public class PromotionTest{
   public static void main(String args[]){
      int i = 5;
      float f = 5.5f;
      double d = 3.8;
      char c = 'a';
      if (i == f) c++;
      if (((int) (f + d)) == ((int) f + (int) d)) c += 2;
      System.out.println(c);
   }
}

Select 1 option(s):
41.

Question:

Given the following complete contents of TestClass.java:

import java.util.ArrayList;
import java.util.Collections;

class Address implements Comparable<Address>{
    String street;
    String zip;
    public Address(String street, String zip){
        this.street = street; this.zip = zip;
    }
    public int compareTo(Address o) {
        int x = this.zip.compareTo(o.zip);
        return x == 0? this.street.compareTo(o.street) : x;
    }
}
public class TestClass {
    public static void main(String[] args) {
        ArrayList<Address> al = new ArrayList<>();
        al.add(new Address("dupont dr", "28217"));
        al.add(new Address("sharview cir", "28217"));
        al.add(new Address("yorkmont ridge ln", "11223"));        
        Collections.sort(al);
        for(Address a : al) System.out.println(a.street+" "+ a.zip);
    }
}


What will be printed?

Select 1 option(s):
42.

Question:

Given:

interface I { } class A implements I{
public String toString(){ return "in a"; }
}
class B extends A{
public String toString(){ return "in b"; }
}
public class TestClass {
public static void main(String[] args) {
B b = new B();
A a = b;
I i = a;
System.out.println(i);
System.out.println((B)a);
System.out.println(b);
}
}

What will be printed when the above code is compiled and run?

Select 1 option(s):
43.

Question: Which of the following sets of interface definitions are valid?

Select 1 option(s):
44.

Question:

Consider the following code.

LocalDate d = LocalDate.now();
Locale loc = new Locale("fr", "FR");
// 1 insert code here.

What should be inserted at //1 above so that it will print the date in French format?

Select 1 option(s):
45.

Question: Which of the following statements will correctly create and initialize an array of Strings to non null elements?

Select 4 option(s):
46.

Question: Which of the following are valid JDBC URLs?

Select 1 option(s):
47.

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 = List.of(
        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):
48.

Question:

Consider the following code:

        Locale.setDefault(new Locale("es", "ES"));
        ResourceBundle rb = ResourceBundle.getBundle("appmessages");
        String msg = rb.getString("greetings");
        System.out.println(msg);


You have created a valid resource bundle file named appmessages_es_ES.properties that contains 'greetings' property. However, when you run the above code, you get an exception saying, "java.util.MissingResourceException: Can't find bundle for base name appmessages, locale es_ES".

What could be the reason?

Select 1 option(s):
49.

Question: What will the following code snippet print:


Float f = null;
try{
   f = Float.valueOf("12.3");
   String s = f.toString();
   int i = Integer.parseInt(s);
   System.out.println(""+i);
}
catch(Exception e){
   System.out.println("trouble : "+f);
}

Select 1 option(s):
50.

Question:

Given:

class Booby{
}
class Dooby extends Booby{
}
class Tooby extends Dooby{
}

public class TestClass {
    Booby b = new Booby();
    Tooby t = new Tooby();
    public void do1(List<? super Dooby> dataList){
        //1 INSERT CODE HERE
    }
    public void do2(List<? extends Dooby> dataList){
        //2 INSERT CODE HERE
    }    
}

and the following four statements:

1.   b = dataList.get(0);
2.   t = dataList.get(0);
3.   dataList.add(b);
4.   dataList.add(t);

What can be inserted in the above code?

Select 1 option(s):
51.

Question:

Consider the following classes in one file named A.java...

abstract class A{
   protected int m1(){ return 0; }
}
class B extends A{
   @Override
   int m1(){ return 1; }
}

Which of the following statements are correct.

Select 1 option(s):
52.

Question:

Consider the following array definitions:

int[] array1, array2[];
int[][] array3;
int[] array4[], array5[];

Which of the following are valid statements?

Select 3 option(s):
53.

Question:

Consider the following code :

  String id = c.readLine("%s", "Enter UserId:"); //1
  System.out.println("userid is " + id); //2
  String pwd = c.readPassword("%s", "Enter Password :"); //3
  System.out.println("password is " + pwd); //4


Assuming that c is a valid reference to java.io.Console and that a user types jack as userid and jj123 as password, what will be the output on the console?

Select 1 option(s):
54.

Question:

Consider the following program:

public class TestClass{
public static void main(String[] args) { calculate(2); }
public static void calculate(int x){
String val;
switch(x){
case 2:
default:
val = "def";
}
System.out.println(val);
}
}

What will happen if you try to compile and run the program?

Select 2 option(s):
55.

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

public static void main(String[] args) {
    Stream<List<String>> s1 = Stream.of(
                Arrays.asList("a", "b"),
                Arrays.asList("a", "c")
        );

    Stream<String> news = s1.filter(s->s.contains("c"))
            .flatMap(olds -> olds.stream());
    news.forEach(System.out::print);
}

Select 1 option(s):