Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
System.in is of type java.io.InputStream and System.out and System.error of type java.io.PrintStream. public static void main(String args[]) { System.out.println("Type a character: "); int val1 = 0; int val2 = 0; String str1 = ""; String str2 = ""; try { // get single character val1 = new InputStreamReader(System.in).read(); // get single character val2 = System.in.read(); // get line BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); str1 = br.readLine(); // get line Scanner scanner = new Scanner(System.in); str2 = scanner.next(); scanner.close(); } catch (IOException ioe) { System.err.println("Cannot read input " + ioe); System.exit(-1); } System.out.println("You typed: " + val1); System.out.println("You typed: " + val2); System.out.println("You typed: " + str1); System.out.println("You typed: " + str2); } Type a character: ab cd e Phong Nog You typed: 97 You typed: 99 You typed: d e You typed: Phong public static void main(String[] args) { LocalDate date1 = LocalDate.of(2010, Month.AUGUST, 20); LocalDate date2 = LocalDate.of(2008, Month.APRIL, 21); System.out.println(Period.between(date1, date2)); System.out.println(Period.between(date1, date2).getYears()); } P-2Y-3M-29D -2 The Instant class stores the number of seconds elapsed since the start of the Unix epoch (1970-0101t00:00:00Z). the Instant class is suitable for storing a log of application events in a file as timestamp values. try { PrintStream ps = new PrintStream("myLog.txt"); System.setErr(ps); System.err.println(System.currentTimeMillis()); } catch (Exception ex) { } } When you execute this code segment, the program will create a file named ?og.txtand print the string 471744680789” in that file. public static void main(String args[]) { try { int a; System.out.print("Type some words: "); while((a = System.in.read()) != -1){ System.out.print((char)a); }; } catch (IOException e) { e.printStackTrace(); } } Type some words: Phong Ngo Phong Ngo public static void main(String[] files) { String srcFile = "log.txt"; String dstFile = "log1.txt"; try (BufferedReader inputFile = new BufferedReader(new FileReader(srcFile)); BufferedWriter outputFile = new BufferedWriter(new FileWriter(dstFile))){ int ch = 0; while ((ch = inputFile.read()) != -1) { outputFile.write((char) ch); } } catch (FileNotFoundException fnfe) { System.err.println("Cannot open the file " + fnfe.getMessage()); } catch (IOException ioe) { System.err.printf("Error when processing file; exiting ... "); } } Copy content from ?og.txtto ?og1.txt” public static void main(String[] args) { // read the input file String fileName = "log1.txt"; // automatically sort the words in alphabetical order Set<String> words = new TreeSet<>(); try (Scanner tokenizingScanner = new Scanner(new FileReader(fileName))){ tokenizingScanner.useDelimiter("\\W"); // while space while (tokenizingScanner.hasNext()) { String word = tokenizingScanner.next(); if (!word.equals("")) { words.add(word.toLowerCase()); } } for (String word : words) { System.out.print(word + '\t'); } } catch (FileNotFoundException fnfe) { System.err.println("Cannot read the input file"); } } File: ngo Thanh Phong Print: ngo phong thanh class Base { } class DeriOne extends Base { } class DeriTwo extends Base { } class ArrayStore { public static void main(String[] args) { Base[] baseArr = new DeriOne[3]; baseArr[0] = new DeriOne(); baseArr[2] = new DeriTwo(); System.out.println(baseArr.length); } } this program throws an ArrayStoreException Which of the following method(s) from Objectclass can be overridden finalize(), clone() class Color { int red, green, blue; Color() { this(10, 10, 10); } Color(int r, int g, int b) { red = r; green = g; blue = b; } String toString() { return "The color is: " + " red = " + red + " green = " + green + " blue = " + blue; } public static void main(String[] args) { // implicitly invoke toString method System.out.println(new Color()); } } Compiler error: attempting to assign weaker access privileges; toStringwas public in Object Static interface method cannot be inherited. interface A { public static int compute (){ return 1 + 1; } } interface AA extends A{ } class X implements A, AA{ } public class Test { int a = A.compute(); int aa = AA.compute(); // Error } X can implement multiple interfaces each of which can have a static implementation. Therefore, the compiler would not know which one to choose? When you create an anonymous class for an interface, it extends from Object. For example, button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { } } ); But if you make an anonymous class from another class then it extends from that class. For example, consider the following class: class MyListener implements ActionListener { public void actionPerformed(ActionEvent ae) { System.out.println("MyListener class"); } } button.addActionListener( new MyListener() { public void actionPerformed(ActionEvent ae) { System.out.println("Anonymous Listener class"); } } ); Here the anonymous class actually extends from MyListener class and successfully overrides the actionPerformed() method. You cannot extend an enum from another enum or class because an enum implicitly extends java.lang.Enum. But an enum can implement interfaces. Compiler provides an enum with two public static methods automatically - values() and valueOf(String). The values method returns an array of its constants and valueOf method tries to match the String argument exactly (i.e. case sensitive) with an enum constant and returns that constant if successful otherwise it throws java.lang.IllegalArgumentException. class Test { public enum K { PHONG, NGO }; public static void main(String[] args) { System.out.println(K.valueOf("NGO")); System.out.println(K.values()); System.out.println(K.values().length); } } Print: NGO [LTest$K;@6d06d69c 2 What classes can a non-static nested class extend? Any class. An anonymous class can be declared in a static method. abstract class SomeClass { public abstract void m1(); } public class TestClass { public static SomeClass getSomeClass() //note static { return new SomeClass() { public void m1() { } }; } } Anonymous classes cannot be declared static. Note the difference between an Inner class and a static nested class. Inner class means a NON STATIC class defined inside a class. public class A // outer class{ static public class B // Static Nested class . It can be used in other // places: A.B b = new A.B(); There is no outer instance. { } class C // Inner class. It can only be used like this: A.C c = new A().new // C(); Outer instance is needed. { } } public static String joinWithPrefixPostfix(String[] arrayOfString){ return Arrays.asList(arrayOfString) .stream() //.map(...) .collect(Collectors.joining(",","[","]")); } As we can see in the Collectors.joining() method, we are declaring our prefix as ‘[‘ and postfix as ‘]’; hence the generated String will be created with declared […..] format. Convert a String to a Character list: public static List<Character> splitToListOfChar(String str) { return str.chars() .mapToObj(item -> (char) item) .collect(Collectors.toList()); } One interesting fact to note here it that the chars() method converts the String into a stream of Integer where each Integer value denotes the ASCII value of each and every Char sequence. That’s why we need to explicitly typecast the mapper object in the mapToObj() method. One can define a class as a static member of any top-level class. Now consider the following contents of a file named I1.java ... public interface I1 { public void mA(); public interface InnerI1 { int k = 10; public void innerA(); } } Here, interface InnerI1 is implicitly STATIC and so is called as static nested interface. 'k' is a static (& final) member of this interface. If you do 'javap' on I1 it prints: Compiled from I1.java public interface I1 /* ACC_SUPER bit NOT set */ { public abstract void mA(); public static interface I1. InnerI1 /* ACC_SUPER bit NOT set */ { public static final int k; public abstract void innerA(); } } This interface can be referred to in other places like: class MyClass implements I1.InnerI1 { ... } Anonymous inner classes cannot have any 'extends' or 'implements' clause. Anonymous inner classes cannot be static. Consider the anonymous inner class for catching action events: ActionListener al = new ActionListener(){ public void actionPerformed(ActionEvent e){ } }; Here, the anonymous class implicitly extends Object and implements the interface ActionListener. Explicit extends or implements clauses are not allowed for such classes. Other inner class (i.e. non anonymous) can have them. Consider the following (although of no use) class: public class TestClass { public TestClass(int i) { } public void m1() { TestClass al = new TestClass(10){ public void actionPerformed(ActionEvent e) { } }; } } This illustrates: 1. Inner class can extend the outer class. 2. Anonymous inner class can be created for classes. (Not just for interfaces). They implicitly extend the class.(Here, TestClass) Anonymous inner class can have initialization parameter. (If the class they extend has a corresponding constructor). 3. Type A is a template for other types in the application. Type A implements method process(). Type A declares but does not implement method prepare(). A may be an abstract class or an interface. You want to execute your tasks after a given delay. Which ExecutorService would you use ? ScheduledExecutorService The following are the details of the interface ScheduledExecutorService: All Superinterfaces: Executor, ExecutorService All Known Implementing Classes: ScheduledThreadPoolExecutor An ExecutorService that can schedule commands to run after a given delay, or to execute periodically. The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution. The scheduleAtFixedRate and scheduleWithFixedDelay methods create and execute tasks that run periodically until cancelled. Following is a usage example that sets up a ScheduledExecutorService to beep every ten seconds for an hour: import static java.util.concurrent.TimeUnit.*; import java.util.concurrent.*; public class Test { private final ScheduledExecutorService scheduler = Executors .newScheduledThreadPool(1); public void beepForAnHour() { final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate( () -> System.out.println("beep"), 0, 10, SECONDS); scheduler.schedule(() -> beeperHandle.cancel(true), 60 * 60, SECONDS); } public static void main(String args[]) { new Test().beepForAnHour(); } } Local (i.e. inside a method) nested classes cannot be declared static. Inner classes can declare a static members only if it is a constant (i.e. final). Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. the name of the method used to schedule a thread for execution: Start Following are some of the important interfaces with their corresponding implementations provided in the JDK. Map : HashMap and TreeMap. SortedMap : TreeMap NavigableMap : TreeMap, ConcurrentSkipListMap. Set : AbstractSet and HashSet SortedSet : TreeSet NavigableSet : ConcurrentSkipListSet, TreeSet List : AbstractList, LinkedList, Vector, ArrayList For answering questions in the exam, it is extremely important for you to understand the following description given for the equals method: It is reflexive: for any reference value x, x.equals(x) should return true. It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified. For any non-null reference value x, x.equals(null) should return false. public int hashCode() Returns a hash code value for the object. A functional interface is an interface that contains exactly one abstract method. It may contain zero or more default methods and/or static methods in addition to the abstract method. An example of functional interface: import java.util.ArrayList; import java.util.List; interface Predicate<T> { boolean test(T t); } class Data { public int value; } public class Test { public void printImportantData(List<Data> dataList, Predicate<Data> p) { for (Data d : dataList) { if (p.test(d)) System.out.println(d); } } public static void main(String args[]) { Data data = new Data(); data.value = 4; List<Data> list = new ArrayList<>(); list.add(data); new Test().printImportantData(list, d -> d.value > 1); } } Which variables of the encapsulating class can an inner class access, if the inner class is defined in an instance method of the encapsulating class: All static variables All final instance variables All instance variables All final and effectively final automatic variables public class Test { final int fi = 4; static final int sfi = 10; static int si = 3; int ii = 20; public void inner() { int ai1 = 30; // automatic variable int ai2 = 30; // automatic variable ai2 = 31;// ai is not effectively final anymore. static int s = 3; //Compile failed final int fai = 40; // automatic final variable class Inner { public Inner() { System.out.println(sfi + fi + si + ii + fai + ai1); } } new Inner(); } public static void main(String[] args) { new Test().inner(); } } Which variables declared in the encapsulating class or in the method, can an inner class access if the inner class is defined in a static method of encapsulating class? All static variables All final or effectively final variables public class Test { static int si = 10; int ii = 20; public static void inner() { int ai = 30; // automatic variable ai = 31; // ai is not effectively final anymore. final int fai = 40; // automatic final variable static int s = 3; // Compile failed class Inner { public Inner() { System.out.println(si + " " + fai); } } new Inner(); } public static void main(String[] args) { Test.inner(); } } A JDBC driver implementation must provide implementation classes: java.sql.Driver java.sql.Connection java.sql.Statement java.sql.ResultSet public interface Callable<V>{ V call() throws Exception; } A task that returns a result and may throw an exception. Implementers define a single method with no arguments called call. The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception. A java.util.concurrent.Callable is used when you expect your threads to return a computed result. You can submit instances of a Callable to an ExecutorService: Future<Long> result = null; ExecutorService executor = Executors.newFixedThreadPool(10); Callable<Long> worker = new MyCallable(); //This call returns immediately. result = executor.submit(worker); The result of the Callable's call() method can be retrieved from the Future object. //Call to Future.get() blocks until the result is available. //so don't call it here. //System.out.println("Result is "+result.get()); while(!result.isDone()){ try { //Do something else and check later Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } //Since result.isDone() is true, the result is available now System.out.println("Result is "+result.get()); To enable assertions, you must use: java -ea TestClass or java -enableassertions TestClass Code that uses generic collection classes can interoperate with code that uses raw collections classes because of type erasure Type erasure means that a compiled java class does not contain any of the generic information that is present in the java file. In other words, the compiler removes the generic information from a java class when it compile it into byte code. For example, List<String> list; and List list; are compiled to the same byte code. Therefore, at run time, it does not matter whether you've used generic classes or not and this allows both kinds of classes to interoperate because they are essentially the same class to the JVM. Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead. Reification: This is just the opposite of type erasure. Here, all the type information is preserved in the byte code. In Java, arrays are reified. For example, ArrayList[] alArray = new ArrayList[1]; Collection[] cArray = alArray; cArray[0] = new HashSet(); The above code will compile fine. But it will throw an java.lang.ArrayStoreException at run time because the byte code contains the information that cArray actually points to an array of ArrayLists and not of HashSets. A Callable cannot be passed to Thread for Thread creation but a Runnable can be. i.e. new Thread( aRunnable ); is valid. But new Thread( aCallable ); is not. Therefore, if you want to execute a task directly in a Thread, a Callable is not suitable. You will need to use a Runnable. You can achieve the same by using an ExecutorService.submit( aCallable ), but in this case, you are not controlling the Thread directly. When your task might throw a checked exception and you want to execute it in a separate Thread. package com.enthu; public class Resource { private String data = "DATA"; String getData(){ return data; } void setData(String data){ this.data = data == null ? "" : data; } boolean equals(Resource r){ return (r != null && r.getData().equals(this.getData())); } } If two distinct Resource objects are determined to be equal using a call to equals method, then their 'data' fields must have contained the same string value. Two distinct Resource objects may be considered "not equal" even if their data values are same. here are several concepts at play here: 1. The signature of the standard equals method in Object class is public boolean equals(Object ). So you cannot override that method with anything which is not public. In this case, however, Resource class does not even have equals(Object ) method. So it is not overriding Object class's equals method. It is overloading it and is thus free to make it private, protected, or default access. 2. The parameter type of Object class's equals method is Object, which means that you can pass any object as an argument. 3. A method with default access is accessible only to classes within that package. 4. When multiple methods of a class are applicable to be selected, the most specific method is chosen. So in effect, Resource class has two equals methods: 1. public boolean equals(Object ) : Inherited from Object class. Accessible from any class. Default behavior is to check whether the two references point to the same object or not. 2. boolean equals(Resource ) : Defined in Resource class. Accessible only from classes within the same ( com.enthu ) package. Default behavior is to check the contents of data field. class Book { protected final int pages = 100; final void mA() { System.out.println("In B.mA " + pages); } } class Encyclopedia extends Book { private int pages = 200; // 1 void mB() { System.out.println("In E.mB " + pages); } void mA(){ //2 System.out.println("In E.mA "+pages); } } public class Test { public static void main(String[] args) { Book o1 = new Encyclopedia(); // 3 Book o2 = new Book(); o1.mA(); // 4 o1.mB(); //5 o2.mA(); } } Which lines will cause compilation to fail? //2 and //5 //1 is ok. Remember that variables are not overridden. They are shadowed and it is ok for a subclass to shadow a variable defined in the base class. Note that if you do System.out.println(o1.pages); it will print 100. But if you do System.out.println(((Encyclopedia)o1).pages); it will not compile because pages has private access in Encyclopedia. For the same reason, if you have Encyclopedia o3 = new Encyclopedia(); and if you do System.out.println(o3.pages); it will not compile. But System.out.println(((Book)o3).pages); will compile fine and print 100;. //2 will fail because you cannot override a final method. What can you do to make a class immutable? Make member fields private and final and include public getters for them. Make the class final. Instead of a default no-args constructor, create a constructor that initializes the members. public class Test{ private int a; private int b; public void setA(int i){ this.a = i; } public int getA(){ return this.a; } public void setB(int i){ this.b = i; } public int getB(){ return b; } public boolean equals(Object obj) { return ( obj instanceof Test && this.a == ((Test) obj).a ); } public int hashCode() { //1 } } Which of the following options would satisfy the equals and hashCode contract at //1? return 0; return a; return a*a; return a/2; return a+b; // Not valid because two object will be equal if their a values are same, but they will return different hashcodes, if their b values are different. import java.util.*; interface Birdie { void fly(); } class Dino implements Birdie { public void fly() { System.out.println("Dino flies"); } public void eat() { System.out.println("Dino eats"); } } class Bino extends Dino { public void fly() { System.out.println("Bino flies"); } public void eat() { System.out.println("Bino eats"); } } public class Test { public static void main(String[] args) { List<Birdie> m = new ArrayList<>(); m.add(new Dino()); m.add(new Bino()); for (Birdie b : m) { b.fly(); b.eat(); // Not compile ((Bino)b).eat(); //OK } } } public class GoodOne { int theval; public int hashCode() { return theval%3; } public boolean equals(Object obj) { try{ // 1 insert code here. }catch(Exception e) { return false; } } } Which of the following options may be inserted at //1 so that the equals and hashCode contract is not violated? return this == obj? true : (theval%3 == 0 && ((GoodOne)obj).theval%3==0) ? true :false; //OK return true; // Not OK return theval%2 == 0? true :false; // Not OK return ((int)Math.random())*10%3 == 0? true :false; // Not OK return false; //Not OK Option 2 is correct because hashCode() for all the multiples of 3 is 0. Therefore, if we return true in the equals() method for all the multiples of 3, the condition will be met. It also returns true if the object is compared with itself. Option 3 is not correct because then 2 and 6 would be considered equal, but their hash codes will be different (2 and 0). This means that the objects are considered equal if their theval%3 is 0. Further, if the two objects are determined to be equal, then their hashcodes ( theval%3) will always be same (zero). So it satisfies the requirements for hashCode and equals methods. The rule to remember is: If the equals() method returns true, the hashCode() of the two objects MUST be the same. The reverse is desirable but not necessary. Further, equals method must follow these rules: It should be reflexive: for any reference value x, x.equals(x) should return true. It should be symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It should be transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It should be consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified. For any non-null reference value x, x.equals(null) should return false. public class Test { int i = 10; class Inner { public void methodA(){ System.out.println(i); //OK System.out.println(Test.this.i); //OK } } } An enum cannot be defined inside any method or constructor. public enum EnumA{ A, AA, AAA}; //1 public class Test {} Since both EnumA and TestClass are public, they must be defined in a file with a name of EnumA.java and TestClass.java respectively. 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 ? public void m1() throws SQLException, IOException; // NOT OK public void m1(){}; //OK Which of the following is a valid reason for creating an abstract class? You need to have a root class for a hierarchy of related classes. You want to pass different implementations for the same abstraction in method calls. You are only modeling the behavior of an abstract concept. (An interface is used for this purpose.) public enum Switch{ ON, OFF } if( s == Switch.OFF) { System.out.println("It is off!"); } if( s.equals(Switch.OFF)) { System.out.println("It is off!"); } switch(s) { case OFF : System.out.println("It is off!"); break; } switch(s) { case Switch.OFF : System.out.println("It is off!"); break; } An enum switch case label must be the unqualified name of an enumeration constant. So it should be: case OFF instead of case Switch.OFF. package mypack; public class TestOuter { public static class TestInner { } } Which of the following options are correct? new TestOuter.TestInner(). class OuterWorld { private InnerPeace i = new InnerPeace(); private class InnerPeace { private String reason = "none"; } } What can be the class of an object 'x' that can access 'reason'? OuterWorld Even though reason is a private member of InnerPeace, InnerPeace itself is a member of OuterWorld and so OuterWorld can access 'reason'. For example, you can have the following method defined inside OuterWorld and call it from outside OuterWorld: void m() { System.out.println(i.reason); } public class TestClass { public class A { A(){ System.out.println("A"); } } public static class B { B(){ System.out.println("B"); } } public void useClasses() { new TestClass().new A(); new TestClass.B(); new A(); new TestClass.A(); } public static void main(String[] args){ new TestClass().useClasses(); } } A, B, A, A enum Season{ SPRING, SUMMER, FAIL, WINTER{ public String info(){ return "cold"; } }; public String info(){ return "season"; } } //OK public static void main(String args[]) { String[] names = new String[]{"bb23", "BB23", "23bB", "b23B", "bB23", "B23b", "23Bb"}; System.out.println(Arrays.toString(names)); List<String> list = Arrays.asList(names); Collections.sort(list); System.out.println(Arrays.toString(names)); System.out.println(list); } [bb23, BB23, 23bB, b23B, bB23, B23b, 23Bb] [23Bb, 23bB, B23b, BB23, b23B, bB23, bb23] [23Bb, 23bB, B23b, BB23, b23B, bB23, bb23] public static void main(String args[]) { Deque<Integer> d = new ArrayDeque<>(); d.add(1); d.add(0); d.push(2); d.pop(); d.offerFirst(3); d.remove(); System.out.println(d); } [1, 0] add(e) is a queue method that adds the element to the end while push() is a stack method that adds the element to the front. Therefore, the contents of d change as follows: 1 2, 1 Now, pop() is a stack method that removes the element from the front, so d now contains: 1 offer(e) is a queue method that adds the element to the end. But offerFirst(e), adds the element in the front. Therefore, the contents of d change to: 3, 1 remove() is a queue method that removes the element from the front. Therefore, d now contains: 1, 0 Queue is a FIFO structure (i.e. add to the end and remove from the front). It has methods offer(e)/add(e) and pop()/poll()/remove() for this purpose. Note that offer and add are similar while poll and remove are similar. peek(), peekFirst(): return the first element from the front of the queue but does not remove it from the queue. peekLast() : returns the last element from the end of the queue but does not remove it from the queue. pollFirst()/pollLast() - poll is a Queue method. Therefore pollFirst and pollLast will remove elements from the front and from the end respectively. offerFirst(e)/offerLast(e) - offer is a Queue method. Therefore offerFirst and offerLast will add elements to the front and to the end respectively. addFirst(e)/addLast(e) - add is a Queue method. Therefore addFirst and addLast will add elements to the front and to the end respectively. class Booby{} class Dooby extends Booby{} class TooBy extends Dooby{} public class Test { Booby b = new Booby(); TooBy t = new TooBy(); public static void main(String args[]) { } public void addData1(List<? super Dooby> dataList) { dataList.add(t); } public void addData2(List<? extends Dooby> dataList){ b = dataList.get(0); } } 1. addData1(List<? super Dooby> dataList) : This means that dataList is a List whose elements are of a class that is either Dooby or a super class of Dooby. We don't know which super class of Dooby. Thus, if you try to add any object to dataList, it has to be a assignable to Dooby. Thus, dataList.add(b); will be invalid because b is not assignable to Dooby. Further, if you try to take some object out of dataList, that object will be of a class that is either Dooby or a Superclass of Dooby. Only way you can declare a variable that can be assigned the object retrieved from dataList is Object obj. Thus, t = dataList.get(0); and b = dataList.get(0); are both invalid. 2. addData2(List<? extends Dooby> dataList) This means that dataList is a List whose elements are of a class that is either Dooby or a subclass of Dooby. Since we don't know which subclass of Dooby is the list composed of, there is no way you can add any object to this list. If you try to take some object out of dataList, that object will be of a class that is either Dooby or a subclass of Dooby and thus it can be assigned to a variable of class Dooby or its superclass.. Thus, t = dataList.get(0) ; is invalid. Print: dick, hary and tom in that order: public static void main(String args[]) { Collection<String> treeSet = new TreeSet<>(); treeSet.add("tom"); treeSet.add("dick"); treeSet.add("harry"); treeSet.add("tom"); treeSet.forEach(System.out::println); } dick harry tom Map hm = new ConcurrentHashMap(); hm.put(null, "asdf"); //1 hm.put("aaa", null); //2 hm = new HashMap(); hm.put(null, "asdf"); //3 hm.put("aaa", null); //4 List list = new ArrayList(); list.add(null); //5 list.add(null); //6 list = new CopyOnWriteArrayList(); list.add(null); //7 Which of the above lines will throw NullPointerException? 1 and 2. Remember that HashMap supports adding null key as well as null values but ConcurrentHashMap does not. Inserting null key or null in a ConcurrentHashMap will throw a NullPointerException. Some candidates have reported getting a question on this aspect of ConcurrentHashMap. 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. => LinkedHashMap The LinkedHashMap class maintains the elements in the order of their insertion time. This property can be used to build the required cache as follows: 1. Insert the key-value pairs as you do normally where key will be the object identifier and value will be the object to be cached. 2. When a key is requested, remove it from the LinkedHashMap and then insert it again. This will make sure that this pair marked as inserted latest. 3. If the capacity is full, remove the first element. Note that you cannot simply insert the key-value again (without first removing it) because a reinsertion operation does not affect the position of the pair. 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 It will throw an exception at run time due to code at //1.(It will throw a ClassCastException.) Remember that any time you want to sort a collection of items, you need code that "sorts" the elements. equals method can only tell whether two objects are equal or not but it cannot tell which object comes before and which after. To figure this out, either the objects themselves should be able to tell that (by implementing java.lang.Comparable interface) or you need to use a separate java.util.Comparator instance that can compare the objects. Here, no Comparator is supplied to the sorted() method. Therefore, at run time, when the sorted method tries to cast Book object to Comparable, it will fail. 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); } } It will compile without warning but will throw an exception at runtime. Note that TreeSet is an ordered set that keeps its elements in a sorted fashion. When you call the add() method, it immediately compares the element to be added to the existing elements and puts the new element in its appropriate place. Thus, the foremost requirement of a TreeSet is that not only the elements must implement Comparable interface (which has the compareTo() method), but they must also be mutually comparable. For example, you might have two classes \\\A\\\ and \\\B\\\ both implementing Comparable interface. But if their compareTo() method does not work with both the types, you cannot add both type of elements in the same TreeSet. In this question, Person class does not implement Comparable interface. Ideally, when you add the first element, since there is nothing to compare this element to, there should be no exception. But when you add the second element, TreeSet tries to compare it with the existing element, thereby throwing ClassCastException because they don't implement Comparable interface. However, this behavior was changed in the TreeSet implementation recently and it throws a ClassCastException when you add the first element itself. The compiler knows nothing about this requirement of TreeSet since it is an application level requirement and not a language level requirement. So the program compiles fine without any warning. public <E extends CharSequence> Collection<E> getWordsStartWith(Collection<E> input, char ch){ Collection<E> returnValue = new ArrayList<E>(); int len = input.size(); for(E e : input){ if(e.charAt(0) == ch) returnValue.add(e); } return returnValue; } public void checkIt(){ List<String> a = new ArrayList<String>(); a.add("apple"); a.add("cherry"); Set<StringBuffer> b = new HashSet<StringBuffer>(); b.add(new StringBuffer("pineApple")); Collection<String> ac = getWordsStartWith(a, 'a'); Collection<StringBuffer> bc = getWordsStartWith(b, 'b'); } public double process(double payment, int rate) { double defaultrate = 0.10;// 1 if (rate > 10) defaultrate = rate;// 2 class Implement { public int apply(double data) { Function<Integer, Integer> f = x -> x + (int) (x * return f.apply((int) data); // 4 } defaultrate);// 3 } Implement i = new Implement(); return i.apply(payment); } What changes, when applied independent of each other, will enable the following code to compile? There are two ways: Remove code at //2, Change //3 to: Function<Integer, Integer> f = x->x+(int)(x*rate); public double process(double payment, int rate) { double defaultrate = 0.10;// 1 if (rate > 10) defaultrate = rate;// 2 class Implement { public int apply(double data) { BiFunction<Integer, Double, Integer> f = (m, n)->m+(int)(n*m); return f.apply((int)data, defaultrate); //Not compile } } Implement i = new Implement(); return i.apply(payment); } Because Variable: defaultrate is not final or effective final variable. public double process(double payment, int rate) { double defaultrate = 0.10;// 1 if (rate > 10) defaultrate = rate;// 2 class Implement { public int apply(double data) { BiFunction<Integer, Double, Integer> f = (m, n)->m+(int)(n*m); return f.apply((int)data, payment); //OK } } Implement i = new Implement(); return i.apply(payment); } List<Integer> ls = Arrays.asList(3,4,6,9,2,5,7); System.out.println(ls.stream().reduce(Integer.MIN_VALUE, (a, b)->a>b?a:b)); //1 System.out.println(ls.stream().max(Integer::max).get()); //2 System.out.println(ls.stream().max(Integer::compare).get()); //3 System.out.println(ls.stream().max((a, b)->a>b?a:b)); //4 System.out.println(ls.stream().max((a, b)->a>b?a:b).get()); //5 3 9 9 Optional[3] 3 1. The reduce method needs a BinaryOperator. This interface is meant to consume two arguments and produce one output. It is applied repeatedly on the elements in the stream until only one element is left. The first argument is used to provide an initial value to start the process. (If you don't pass this argument, a different reduce method will be invoked and that returns an Optional object. ) 2. The Stream.max method requires a Comparator. All you need to implement this interface using a lambda expression is a reference to any method that takes two arguments and returns an int. The name of the method doesn't matter. That is why it is possible to pass the reference of Integer's max method as an argument to Stream's max method. However, Integer.max works very differently from Integer.compare. The max method returns the maximum of two numbers while the compare method returns a difference between two numbers. Therefore, when you pass Integer::max to Stream's max, you will not get the correct maximum element from the stream. That is why //2 will compile but will not work correctly. //4 is basically same as //2. It will not work correctly for the same reason. List<Double> list = Arrays.asList(10.5, 15.5); list.stream().map(x -> x + 10); list.stream().forEach(System.out::println); 10.5 15.5 Remember that Double objects are immutable. Therefore, the first call to forEach does not change the elements in the original list on which the stream is based. It only replaces the elements of that stream with new ones. Therefore, when you call dlist.stream() the second time, a new stream is created and it has the same elements as the list i.e. 10.0 and 12.0. If it were a Stream of mutable objects such as StringBuilders and if you append something to the elements in the first forEach, that would change the original StringBuilder objects contained in the list. In that case, the second forEach will actually print the updated values. For example, the following code will indeed print ab and aab. List<StringBuilder> dList = Arrays.asList(new StringBuilder("a"), new StringBuilder("aa")); dList.stream().forEach(x->x.append("b")); dList.stream().forEach(x->System.out.println(x)); List<Double> list = Arrays.asList(10.5, 15.5); list.stream().map(x -> x + 10).forEach(System.out::println); 20.5 25.5 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? hm.forEach((key, entry)->System.out.println(entry)); This will compile and run fine but will only print the values and not the keys. hm.forEach(System.out.println("%d %s")); This will not compile because Map's forEach method requires BiConsumer object. A BiConsumer takes exactly two parameters but println method takes only one and therefore cannot be used to implement BiConsumer. hm.forEach((key, value)->System.out.printf("%d %s ", key, value)); //OK hm.forEach(System.out::println); //Not compile This will not compile because Map's forEach method requires BiConsumer object. A BiConsumer takes exactly two parameters but println method takes only one and therefore cannot be used to implement BiConsumer. hm.forEach(entry->System.out.println(entry)); //Not compile This will not compile for the same reason as above. This lambda expression does not capture BiConsumer interface. BinaryOperator<String> bo = (s1, s2) -> s1.concat(s2); List<String> names = new ArrayList<>(); names.add("Bill"); names.add("George"); names.add("Obama"); String finalvalue = names.stream().reduce("Hello : ", bo); System.out.println(finalvalue); Hello : BillGeorgeObama The reduce method of a Stream is mean to reduce a stream into just one value. It combines two elements of a stream at a time using a given BinaryOperator, and replaces those two elements in the stream with the return value of the apply method of BinaryOperator. It keeps on doing this reduction until there is just one value left. There are three versions of reduce : Optional<T> reduce(BinaryOperator<T> accumulator) Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any. T reduce(T identity, BinaryOperator<T> accumulator) Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value. Which of the following standard functional interfaces is most suitable to process a large collection of int primitives and return processed data for each of them? IntFunction //imports not shown class Movie{ static enum Genre {DRAMA, THRILLER, HORROR, ACTION }; private Genre genre; private String name; Movie(String name, Genre genre){ this.name = name; this.genre = genre; } //accessors not shown } public class FilteringStuff { public static void main(String[] args) { List<Movie> movies = Arrays.asList( new Movie("On the Waterfront", Movie.Genre.DRAMA), new Movie("Psycho", Movie.Genre.THRILLER), new Movie("Oldboy", Movie.Genre.THRILLER), new Movie("Shining", Movie.Genre.HORROR) ); Predicate<Movie> horror = mov->mov.getGenre() == Movie.Genre.THRILLER; Predicate<Movie> name = mov->mov.getName().startsWith("O"); //1 INSERT CODE HERE .forEach(mov->System.out.println(mov.getName())); } } movies.stream().filter(horror).filter(name) void java.util.Map.forEach(BiConsumer<T, U>): Method ?oreachof Map require a parameter is a BiConsumer<T,U>, not Consumner<T>. Example: List<Book> books = Arrays.asList( new Book("Atlas Shrugged", 10.0), new Book("Freedom at Midnight", 5.0), new Book("Gone with the wind", 5.0) ); Map<String, Double> bookMap = books.stream().collect(Collectors.toMap(b -> b.getTitle(), b -> b.getPrice())); BiConsumer<String, Double> func = (a, b) -> { if(a.startsWith("F")){ System.out.println(b); } }; bookMap.forEach(func); 5.0 AtomicInteger ai = new AtomicInteger(); Stream<Integer> stream = Stream.of(11, 11, 22, 33).parallel(); stream.filter(e -> { ai.incrementAndGet(); return e % 2 == 0; }).forEach(System.out::println); System.out.println(ai); Print: 22 4 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); Print: 0 Notice that filter is an intermediate operation. It does not do anything until a terminal operation is invoked on the stream. Therefore, in this case, ai will remain 0. public static void main(String[] args) { AtomicInteger ai = new AtomicInteger(); Stream<Integer> stream = Stream.of(11, 11, 22, 33).parallel(); stream.filter(e -> { ai.incrementAndGet(); return e % 2 == 0; }); stream.forEach(System.out::println); System.out.println(ai); } => Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed public class Course{ private String id; private String category; public Course(String id, String category){ this.id = id; this.category = category; } public String toString(){ return id+" "+category; } //accessors not shown } What will the following code print? List<Course> s1 = Arrays.asList( new Course("OCAJP", "Java"), new Course("OCPJP", "Java"), new Course("C#", "C#"), new Course("OCEJPA", "Java") ); System.out.println(s1.get(0)); s1.stream() .collect(Collectors.groupingBy(c -> c.getCategory())) .forEach((m, n) -> System.out.println(m)); s1.stream() .collect(Collectors.groupingBy(c->c.getCategory())) .forEach((m, n)->System.out.println(n)); => OCAJP Java C# Java [C# C#] [OCAJP Java, OCPJP Java, OCEJPA Java] It is important to understand that the return type of the collect method depends on the Collector that is passed as an argument. In this case, the return type would be Map<K, List<T>> because that is the type specified in the Collector returned by the groupingBy method. Java 8 has added a default forEach method in Map interface. This method takes a BiConsumer function object and applies this function to each key-value pair of the Map. In this case, m is the key and n is the value. A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list. The streams classes have multiple forms of general reduction operations, called reduce() and collect(), as well as multiple specialized reduction forms such as sum(), max(), or count(). The Collector created by Collectors.toMap throws java.lang.IllegalStateException if an attempt is made to store a key that already exists in the Map. Example: List<Book> books = Arrays.asList( new Book("Gone with the wind", 5.0), new Book("Gone with the wind", 10.0), new Book("Atlas Shrugged", 15.0) ); books.stream().collect(Collectors.toMap((b->b.getTitle()), b>b.getPrice())).forEach((a, b)->System.out.println(a+" "+b)); If you want to collect items in a Map and if you expect duplicate entries in the source, you should use Collectors.toMap(Function, Function, BinaryOperator) method. The third parameter is used to merge the duplicate entries to produce one entry. For example, in this case, you can do: Collectors.toMap(b->b.getTitle(), b->b.getPrice(), (v1, v2)->v1+v2) This Collector will sum the values of the entries that have the same key. Therefore, it will print : Gone with the wind 15.0 Atlas Shrugged 15.0 List<Double> list = Arrays.asList(10.5, 15.5); DoubleStream intStream1 = list.stream(); //Not compile Stream<Double> intStream2 = list.stream(); //OK List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17); //1 Stream<Integer> primeStream = primes.stream(); //2 Predicate<Integer> test1 = k->k<10; //3 long count1 = primeStream.filter(test1).count();//4 Predicate<Integer> test2 = k->k>10; //5 long count2 = primeStream.filter(test2).count(); //6 System.out.println(count1+" "+count2); //7 Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed The only problem with the given code is that a stream cannot be reused once a terminal operation has been invoked on it. Therefore, line 6 will throw java.lang.IllegalStateException: stream has already been operated upon or closed. It will print 34 if lines 4 to 7 are replaced with: primeStream.collect(Collectors.partitioningBy(test1, Collectors.counting())) .values().forEach(System.out::print); (3 elements >= 10 and 4 elements < 10) List<Double> list = Arrays.asList(10.5, 15.5); Stream<Double> intStream = list.stream(); Function<Double, Double> test = x -> x + 1; intStream.map(test).forEach(System.out::println); 11.5 16.5 Which of the following method(s) of java.util.stream.Stream interface is/are used for reduction? Reduce, min and max are valid reduction operations. The Stream version of these methods take a Comparator as an argument, while the versions in specialized streams such as IntStream and DoubleStream do not take any argument. Sum: This is a valid reduction operation but it is not in java.util.stream.Stream interface. Methods to sum up the numbers in a stream are available in specialized Stream interfaces such an IntStream, LongStream, and DoubleStream. 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); List<Book> books = Arrays.asList( new Book( "There is a hippy on the highway", "Thriller", "James Hadley Chase"), new Book("Coffin from Hongkong", "Thriller", "James Hadley Chase"), new Book("The Client", "Thriller", "John Grisham"), new Book("Gone with the wind", "Fiction", "Margaret Mitchell")); Map<String, Map<String, List<Book>>> classified = null; classified = books.stream().collect(Collectors.groupingBy(Book::getGenre, Collectors.groupingBy(Book::getAuthor))); System.out.println(classified); {Thriller={James Hadley Chase=[Book@448139f0, Book@7cca494b], John Grisham=[Book@7ba4f24f]}, Fiction={Margaret Mitchell=[Book@3b9a45b3]}} public V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key. For example, to either create or append a String msg to a value mapping: map.merge(key, msg, String::concat) If the function returns null the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged. Map<String, Integer> map1 = new HashMap<>(); map1.put("a", 1); map1.put("b", 1); map1.merge("b", 1, (i1, i2) -> i1 + i2); map1.merge("c", 3, (i1, i2) -> i1 + i2); System.out.println(map1); {a=1, b=2, c=3} Map<String, Integer> map1 = new HashMap<>(); map1.put("a", 1); map1.put("b", 1); map1.merge("b", 1, (i1, i2) -> i1 =- i2); map1.merge("c", 3, (i1, i2) -> i1 /= i2); System.out.println(map1); {a=1, b=-1, c=3} Map<String, Integer> map1 = new HashMap<>(); map1.put("a", 1); map1.put("b", 1); map1.merge("b", 1, (i1, i2) -> i1 =- i2); map1.merge("c", null, (i1, i2) -> i1 + i2); System.out.println(map1); Exception in thread "main" java.lang.NullPointerException Map<String, Integer> map1 = new HashMap<>(); map1.put("a", 1); map1.put("b", null); map1.merge("b", 1, (i1, i2) -> i1 =- i2); map1.merge("c", 2, (i1, i2) -> i1 + i2); System.out.println(map1); {a=1, b=1, c=2} Map<String, Integer> map1 = new HashMap<>(); map1.put("a", 1); map1.put("b", null); map1.merge("b", 1, (i1, i2) -> null); map1.merge("c", 2, (i1, i2) -> null); System.out.println(map1); {a=1, b=1, c=2} Map<String, Double> map1 = new HashMap<>(); map1.put("a", 1.0); map1.put("b", 2.0); map1.put("c", 2.0); map1.merge("b", 1.0, (i1, i2) -> i1 - i2); map1.merge("c", 3.0, (i1, i2) -> i1 / i2); System.out.println(map1); => {a=1.0, b=1.0, c=0.6666666666666666} 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); <An Optional containing 13, 14, or 15>:<An Optional containing 13, 14, or 15> Since the first stream is made parallel, it may be partitioned into multiple pieces and each piece may be processed by a different thread. findAny may, therefore, return a value from any of those partitions. Hence, any number from 13 to 15 may be printed. The second stream is sequential and therefore, ideally, findAny should return the first element. However, findAny is deliberately designed to be non-deterministic. Its API specifically says that it may return any element from the stream. If you want to select the first element, you should use findFirst. Further findAny returns Optional object. Therefore, the output will be Optional[13] instead of just 13 (or any other number). => Object o = IntStream.range(0, 5).boxed().filter(x -> x>1).findAny(); //OK Print: Optional[2] Object o = IntStream.range(0, 5).boxed().filter(x -> x>1).collect(Collectors.toList()); System.out.println(o); // Print: [2, 3, 4] Object o = IntStream.rangeClosed(0, 5).boxed().filter(x -> x>1).collect(Collectors.toList()); System.out.println(o); // Print: [2, 3, 4, 5] 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 values? a b 1 2 Stream.of(l1, l2).flatMap((x)->x.stream()).forEach((x)>System.out.println(x)); 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") ); List<String> genreList; //Not compile List<String> genreList = new ArrayList<>(); //OK //INSERT CODE HERE System.out.println(genreList); Which of the following options will correctly make genreList refer to a List containing the genres of the books present in books List? books.stream().map(Book::getGenre).forEach(s->genreList.add(s)); genreList = books.stream().map(Book::getGenre).collect(Collectors.toList()); books.stream().map(Book::getGenre).forEach(genreList::add); books.stream().map(b->b.getGenre()).forEach(genreList::add); List<Integer> ls = Arrays.asList(1, 2, 3); Which of the following options will compute the sum of all Integers in the list correctly? double sum = ls.stream().reduce(0, (a, b)->a+b); double sum = ls.stream().mapToInt(x->x).sum(); List<Integer> ls = Arrays.asList(1, 2, 3); int x = ls.stream().mapToInt(x -> x).sum(); // Not compile => int rs = ls.stream().mapToInt(x -> x).sum(); //OK List<Integer> ls = Arrays.asList(1, 2, 3); double sum = 0; ls.stream().forEach(a -> { sum = sum + a; }); Not compile This code is almost correct but for the fact that only final or effective final local variables can be used in a lambda expression. Here, the code is trying to use sum and sum is not final. Effectively final means that even though it is not declared as final, it is not assigned any value anywhere else after the first assignment. The compiler determines that this variable never changes and considers it as final. List<Integer> ls = Arrays.asList(1, 2, 3); ls.stream().forEach(a -> { double sum = 1; sum = sum + a; System.out.println(sum); }); // Print( 2.0, 3.0, 4.0) List<Integer> ls = Arrays.asList(1, 2, 3); double sum = 1; ls.stream().forEach(a -> { double b = 1; b = sum + a; System.out.println(b); }); // Print( 2.0, 3.0, 4.0) package trywithresources; import java.io.IOException; public class Device implements AutoCloseable{ String header = null; public Device(String name) throws IOException{ header = name; if("D2".equals(name)) throw new IOException("Unknown"); System.out.println(header + " Opened"); } public String read() throws IOException{ return ""; } public void close(){ System.out.println("Closing device "+header); throw new RuntimeException("RTE while closing "+header); } public static void main(String[] args) throws Exception { try(Device d1 = new Device("D1"); Device d2 = new Device("D2")){ throw new Exception("test"); } } } It will end up with an IOException containing message "Unknown" and a suppressed RuntimeException containing message "RTE while closing D1": D1 Opened Exception in thread "main" Closing device D1 java.io.IOException: Unknown at Test.<init>(Test.java:10) at Test.main(Test.java:25) Suppressed: java.lang.RuntimeException: RTE while closing D1 at Test.close(Test.java:20) at Test.main(Test.java:27) Device D1 is created successfully but an IOException is thrown while creating Device D2. Thus, the control never enters the try block and throw new Exception("test") is never executed. Since one resource was created, its close method will be called (which prints Closing device D1). Any exception that is thrown while closing a resource is added to the list of suppressed exceptions of the exception thrown while opening a resource (or thrown from the try block.) 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 (FileNotFoundException | IndexOutOfBoundsException e) { e.printStackTrace(); } The program will not compile because it does not handle exceptions correctly. Remember that most of the I/O operations (such as opening a stream on a file, reading or writing from/to a file) throw IOException and this code does not handle IOException. FileNotFoundException is a subclass of IOException and IndexOutOfBoundsException is subclass of RuntimeException. The code can be fixed by replacing FileNotFoundException | IndexOutOfBoundsException with IOException or by adding another catch block that catches IOException. { Code that uses Assertions cannot be run on version below 1.4 Assertions require changes at the API level. Assertions don? require changes at the JVM level. public void openSocket(int port) assert port > 1000; ... } // wrong => Input params of a public method should not be validated using assertions. { public void openSocket(int port) Socket s = //valid code to open socket here ... assert s != null; } // OK public boolean doSomething() { ... } public void someMethod() { assert doSomething(); } // Wrong Assertions should not have side effects. The only case where this could be justified is when you are trying to find out whether or not assertions are enabled in your code: boolean enabled = false; assert enabled = true; if(enabled) System.out.println("Assertions are enabled") else System.out.println("Assertions are disabled") Assertions should be used for: 1. Validating input parameters of a private method.[But NOT for public methods. public methods should throw regular exceptions when passed bad parameters.) 2. Anywhere in the program to ensure the validity of a fact which is almost certainly true. For example, if you are sure that i will only be either 1 or 2, you can use an assertion like this: ... if(i == 1) { ... } else if( i == 2) { ... } else { assert false : "cannot happen. i is "+i; } ... { public void assertTest() ... assert value == 10 : "Value is not 10"; } // OK The following are the two valid ways of writing assertions: assert <boolean_expression>; assert <boolean_expression> : <any_expression_but_void>; 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(); } The program will not compile because line //2 is invalid. The auto-closeable variables defined in the try-with-resources statement are implicitly final. Thus, they cannot be reassigned. public class Test { public static void main(String args[]) { try(Test t = new Test()){ } } } Compile failed. Remember that when you use a resource in try-with-resources, the resource must implement java.lang.AutoCloseable interface. In this case, although Device class contains the close() method required by this interface but it does not say that it implements AutoCloseable in its declaration. Therefore, compilation will fail. 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.read(); d.writeHeader("TEST"); d.close(); }catch(IOException e){ System.out.println("Got Exception"); } } public static void main(String[] args) { Device.testDevice(); } } => Device Opened Device closed Got Exception => Catch and finally blocks are executed after the resource opened in try-with-resources is closed. Therefore, Device Closed will be printed before Got Exception. => If an exception is thrown within the try-with-resources block, then that is the exception that the caller gets. But before the try block returns, the resource's close() method is called and if the close() method throws an exception as well, then this exception is added to the original exception as a supressed exception. Consider the following code that uses an assertion to ensure that the program is supplied with 2 arguments: public class TestClass { public static void main(String[] args) { assert args.length == 2 : "Must give two arguments"; ... } } Which of the given statements regarding the above code are correct? The programmer should throw a RuntimeException instead of using an assertion in this case. For this reason, input validation should always be done using the standard exception mechanism: if( args.length arguments"); != 2 ) throw new RuntimeException("Must give two -da: It is a short form for 'disable assertions'. What will the following code print? Duration d = Duration.ofDays(1); System.out.println(d); d = Duration.ofMinutes(0); System.out.println(d); Period p = Period.ofMonths(0); System.out.println(p); PT24H PT0S P0D Duration counts in terms of hours, minutes, and seconds. Therefore, days are converted into hours. That is why the first println prints PT24H and not PT1D. A Duration of 0 is printed as 0S and a Period of 0 is printed as 0D. LocalDateTime ld = LocalDateTime.of(2015, Month.OCTOBER, 31, 10, 0); ZonedDateTime date = ZonedDateTime.of(ld, ZoneId.of("US/Eastern")); date = date.plus(Duration.ofDays(1)); System.out.println(date); date = ZonedDateTime.of(ld, ZoneId.of("US/Eastern")); date = date.plus(Period.ofDays(1)); System.out.println(date); 2015-11-01T09:00-05:00[US/Eastern] (Only for the end of month: hour = hour - 1) 2015-11-01T10:00-05:00[US/Eastern] For example, consider adding a period of one day and a duration of one day to 18:00 on the evening before a daylight savings ends. The Period will add the conceptual day and result in a ZonedDateTime at 18:00 the following day. By contrast, the Duration will add exactly 24 hours, resulting in a ZonedDateTime at 17:00 the following day (assuming a one hour DST gap) because when the DST ends, the clock is shifted one hour back i.e. as soon as the clock hits 2 AM, it is shifted back to 1AM. Therefore, 18:00 of the next day will actually be 17:00. LocalDateTime ldt = LocalDateTime.of(2015, Month.AUGUST, 20, 20, 20, 20); ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.of("US/Eastern")); zdt.plusDays(1); // 1 System.out.println(zdt); Print: 2015-08-20T20:20:20-04:00[US/Eastern] // Day don’t change Change line //1 with: zdt = zdt.plusDays(1); Print: 2015-08-21T20:20:20-04:00[US/Eastern] LocalDateTime ldt = LocalDateTime.of(2015, Month.AUGUST, 20, 20, 20, 20); ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.of("GMT+2")); System.out.println(zdt); 2015-08-20T20:20:20+02:00[GMT+02:00] Instant start = Instant.parse("2015-06-25T16:13:30.00z"); start.plus(10, ChronoUnit.HOURS); System.out.println(start); Duration timeToCook = Duration.ofHours(1); Instant readyTime = start.plus(timeToCook); System.out.println(readyTime); LocalDateTime ltd = LocalDateTime.ofInstant(readyTime, ZoneId.of("GMT+2")); System.out.println(ltd); 2015-06-25T16:13:30Z 2015-06-25T17:13:30Z 2015-06-25T19:13:30 1. The first println prints the same Instant because calling plus on an Instance doesn't change that Instance. It returns a new instance. 2. Adding 1 hour to 16:13, will change it to 17:13, which is what the second println prints. 3. A Timezone of GMT+2 means that in that time zone, the time is 2 hours ahead of GMT. Thus, when it is 17:13 in GMT, it is 19:13 in GMT+2. Instant now = Instant.now(); Instant now2 = now.truncatedTo(ChronoUnit.DAYS); //OK Instant now3 = now.truncatedTo(TemporalUnit.DAYS); //Not compile System.out.println(now2); Instant class has a truncatedTo method that takes in a TemporalUnit and returns a new Instant with the fields smaller than the passed unit set to zero. For example, if you pass ChronoUnit.DAYS, hours, minutes, seconds, and nano-seconds will be set to 0 in the resulting Instant. TemporalUnit is an interface and ChronoUnit is a class that implements this interface and defines constants such as DAYS, MONTHS, and YEARS. FYI, any unit larger than ChronoUnit.DAYS causes the truncatedTo method to throw UnsupportedTemporalTypeException. Identify valid statements. Locale myLocale = Locale.getDefault(); Locale myLocale = Locale.US; Locale myLocale = new Locale("ru", "RU"); Consider the following piece of code: Locale.setDefault(new Locale("fr", "CA")); //Set default to French Canada Locale l = new Locale("jp", "JP"); ResourceBundle rb = ResourceBundle.getBundle("appmessages", l); String msg = rb.getString("greetings"); System.out.println(msg); You have created two resource bundle files with the following contents: #In appmessages.properties: greetings=Hello #In appmessages_fr_FR.properties: greetings=bonjour Given that this code is run on machines all over the world. Which of the following statements are correct? It will run without any exception all over the world. While retrieving a message bundle, you are passing a locale explicitly (jp/JP). Therefore, it will first try to load appmessages_jp_JP.properties. Since this file is not present, it will look for a resource bundle for default locale. Since you are changing the default locale to "fr", "CA", it will look for appmessages_fr_CA.properties, which is also not present. Remember that when a resource bundle is not found for a given locale, the default locale is used to load the resource bundle. Every effort is made to load a resource bundle if one is not found and there are several fall back options (in absence of appmessages_fr_CA.properties, it will look for appmessages_fr.properties). As a last resort, it will try to load a resource bundle with no locale information i.e. appmessages.properties in this case. (An exception is thrown when even this resource bundle is not found.) Since appmessages.properties is available, the code will never throw an exception in any locale. Which of the following are required to construct a Locale? Language Locale needs at least a language to be constructed. It has three constructors - Locale(String language) Construct a locale from a language code. Locale(String language, String country) Construct a locale from language, country. Locale(String language, String country, String variant) Construct a locale from language, country, variant. You have multiple threads in your application that need to generate random numbers between 1 to 10 (both inclusive) frequently. Which of the following statements would you use considering overhead and contention as the main criteria? int r = (int) Math.random()*10; // NOT OK There are two issues with this code: 1. It will always assign 0 to i because Math.random() returns a double between 0 and less than 1 and since casting operator i.e. (int) takes precedence to *, the double value returned by Math.random() will be converted to int first, which will make it 0. 0*10 will be 0. So, you should do: int r = (int) (Math.random()*10); 2. When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random(). This method is properly synchronized to allow correct use by more than one thread. In other words, Math.random() is a synchronized method, so it can be used by multiple threads but at the cost of performance. int r = ThreadLocalRandom.current().nextInt(1, 11); Note that the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs. There are a few basic questions about generating random numbers in the exam. Besides Math.random() method, you should know about ThreadLocalRandom class. public class ThreadLocalRandom extends Random A random number generator isolated to the current thread. Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention. Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers in parallel in thread pools. Usages of this class should typically be of the form: ThreadLocalRandom.current().nextX(...) (where X is Int, Long, etc). When all usages are of this form, it is never possible to accidently share a ThreadLocalRandom across multiple threads. Which of the following options correctly create an ExecutorService instance? ExecutorService es = Executors.newFixedThreadPool(2); You need to remember the following points about a few important classes in java.util.concurrent package: 1. ExecutorService interface extends Executor interface. While Executor allows you to execute a Runnable, ExecutorService allows you to execute a Callable. 2. Executors is a utility class that provides several static methods to create instances of ExecutorService. All such methods start with new e.g. newSingleThreadExecutor(). You should at least remember the following methods: newFixedThreadPool(int noOfThreads), newSingleThreadExecutor(), newCachedThreadPool(), newSingleThreadScheduledExecutor(), newScheduledThreadPool(int corePoolSize). class ComplicatedTask extends RecursiveTask<Integer>{ int[] ia; int from; int to; public ComplicatedTask(int[] ia, int from, int to){ this.ia = ia; this.from = from; this.to = to; } public int transform(int t){ //this is a CPU intensive operation that //transforms t and returns the value } protected Integer compute() { if(from == to){ return transform(ia[from]); } else if(from+1==to){ return transform(ia[from])+transform(ia[to]); } else{ int mid = (from+to)/2; ComplicatedTask newtask1 = new ComplicatedTask(ia, from, mid); ComplicatedTask newtask2 = new ComplicatedTask(ia, mid+1, to); newtask1.fork(); int x = newtask2.compute(); //LINE A int y = newtask1.join(); //LINE B return x+y; } } } What will happen if LINE A and LINE B are flipped i.e. LINE B is moved before LINE A? There will not be any impact on the final answer but performance will be degraded. The order of join() and compute() is critical. Remember that fork() causes the sub-task to be submitted to the pool and another thread can execute that task in parallel to the current thread. Therefore, if you call join() on the newly created sub task, you are basically waiting until that task finishes. This means you are using up both the threads (current thread and another thread from the pool that executes the subtask) for that sub task. Instead of waiting, you should use the current thread to compute another subtask and when done, wait for another thread to finish. This means, both the threads will execute their respective tasks in parallel instead of in sequence. Therefore, even though the final answer will be the same, the performance will not be the same. The key for non-dumb examples, which is hinted at nicely by the name RecursiveTask, is that your compute method can create other RecursiveTask objects and have the pool run them in parallel. First you create another object. Then you call its fork method. That actually starts parallel computation fork itself returns quickly, but more computation is now going on. When you need the answer, you call the join method on the object you called fork on. The join method will get you the answer from compute() that was figured out by fork. If it is not ready yet, then join will block (i.e., not return) until it is ready. So the point is to call fork ?arlyand call join ?ate doing other useful work in-between. You have to complete a big task that operates on a large array of integers. The task has to look at each element of the array and update that element. The new value of the element is generated by a utility class's static method, which takes in the existing value as a parameter and returns the new value. This method is computationally very intensive. Subclass RecursiveAction and implement the compute() method that computes the new value but does not return anything. Create a RecursiveAction that subdivides the task into two, then forks one of the tasks and computes another. Since there is no requirement to do anything with the newly computed value (such as summing them up), you don't need to return that value to anybody. You just need to update the array element with the new value. Therefore, you don't need RecursiveTask, you need RecursiveAction. The following is a possible implementation: import import import import java.util.ArrayList; java.util.Arrays; java.util.concurrent.ForkJoinPool; java.util.concurrent.RecursiveAction; public class ComplicatedAction extends RecursiveAction{ int[] ia; int from; int to; public ComplicatedAction(int[] ia, int from, int to){ this.ia = ia; this.from = from; this.to = to; } protected void compute() { if(from == to){ //Update the value using logic implemented somewhere else. ia[from] = UtilityClass.utilityMethod(ia[from]); } else{ int mid = (from+to)/2; ComplicatedAction newtask1 = new ComplicatedAction(ia, from, mid); ComplicatedAction newtask2 = new ComplicatedAction(ia, mid+1, to); newtask2.fork(); newtask1.compute(); newtask2.join(); } } public static void main(String[] args) { int ia[] = new int[]{ 1, 2, 3, 4 , 5, 6, 7 }; ForkJoinPool fjp = new ForkJoinPool(); ComplicatedAction st = new ComplicatedAction(ia, 0, 6); fjp.invoke(st); System.out.print("New Array Values = "); for(int i : ia) System.out.print(i+" "); } } class UtilityClass{ public static int utilityMethod(int x) { return x+1; } } You have a collection (say, an ArrayList) which is read by multiple reader threads and which is modified by a single writer thread. The collection allows multiple concurrent reads but does not tolerate concurrent read and write. Which of the following strategies will you use to obtain best performance? Encapsulate the collection into another class and use ReadWriteLock to manage read and write access. Since the collection allows multiple simultaneous reads, it is ok for multiple threads to access the collection simultaneously if they are not modifying the collection. On the other hand, a writer thread must get sole custody of the collection before modifying. This can be easily achieved by using a ReadWriteLock. For example: public class MultipleReadersSingleWriter { private final ArrayList<String> theList = new ArrayList<String>(); //Note that ReadWriteLock is an interface. private final ReadWriteLock rwl = new ReentrantReadWriteLock(); private final Lock r = rwl.readLock(); private final Lock w = rwl.writeLock(); public String read(){ r.lock(); try{ System.out.println("reading"); if(theList.isEmpty()) return null; else return theList.get(0); }finally{ r.unlock(); } } public void write(String data){ w.lock(); try{ System.out.println("Written "+data); theList.add(data); }finally{ w.unlock(); } } } Which of the following statements are true regarding the Fork/Join framework? The worker threads in the ForkJoinPool extend java.lang.Thread and are created by a factory. By default, they are created by the default thread factory but another factory may be passed in the constructor. They do extend Thread. One worker thread may steal work from another worker thread. A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute subtasks created by other active tasks (eventually blocking waiting for work if none exist). This enables efficient processing when most tasks spawn other subtasks (as do most ForkJoinTasks). From a ReadWriteLock, you can get one read lock (by calling lock.readLock() ) and one write lock (by calling lock.writeLock() ). Even if you call these methods multiple times, the same lock is returned. A read lock can be locked by multiple threads simultaneously (by calling lock.readLock().lock() ), if the write lock is free. If the write lock is not free, a read lock cannot be locked. The write lock can be locked (by calling lock.writeLock().lock() ) only by only one thread and only when no thread already has a read lock or the write lock. In other words, if one thread is reading, other threads can read, but no thread can write. If one thread is writing, no other thread can read or write. Methods that do not modify the collection (i.e. the threads that just "read" a collection) should acquire a read lock and threads that modify a collection should acquire a write lock. The benefit of this approach is that multiple reader threads can run without blocking if the write lock is free. This increases performance for read only operations. The following is the complete code that you should try to run: public class Student { private Map<String, Integer> marksObtained = new HashMap<String, Integer>(); private ReadWriteLock lock = new ReentrantReadWriteLock(); public void setMarksInSubject(String subject, Integer marks){ lock.writeLock().lock(); //1 try{ marksObtained.put(subject, marks); }finally{ lock.writeLock().unlock(); //2 } } public double getAverageMarks(){ lock.readLock().lock(); //3 double sum = 0.0; try{ for(Integer mark : marksObtained.values()){ sum = sum + mark; } return sum/marksObtained.size(); }finally{ lock.readLock().unlock();//4 } } public static void main(String[] args) { final Student s = new Student(); //create one thread that keeps adding marks new Thread(){ public void run(){ int x = 0; while(true){ int m = (int)(Math.random()*100); s.setMarksInSubject("Sub "+x, m); x++; } } }.start(); //create 5 threads that get average marks for(int i=0;i<5; i++){ new Thread(){ public void run(){ while(true){ double av = s.getAverageMarks(); System.out.println(av); } } }.start(); } } } Note that if you remove the line //1, //2, //3, and //4, (i.e. if you don't use any locking), you will see a ConcurrentModificationException. import import import public java.util.Iterator; java.util.Map.Entry; java.util.concurrent.ConcurrentHashMap; class Cache { static ConcurrentHashMap<String, Object> chm = new ConcurrentHashMap<String, Object>(); public static void main(String[] args) { chm.put("a", "aaa"); chm.put("b", "bbb"); chm.put("c", "ccc"); new Thread(){ public void run(){ Iterator<Entry<String, Object>> it = Cache.chm.entrySet().iterator(); while(it.hasNext()){ Entry<String, Object> en = it.next(); if(en.getKey().equals("a") || en.getKey().equals("b")){ it.remove(); } } } }.start(); new Thread(){ public void run(){ Iterator<Entry<String, Object>> it = Cache.chm.entrySet().iterator(); while(it.hasNext()){ Entry<String, Object> en = it.next(); System.out.print(en.getKey()+", "); } } }.start(); } } Which of the following are possible outputs when the above program is run? It may print any combination except: a, or b, or a, b, or b, a Print: a, b, c or c Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time. Given: public class Counter{ static AtomicInteger ai = new AtomicInteger(0); public static void increment(){ //1 } //other valid code } This class is supposed to keep an accurate count for the number of times the increment method is called. Several classes share this class and call its increment method. What should be inserted at //1 ? ai.incrementAndGet(); ai.addAndGet(1); ai.set(ai.get()+1); // Not OK This is wrong because between the time when ai.get() returns a value and ai.set() is called, another thread may call increment and may get to execute ai.set with the same value. This will make you lose one increment. You are using a RDBMS database from a company named Fandu Tech. It provides a JDBC 4.0 compliant driver implementation in class com.fandu.sql.Driver. Which of the following lines of code is/are required to get the driver loaded? None of the above. In JDBC 4.0, the drivers are loaded automatically based on the information provided by the driver's META-INF/services/java.sql.Driver file. Therefore, no java code in necessary to load the driver classes. Prior to JDBC 4.0, the application code would have to load the Driver class explicitly using Class.forName method, for example - Class.forName("com.xyz.jdbc.Driver"). However, with JDBC 4.0, applications no longer need to do this. The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry: my.sql.Driver When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application. ResultSetMetaData gives you the information about the result of executing a query. You can retrieve this object by calling getMetaData() on ResultSet. ResultSetMetaData contains several methods that tell you about the ResultSet. Some important methods are: getColumnCount(), getColumnName(int col), getColumnLabel(int col), and getColumnType(int col). Remember that the column index starts from 1. Given that a code fragment has just created a JDBC Connection and has executed an update statement, Changes to the database will be committed right after the update statement has completed execution. A Connection is always in auto-commit mode when it is created. As per the problem statement, an update was fired without explicitly disabling the auto-commit mode, the changes will be committed right after the update statement has finished execution. The way to allow two or more statements to be grouped into a transaction is to disable the autocommit mode. Since it is enabled by default, you have to explicitly disable it after creating a connection by calling con.setAutoCommit(false); Consider the following code: Connection c = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", "app"); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("select * from STUDENT"); stmt.close(); while(rs.next()){ System.out.println(rs.getInt(1)); } c.close(); Assuming that STUDENT table has 2 records contains values 1 and 2 for the first column, what will this code print? Exception at run time. If the ResultSet object that you are iterating is closed, you will get an exception saying: Exception in thread "main" java.sql.SQLException: ResultSet not open. In this case, although we are not closing the ResultSet directly, we are closing the Statement object from which the ResultSet was retrieved and when a Statement object is closed, its current ResultSet object, if one exists, is also closed. Connection con = DriverManager.getConnection(dbURL); con.setAutoCommit(false); 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? con.commit(); Since auto-commit has been disabled in the given code (by calling con.setAutoCommit(false)), you have to call commit() on Connection object explicitly to commit the changes to the database. Connection c = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", "app"); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("select * from CUSTOMER_ORDER"); //LINE 10 stmt.close(); //LINE 11 while(rs.next()){ //LINE 12 System.out.println(rs.getString("AMOUNT")); //LINE 13 } c.close(); It will throw an exception at //LINE 12 A CallableStatement is easier to build and call from JDBC code than a PreparedStatement. This is true because you don't have to write any SQL query in Java code. You just use the name of the stored procedure. The queries are already there inside the stored procedure, which exists in the Database and not in JDBC code. public class MyThread implements Runnable { Thread w; public void start() { w = new Thread(this); //w.start();if this line is uncommented out, //program will print 2 times: Working… } public void run() { System.out.println(" Working..."); } public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); // print nothing Thread t2 = new Thread(new MyThread()); t2.start(); // print: Working... } } Working... You have created several threads in your application. To ensure that important tasks are performed quickly, you have increased the priority of some threads and lowered the priority of others. At run time, however, you observe that the lower priority threads rarely get a chance to run. What is this problem called? Starvation. Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU. Thread starvation may be caused because of different thread priorities. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time. public class MyThread extends Thread { MyThread w; public void start() { w = new MyThread(); w.start(); } public void run() { System.out.println(" Working..."); } public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); // print nothing Thread t2 = new Thread(new MyThread()); t2.start(); // print: Working... } } Exception in thread "main" java.lang.StackOverflowError. The exam needs you to understand and differentiate among Deadlock, Starvation, and Livelock. The following are brief descriptions taken from Oracle Java Tutorial: 1. Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. For example, two threads T1 and T2 need a File and a Printer. T1 acquires the lock for the file and is about to acquire the lock for the Printer but before it could acquire the lock, T2 acquires the lock for the Printer and tries to acquire the lock for the file (which is already held by T1). So now, both the threads keep waiting for ever for each other to release their locks and neither will be able to proceed. 2. Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. 3.Livelock: A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result. As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked they are simply too busy responding to each other to resume work. For example, after acquiring the File lock, T1 tries to acquire the Printer lock. Finding the Printer lock to be already taken, it releases the lock for the File and notifies T2. At the same time, T2 tries to acquire the File lock and seeing that it is already taken it releases Printer lock and notifies T1. This process can go on and on, both the threads releasing and acquiring the locks in tandem but none of them getting both the locks at the same time. So neither of the threads is blocked but neither of the threads is able to do any real work. All they are doing is notifying each other. { class CoolThread extends Thread String id = ""; public CoolThread(String s){ this.id = s; } public void run() { System.out.println(id+" End"); } public static void main(String args []) { Thread t1 = new CoolThread("AAA"); t1.setPriority(Thread.MIN_PRIORITY); Thread t2 = new CoolThread("BBB"); t2.setPriority(Thread.MAX_PRIORITY); t1.start(); t2.start(); } } The order of "AAA End" and "BBB End" cannot be determined. In this case, the program is trying to manipulate the scheduling of thread using priorities which is a bad idea. Simply because operating systems behave differently about priorities. For example, Windows uses Time Slicing i.e. it gives time to all the thread in proportion of their priorities but many unix systems do not let low priority threads run at all if a higher priority thread is running. So the output cannot be determined. The synchronized keyword can be applied to any non-abstract instance method of a class. public class MyThread implements Runnable { public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); //testNormal(3, 3, 5); testAsynchronous(3, 3, 5); System.out.printf("Elapsed time: %d seconds\n", (System.currentTimeMillis() - start) / 1000); } private static void testNormal(int s1, int s2, int s3) { String r1 = doLongTask(s1); String r2 = doLongTask(s2); String r3 = doLongTask(s3); System.out.println(r1); System.out.println(r2); System.out.println(r3); } private static void testAsynchronous(int s1, int s2, int s3) throws InterruptedException, ExecutionException { int poolSize = 3; ExecutorService executor = Executors.newFixedThreadPool(poolSize); Future<String> r1 = executor.submit(() -> { return doLongTask(s1); }); Future<String> r2 = executor.submit(() -> { return doLongTask(s2); }); Future<String> r3 = executor.submit(() -> { return doLongTask(s3); }); System.out.println(r1.get()); System.out.println(r2.get()); System.out.println(r3.get()); executor.shutdown(); } private static String doLongTask(int second) { try { Thread.sleep(1000 * second); return "Finish after " + second + " second"; } catch (InterruptedException ex) { return null; } } @Override public void run() {} } Chay thong thuong: testNormal(3, 3, 5); => T?ng th?i gian th?c hi?n s? l3+3+5 = 11 (gi?). Chay đong thoi: testAsynchronous(3, 3, 5); => Tong thoi gian th?c hi?n se la (gi?). Co nhieu tinh huong thuc te co the ap dung ki thuat nay khong? Ban than toi thi co 2 truong hop: 1. Mot chuong trinh lay link download anh tu nhieu link truyen online khac nhau 2. Mot bao cao ma minh phai select du lieu lon trong CSDL trong vong for (vd: bao cao theo tung thang) public class TestClass implements Runnable { int x = 0, y = 0; public void run() { while(true) { x++; y++; System.out.println(" x = "+x+" , y = "+y); } } public static void main(String[] args) { TestClass tc = new TestClass(); new Thread(tc).start(); new Thread(tc).start(); } } Nothing can be said about the sequence of values. Here, both the threads are trying to use the same fields of the same object. The order of execution of thread can never be told so we cannot tell which variable be used by which thread at what time. So the output cannot be determined. For example, consider this situation: First T1 runs, goes into the while loop, increments x (So x =1, y=0) immediately. The OS decides to switch to T2, so T2 runs, increments x (so x=2, y=0), increments y (So, x=2, y=1), prints the values ( 2, 1). Now, the OS switches to T1, so it increments y (So, x = 2, y=2) and prints 2, 2. Here, you can see that the output is 2, 1 and 2, 2. That is why we cannot be sure about the output. Because when the OS will schedule what thread is totally up to the OS. { Further, since the variables x and y are not declared as volatile, the updates made by one thread may not be visible to another thread at all. It is, therefore, possible that both the threads will find x and y to be 0, 0 at the beginning and update them by 1 in each iteration. class A extends Thread public void run() { System.out.println("Starting loop"); while(true){}; //1 System.out.println("Ending loop"); // } Unreachable code } public class TestClass { public static void main(String args[]) throws Exception { A a = new A(); a.start(); Thread.sleep(1000);//2 a.interrupt();//3 } } This will not compile. It will run and end cleanly if //1 is replaced with while(!isInterrupted()) { } and print: Starting loop, Ending loop If comment out line 3, print: Starting loop public class Test extends Thread { static int x, y; // 1 public synchronized void run(){ for(;;){ x++; y++; System.out.println(x+" "+y);} } public static void main(String[] args) { new Test().start(); new Test().start(); } } What will the above code print? You cannot say anything about the values. You may be tempted by the synchronized keyword on the run method. But note that there are two different thread objects and both the threads are acquiring locks for their own thread object. Therefore, in this case, the synchronized block will not help. If remove “static” modifier: program will print two results are the same: 1 1, 2 2, ….. { class MyRunnable implements Runnable public static void main(String[] args) { new Thread( new MyRunnable(2) ).start(); } public void run(int n) { for(int i=0; i<n; i++) { System.out.println("Hello World"); } } } This program will not even compile. When a non-abstract class implements Runnable interface, it must implement public void run() method. (run With no parameters). In this case, this class has a run method but it takes an int as a parameter. Moreover, there is no constructor for this class that take an int. So new MyRunnable(2) is invalid. If a synchronized method throws an exception in its execution, the lock acquired by the method due to the usage of synchronized keyword is released automatically. The Java exception mechanism is integrated with the Java synchronization model, so that locks are released if synchronized statements and invocations of synchronized methods complete abruptly. { class MyClass implements Runnable int n = 0; public MyClass(int n){ this.n = n; } public static void main(String[] args) { new MyClass(2).run(); new MyClass(1).run(); } public void run() { for(int i=0; i<n; i++) { System.out.println("Hello World"); } } } thrice. run() method is executed as any normal method. Which causes "Hello World" to be printed { public class MyThread extends Thread String msg = "default"; public MyThread(String s) { msg = s; } public void run() { System.out.println(msg); } public static void main(String args[]) { new MyThread("String1").run(); new MyThread("String2").run(); System.out.println("end"); } } It will always print String1, String2, and end, in that order. Although two new threads are created but none of them is started (remember run() does not start a thread. start() does) Here, run is called just like any other ordinary method in the main thread. Which of these exceptions can be thrown by the wait() method of java.lang.Object class? InterruptedException InterruptedException is thrown if it is interrupted by another thread. IllegalMonitorStateException This exception is thrown if it is not called in a synchronized block. class MyRunnable implements Runnable { MyRunnable(String name) { new Thread(this, name).start(); //Line 1 } public void run() { System.out.println(Thread.currentThread().getName()); } } public class TestClass { public static void main(String[] args) { Thread.currentThread().setName("MainThread"); MyRunnable mr = new MyRunnable("MyRunnable"); mr.run(); } } It will print MainThread as well as MyRunnable 1. The statement : Thread.currentThread().setName("MainThread"); in the main() method sets the name of the current thread. This is the thread that is running the main method. 2. The statement: MyRunnable mr = new MyRunnable("MyRunnable"); creates a new MyRunnable object. In its constructor, it creates a new threads with the name "MyRunnable" and also starts this thread. 3. Now there are two threads running: The main thread (having the name "MainThread") and the MyRunnable thread (having the name "MyRunnable"). 4. The myrunnable thread executes the run method and prints "MyRunnable" because that is the name of the thread that called the run() method. On the other hand when the main method calls mr.run(), it prints "MainThread" because that is the name of the thread that has called the run method(). Therefore, both, Main and MyRunnable will be printed. Note that the order cannot be determined because the OS decides which thread to schedule when. If change line 1 with: new Thread(this).start(); : it will print: MainThread Thread-0 import java.nio.file.Path; import java.nio.file.Paths; public class PathTest { static Path p1 = Paths.get("c:\\main\\project\\Starter.java"); public static String getData(){ String data = p1.getName(0).toString(); return data; } public static void main(String[] args) { System.out.println(getData()); } } main Remember the following 4 points about Path.getName() method : 1. Indices for path names start from 0. 2. Root (i.e. c:\) is not included in path names. 3. \ is NOT a part of a path name. 4. If you pass a negative index or a value greater than or equal to the number of elements, or this path has zero name elements, java.lang.IllegalArgumentException is thrown. It DOES NOT return null. Thus, for example, If your Path is "c:\\code\\java\\PathTest.java", p1.getRoot() is c:\ ((For Unix based environments, the root is usually / ). p1.getName(0) is code p1.getName(1) is java p1.getName(2) is PathTest.java p1.getName(3) will cause IllegalArgumentException to be thrown. Path p1 = Paths.get("\\personal\\readme.txt"); Path p2 = Paths.get("\\index.html"); Path p3 = p1.relativize(p2); System.out.println(p3); ..\..\index.html You need to understand how relativize works for the purpose of the exam. The basic idea of relativize is to determine a path, which, when applied to the original path will give you the path that was passed. For example, "a/c" relativize "a/b" is "../b" because "/a/c/../b" is "/a/b" Notice that "c/.." cancel out. Please go through the following description of relativize() method, which explains how it works in more detail. public Path relativize(Path other) Constructs a relative path between this path and a given path. Relativization is the inverse of resolution. This method attempts to construct a relative path that when resolved against this path, yields a path that locates the same file as the given path. For example, on UNIX, if this path is "/a/b" and the given path is "/a/b/c/d" then the resulting relative path would be "c/d". Where this path and the given path do not have a root component, then a relative path can be constructed. A relative path cannot be constructed if only one of the paths have a root component. Where both paths have a root component then it is implementation dependent if a relative path can be constructed. If this path and the given path are equal then an empty path is returned. For any two normalized paths p and q, where q does not have a root component, p.relativize(p.resolve(q)).equals(q) When symbolic links are supported, then whether the resulting path, when resolved against this path, yields a path that can be used to locate the same file as other is implementation dependent. For example, if this path is "/a/b" and the given path is "/a/x" then the resulting relative path may be "../x". If "b" is a symbolic link then is implementation dependent if "a/b/../x" would locate the same file as "/a/x". Given that test1.txt exists but test2.txt doesn't exist, consider the following code? public class FileCopier { public static void copy1(Path p1, Path p2) throws Exception { Files.copy(p1, p2, StandardCopyOption.COPY_ATTRIBUTES); } public static void main(String[] args) throws Exception { Path p1 = Paths.get("c:\\temp\\test1.txt"); Path p2 = Paths.get("c:\\temp\\test2.txt"); copy1(p1, p2); } } Which file attributes will be copied over to test2.txt? Copying of the attributes is platform and system dependent. From the JavaDoc API documentation for Files.copy: Attempts to copy the file attributes associated with source file to the target file. The exact file attributes that are copied is platform and file system dependent and therefore unspecified. Minimally, the last-modified-time is copied to the target file if supported by both the source and target file store. Copying of file timestamps may result in precision loss. Files.copy method will copy the file test1.txt into test2.txt. If test2.txt doesn't exist, it will be created. However, Files.isSameFile method doesn't check the contents of the file. It is meant to check if the two path objects resolve to the same file or not. In this case, they are not, and so, it will return false. The following is a brief JavaDoc description for both the methods: public static Path copy(Path source, Path target, CopyOption... options) throws IOException Copy a file to a target file. This method copies a file to the target file with the options parameter specifying how the copy is performed. By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target are the same file, in which case the method completes without copying the file. File attributes are not required to be copied to the target file. If symbolic links are supported, and the file is a symbolic link, then the final target of the link is copied. If the file is a directory then it creates an empty directory in the target location (entries in the directory are not copied). The options parameter may include any of the following: REPLACE_EXISTING If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced. COPY_ATTRIBUTES Attempts to copy the file attributes associated with this file to the target file. The exact file attributes that are copied is platform and file system dependent and therefore unspecified. Minimally, the last-modified-time is copied to the target file if supported by both the source and target file store. Copying of file timestamps may result in precision loss. NOFOLLOW_LINKS Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied. It is implementation specific if file attributes can be copied to the new link. In other words, the COPY_ATTRIBUTES option may be ignored when copying a symbolic link. An implementation of this interface may support additional implementation specific options. Copying a file is not an atomic operation. If an IOException is thrown then it possible that the target file is incomplete or some of its file attributes have not been copied from the source file. When the REPLACE_EXISTING option is specified and the target file exists, then the target file is replaced. The check for the existence of the file and the creation of the new file may not be atomic with respect to other file system activities. Assuming that a file named "a.java" exists in c:\pathtest\ as well as in c:\pathtest\dir2, what will happen when the following code is compiled and run? //imports not shown public class MoveTest { public static void main(String[] args) throws IOException { Path p1 = Paths.get("c:\\pathtest\\a.java"); Path p2 = Paths.get("c:\\pathtest\\dir2\\a.java"); Files.move(p1, p2, StandardCopyOption.ATOMIC_MOVE); Files.delete(p1); System.out.println(p1.toFile().exists()+" "+ p2.toFile().exists()); } } It will throw an exception at run time. There are two contradictory factors at play here. 1. By default, Files.move method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. Therefore, this code should throw an exception because a.java exists in the target directory. 2. However, when the CopyOption argument of the move method is StandardCopyOption.ATOMIC_MOVE, the operation is implementation dependent if the target file exists. The existing file could be replaced or an IOException could be thrown. If the exiting file at p2 is replaced, Files.delete(p1) will throw java.nio.file.NoSuchFileException. Therefore, in this case, the given code on the whole will end up with an exception. NOTE: Some candidates have reported being tested on StandardCopyOption.ATOMIC_MOVE. Unfortunately, it is not clear whether the exam tests on the implementation dependent aspect of this option. If you get a question on it and the options do not contain any option referring to its implementation dependent nature, we suggest the following: Assume that the move operation will succeed and then the delete operation will throw a java.nio.file.NoSuchFileException. What will the following code fragment print? Path p1 = Paths.get("c:\\personal\\.\\photos\\..\\readme.txt"); Path p2 = p1.normalize(); System.out.println(p2); c:\personal\readme.txt Path p1 = Paths.get("c:\\personal\\..\\photos\\..\\readme.txt"); Path p2 = p1.normalize(); System.out.println(p2); => c:\readme.txt Notice that . is always redundant and is removed by itself, while .. and the preceding directory cancel each other out because .. means parent directory. For example, a/b/.. is same as a. The following is the complete JavaDoc API description of this method: public Path normalize() Returns a path that is this path with redundant name elements eliminated. The precise definition of this method is implementation dependent but in general it derives from this path, a path that does not contain redundant name elements. In many file systems, the "." and ".." are special names used to indicate the current directory and parent directory. In such file systems all occurrences of "." are considered redundant. If a ".." is preceded by a non-".." name then both names are considered redundant (the process to identify such names is repeated until is it no longer applicable). This method does not access the file system; the path may not locate a file that exists. Eliminating ".." and a preceding name from a path may result in the path that locates a different file than the original path. This can arise when the preceding name is a symbolic link. Returns: the resulting path or this path if it does not contain redundant name elements; an empty path is returned if this path does have a root component and all name elements are redundant Path p1 = Paths.get("\\readm.txt"); Path p = Paths.get("\\photo\\readme.txt"); System.out.println(p.relativize(p1)); => ..\..\readm.txt Path p1 = Paths.get("\\readm.txt"); Path p = Paths.get("\\photo\\readme.txt"); System.out.println(p1.relativize(p)); => ..\photo\readme.txt Path p1 = Paths.get("c:\\personal\\.\\photos\\..\\photo\\..\\readme.txt"); Path p2 = p1.normalize(); System.out.println(p2); => c:\personal\readme.txt Which of the following are valid enum values defined in java.nio.file.FileVisitResult? SKIP_SIBLINGS SKIP_SUBTREE java.nio.file.FileVisitResult defines the following four enum constants CONTINUE Continue. SKIP_SIBLINGS Continue without visiting the siblings of this file or directory. SKIP_SUBTREE Continue without visiting the entries in this directory. TERMINATE Terminate. The following line of code has thrown java.nio.file.FileSystemNotFoundException when run. What might be the reason(s)? Path p1 = Paths.get(new URI("file://e:/temp/records")); The file system, identified by the URI, does not exist. OK The provider identified by the URI's scheme component is not installed. // OK The preconditions on the uri parameter do not hold.// Not OK This could be a cause for IllegalArgumentException but not for FileSystemNotFoundException. The security manager is installed and it denies an unspecified permission to access the file system. This is a cause for SecurityException. The following JavaDoc API description of Paths.get(URI ) method is important for the exam. Pay close attention to the exceptions that it throws public static Path get(URI uri) Converts the given URI to a Path object. This method iterates over the installed providers to locate the provider that is identified by the URI scheme of the given URI. URI schemes are compared without regard to case. If the provider is found then its getPath method is invoked to convert the URI. In the case of the default provider, identified by the URI scheme "file", the given URI has a non-empty path component, and undefined query and fragment components. Whether the authority component may be present is platform specific. The returned Path is associated with the default file system. The default provider provides a similar round-trip guarantee to the File class. For a given Path p it is guaranteed that Paths.get(p.toUri()).equals( p.toAbsolutePath()) so long as the original Path, the URI, and the new Path are all created in (possibly different invocations of) the same Java virtual machine. Whether other providers make any guarantees is provider specific and therefore unspecified. Parameters: uri - the URI to convert Returns: the resulting Path Throws: IllegalArgumentException - if preconditions on the uri parameter do not hold. The format of the URI is provider specific. FileSystemNotFoundException - The file system, identified by the URI, does not exist and cannot be created automatically, or the provider identified by the URI's scheme component is not installed SecurityException - if a security manager is installed and it denies an unspecified permission to access the file system What will the following code print? Path p1 = Paths.get("c:\\temp\\test.txt"); Path p2 = Paths.get("c:\\temp\\report.pdf"); System.out.println(p1.resolve(p2)); => c:\temp\report.pdf Path p1 = Paths.get("c:\\temp\\test.txt"); Path p2 = Paths.get("c:\\tem\\dd\\report.pdf"); System.out.println(p1.resolve(p2)); => c:\tem\dd\report.pdf When the argument to resolve starts with the root (such as c: or, on *nix, a /), the result is same as the argument. Please go through the following description of Path.resolve() method as given in JavaDoc API: public Path resolve(Path other) Resolve the given path against this path. If the other parameter is an absolute path then this method trivially returns other. If other is an empty path then this method trivially returns this path. Otherwise this method considers this path to be a directory and resolves the given path against this path. In the simplest case, the given path does not have a root component, in which case this method joins the given path to this path and returns a resulting path that ends with the given path. Where the given path has a root component then resolution is highly implementation dependent and therefore unspecified. Parameters: other - the path to resolve against this path Returns: the resulting path Given that the file test.txt is accessible and contains multiple lines, which of the following code fragments will correctly print all the lines from the file? Stream<String> lines = Files.lines(Paths.get("test.txt")); lines.forEach(System.out::println); //OK Stream<String> lines = Files.lines(Paths.get("test.txt"), Charset.defaultCharset()); lines.forEach(s -> System.out.println(s)); //OK Stream<String> lines = Files.find(Paths.get("test.txt")); lines.forEach(System.out::println); //Not OK Files.find method returns a stream of Path objects. The following is the correct signature for the find method. public static Stream<Path> find(Path start, int maxDepth, BiPredicate<Path,BasicFileAttributes> matcher, FileVisitOption... options) throws IOException Return a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file. Stream<String> lines = Files.list(Paths.get("test.txt")); lines.forEach(x->System.out.println(x)); //Not OK The usage of Files.list method is correct but it returns a stream of Path objects for files contained in a directory. Unlike the Files.find method, the list method doesn't search for files. It just returns all the files in a given directory. If you change the code to Stream<Path> lines = Files.list(Paths.get("c:\\temp\\test.txt"));, it will compile but will throw java.nio.file.NotDirectoryException because test.txt is not a directory. What will the following code fragment print? Path p1 = Paths.get("c:\\..\\temp\\test.txt"); System.out.println(p1.normalize().toUri()); file:///c:/temp/test.txt In this case, .. is at the top level and there is no parent directory at this level. Therefore, it is redundant and is removed from the normalized path. Had there been a parent directory for .., for example, c:/temp/../test.txt, the parent directory and .. would cancel out ( i.e. the result would be c:/test.txt ). The following is the complete JavaDoc API description of this method: public Path normalize() Returns a path that is this path with redundant name elements eliminated. The precise definition of this method is implementation dependent but in general it derives from this path, a path that does not contain redundant name elements. In many file systems, the "." and ".." are special names used to indicate the current directory and parent directory. In such file systems all occurrences of "." are considered redundant. If a ".." is preceded by a non-".." name then both names are considered redundant (the process to identify such names is repeated until is it no longer applicable). This method does not access the file system; the path may not locate a file that exists. Eliminating ".." and a preceding name from a path may result in the path that locates a different file than the original path. This can arise when the preceding name is a symbolic link. Returns: the resulting path or this path if it does not contain redundant name elements; an empty path is returned if this path does have a root component and all name elements are redundant Given the following code (assume appropriate imports): public class IOTest { public static void main(String[] args) { Path myfile = Paths.get("test.txt"); try(BufferedReader 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? java.nio.file.NoSuchFileException: test.txt //OK This exception will be thrown when the program tries to create a BufferedReader to read the file specified by the Path object. java.nio.file.InvalidPathException : test.txt //Not OK This exception is thrown when the argument passed while creating Path object is invalid. For example, "c:c:test.txt". In the given code, the path string is valid, so this exception will not be thrown. The existence of the file is not checked at the time of creation of Path object. 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 checked exceptions may be thrown by this code? None None of the calls to Console throw any checked exception. Call to System.console() doesn't throw any exception either. It just returns null if Console is not available. Observe that //2 will throw a NullPointerException (which is not a checked exception) if System.console() returns null. System.console() returns null when the program is run in an environment where there is no console, for example, as a service using javaw. Remember that the readLine and readPassword methods of Console do not declare any checked exceptions. Therefore, calls to these methods need not be wrapped in a try block or declared in the throws clause of the calling method. 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? It will not compile. Note that the return type of readPassword is char[] and not a String. So it will not compile. If you replace String pwd to char[] pwd, you will get the following output: Enter UserId:jack userid is jack Enter Password : password is [C@1fb8ee3 Observe that password is not echoed while the user is typing and char[] is an object, which is printed out as [C@1fb8ee3. File f = new File("x");//1 BufferedReader bfr1 = new BufferedReader(new FileReader(f)); //2 BufferedReader bfr2 = new BufferedReader( bfr1 ); //3 PrintWriter pw = new PrintWriter(new FileReader(f)); // Not compile To customize the behavior of class serialization, the readObject and writeObject methods should be overridden. Constructor of the class for an object being deserialized is never invoked. If an object is being deserialized, that means the class of that object implements Serializable. Therefore, its constructor will never be called. However, constructor for the super class may be invoked if the super class does not implement serializable interface. Given: public static void createFile(String name) throws Exception{ try ( OutputStream os = new FileOutputStream(name); ) { //INSERT CODE HERE //flush and close the streams that are open } } Which of the following combinations of the lines of code and their outcome when inserted above, are correct? PrintWriter pw = new PrintWriter(os); pw.write(1); Size of the file depends on default character encoding. //OK PrintWriter's write method writes a single character to the file. The size in bytes of a character depends on the default character encoding of the underlying platform. For example, if the encoding is UTF-8, only 1 byte will be written and the size of the file will be 1 byte. os.write(99); A file of size 1 byte will be created. //OK Note that the write(int b) method of various streams based classes such as FileOutputStream take an int parameter but write only the low 8 bits (i.e. 1 byte) of that integer. DataOutputStream provides methods such as writeInt, writeChar, and writeDouble, for writing complete value of the primitives to a file. So if you want to write an integer to the file, you should use writeInt(1) in which case a file of size 4 bytes will be created. You can read back the stored primitives using methods such as DataInputSream.readInt(). (Note: DataInput/DataOutputStream is not mentioned explicitly in the exam objectives.) BufferedOutputStream bos = new BufferedOutputStream(os); PrintWriter pw = new PrintWriter(bos); pw.print(99); A file of size 1 byte will be created. //Not OK PrintWriter's print(int) method actually writes the string produced by String.valueOf(int). This string is translated into bytes according to the platform's default character encoding, and these bytes are written in using the write(int) method. Therefore, in this case, if the default character encoding is UTF-8, 2 bytes will be written. os.writeInt(99); A file of size 4 bytes will be created. //Not OK OutputStream does not provide methods for writing primitives. It writes bytes only. Therefore, this will not compile. PrintWriter pw = new PrintWriter(os); pw.writeInt(1); A file of size 4 bytes will be created. //Not OK PrintWriter does not provide explicit methods for writing primitives (i.e. writeInt, writeBoolean, etc.). It has overloaded print methods that take various primitives (i.e. print(int), print(boolean), print(long), and print(char) as arguments). Therefore, this will not compile. public class Data implements java.io.Serializable{ public static String f1; public static transient int f2; public transient boolean f3; public final static String f4 = "4"; public String f5 = "5"; } Data d.f1 d.f2 d.f3 d = = = = new Data(); "f1"; 2; true; Which fields of the above class will be preserved when the object referred to by the variable 'd' is serialized and deserialized in another JVM? f4, f5. f3 is an instance variable. Since its value is not same as its default value, serialization is the only means through which it can be preserved. But it is declared transient, which excludes it from being serialized. Therefore, the value of f3 will not be serialized and so it cannot be retrieved back upon de-serialization. Remember that static fields are never serialized irrespective of whether they are marked transient or not. In fact, making static fields as transient is redundant. Thus, f1, f2 and f4 will not be serialized at all. However, since f4 is being initialized as a part of class initialization, it will be initialized to the same value in another JVM. Thus, its value will be same as the one initialized by the code. Which of the following methods are available in java.io.Console? readPassword char[] readPassword() Reads a password or passphrase from the console with echoing disabled char[] readPassword(String fmt, Object... args) Provides a formatted prompt, then reads a password or passphrase from the console with echoing disabled. reader java.io.Reader reader() Retrieves the unique Reader object associated with this console. writer java.io.PrintWriter writer() Retrieves the unique PrintWriter object associated with this console. readLine String readLine() Reads a single line of text from the console. String readLine(String fmt, Object... args) Provides a formatted prompt, then reads a single line of text from the console. format Console format(String fmt, Object... args) Writes a formatted string to this console's output stream using the specified format string and arguments. Notice that it returns the same Console object again. Thus, you can chain the format calls. For example, con.format("%dth visitor logged in.", n).format("Id is %d.", id).format("Name is %s", name); How many methods have to be provided by a class that is not abstract and that says it implements Serializable interface? 0 Serializable interface does not declare any methods. That is why it is also called as a "marker" interface. Identify correct statements about java.io.Console class? You can read as well as write only character data from/to it. Console is meant to interact with the user typically through command/shell window and keyboard. Thus, binary data doesn't make sense for the console. You can read whatever the user types using readLine() and readPassword() method. You can also acquire a Reader object using reader() method on Console object. All these provide character data. Similarly, you can acquire PrintWriter object using writer() method on Console, which allows you to write character data to the console. Which of the following statements about Java serialization are correct? Multiple copies of an object may be added to a stream. The statement is a bit vague. It is trying to convey that the same object can be serialized multiple times to a stream. Thus, you may have mutliple copies of the same object in the stream and when you read the stream back, you will get multiple objects. //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);) { byte[] buffer = new byte[1024]; int 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? The program will compile and run without any exception. test2.txt will be created automatically and contents of test1.txt will be copied to it. Which of the following method implementations will write a boolean value to the underlying stream? public void usePrintWriter(PrintWriter pw) throws IOException{ boolean bval = true; pw.print(bval); } Although the throws IOException clause is not required here, it is not invalid. } public void usePrintWriter(PrintWriter pw) { boolean bval = true; pw.print(bval); public void usePrintWriter(PrintWriter pw) { boolean bval = true; pw.println(bval); } Remember that none of PrintWriter's print or write methods throw I/O exceptions (although some of its constructors may). This is unlike other streams, where you need to include exception handling (i.e. a try/catch or throws clause) when you use the stream. Given that the file test.txt contains : 12345678 What will the following code print when compiled and run? public static void main(String[] args) throws Exception{ try(FileInputStream fis = new FileInputStream("c:\\temp\\test.txt"); InputStreamReader isr = new InputStreamReader(fis)){ while(isr.ready()){ isr.skip(1); int i = isr.read(); char c = (char) i; System.out.print(c); } } } It will print 2468 The ready method just checks if there are more bytes available to read. The skip method skips the given number of characters i.e. it basically moves the file pointer one character ahead. The read method reads one character. Overall, the code simply skips one character after reading each character. Therefore, it prints 2468. public class Java8Tester { public static void main(String args[]){ List<String> names2 = new ArrayList<String>(); names2.add("Mahesh "); names2.add("Suresh "); names2.add("Ramesh "); names2.add("Naresh "); names2.add("Kalpesh "); Java8Tester tester = new Java8Tester(); tester.sortUsingJava8(names2); System.out.println(names2); } //sort using java 8 private void sortUsingJava8(List<String> names){ Collections.sort(names, (s1, s2) -> s1.compareTo(s2)); } } => [Kalpesh , Mahesh , Naresh , Ramesh , Suresh ] Collectors // Accumulate names into a List List<String> list = people.stream().map(Person::getName).collect(Collectors.toList()); // Accumulate names into a TreeSet Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new)); // Convert elements to strings and concatenate them, separated by commas String joined = things.stream().map(Object::toString).collect(Collectors.joining(", ")); // Compute sum of salaries of employee int total = employees.stream().collect(Collectors.summingInt(Employee::getSalary))); // Group employees by department Map<Department, List<Employee>> byDept = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment)); // Compute sum of salaries by department Map<Department, Integer> totalByDept = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.summingInt(Employee::getSalary))); // Partition students into passing and failing Map<Boolean, List<Student>> passingFailing = students.stream() .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD)); public final class Test { final private String name; Test(String name) { this.name = name; getName(); } //code here } Which of the following code will make an instance of this class immutable. A. B. C. D. E. public String getName(){return name;} public String getName(String value){ name=value; return value;} private String getName(){return name+"a";} public final String getName(){return name+="a";} All of Above. => Option A,C are correct. Option B and D have a compile error since name variable is final. Option C is private and doesn't change the name value. Option A is public and doesn't change the name value. Consider the following code: 1. class SuperClass{ 2. protected void method1(){ 3. System.out.print("M SuperC"); 4. 5. } } 6. 7. class SubClass extends SuperClass{ 8. private void method1(){ 9. 10. System.out.print("M SubC"); } 11. 12. public static void main(String[] args){ 13. SubClass sc = new SubClass(); 14. sc.method1(); 15. 16. } } What will be the result? A. M SubC. B. M SuperC. C. M SuperCM SubC. D. Compilation fails. E. None of above. => Option D is correct. The code fails to compile at line 8, cannot reduce the visibility of the inherited method from SuperClass. public class Test { public static void main(String args[]) { Runnable r = () -> System.out.println("Running"); Thread thread = new Thread(r); thread.start(); } } => Because: @FunctionalInterface public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); } compareTo is a method that is only available in String object, not any other objects: public class Test { public static <T> int count(T[] array, T elem) { //1 int count = 0; for (T e : array) if( e.compareTo(elem) > 0){ ++count; // Compile failed System.out.println(e); } return count; } public static void main(String[] args) { Integer[] a = {1,2,3,4,5}; int n = Test.<Integer>count(a, 3); System.out.println(n); } } => If change type “T” to “Integer” also have the same result: Compile failed. => If change line 1 become: public static <T extends Comparable<T>> int count(T[] array, T elem). It will print: 4, 5, 2. Because: -public abstract class Number implements java.io.Serializable{} -public final class String implements java.io.Serializable, Comparable<String>, CharSequence{} public class Program { public static void main(String[] args) { Thread th = new Thread(new Runnable(){ static { System.out.println("initial"); } // Compile failed @Override public void run() { System.out.println("start"); } }); th.start(); } } => Becouse you cannot declare static initializers in an anonymous class. which of the following database url are correct: A. jdbc:mysql://localhost:3306 B. jdbc:mysql://localhost:3306/sample C. jdbc:mysql://localhost:3306/sample/user=root?password=secret D. jdbc:mysql://localhost:3306/sample?user=root&password=secret E. All => A,B and D are correct. => The correct usrl format is the following: jdbc:mysql://[host][,failoverhost...] [:port]/[database] [?propertyName1][=propertyValue1] [&propertyName2][=propertyValue2]... final class A{ private String s; public A(String s){ this.s = s; } public String toString(){ return s; }; public void setA(String a){ this.s+= a; }; } public final class Immutable { private final A a; public Immutable(A a){ this.a = a; } public String toString(){ return a.toString();}; public static void main(String[] args){ A a = new A("Bye"); Immutable im = new Immutable(a); System.out.println(im); a.setA(" bye"); System.out.println(im); } } => Print: Bye, Bye bye public class Program { public static void main(String[] args) throws InterruptedException{ Callable<String> c = new Callable<String>(){ @Override public String call() throws Exception { String s=""; for (int i = 0; i < 10; i++) { s+=i;} return s; } }; ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(c); try { String result = future.get(); System.out.println(result); } catch (ExecutionException e) { e.printStackTrace(); } } } //=> 0123456789 package pkg1; public class One{ protected void showMe() { System.out.println("Hello from showMe() One Class"); } } package pkg2; import pkg1.One; class Two extends One { void callShowMe() { new One().showMe(); // 1: compile failed } } => Line 1: Compile failed: Request change method “showMe” to public. => Change line 1 to: “showMe();”: It will compile and print: "Hello from showMe() One Class" Which of the following code segments will correctly write the text FINAL TEXT at the end of a file file.txt ? RandomAccessFile raf = new RandomAccessFile("file.txt", "rw"); raf.seek( raf.length() ); raf.writeChars("FINAL TEXT"); ```` How will you initialize a SimpleDateFormat object so that the following code will print the full name of the month of the given date? SimpleDateFormat sdf = new SimpleDateFormat("MMMM", Locale.FRANCE); M => 2, 12 MM => 02, 12 MMM => févr., déc. MMMM => février, décembre Which of the following File Attribute views support manipulating the owner of a file? - PosixFileAttributeView(OK): Unix based file systems provide this view. This view supports the following attributes in addition to BasicFileAttributeView: "permissions" : Set<PosixFilePermission> "group" : GroupPrincipal The permissions attribute is used to update the permissions, owner, or group-owner as by invoking the setPermissions, setOwner, and setGroup methods respectively. - DosFileAttributeView: This view supports the following attributes in addition to BasicFileAttributeView: readonly Boolean hidden Boolean system Boolean archive Boolean - BasicFileAttributeView: This view supports only the following attributes: "lastModifiedTime" FileTime "lastAccessTime" FileTime "creationTime" FileTime "size" Long "isRegularFile" Boolean "isDirectory" Boolean "isSymbolicLink" Boolean "isOther" Boolean "fileKey" Object DosFileAttributeView and PosixFileAttribute view extend BasicFileAttributeView. For the purpose of the exam, you need to know the basic codes for printing out a date. The important ones are m, M, d, D, y, s, S, h, H, and z. Letter Date or Time Component Presentation Examples G Era designator Text AD y Year Year 1996; 96 Y Week year Year 2009; 09 M Month in year Month July; Jul; 07 w Week in year Number 27 W Week in month Number 2 D Day in year Number 189 d Day in month Number 10 F Day of week in month Number 2 E Day name in week Text Tuesday; Tue u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1 a Am/pm marker Text PM H Hour in day (0-23) Number 0 k Hour in day (1-24) Number 24 K Hour in am/pm (0-11) Number 0 h Hour in am/pm (1-12) Number 12 m Minute in hour Number 30 s Second in minute Number 55 S Millisecond Number 978 z Time zone General time zone Pacific Standard Time; PST; GMT-08:00 Z Time zone RFC 822 time zone -0800 X Time zone ISO 8601 time zone -08; -0800; -08:00 Which of the following code fragments correctly prints all the roots of the default file system? FileSystem fs = FileSystems.getDefault(); Iterable<Path> roots = fs.getRootDirectories(); for(Path p : roots){ System.out.println(p); } Iterator<Path> it = roots.iterator(); while(it.hasNext()){ System.out.println(it.next()); } Which of the following are valid ways to create a RandomAccessFile? RandomAccessFile raf = new RandomAccessFile("c:\\temp\\test.txt", "rws"); RandomAccessFile raf = new RandomAccessFile(new File("c:\\temp\\test.txt"), "rws"); RandomAccessFile provides the following two constructors RandomAccessFile(File file, String mode) throws FileNotFoundException Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. RandomAccessFile(String name, String mode) throws FileNotFoundException Creates a random access file stream to read from, and optionally to write to, a file with the specified name. The mode argument specifies the access mode in which the file is to be opened. The permitted values and their meanings are: "r": Open for reading only. Invoking any of the write methods of the resulting object will cause an IOException to be thrown. "rw": Open for reading and writing. If the file does not already exist then an attempt will be made to create it. "rws": Open for reading and writing, as with "rw", and also require that every update to the file's content or metadata be written synchronously to the underlying storage device. "rwd": Open for reading and writing, as with "rw", and also require that every update to the file's content be written synchronously to the underlying storage device. The "rwd" mode can be used to reduce the number of I/O operations performed. Using "rwd" only requires updates to the file's content to be written to storage; using "rws" requires updates to both the file's content and its metadata to be written, which generally requires at least one more low-level I/O operation. Given: public static void createFile(String name) throws Exception{ try ( OutputStream os = new FileOutputStream(name); ) { //INSERT CODE HERE //flush and close the streams that are open } } Which of the following combinations of the lines of code and their outcome when inserted above, are correct? os.write(1); A file of size 1 byte will be created. BufferedOutputStream bos = new BufferedOutputStream(os); DataOutputStream dos = new DataOutputStream(bos); dos.write(1); A file of size 1 byte will be created. Complete the following code fragment so that it will print owner's name of a file: Path path = Paths.get("c:\\temp\\test.txt"); //INSERT CODE HERE System.out.println(ownername); (Assume that the file system supports owner name for a file.) PosixFileAttributeView pfav = Files.getFileAttributeView(path, PosixFileAttributeView.class); PosixFileAttributes attrs = pfav.readAttributes(); String ownername = attrs.owner().getName(); Which method do you need to implement if you want to implement your own java.nio.file.PathMatcher? boolean matches(Path path) 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())); SimpleDateFormat sdf = new SimpleDateFormat("zzzz", Locale.FRANCE); Date and Time Pattern "yyyy.MM.dd G 'at' HH:mm:ss z" "EEE, MMM d, ''yy" "h:mm a" "hh 'o''clock' a, zzzz" "K:mm a, z" "yyyyy.MMMMM.dd GGG hh:mm aaa" "EEE, d MMM yyyy HH:mm:ss Z" "yyMMddHHmmssZ" "yyyy-MM-dd'T'HH:mm:ss.SSSZ" "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" "YYYY-'W'ww-u" Result 2001.07.04 AD at 12:08:56 PDT Wed, Jul 4, '01 12:08 PM 12 o'clock PM, Pacific Daylight Time 0:08 PM, PDT 02001.July.04 AD 12:08 PM Wed, 4 Jul 2001 12:08:56 -0700 010704120856-0700 2001-07-04T12:08:56.235-0700 2001-07-04T12:08:56.235-07:00 2001-W27-3 Consider the following code: public static void appendTest() throws Exception { Path myPath = Paths.get("c:\\temp\\text.txt"); UserPrincipal up = myPath.getFileSystem().getUserPrincipalLookupService().lookupPrincipalByName("john"); Files.setOwner(myPath, up); try ( //INSERT CODE HERE ) { br.write("..appended."); } System.out.println("done"); } Assuming that text.txt exists, which of the following statements will correctly open the file and append data to it, which is written to the disk synchronously but allows the meta data to be written to the disk later? BufferedWriter br = Files.newBufferedWriter(myPath, Charset.forName("UTF-8"), new OpenOption[]{StandardOpenOption.APPEND, StandardOpenOption.DSYNC}) Since the file already exists, APPEND option will cause data to be written at the end. DSYNC option forces the data to be written to the disk synchronously but allows the meta data to be written to the disk later. BufferedWriter br = Files.newBufferedWriter(myPath, Charset.forName("UTF-8"), new OpenOption[]{StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.DSYNC}) This is same as option 3. The WRITE option is redundant in this case because the file already exists. Had the file not been present, it would have thrown java.nio.file.NoSuchFileException. This answer is not good: BufferedWriter br = Files.newBufferedWriter(myPath, Charset.forName("UTF-8"), new OpenOption[]{StandardOpenOption.WRITE, StandardOpenOption.DSYNC}) WRITE option will cause the file to be written from the beginning. Thus, it will overwrite existing data. FileInputStream fis = new FileInputStream("c:\\temp\\test.txt"); FileOutputStream fos = new FileOutputStream("c:\\temp\\test.txt"); RandomAccessFile ras = new RandomAccessFile("c:\\temp\\test.txt", "rw"); FileWriter fw = new FileWriter("c:\\temp\\test.txt"); FileChannel f1 = fis.getChannel(); //1 FileChannel f2 = fos.getChannel(); //2 FileChannel f3 = ras.getChannel(); //3 FileChannel f4 = fw.getChannel(); //4 //4 will not compile. Given the following code: RandomAccessFile raf = new RandomAccessFile("c:\\temp\\test.txt", "rwd"); raf.writeChars("hello"); raf.close(); Which of the following statements are correct? If the file test.txt does not exist, an attempt will be made to create it. Answers are not good: - - If the file test.txt exists, it will be overwritten and all the existing data will be lost. Only the initial 5 characters (i.e. 10 bytes) of the file will be overwritten. Any existing data beyond the first 10 bytes will be left untouched. If the file test.txt exists, the given characters will be appended to the end of the existing data. When you open the file, the file pointer is at the first position. So the given characters will be written at the beginning of the file. Consider the following code: String s = "hello"; byte i = 100; FileOutputStream fos = new FileOutputStream("c:\\temp\\data.bin"); DataOutputStream dos = new DataOutputStream(fos); //WRITE s to file //WRITE i to file dos.flush(); dos.close(); fos.close(); DataInputStream dis = new DataInputStream(new FileInputStream("c:\\temp\\data.bin")); //READ s from file //READ i from file Which methods should be used to write and read s and i to/from the data.bin file? writeUTF, writeByte and readUTF, readByte DSYNC keeps only the file content and not the file meta data synchronized with the underlying storage device. The following is a list of constants provided by java.nio.file.StandardOpenOption: APPEND If the file is opened for WRITE access then bytes will be written to the end of the file rather than the beginning. CREATE Create a new file if it does not exist. CREATE_NEW Create a new file, failing if the file already exists. DELETE_ON_CLOSE Delete on close. DSYNC Requires that every update to the file's content be written synchronously to the underlying storage device. READ Open for read access. SPARSE Sparse file. SYNC Requires that every update to the file's content or metadata be written synchronously to the underlying storage device. TRUNCATE_EXISTING If the file already exists and it is opened for WRITE access, then its length is truncated to 0. WRITE Open for write access You want to create a new file. If the file already exists, you want the new file to overwrite the existing one (the content of the existing file, if any, should go away). Which of the following code fragments will accomplish this? Path myfile = Paths.get("c:\\temp\\test.txt"); BufferedWriter br = Files.newBufferedWriter(myfile, Charset.forName("UTF-8"), new OpenOption[] {StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE}); If the file already exists, TRUNCATE_EXISTING will take care of the existing content. If the file does not exist, CREATE will ensure that it is created. Answers are not good: - - - Path myfile = Paths.get("c:\\temp\\test.txt"); BufferedWriter br = Files.newBufferedWriter(myfile, Charset.forName("UTF-8"), new OpenOption[] {StandardOpenOption.CREATE}); CREATE option will cause the file to be overwritten from the start of the file and it will NOT get rid of the existing content. Path myfile = Paths.get("c:\\temp\\test.txt"); BufferedWriter br = Files.newBufferedWriter(myfile, Charset.forName("UTF-8"), new OpenOption[] {StandardOpenOption.CREATE_NEW}); CREATE_NEW will cause an exception to be thrown if the file already exists. Path myfile = Paths.get("c:\\temp\\test.txt"); BufferedWriter br = Files.newBufferedWriter(myfile, Charset.forName("UTF-8"), new OpenOption[] {StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE_NEW}); If the file already exists, TRUNCATE_EXISTING will take care of the existing content. If the file does not exist, CREATE will ensure that it is created. StandardOpenOption gives you several ways of opening a file. You can mix and match the options to achieve the desired objective. We encourage you to run the following code with different open options and observe how it behaves. Observe that some combinations such as StandardOpenOption.CREATE, StandardOpenOption.READ do not make sense if put together and therefore an IllegalArgumentException will be thrown in such cases. There are questions on the exam that expect you to know such combinations. import import import public { java.io.BufferedWriter; java.nio.charset.Charset; java.nio.file.*; class TestClass public static void main(String args[]) throws Exception { Path writeFile = Paths.get("c:\\temp\\test.txt"); BufferedWriter br = Files.newBufferedWriter(writeFile, Charset.forName("UTF-8"), new OpenOption[] {StandardOpenOption.CREATE, StandardOpenOption.READ}); br.write("This text file is created using Path API"); br.flush(); br.close(); } } Which of the following code fragments allow you to hide the file test.txt? Path p = Paths.get("c:\\temp\\test.txt"); Files.setAttribute(p, "dos:hidden", true, NOFOLLOW_LINKS); Path p = Paths.get("c:\\temp\\test.txt"); Files.setAttribute(p, "dos:hidden", true); Which of the following statements are valid usages of StandardOpenOption options that control how the file is opened? new OpenOption[]{StandardOpenOption.WRITE, StandardOpenOption.DELETE_ON_CLOSE} new OpenOption[]{StandardOpenOption.READ, StandardOpenOption.DELETE_ON_CLOSE} new OpenOption[]{StandardOpenOption.DELETE_ON_CLOSE, StandardOpenOption.TRUNCATE_EXISTING} (This is a valid combination but will throw java.nio.file.NoSuchFileException if the file does not exist.) new OpenOption[]{StandardOpenOption.READ, StandardOpenOption.SYNC} Observe that some combinations such as CREATE and READ do not make sense if put together and therefore an IllegalArgumentException will be thrown in such cases. There are questions on the exam that expect you to know such combinations. JavaDoc API does not explicitly mention which combinations are invalid and so in many cases it is not easy to spot a valid/invalid combination. For example, if you want to truncate a file, then you must open it with an option that allows writing. Thus, READ and TRUNCATE_EXISTING (or WRITE, APPEND, or DELETE_ON_CLOSE) should not go together. However, on Java 8, READ and DELETE_ON_CLOSE work fine together. Please note that the validity of these combinations also depends on the OS and the file system used. So it is not possible to precisely determine which combinations will always be invalid. The following is a list of constants provided by java.nio.file.StandardOpenOption: APPEND If the file is opened for WRITE access then bytes will be written to the end of the file rather than the beginning. CREATE Create a new file if it does not exist. CREATE_NEW Create a new file, failing if the file already exists. DELETE_ON_CLOSE Delete on close. DSYNC Requires that every update to the file's content be written synchronously to the underlying storage device. READ Open for read access. SPARSE Sparse file. SYNC Requires that every update to the file's content or metadata be written synchronously to the underlying storage device. TRUNCATE_EXISTING If the file already exists and it is opened for WRITE access, then its length is truncated to 0. WRITE Open for write access. Which of the following code fragments correctly prints all the roots of the default file system? File[] roots = File.listRoots(); for(File f : roots){ System.out.println(f); } Iterable<Path> roots = FileSystems.getDefault().getRootDirectories(); for(Path p : roots){ System.out.println(p); } Given : glob pattern: glob:?{pdf,rtf} Actual name of the files in a directory (Separated by comma, not including the space): .rtf, a.pdf, ab.rtf, ab.pdf, pdf Which files will be captured by the glob pattern? .rtf Remember that ? matches exactly one character in a glob pattern (as opposed to zero or one in a regex). Therefore, ?{pdf,rtf} will match only those file names that have exactly four characters and the last three characters have to be pdf or rtf. Since ? matches exactly 1 character in a glob pattern, this doesn't satisfy glob pattern ?pdf. But the following would print true: Pattern p = Pattern.compile(".?pdf"); //Notice that .? matches 0 or 1 character Matcher m = p.matcher("pdf"); System.out.println(m.matches()); //prints true. Matcher m = p.matcher(".pdf"); System.out.println(m.matches()); //prints true. Which of the following are valid ways to create a RandomAccessFile? DataOutput raf = new RandomAccessFile(new File("c:\\temp\\test.txt"), "rw"); RandomAccessFile does not extend from InputStream or OutputStream. But it does implement java.io.DataOutput and java.io.DataInput interfaces (and Closeable and AutoCloseable interfaces as well). RandomAccessFile provides the following two constructors RandomAccessFile(File file, String mode) throws FileNotFoundException Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. RandomAccessFile(String name, String mode) throws FileNotFoundException Creates a random access file stream to read from, and optionally to write to, a file with the specified name. Consider the following code: public static void findFiles() throws Exception{ Path dir = Paths.get("c:\\temp"); //INSERT CODE HERE for(Path p : ds){ System.out.println(p); } } catch(Exception e){ e.printStackTrace(); } } What should be inserted in the above code so that it will print all the files with extension gif and jpeg? try{ DirectoryStream<Path> ds = Files.newDirectoryStream(dir, "*.{gif,jpeg}"); Files.newDirectoryStream(Path dir, String globPattern) Opens a directory, returning a DirectoryStream to iterate over the entries in the directory. The elements returned by the directory stream's iterator are of type Path, each one representing an entry in the directory. The Path objects are obtained as if by resolving the name of the directory entry against dir. The entries returned by the iterator are filtered by matching the String representation of their file names against the given globbing pattern. There are questions in the exam that expect you to know basic syntax for the glob pattern. The following description from JavaDoc API is sufficient :String representation of the path is matched using a limited pattern language that resembles regular expressions but with a simpler syntax. For example: *.java : Matches a path that represents a file name ending in .java *.* : Matches file names containing a dot *.{java,class} : Matches file names ending with .java or .class foo.? : Matches file names starting with foo. and a single character extension /home/*/* : Matches /home/gus/data on UNIX platforms /home/** : Matches /home/gus and /home/gus/data on UNIX platforms C:\\* : Matches C:\foo and C:\bar on the Windows platform (note that the backslash is escaped; as a string literal in the Java Language the pattern would be "C:\\\\*") The following rules are used to interpret glob patterns: The * character matches zero or more characters of a name component without crossing directory boundaries. The ** characters matches zero or more characters crossing directory boundaries. The ? character matches exactly one character of a name component. The backslash character (\) is used to escape characters that would otherwise be interpreted as special characters. The expression \\ matches a single backslash and "\{" matches a left brace for example. The [ ] characters are a bracket expression that match a single character of a name component out of a set of characters. For example, [abc] matches "a", "b", or "c". The hyphen (-) may be used to specify a range so [a-z] specifies a range that matches from "a" to "z" (inclusive). These forms can be mixed so [abce-g] matches "a", "b", "c", "e", "f" or "g". If the character after the [ is a ! then it is used for negation so [!a-c] matches any character except "a", "b", or "c". Within a bracket expression the *, ? and \ characters match themselves. The (-) character matches itself if it is the first character within the brackets, or the first character after the ! if negating. The { } characters are a group of subpatterns, where the group matches if any subpattern in the group matches. The "," character is used to separate the subpatterns. Groups cannot be nested. Leading period/dot characters in file name are treated as regular characters in match operations. For example, the "*" glob pattern matches file name ".login". The Files.isHidden method may be used to test whether a file is considered hidden. All other characters match themselves in an implementation dependent manner. This includes characters representing any name-separators. The matching of root components is highly implementation-dependent and is not specified. Consider the directory structure shown in the attached image. (context root is a directory, which contains two files Home.htm, index.html and a directory web-inf, which in turn contains a file web.xml) How will you create a PathMatcher that will match web.xml, Home.htm, and index.html? PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**.{htm*,xml}"); Returns a PathMatcher that performs match operations on the String representation of Path objects by interpreting a given pattern. The syntaxAndPattern parameter identifies the syntax and the pattern and takes the form: syntax:pattern where ':' stands for itself. A FileSystem implementation supports the "glob" and "regex" syntaxes, and may support others. The value of the syntax component is compared without regard to case. When the syntax is "glob" then the String representation of the path is matched using a limited pattern language that resembles regular expressions but with a simpler syntax. For example: *.java Matches a path that represents a file name ending in .java *.* Matches file names containing a dot *.{java,class} Matches file names ending with .java or .class foo.? Matches file names starting with foo. and a single character extension /home/*/* Matches /home/gus/data on UNIX platforms /home/** Matches /home/gus and /home/gus/data on UNIX platforms C:\\* Matches C:\foo and C:\bar on the Windows platform (note that the backslash is escaped; as a string literal in the Java Language the pattern would be "C:\\\\*") The following rules are used to interpret glob patterns: The * character matches zero or more characters of a name component without crossing directory boundaries. The ** characters matches zero or more characters crossing directory boundaries. The ? character matches exactly one character of a name component. The backslash character (\) is used to escape characters that would otherwise be interpreted as special characters. The expression \\ matches a single backslash and "\{" matches a left brace for example. The [ ] characters are a bracket expression that match a single character of a name component out of a set of characters. For example, [abc] matches "a", "b", or "c". The hyphen (-) may be used to specify a range so [a-z] specifies a range that matches from "a" to "z" (inclusive). These forms can be mixed so [abce-g] matches "a", "b", "c", "e", "f" or "g". If the character after the [ is a ! then it is used for negation so [!a-c] matches any character except "a", "b", or "c". Within a bracket expression the *, ? and \ characters match themselves. The (-) character matches itself if it is the first character within the brackets, or the first character after the ! if negating. The { } characters are a group of subpatterns, where the group matches if any subpattern in the group matches. The "," character is used to separate the subpatterns. Groups cannot be nested. Leading period/dot characters in file name are treated as regular characters in match operations. For example, the "*" glob pattern matches file name ".login". The Files.isHidden method may be used to test whether a file is considered hidden. All other characters match themselves in an implementation dependent manner. This includes characters representing any name-separators. The matching of root components is highly implementation-dependent and is not specified. When the syntax is "regex" then the pattern component is a regular expression as defined by the Pattern class. For both the glob and regex syntaxes, the matching details, such as whether the matching is case sensitive, are implementation-dependent and therefore not specified. Parameters: syntaxAndPattern - The syntax and pattern Returns: A path matcher that may be used to match paths against the pattern Throws: IllegalArgumentException - If the parameter does not take the form: syntax:pattern PatternSyntaxException - If the pattern is invalid UnsupportedOperationException - If the pattern syntax is not known to the implementation Which of the following statements are valid usages of StandardOpenOption options that determine how the file is opened? new OpenOption[]{StandardOpenOption.WRITE, StandardOpenOption.DSYNC} new OpenOption[]{StandardOpenOption.APPEND, StandardOpenOption.SYNC} Given the following code fragment: RandomAccessFile raf = new RandomAccessFile("c:\\temp\\test.txt", "rwd"); //INSERT CODE HERE raf.close(); DataInputStream 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? raf.writeUTF("hello world"); Remember that RandomAccessFile implements DataInput as well as DataOutput interfaces. Therefore, in this case, you can use raf as an instance of DataOutput and call its writeUTF(String) method. Which of the following statements correctly creates a PathMatcher? PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**.{htm,xml}"); FYI, the given glob pattern matches all the files with extension .htm or .xml. ** means, the pattern will match across directory boundaries. For example, It will match index.htm as well as c:\temp\test\index.htm But if you replace ** with *, it will match only index.htm. A file system is the factory for several types of objects: The getPath method converts a system dependent path string, returning a Path object that may be used to locate and access a file. The getPathMatcher method is used to create a PathMatcher that performs match operations on paths. The getFileStores method returns an iterator over the underlying file-stores. The getUserPrincipalLookupService method returns the UserPrincipalLookupService to lookup users or groups by name. The newWatchService method creates a WatchService that may be used to watch objects for changes and events. Identify the correct statements about the following code: try{ List<String> data = Files.readAllLines(Paths.get("c:\\temp\\test.txt")); data.stream().forEach( line ->{ try{ Files.write(Paths.get("c:\\temp\\test2.txt"), line.getBytes(), StandardOpenOption.APPEND); }catch(Exception e){ System.out.println("Exception Inner"); e.printStackTrace(); } } ); }catch(Exception e2){ System.out.println("Exception Outer"); } It will print Exception Inner if test.txt exists and test2.txt does not exist. Observe that the mode in which test2.txt is being opened is APPEND. The file has to exist before you can append to it. Therefore, it will throw an exception if test2.txt does not already exist. Contents of test.txt will be copied at the end of test2.txt exactly as they are only if test2.txt already exists. (Not Good): This is almost correct but for the part "exactly they are". Observe that write method does not automatically add new lines. Therefore, the new line characters of the original file will not be copied over to test2.txt. What will be the result? class A { private String s; public A(String in) { this.s = in; } public boolean equals(Object in) { if (getClass() != in.getClass()) return false; A a = (A) in; boolean ret = (this.s.equals(a.s)); return ret; } }; public class Program { public static void main(String[] args) { A a1 = new A("A"); A a2 = new A("A"); if (a1 == a2) // Line 1 System.out.println("true"); else System.out.println("false"); } } False. If change line 1 become: a1.equals(a2) .It will print: True import import import import java.util.ArrayList; java.util.Collections; java.util.Comparator; java.util.List; class Person{ private String name; private int age; Person(String name, int age){ this.name = name; this.age = age; } public String toString(){ return name + " " + age; } public static Comparator<Person> COMPARATOR = new Comparator<Person>() { public int compare(Person o1, Person o2) { return (o1.age - o2.age); } }; } public class Program { public static void main(String[] args) { List<Person> list = new ArrayList<Person>(); list.add(new Person("John",50)); list.add(new Person("Frank",15)); list.add(new Person("Adam",20)); Collections.sort(list,Person.COMPARATOR); list.forEach(a -> System.out.print(a.toString()+" ")); } } Frank 15 Adam 20 John 50 import java.util.Comparator; import java.util.Set; import java.util.TreeSet; class Person{ private String name; private int age; Person(String name, int age){ this.name = name; this.age = age; } public String toString(){ return name + " " + age; } public static Comparator<Person> COMPARATOR = new Comparator<Person>() { public int compare(Person o1, Person o2) { return (o1.age - o2.age); // line 1 }; }; }; public class Program { public static void main(String[] args) { Set<Person> list = new TreeSet<Person>(Person.COMPARATOR); list.add(new Person("John",15)); list.add(new Person("Frank",5)); list.add(new Person("Adam",15)); list.forEach(a -> System.out.print(a.toString()+" ")); } } Frank 5 John 15 If change line 1: o1.name.compareTo(o2.name). It will print: Adam 15 Frank 5 John 15 public class Program { public static void main(String[] args){ String url = "jdbc:derby:testdb/create=true"; try{ Connection conn = DriverManager.getConnection(url); String query = "select name from contacts"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); // line 1 while (rs.next()) { String name = rs.getString("Name"); System.out.println(name); } }catch(SQLException e){ System.out.println(e.getMessage()); } } } We can change line 1: boolean result = stmt.execute(query); With wrong url, this program never throw any exception. It just print can’t connect to that DB. public class Program { public static <T> int count(T[] array) { int count = 0; for (T e : array) ++count; return count; } public static void main(String[] args) { Integer[] a = {1,2,3,4,5}; //Code here System.out.println(n); } } which of the following are A. B. C. D. E. int int int int All n n n n = = = = valid method's invocation. <Integer>Program.count(a); Program.<Integer>count(a); Program.count<Integer>(a); Program.count(a); B, D Which of the following Statement are true? An anonymous class has access to the members of its enclosing class. An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final. You cannot declare static initializers or member interfaces. An anonymous class can have static members provided that they are constant variables. class A{ private String s; public A(String s) { this.s = s; }; public String toString() { return s; } } public class Program { public static void main(String[] args) { List<A> list = new ArrayList<A>(); list.add(new A("flower")); list.add(new A("cat")); list.add(new A("house")); list.add(new A("dog")); Collections.sort(list); //line 1 list.forEach(a -> System.out.print(a.toString() + " ")); } } The code will not compile because of line 1. the code will not compile becouse class A doesnt's implement Comparable interface. Which of those are valid Standard Streams? System.in System.out Which is/are true? In FileInputStream and FileOutputStream each read or write request is handled directly by the underlying OS. Programs use byte streams to perform input and output of 8-bit bytes. Character stream I/O automatically translates this internal format to and from the local character set. There are two general-purpose byte-to-character "bridge" streams: InputStreamReader and OutputStreamWriter. Your application requires to store name value pairs such that the order of entries returned while iterating through the structure is deterministic. In other words, if you iterate over the same structure twice, the order of elements returned in both the iterations will be the same. Which of the following classes would you use? LinkedHashMap(It is a linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.) TreeMap(It always returns the entries in sorted order.) HashMap(Not good ): HashMap does not guarantee to return the elements in a pre-determined order while iterating. public class TestClass extends Thread { public void run() { for(;;); } public static void main(String args[]) { System.out.println("Starting Main"); new TestClass().start(); System.out.println("Main returns"); } } It will print Starting Main It will print Main returns The program will never exit. 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 } } There is no problem with the code. The given code illustrates how to define a generic class. It has two generic types K and V. The only interesting piece of code here is this method: public static <X> PlaceHolder<X, X> getDuplicateHolder(X x){ return new PlaceHolder<X, X>(x, x); } You could write the same method in the following way also: public static <X> PlaceHolder<X, X> getDuplicateHolder(X x){ return new PlaceHolder<>(x, x); //use diamond operator because we already know that X is a generic type. } //In file VehicleType package objective1; public enum VehicleType { SUV, SEDAN, VAN, SPORTSCAR; public VehicleType() { } } VehicleType's constructor cannot be public. An enum's constructor is private by default. You cannot apply public or protected to the constructor. private is allowed but is redundant. public class TestClass { public static void main(String args[]) { A[] a, a1; B[] b; a = new A[10]; a1 = a; b = new B[20]; a = b;// 1 b = (B[]) a;// OK b = (B[]) a1; // Exception here: java.lang.ClassCastException } } class A { } class B extends A { } The program will throw a java.lang.ClassCastException at the line labeled 3 when run. The cast at line 2 is needed. The line 1 will be allowed during compilation, since assignment is done from a subclass reference to a superclass reference. The cast in line 2 is needed because a superclass reference is assigned to a subclass reference variable. And this works at runtime because the object referenced to by a is actually of an array of B. Now, the cast at line 3 will tell the compiler that don't worry (I'm a good programmer and I know what I am doing !!), the object referenced by the super class reference( a1) will actually be of class B at run time. So there is no error at compile time. But at run time, this fails because the actual object is not an array of B but is an array of A. public class TestClass { public int methodA(int a){ return a*2; } //1 public long methodA(int a){ return a; } //2 public static void main(String[] args) { int i = 0; i = new TestClass().methodA(2); System.out.println( i ); } } The program will not compile. Signature of the method comprises the method name, input parameters and their order. The return type is not considered. So, the two methods have same signature and this is illegal. You cannot have two methods of same signature in the same class. A Connection is always in auto-commit mode when it is created. As per the problem statement, an update was fired without explicitly disabling the auto-commit mode, the changes will be committed right after the update statement has finished execution. Given: Connection c = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", "app"); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("select * from STUDENT"); Which additional classes from java.sql package will you use if you want to find out how many columns are returned by the query? ResultSetMetaData A synchronized method cannot be executed simultaneously by more than one thread on the same object. Given the following method: public static void copy(String fileName1, String fileName2) throws Exception{ try ( InputStream is = new FileInputStream(fileName1); OutputStream os = new FileOutputStream(fileName2); ) { 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); } } } What will happen fileName1 contains only 100 bytes and fileName2 contains 200 bytes? fileName2 will end up with 100 bytes. InputStream.read() fills the buffer with the bytes actually read. So even if the buffer is larger than the available number of bytes, it is not a cause for any exception. 2. When you create a FileOutputStream without specifying the append mode (which can be true or false), it overwrites the existing file. Which of the statements regarding the join() method of Thread class is correct? The thread that calls the join() method, pauses until the other thread ends (i.e. finishes its run() method.) There is no need for any thread to hold any lock. class A { public void getItDone(int counter) { assert counter >= 0 : "Less than zero"; for(int i=0; i<counter; i++){ } } } class B extends A { public void getItDone(int counter) { assert counter < 100 : "Greater than 100"; for(int i=counter; i>0; i--){ } } public static void main(String args[]) { A a = new B(); a.getItDone(-4); } } The classes will compile and execute without any problem. getItDone() method of class B overrides the getItDone() method of class A. Thus, the assertion succeeds because -4 is less than 100. The loop is never entered and the program terminates. What will the following code print? Path p1 = Paths.get("\\photos\\vacation"); Path p2 = Paths.get("\\yellowstone"); System.out.println(p1.resolve(p2)+" "+p1.relativize(p2)); \yellowstone ..\..\yellowstone 1. Since the argument to resolve starts with \\, the result will be the same as the argument. If the argument doesn't start with a \ and it doesn't start with a root such as c:, the output is the result on appending the argument to the path on which the method is invoked. 2. To arrive at \\yellowstone from \\photos\\vacation, you have to first go two directories up and then down to yellowstone. Therefore, p1.relativize(p2) will be ..\..\yellowstone Given : import java.util.*; class MyStringComparator implements Comparator { public int compare(Object o1, Object o2) { int s1 = ((String) o1).length(); int s2 = ((String) o2).length(); return s1 - s2; } } and static String[] sa = { "d", "bbb", "aaaa" }; Select correct statements. Arrays.binarySearch(sa, "cc", new MyStringComparator()); will return -2. Since there is no string of length 2 in sa, nothing in sa matches the string "cc". So the return value has to be negative. Further, if the value "cc" were to be inserted in sa, it would have to be inserted after "d" i.e. at index 1. Thus, the return value will be -(index+1) = -2. Arrays.binarySearch(sa, "c", new MyStringComparator()); will return 0. There is only one string of length 1 in sa, and it is at index 0. This Comparator returns the difference in length of two strings. Thus, two strings of same length are considered equal by this comparator. Arrays.binarySearch() method returns the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. public class MyStringComparator implements Comparator<String>{ // Comparator<T> @Override public int compare(String o1, String o2) { return o1.length() - o2.length(); } public static void main(String[] args){ String[] arr = {"a", "aa", "aaa", "aa"}; System.out.println(Arrays.binarySearch(arr, "bbb", new MyStringComparator())); } } 2 Given: public class PlaceHolder<K, V> { private K k; private V v; public PlaceHolder(K k, V v){ this.k = k; this.v = v; } public K getK() { return k; } public static <X> PlaceHolder<X, X> getDuplicateHolder(X x){ return new PlaceHolder<X, X>(x, x); } public static void main(String[] args) { PlaceHolder<String, String> ph1 = PlaceHolder.getDuplicateHolder("b"); //1 PlaceHolder<String, String> ph2 = PlaceHolder<String>.getDuplicateHolder("b"); //2 PlaceHolder<String, String> ph3 = PlaceHolder<>.getDuplicateHolder("b"); //3 PlaceHolder<> ph4 = new PlaceHolder<String, String>("a", "b"); //4 PlaceHolder<?, ?> ph5 = new PlaceHolder(10, 10); //5 PlaceHolder<String, String> ph2 = PlaceHolder<String ,String>.getDuplicateHolder(); //6 } PlaceHolder<String, String> ph4 = new PlaceHolder<String, String>("a", "b"); //7 PlaceHolder<String, String> ph2 = PlaceHolder.<String>getDuplicateHolder("b");//8 } Which lines will fail compilation? //2, //3, //4, //6 Consider the following code: import java.util.*; public class TestClass { public static void main(String[] args) { // put declaration here m.put("1", new ArrayList()); m.put(1, new Object()); //2 m.put(1.0, "Hello"); //3 System.out.println(m); //1 } } How can 'm' be declared such that the above code will compile and run without errors? Map m = new TreeMap(); // Not good This will throw an exception at runtime because the keys of a TreeMap must be mutually comparable. Here, String, Integer, and Double are not mutually comparable. Map<Object, Object> m = new TreeMap<Object, Object>(); // Not good Same problem as the first option. Map<Object, ? super ArrayList> m = new LinkedHashMap<Object, ArrayList(); will work if lines //2 and //3 are commented out. //OK Map m = new HashMap(); //OK Map<Object, Object> m = new HashMap<Object, Object>(); //OK Identify the correct statements about the following code:List<Integer> values = Arrays.asList(2, 4, 6, 9); //1 Predicate<Integer> check = (Integer i) -> { System.out.println("Checking"); return i == 4; //2 }; Predicate even = (Integer i)-> i%2==0; // Not compile values.stream().filter(check).filter(even).count(); //4 Observe the lambda expression used to instantiate the Predicate is using Integer as the type of the variable. To make this work, the declaration part must be typed to Integer. Like this: Predicate<Integer> even = (Integer i)-> i%2==0; //3 Another option is to used Object type like this: Predicate even = (Object i)-> ((Integer)i)%2==0; or Predicate even = i -> ((Integer)i)%2==0; After you fix the line at //3, it will print: Checking Checking Checking Checking List<Integer> values = Arrays.asList(2, 4, 6, 9); //1 Predicate<Integer> check = (Integer i) -> { System.out.println("Checking"); return i == 4; //2 }; Predicate<Integer> even = i-> i%2==0; // Not compile long cnt = values.stream().filter(check).filter(even).count(); //4 System.out.println(cnt); Checking Checking Checking Checking 1 Write the command line that you will use to compile the following program. (Do not use any extra spaces. Start with javac) public class Assertion { public void assert(int k) { System.out.println("k is "+k); } public static void main(String[] args) { Assertion a = new Assertion(); a.assert(Integer.parseInt(args[0]); //4 } } javac –source 1.3 Assertion.java A programmer is using the following class for wrapping objects and passing it around to multiple threads. Which of the given statements regarding this class are correct? public class DataObjectWrapper { private final Object obj; public DataObjectWrapper(Object pObj){ obj = pObj; } public Object getObject() { return obj; } } Objects of this class are thread safe but you cannot say anything about the objects wrapped by this class. IntFunction<String> f = x -> Integer.toString(x); System.out.println(f.apply(56)); 56 Which of the following statements is/are true about java.util.function.IntFunction? It takes int primitive as an argument. It can be parameterized to return any thing. For example, IntFunction<String> f = x->""+x; returns a String. It avoids additional cost associated with auto-boxing/unboxing. Remember that primitive and object versions of data types (i.e. int and Integer, double and Double, etc.) are not really compatible with each other in java. They are made compatible through the extra step of auto-boxing/unboxing. Thus, if you have a stream of primitive ints and if you try to use the object versions of Stream and Function (i.e. Stream<Integer> and Function<Integer, Integer>, you will incur the cost of boxing and unboxing the elements. To eliminate this problem, the function package contains primitive specialized versions of streams as well as functional interfaces. For example, instead of using Stream<Integer>, you should use IntStream. You can now process each element of the stream using IntFunction. This will avoid auto-boxing/unboxing altogether. Thus, whenever you want to process streams of primitive elements, you should use the primitive specialized streams (i.e. IntStream, LongStream, and DoubleStream) and primitive specialized functional interfaces (i.e. IntFunction, IntConsumer, IntSupplier etc.) to achieve better performance. Given: public class Book{ String isbn; String title; public Book(String isbn, String title){ this.isbn = isbn; this.title = title; } public int compareTo(Book b){ return this.isbn.compareTo(b.isbn); } //accessors not shown } Assuming that getBooksByAuthor is a valid method that returns a List of Books, which of the following statements is/are true? and the following code snippet: List<Book> books = getBooksByAuthor("Ludlum"); Collections.sort(books, (b1, b2)->b1.getTitle().compareTo(b2.getTitle())); //OK List<Integer> ls = Arrays.asList(10, 47, 33, 23); int max = ls.stream().max(Comparator.comparing(a->a)).get(); System.out.println(max); //1 Comparator.comparing method requires a Function that takes an input and returns a Comparable. This Comparable, in turn, is used by the comparing method to create a Comparator. The max method uses the Comparator to compare the elements int he stream. The lambda expression a->a creates a Function that takes an Integer and returns an Integer (which is a Comparable). Here, the lambda expression does not do much but in situations where you have a class that doesn't implement Comparable and you want to compare objects of that class using a property of that class that is Comparable, this is very useful. The call to get() is required because max(Comparator ) return an Optional object. interface House{ public default String getAddress(){ return "101 Main Str"; } } interface Office { public static String getAddress(){ return "101 Smart Str"; } } interface WFH extends House, Office{ } class HomeOffice implements House, Office{ public String getAddress(){ return "R No 1, Home"; } } public class TestClass { public static void main(String[] args) { Office off = new HomeOffice(); //1 System.out.println(off.getAddress()); //2 } } Line at //2 will cause compilation to fail. Since the declared type of variable off is Office, compiler will check the call to getAddress against Office interface. However, getAddress in Office is static and Java 8 requires static interface method to be invoked using the interface name instead of a reference variable. That is why, the compiler will raise the following error message: TestClass.java:26: error: illegal static interface method call System.out.println(h.getAddress()); //2 ^ the receiver expression should be replaced with the type qualifier 'Office' 1 error If change Line 1 become: HomeOffice off = new HomeOffice();// 1 It print: R No 1, Home The signature of a method in a class is as follows: public static <E extends CharSequence> List<? super E> doIt(List<E> nums) This method is being called in the following code: result = doIt(in); Given that String implements CharSequence interface, what should be the reference type of 'in' and 'result' variables? ArrayList<String> in; List result; The input parameter has been specified as List<E>, where E has to be some class that extends CharSequence. So ArrayList<String>, List<String>, ArrayList<CharSequence> or List<CharSequence> are all valid as reference types for 'in'. The output type of the method has been specified as List<? super E> , which means that it is a List that contains objects of some class that is a super class of E. Here, E will be typed to whatever is being used for 'in'. For example, if you declare ArrayList<String> in, E will be String. The important concept here once the method returns, there is no way to know what is the exact class of objects stored in the returned List. So you cannot declare out in a way that ties it to any particular class, not even Object. Consider the following program: import java.util.*; class Book { private String isbn; public Book(String isbn){ this.isbn = isbn; } public boolean equals(Object o){ return (o instanceof Book && ((Book)o).isbn.equals(this.isbn)); } // ... setters and getters } class BookStore { Map<Book, Integer> map = new HashMap<Book, Integer>(); public BookStore(){ Book b = new Book("A111"); map.put(b, 10); b = new Book("B222"); map.put(b, 5); } Integer getNumberOfCopies(Book b){ return map.get(b); } public static void main(String[] args){ BookStore bs = new BookStore(); Book b = new Book("A111"); System.out.println(bs.getNumberOfCopies(b)); } //1 } What can be done so that it will print 10 at line //1? Add the following hashCode method to Book: public int hashCode(){ return 100; } Identify correct statements about the following code: List<String> vals = Arrays.asList("a", "b"); String join = vals.parallelStream() .reduce("_", (a, b)->a.concat(b) ); System.out.println(join); It will print either _ab or _a_b Since we are creating a parallel stream, it is possible for both the elements of the stream to be processed by two different threads. In this case, the identity argument will be used to reduce both the elements. Thus, it will print _a_b. It is also possible that the result of the first reduction ( _a ) is reduced further using the second element (b). In this case, it will print _ab. Even though the elements may be processed out of order individualy in different threads, the final output will be produced by joining the individual reduction results in the same order. Thus, the output can never have b before a. What will the following code print when compiled and run? class Widget { String data = "data"; public void doWidgetStuff() { System.out.println(data); } } class GoodWidget extends Widget{ String data = "big data"; public void doWidgetStuff() { } } public class WidgetUser{ public static void main(String[] args) { Widget w = new GoodWidget(); ((Widget)w).doWidgetStuff(); } } It will not print anything. Notice that the explicit cast to Widget has no impact because the class of the reference is not considered while invoking the instance methods at all. But if you try to access the field (or a static method) directly, the class of the reference is used. Therefore, System.out.println(w.data); //prints data System.out.println(((GoodWidget)w).data); //prints big data Given: class class class class Game{ } Cricket extends Game{ } Instrument{ } 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. class Bowler implements Player<Guitar>{ public void play(Guitar o){ } } //OK class MidiPlayer implements MusicPlayer { public void play(Guitar g){ } } // Not OK Observe that this is a non-typed usage of MusicPlayer. Since MusicPlayer has not been typed to anything, that means, it should be able to work with any object. Thus, MidiPlayer must have a method play(Object ). class MidiPlayer implements MusicPlayer<Instrument> { public void play(Guitar g){ } } //Not OK MidiPlayer must have a method play(Object ). public static void main(String[] args) { File f = null; boolean bool = false; try { // returns pathnames for files and directory f = new File("C:/Texts/TutorialsPoint/Java"); //Line 1 // create directories bool = f.mkdir(); // Line 2 // print System.out.print("Directory created? " + bool); } catch (Exception e) { // if any error occurs e.printStackTrace(); } } Directory created? False There is no directory is created. If change line 1 become: f = new File("C:/Texts"); It will print: Directory created? True And Folder: “Texts” is created in driver C. If change line 2 become: bool = f.mkdirs(); It will print: Directory created? True And that directory also is created. Assume that the following directory exists: c:\a\b\c A File object is created as follows: File f = new File("c:\\a\\b\\c\\d\\e"); Given that directories d and e do not exist under c, which of the following statements are correct? f.mkdirs(); will create directory d under c and directory e under d. f.getParentFile() will return a File Object representing c:\a\b\c\d getParent() returns a String and getParentFile() returns a File object. Which of the following statements regarding java.util.HashSet is correct? It allows null value to be stored. It keeps the elements in a sorted order.// Not OK Sets implementing the SortedSet interface such as TreeSet, keep the elements sorted. Given: ConcurrentMap<String, Object> cache = new ConcurrentHashMap<>(); cache.put("111", student1); (Assume that student1 and student2 are references to a valid objects.) Which of the following statements are legal but will NOT modify the Map referenced by cache? cache.putIfAbsent("111", student2); putIfAbsent first checks if the key already exists in the Map and if it does, does nothing. In other words, this method does not overwrite a key with new value. The check and update happens atomically. Since the given Map already contains a key "111", this call will not modify the Map. Which of the following code fragments can you use to get a JDBC connection? Properties p = new Properties(); p.setProperty("user", userid); p.setProperty("password", pwd); Connection c = DriverManager.getConnection(dburl, p); Assuming that the table student2 does not have any row, how many rows will be present in this table after the following code is executed? try (Connection c = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", c.setAutoCommit(false); Statement stmt = c.createStatement(); int a1 = stmt.executeUpdate("insert into STUDENT2 values (1, Savepoint sp1 = c.setSavepoint(); int a2 = stmt.executeUpdate("insert into STUDENT2 values (2, c.rollback(); int a3 = stmt.executeUpdate("insert into STUDENT2 values (3, c.setAutoCommit(true); int a4 = stmt.executeUpdate("insert into STUDENT2 values (4, } catch (SQLException e) { e.printStackTrace(); } "app");) { 'aaa', 1.1)"); 'bbb', 2.1)"); 'ccc', 3.1)"); 'ddd', 4.1)"); 2 First, the connection's auto commit mode is set to false and then two rows are inserted. However, since autocommit is false, they are not committed yet. Now, c.rollback() is called. This will cause the whole transaction to rollback. Although we created a SavePoint, we did not pass it to rollback and so the save point will have not be respected and both the rows will be lost. This transaction ends here. Next, row 3 is inserted in a new transaction and since autocommit is still false at this point, it is not commited yet. The transaction is still running. Now, when c.setAutoCommit(true) is called, the auto-commit status changes from false to true and this causes the existing transaction to commit thereby committing row 3. Finally, row 4 is inserted and committed immediately because autocommit is true. Therefore, the table will end up with 2 rows. Consider the following code : public class TestClass extends Thread { class Runner implements Runnable { public void run() { Thread[] t = new Thread[5]; for(int i=0; i<t.length; i++) System.out.println(t[i]); } } public static void main(String args[]) throws Exception { TestClass tc = new TestClass(); new Thread( tc.new Runner() ).start(); } } sHow many Thread objects are created by the above program when it is compiled and run? 2 The first Thread object is created at : TestClass tc = new TestClass(); The second Thread object is created at : new Thread( tc.new Runner() ). Runner is not a Thread object. Thread[] t = new Thread[5]; does not create any thread object. It only creates an array that can hold 5 Thread objects. Each of those 5 references are initialized to null. tc.new Runner() is a valid construct because Runner is a non-static inner class. So you cannot do 'new TestClass.Runner()'. RecursiveAction is not an interface. It is an abstract class. Consider the following class: public class Counter { private int count; public void increment(){ System.out.println(count++); } } If two threads call the increment() method on the same Counter instance simultaneously, which of the following are possible outputs? (Assume that there are no other calls to the Counter instance.) 00 01 This is a straight forward implementation on an thread unsafe class. Observe that count is a shared resource that is accessed by multiple threads and there are multiple issues in this code: 1. Since access to count is not synchronized, there is no guarantee that changes made by thread 1 will even be visible to thread 2. Thus, both the threads may print 0 and increment it to 1 even if they run one after the other. To understand this point, you need to read about topic of visibility guarantee provided by the Java memory model. 2. count++ is not an atomic operation, which means that it can be broken up into three separate steps - 1. get the current value of count in cache 2. increment the cache value and 3. update the count with updated cache value. Now, for example, while thread 1 is about to execute step 3, thread 2 may come in and execute steps 1, 2, and 3. Thread 1 then executes the remaining step 3. The result is that value of count will be 1 after both the threads are done, while it should have been 2, and thus one increment operation is lost. Which of the following code fragments are appropriate uses of assertions? public void openSocket(int port) { Socket s = //valid code to open socket here ... assert s != null; } private void processArray(Object[] arr) { assert arr.length == 10; ... } Input params of a private method can be validated using assertions. What SQL standard must a JDBC compliant driver implement? SQL92 As per Section 6.2 of JDBC 4.1 Specification: A JDBC API implementation must support Entry Level SQL92 plus the SQL command Drop Table. Entry Level SQL92 represents a "floor" for the level of SQL that a JDBC API implementation must support. Access to features based on SQL99 or SQL:2003 should be provided in a way that is compatible with the relevant part of the SQL99 or SQL:2003 specification. For an object o1 of class A to access a member(field or method) of object o2 of class B, when the member has no access modifier, class B must be... in the same package as A is in. Consider the following code: public class StaticSyncTest { int sum = 0; public synchronized void add(int x){ sum = sum + x; } public static synchronized void add(StaticSyncTest sst, int x){ sst.sum = sst.sum +x; } public static final StaticSyncTest sst = new StaticSyncTest(); public static void main(String[] args)throws Exception { Thread t = new Thread(){ public void run(){ StaticSyncTest.add(sst, 10); } }; t.start(); sst.add(10); t.join(); System.out.println(sst.sum); } } Which of the following statements is/are correct about the above code? The value of sum may be less than 20 after the main method is finished. The code will print either 10 or 20 but not 0. Here, we are accessing a field from two threads (the main thread and the explicitly created thread in the main method) through two synchornized methods. However both the methods are synchronizing on different objects. The static add method synchronizes on the StaticSyncTest.class object, while the instance add method synchronizes on the StaticSyncTest instance referred to by sst. Therefore, it is possible for the both threads to update sum simultaneously, which may cause one update to be lost. Thus, sum can be 10 or 20. Now, we are trying to read the value of sum from main thread without any synchronization. The Java memory model does not guarantee any updates made to a non-volatile field from one thread to be visible to another thread if the field is not accessed through a synchronized block. But it guarantees that the updates made in the same thread are visible to the same thread. It also guarantees that any updates made by another thread are visible to the current thread after the current thread joins on the other thread. Therefore, this program can never print 0. Had we tried to print sum from yet another thread without synchronizing on the same lock (or without joining on thread t), we could potentially see a value of 0. Consider the following classes: class A implements Runnable{ //valid code here } class B extends A implements Observer { //valid code here } (Assume that Observer has no relation to Runnable.) and the declarations : A a = new A() ; B b = new B(); Which of the following Java code fragments will compile and execute without throwing exceptions? Object o= a ; Runnable r = (Runnable) o; Here you are explicitly telling the compiler that o refers to an object which is Runnable. Object o = b; Runnable r = (Runnable) b; Because b extends A and A implements Runnable. Although o refers to an object which is Runnable but the compiler doesn't know about it. You have to do: Runnable r = (Runnable) o; You can assign a subclass object reference to superclass reference without a cast but to assign a super class object reference to a subclass (or interface) reference you need an explicit cast as in options 2 and 5. What will be the output when the following program is compiled and run? public class TestClass extends Thread { String name = ""; public TestClass(String str) { name = str; } public void run() { try { Thread.sleep( (int) (Math.random()*1000) ); System.out.println(name); } catch(Exception e) { } } public static void main(String[] str) throws Exception { Thread t1 = new TestClass("tom"); Thread t2 = new TestClass("dick"); t1.start();t2.start(); t1.join(); t2.join(); System.out.println("harry"); } } It will always print harry in the end. Here, you have 3 threads in action. The main thread and the 2 threads that are created in main. When a thread calls join() on another thread, the calling thread waits until the other thread dies. Here, the main thread calls join on t1 and t2, so it waits until t1 and t2 die. And then it prints "harry". So, "harry" will always be printed in the end. But t1 and t2 are not dependant on each other and so they don't wait for any other thread. And so the order of their execution depends on the thread scheduler. Therefore, "tom" and "dick" may be printed in any order. class A { public A() { } // A1 public A(String s) { this(); System.out.println("A :" + s); }// A2 } class B extends A { public int B(String s) { System.out.println("B :" + s); return 0; } // B1 // // // } public B(String a){ System.out.println("B :" + a); } public class C extends B { private C() { super(); System.out.println("Hi"); } // C1 //Line 1 //Line 2 //Line 3 //Line 5 public C(String s) { this(); System.out.println("C :" + s); } // C2 public C(int i) { } // C3 //Line 6 } This code compile OK. But if Line 1, 2, 3 are un-commented: Line 5, 6 will be not compile. package jqplus; import java.util.*; public class Testclass { public static void main(String[] args) { NavigableMap<String, String> mymap = new TreeMap<String, String>(); mymap.put("a", "apple"); mymap.put("b", "boy"); mymap.put("c", "cat"); mymap.put("aa", "apple1"); mymap.put("bb", "boy1"); mymap.put("cc", "cat1"); mymap.pollLastEntry(); //LINE 1 mymap.pollFirstEntry(); //LINE 2 NavigableMap<String, String> tailmap = mymap.tailMap("bb", false); //LINE 3 System.out.println(tailmap.pollFirstEntry()); //LINE 4 System.out.println(mymap.size()); //LINE 5 } } What will be returned by the call to tailmap.pollFirstEntry() at //LINE 4 and mymap.size() at //LINE 5? It will return c - cat and 3 NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) Returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey. Thus, //LINE 3 returns a NavigableMap that contains all the elements above bb (not including bb itself because of the second parameter), which means this new map contains only c - cat. //LINE 4 removes and returns the first entry (which is also the only entry in this case), which is c - cat. What will the following code print when run? class Threader extends Thread { public void run() { System.out.println("In Threader"); } } class Pooler extends Thread { public Pooler(){ } public Pooler(Runnable r) { super(r); //1 } public void run() { System.out.println("In Pooler"); } } public class TestClass { public static void main(String[] args) { Threader t = new Threader(); Thread h = new Pooler(t); //2 h.start(); //3 } } In Pooler. If a Thread is created with a Runnable, Thread class's run() method calls the run() method of the given Runnable. So you would expect it to execute Threader's run() method. However, Pooler is overriding Thread class's run() method and so the default behavior of Thread's run() is lost. Which statements regarding the following program are correct? class A extends Thread { static protected int i = 0; public void run() { for(; i<5; i++) System.out.println("Hello"); } } public class TestClass extends A { public void run() { for(; i<5; i++) System.out.println("World"); } public static void main(String args []) { Thread t1 = new A(); Thread t2 = new TestClass(); t2.start(); t1.start(); } } None of these. Notice that i is a static variable and there are 2 threads that are accessing it. None of the threads has synchronized access to the variable. So there is no guarantee which thread will access it when. Further, one thread might increment i while another is executing i<5. So it is possible that more than 5 words may be printed. For example, lets say i is 0 and thread1 starts first loop. It will print Hello. Now, before thread1 could do i++, thread2 might run and it will print "World" while i is still 0. We have added a few more statements to the above program to illustrate the behavior: class A extends Thread { static protected int i = 0; public void run() { for(; i<5; i++) { System.out.println("Hello "+i); try{ Thread.sleep(100); }catch(Exception e){} } } } public class TestClass extends A { public void run() { for(; i<5; i++) { System.out.println("World "+i); try{ Thread.sleep(100); }catch(Exception e){} } } public static void main(String args []) { Thread t1 = new A(); Thread t2 = new TestClass(); t2.start(); t1.start(); } } It prints the following: C:\temp>java TestClass World 0 Hello 0 World 1 Hello 2 World 3 Hello 4 Given the following RDBMS table information : STUDENT Table SID INT Primary Key NAME VARCHAR(50) GPA INT and the following code: Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("select SID, NAME, from STUDENT"); while(rs.next()){ System.out.println( INSERT CODE HERE ); } connection.close(); GPA What can be inserted in the above code so that it will print the GPA value for each student? (Assume that items not specified such as import statements and try/catch block are all valid.) rs.getString(3) Although the value of the GPA field is int, it can still be retrieved using getString(). Note that if a field is of type VARCHAR and if you try to retrieve the value using say getInt(), it may throw an exception at runtime if the value cannot be parsed into an Integer. Which of the following options can be a part of a correct inner class declaration or a combined declaration and instance initialization ? (Assume that SimpleInterface and ComplexInterface are interfaces.) private class C { } //OK new SimpleInterface() { //OK //valid code } new ComplexInterface(x) { //Not OK //valid code } You cannot pass parameters when you implement an interface by an anonymous class. private final abstract class C { } //Not OK A final class can never be abstract. new ComplexClass() implements SimpleInterface { } //Not OK 'implements' part comes only in class definition not in instantiation. Both of these are checked exceptions: ClassNotFoundException, NoSuchFieldException Identify the correct statements about the following code fragment: FileWriter fw = new FileWriter("c:\\temp\\test.txt"); BufferedWriter bfw = new BufferedWriter(fw); bfw.writeUTF("hello"); //1 bfw.newLine(); //2 bfw.write("world"); //3 Compilation error at //1. BufferedWriter does not have writeUTF method but it does have newLine and write(String) methods. 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); } } It will compile without warning but will throw an exception at runtime. Given: List<Student> sList = new CopyOnWriteArrayList<Student>(); Which of the following statements are correct? Multiple threads can safely add and remove objects from sList simultaneously. Which of the following statements about this program are correct? public class CoolThread extends Thread { String id = ""; public CoolThread(String s){ this.id = s; } public void run() { if(id.equals("AAA")) { yield(); } System.out.println(id+" End"); } public static void main(String args []) { Thread t1 = new CoolThread("AAA"); t1.setPriority(Thread.MAX_PRIORITY); Thread t2 = new CoolThread("BBB"); t2.setPriority(Thread.MIN_PRIORITY); t1.start(); t2.start(); } } The order of "AAA End" and "BBB End" cannot be determined. Basically, yield() causes the current thread to pause temporarily and allows another thread to run. However, it is never a good idea to depend on yield() for managing the thread execution because the way it works is highly platform dependent. So the point is, you really cannot be "sure" what effect will yield() have on the threads. Given: String[] p = {"1", "2", "3" }; Which of the following lines of code is/are valid? List<?> list2 = new ArrayList<>(Arrays.asList(p)); //OK Here, list2 is a list of any thing. You cannot add any thing to it and you can only retrieve Objects from it: list2.add(new Object()); list2.add("aaa"); //both will not compile. Object obj = list2.get(0); //Valid String str = list2.get(0); //will not compile. Note that you can add null to it though i.e. list2.add(null); is valid. List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(p)); // Not good. 1 Arrays.asList(T[] ) returns an object of type ArrayList<T>. In this case, it will be ArrayList<String>. Therefore, elements in this list cannot be added to a List of Integers. 1 Consider the following code: import java.util.*; public class TestClass { public static void main(String[] args) { // put declaration here m.put("1", new ArrayList()); m.put(1, new Object()); //2 m.put(1.0, "Hello"); //3 System.out.println(m); //1 } } How can 'm' be declared such that the above code will compile and run without errors? Map<Object, ? super ArrayList> m = new LinkedHashMap<Object, ArrayList>(); will work if lines //2 and //3 are commented out. Map m = new HashMap(); There is an important concept to be understood here so please read this carefully: Map<Object, ?> m = new LinkedHashMap<Object, Object>(); While this is a valid declaration, it will not allow you to put anything into 'm'. The reason is that m is declared to be of type Map that takes an instance of Object class as a key and instance of 'Unknown class' as value. Therefore, if you try to put an Object, or Integer, or anything, the compiler will not allow it because that 'Unknown' class is not necessarily Object or Integer or any other class. Even though the actual object pointed to by 'm' is of type LinkedHashMap<Object, Object>, the compiler looks only at the reference type of the variable. Thus, 'm' is read-only. It would have worked if m were declared as Map<Object, Object> m = .... Because in this case the compiler *knows* that m can take an instance of Object as value. Instance of Object covers all kind of objects. Map<Object, ? super ArrayList> m = new LinkedHashMap<Object, ArrayList>(); You should read it aloud as follows: 'm' is declared to be of type Map that takes an instance of Object class as a key and an instance of 'a class that is either ArrayList or a superclass of Arraylist' as value. This means that the value can be an instance of ArrayList or its subclass (since an ArrayList object or its subclass object can be assigned to a reference of type ArrayList or its super class.). However, you cannot put Object (which is a superclass of ArrayList) in it because the compiler doesn't know the exact superclass that 'm' can take. It could be AbstractList, or Object, or any other super class of ArrayList. The compiler only knows that it is a superclass but not the exact type. So option 4 is correct but 5 is wrong. Thus, you can do: m.add(anyObj, new ArrayList()); Just the opposite of super is extends. Consider the following method: public void m1(List<? extends Number> list) { list.add(new Integer(10)); //Error at compile time because the compiler //only knows that list contains Number or its subclass objects. But it doesn't know the exact type. //Therefore, it will not allow you to add anything to it. Number n = list.get(1); //This will work because the compiler knows that every object in list IS-A Number. } Option 6 is untyped. So it will allow anything to be put into 'm'. 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? IOException|RuntimeException //OK FileNotFoundException|SecurityException|IllegalArgumentException // NOT OK Note that most commonly used methods in Java API that deal with reading or writing files have java.io.IOException in their throws clause. So you must handle this exception. At run time, more specific exceptions such as FileNotFoundException are actually thrown depending on the actual cause of the problem. 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); } } It will throw an exception at runtime. TreeSet is a NavigableSet and so it supports subSet() method : NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) Returns a view of the portion of this set whose elements range from fromElement to toElement. The returned subset is backed by the original set. So if you insert or remove an element from the subset, the same will be reflected on the original set. Further, since the subset is created using a range (fromElement to toElement), the element that you are inserting must fall within that range. Otherwise an IllegalArgumentException is thrown with a message "key out of range.". This is what is happening in this question. The range of subs is 326 to 328 and 329 is out of that range. Therefore, an IllegalArgumentException is thrown at runtime. class Bond{ String ticker = "bac"; double coupon = 8.5; } class Portfolio implements Serializable{ String accountName; transient Bond bond = new Bond(); private void writeObject(ObjectOutputStream os) throws IOException { os.defaultWriteObject(); os.writeObject(bond.ticker); os.writeDouble(bond.coupon); } private void readObject(ObjectInputStream os) throws ClassNotFoundException, IOException { os.defaultReadObject(); this.bond = new Bond(); bond.ticker = (String)os.readObject(); bond.coupon = os.readDouble(); } } Which of the following methods are available in java.util.concurrent.ConcurrentMap in addition to the methods provided by java.util.Map? ConcurrentMap is important for the exam. You should go the API description for this interface. In short: It is a Map providing additional atomic putIfAbsent, remove, and replace methods. Consider following two classes: //in file A.java package p1; public class A { protected int i = 10; public int getI() { return i; } } //in file B.java package p2; import p1.*; public class B extends p1.A { public void process(A a) { a.i = a.i*2; // Line 1 } public static void main(String[] args) { A a = new B(); B b = new B(); b.process(a); System.out.println( a.getI() ); } } What will be the output of compiling and running class B ? It will not compile. Change line 1 become: i = i* 2 // OK Consider the following program: import java.util.*; class Book { private String title, isbn; public boolean equals(Object o){ return (o instanceof Book && ((Book)o).isbn.equals(this.isbn)); } // ... setters and getters for title and isbn } class BookStore { Map<Book, Integer> map = new HashMap<Book, Integer>(); int getNumberOfCopies(Book b){ return map.get(b); } public void addBook(Book b, int numberofcopies){ map.put(b, numberofcopies); } // ... other useful methods. } public class TestClass { static BookStore bs = new BookStore(); public static void main(String[] args) { Book b = new Book(); b.setIsbn("111"); bs.addBook(b, 10); System.out.println(bs.getNumberOfCopies(b)); b = new Book(); b.setIsbn("111"); System.out.println(bs.getNumberOfCopies(b)); } } What will it print when it is compiled and run? There are multiple concepts involved here: 1. Observe that Book class has overridden equals() method but hasn't overridden hashCode() method. The way equals method is coded here makes two Book objects equal if their isbn is equals. However, their hash code values will be different because Object class's hashCode method returns unique hashcode for every object. 2. In the main method, a Book object is stored in BookStore. The same Book object is being used to retrieve the numberofcopies value. Since the object that was stored in the Map and the object that was used to retrieve the value from the map are the same object, their hash codes will be the same and hence map will be able to find it among its name-value pairs. Thus, this will print 10. 3. Next, a new Book object is created. Note that its hash code will be different from the previously created book object. But as per equals() method of Book, they are equal because their isbn are same. When you try to use the new Book object to find the value, map will not find anything because of a different hash code. So map.get() will return null. 4. The return type of the method is an int (and not an Integer). But map.get always returns an object (not a primitive.) So auto-unboxing will try to convert null into an int, which will throw a NullPointerException. 5. There is no warning at compilation because all the operations are valid. LocalDateTime ld1 = LocalDateTime.of(2015, Month.NOVEMBER, 1, 2, 0); ZonedDateTime zd1 = ZonedDateTime.of(ld1, ZoneId.of("US/Eastern")); LocalDateTime ld2 = LocalDateTime.of(2015, Month.NOVEMBER, 1, 1, 0); ZonedDateTime zd2 = ZonedDateTime.of(ld2, ZoneId.of("US/Eastern")); long x = ChronoUnit.HOURS.between(ld1, ld2); long y = ChronoUnit.HOURS.between(zd1, zd2); System.out.println(x); System.out.println(y); -1 -2 Think of it as follows The time difference between two dates is simply the amount of time you need to go from date 1 to date 2. So if you want to go from 1AM to 2AM, how many hours do you need? On a regular day, you need 1 hour. That is, if you add 1 hour to 1AM, you will get 2AM. However, as given in the problem statement, at the time of DST change, 2 AM becomes 1AM. That means, even after adding 1 hour to 1AM, you are not at 2AM. You have to add another hour to get to 2 AM. In total, therefore, you have to add 2 hours to 1AM to get to 2AM. //in file Pets.java enum Pets { DOG("D"), CAT("C"), FISH("F"); static String prefix = "I am "; String name; Pets(String s) { name = prefix + s;} public String getData(){ return name; } } // Not good. Unlike a regular java class, you cannot access a non-final static field from an enum's constructor. ( JLS 8.9.2 ) //in file Pets.java enum Pets { String name; DOG("D"), CAT("C"), FISH("F"); Pets(String s) { name = s;} } // Not good. Enum constants (here, DOG, CAT, and FISH) must be declared before anything else. Therefore, String name; is invalid here. Consider the following class... import java.awt.*; import java.awt.event.*; class TestFrame extends Frame { String s="Message"; public static void main(String args[]) { TestFrame t = new TestFrame(); Button b = new Button("press me"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Message is " +s); } } ); t.add(b); } } It will not compile. It will not compile because member variable 's' is not accessible from the inner class. This is because the inner class is created in a static method so it does not have any reference to TestFrame object. interface Carnivore { default int calories(List<String> food) { System.out.println("calories"); 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) { System.out.println("size"); 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(); process(fnames, t::eat); process(fnames, t::calories); process(fnames, TestClass::size); } } Eating [a, b, c] calories size Don't be confused by twisted code. process(List<String> names, Carnivore c) expects a List<String> and a Carnivore instance as arguments. Carnivore has exactly one abstract method and therefore it is a functional interface. You can either pass a Carnivore instance explicitly or pass a reference to a method that matches the parameter list of Carnivore's abstract method eat(List<String> foods);. t::eat, t::calories, and TestClass::size are all valid method references with the exact same parameter requirements and are therefore valid. Consider the following program. public class TestClass implements Runnable { volatile int x; public void run(){ x = 5; } public static void main(String[] args) { TestClass tc = new TestClass(); tc.x = 10; new Thread(tc).start(); // 1 System.out.println(tc.x); } } What will it print when run? The output cannot be determined. Note that when you create and start a new Thread (at line 1) there are two threads running. (The main() thread and the thread that you just started!). Both the threads are trying to use the same variable. Now, which thread will run first cannot be determined so whether the main() thread reads 'x' first or the new thread changes 'x' first is not known. So the output of the program cannot be determined. Given: class Item{ private int id; private String name; public Item(int id, String name){ this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString(){ return name; } } public class Test { public static void main(String[] args) { List<Item> l = Arrays.asList( new Item(1, "Screw"), new Item(2, "Nail"), new Item(3, "Bolt") ); l.stream() //INSERT CODE HERE .forEach(System.out::print); } } Which of the following options can be inserted in the above code independent of each other, so that the code will print BoltNailScrew? .sorted(Comparator.comparing(a->a.getName())).map((i)>i.getName()) .map((i)->i.getName()).sorted() You want to run Main.class from the command line. It uses two packages good.* and bad.*. You want to enable assertions for all classes of bad.* and at the same time you want to disable them for the package good.*. Which of the following command lines will achieve the above? java -ea:bad... Main This is correct because by default assertions are disabled. So assertions for package good.* need not be disabled explicitly java -ea:bad... -da:good... Main Assertions can be enabled or disabled for specific packages or classes. To specify a class, use the class name. To specify a package, use the package name followed by "..." (three dots): java -ea:<class> myPackage.MyProgram java -da:<package>... myPackage.MyProgram Each enable or disable modifies the one before it. This allows you to enable assertions in general, but disable them in a package and its subpackages: java -ea -da:<package>... myPackage.myProgram To enable assertion for one package and disable for other you can use: java -ea:<package1>... -da:<package2>... myPackage.MyProgram You can enable or disable assertions in the unnamed root (default)package (the one in the current directory) using the following commands: java -ea:... myPackage.myProgram java -da:... myPackage.myProgram Note that when you use a package name in the ea or da flag, the flag applies to that package as well as its subpackages. For example, java -ea:com... -da:com.enthuware... com.enthuware.Main The above command first enables assertions for all the classes in com as well as for the classes in the subpackages of com. It then disables assertions for classes in package com.enthuware and its subpackages. Identify the correct statements about the following code: import java.util.*; 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()); } } It will print 300.0 public V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null. If the function returns null no mapping is recorded. If the function itself throws an (unchecked) exception, the exception is rethrown, and no mapping is recorded. The most common usage is to construct a new object serving as an initial mapped value or memorized result, as in: map.computeIfAbsent(key, k -> new Value(f(k))); Or to implement a multi-value map, Map<K,Collection<V>>, supporting multiple values per key: map.computeIfAbsent(key, k -> new HashSet<V>()).add(v); Parameters: key - key with which the specified value is to be associated mappingFunction - the function to compute a value Returns: the current (existing or computed) value associated with the specified key, or null if the computed value is null public V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value. If the function returns null, the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged. Parameters: key - key with which the specified value is to be associated remappingFunction - the function to compute a value Returns: the new value associated with the specified key, or null if none 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? Put the driver jar in the class path. Retrieve a connection using DriverManager.getConnection. Identify the correct statements regarding JDBC. Starting JDBC 4.0, the JDBC Driver class is not required to be loaded explicitly in the code any more. What will the following code print when compiled and run? abstract class Widget { String data = "data"; public void doWidgetStuff() { } } class GoodWidget extends Widget{ String data = "big data"; public void doWidgetStuff() { System.out.println(data); } } public class WidgetUser{ public static void main(String[] args) { Widget w = new GoodWidget(); w.doWidgetStuff(); } } big data Access to fields (and static methods) is bound at compile time and is never polymorphic. That is why if a field (or a static method) by the same name is defined in the base class as well as the derived class, it is class of the reference (and not the class of the actual object) that determines which field will be accessed. Here, the variable used to access data field is "this" (which is implicit) and it is of type GoodWidget and therefore GoodWidget's data field will be used. If you try to do System.out.println(w.data); in the main method, it will print data because the class of the reference used to access the data field is Widget and not GoodWidget. 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", null); DoubleSupplier ds1 = b1::getPrice; System.out.println(b1.getTitle()+" "+ds1.getAsDouble()); It will throw a NullPointerException. 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? Queue<Request> container = new LinkedList<Request>(); Queue<Request> container = new PriorityQueue<Request>(); Both LinkedList and PriorityQueue classes implement Queue interface. 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 } } ls.stream() .map(MyProcessor::new) .forEach(MyProcessor::process); // OK ls.forEach(MyProcessor::process); // Not compile forEach method of List require a method that have parmeter:Integer. Given: Path p1 = Paths.get("c:\\temp\\test1.txt"); Path p2 = Paths.get("c:\\temp\\test2.txt"); Which of the following code fragments moves the file test1.txt to test2.txt, even if test2.txt exists? Files.move(p1, p2, StandardCopyOption.REPLACE_EXISTING); //OK Files.copy(p1, p2, StandardCopyOption.REPLACE_EXISTING); Files.delete(p1) //OK try(Files.move(p1, p2)){ } // Not OK Files.move returns a Path object (of the destination file), which is not a resource that can be closed because it does not implement AutoCloseable interface. So this will not compile. Given: public class ItemProcessor implements Runnable{ CyclicBarrier cb; //LINE 1 public ItemProcessor(CyclicBarrier cb){ this.cb = cb; } public void run(){ System.out.println("processed"); try { cb.await(); } catch (Exception ex) { ex.printStackTrace(); } } } public class Merger implements Runnable{ //LINE 2 public void run(){ System.out.println("Value Merged"); } } What should be inserted in the following code such that run method of Merger will be executed only after the thread started at 4 and the main thread have both invoked await? public static void main(String[] args) throws Exception{ Merger m = new Merger(); //LINE 3 ItemProcessor ip = new ItemProcessor(cb); ip.start(); //LINE 4 cb.await(); } Make ItemProcessor extend Thread instead of implementing Runnable and add CyclicBarrier cb = new CyclicBarrier(2, m); to //LINE 3 1. ItemProcessor needs to extend Thread otherwise ip.start() will not compile. 2. Since there are a total two threads that are calling cb.await ( one is the ItemProcessor thread and another one is the main thread), you need to create a CyclicBarrier with number of parties parameter as 2. If you specify the number of parties parameter as 1, Merger's run will be invoke as soon as the any thread invokes await but that is not what the problem statement wants. What will the following code fragment print? Path p1 = Paths.get("x\\y"); Path p2 = Paths.get("z"); Path p3 = p1.relativize(p2); System.out.println(p3); ..\..\z Observe what happens when you append this path to p1: x\y + ..\..\z =>x + ..\z =>z This is what we want. So this is the correct answer. A ".." implies parent folder, therefore imagine that you are taking off one ".." from the right side of the plus sign and removing the last name of the path on the left side of the plus sign. For example, .. appended to y makes it y\.., which cancels out. Given: enum Card { HEART, CLUB, SPADE, DIAMOND; } Which of the following code fragments will print HEART CLUB SPADE DIAMOND in that order? for(Card c : Card.values()) System.out.print(c+" "); 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); }); hello,world hello,world Consider the program and select the right option(s). public class TestClass implements Runnable { int x = 0, y = 0; public void run() { while(true) { synchronized(this) { x++; y++; System.out.println(" x = "+x+" , y = "+y); } } } public static void main(String[] args) { TestClass tc = new TestClass(); new Thread(tc).start(); new Thread(tc).start(); } } It will keep on printing values which show x and y always as equal and increasing by 1 at each line. Which of the following statements about Java serialization are correct? Multiple copies of an object may be added to a stream. Which of the following statements are correct regarding synchronization and locks? A thread exclusively owns the intrinsic lock between the time it has acquired the lock and released the lock. A thread can acquire a lock on the class. This is what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class. You have been given an instance of an Executor and you use that instance to execute tasks. How many threads will be created for executing these tasks by the Executor? Number of threads created by the Executor depends on how the Executor instance was created. public class Names { private List<String> list; public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } public void printNames() { System.out.println(getList()); } public static void main(String[] args) { List<String> list = Arrays.asList("Bob Hope", "Bob Dole", "Bob Brown"); Names n = new Names(); n.setList(list.stream().collect(Collectors.toList())); n.getList().forEach(Names::printNames);// Not compile } } Observe that the method printNames does not take any argument. But the argument for forEach method requires a method that takes an argument. The forEach method basically invokes the passed method and gives that method an element of the list as an argument. The following is how you can visualise the working of the given code: Iterator it = list.iterator(); while(it.hasNext()){ Names.printNames(it.next()); //This will not compile because printNames method does not take any argument. } To make it work, the line n.getList().forEach(Names::printNames);/ should be changed to simply: n.printNames(); Given: Stream<String> names = Stream.of("Sarah Adams", "Suzy Pinnell", "Paul Basgall"); Stream<String> firstNames = //INSERT CODE HERE Which of the following options will correctly assign a stream of just first names to firstNames? names.map(e->e.split(" ")[0]); List<String> strList = Arrays.asList("a", "aa", "aaa"); Function<String, Integer> f = x->x.length(); Consumer<Integer> c = x->System.out.print("Len:"+x+" "); strList.stream().map(f).forEach(c); Len:1 Len:2 Len:3 What can be done so that the following program prints "tom", "dick" and "harry" in that order? public class TestClass extends Thread { String name = ""; public TestClass(String str) { name = str; } public void run() { try { Thread.sleep( (int) (Math.random()*1000) ); System.out.println(name); } catch(Exception e) { } } public static void main(String[] str) throws Exception { //1 Thread t1 = new TestClass("tom"); //2 Thread t2 = new TestClass("dick"); //3 t1.start(); //4 t2.start(); //5 System.out.println("harry"); //6 } } Insert t1.join(); and t2.join(); at //4 and //5 respectively. 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? Replace line 1 with : public class Food implements Comparable<Food>{ Add the following a line 2 : public int compareTo(Food f){ return this.name.compareTo(f.name); } For Collections.sort(List<T> ) method to sort a Collection of any class T, that class must implement java.lang.Comparable interface. This interface has only one method: public int compareTo(T o), where T is same as the class to which Comparable is typed. In this case, since we want to sort Food instances, you can type Comparable to Food i.e. Comparable<Food> and therefore, the method parameter will be Food i.e. public int compareTo(Food f). In cases where a class does not implement Comparable or when you want to sort instances based on a different order than the one provided by the class's compareTo method, you can use another class that implements Comparator interface to sort your collection. For example, if you want to sort Food instances based on calories instead of name, you can do it like this: Comparator<Food> c = new Comparator<Food>(){ public int compare(Food o1, Food o2) { return o1.caloriesPerServing o2.caloriesPerServing; } }; and then use Collections.sort(List<T>, Comparator<? super T>) method: Collections.sort(al, c) What will the following code print when run? import java.nio.file.Path; import java.nio.file.Paths; public class PathTest { public static void main(String[] args) { Path p1 = Paths.get("c:\\code\\java\\PathTest.java"); System.out.println(p1.getName(3).toString()); } } It will throw IllegalArgumentException 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:\\main\\project\\Starter.java"); public static String getRoot(){ String root = p1.getRoot().toString(); return root; } public static void main(String[] args) { System.out.println(getRoot()); } } c:\ What will the following code most likely print when compiled and run? List<String> names = Arrays.asList("greg", "dave", "don", "ed", "fred" ); Map<Integer, Long> data = names.stream().collect(Collectors.groupingBy( String::length, Collectors.counting()) ); System.out.println(data.values()); [1, 1, 3] 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 Java 8 functional interfaces to achieve the same? public void process(String name, Double value){ groupedValues.computeIfAbsent(name, (a)->new ArrayList<Double>()).add(value); } The objective of the given code is to collect multiple values for a given key in a map. When a value for a new key is to be inserted, it needs to put a List in the map first before adding the key to the List. computeIfAbsent is perfect for this. This methods checks if the key exists in the map. If it does, the method just returns the value associated with that key. If it doesn't, the method executes the Function, associates the value returned by that Function in the map with that key, and returns that value. Consider the following code: class MyThread extends Thread { int i = 0; public void run() { while(true) { if( i%2 == 0 ) System.out.println("Hello World"); } } } What will be the output when this program is compiled and run from the command line? This will compile but an exception will be thrown at runtime. But also note that there is no standard main() method. So this program cannot run from the command line. If you try to run this program from the command line, the JVM will throw an Error: Error: Main method not found in class MyThread, please define the main method as: public static void main(String[] args) What will the following code print when run? Period p = Period.between(LocalDate.now(), LocalDate.of(2015, Month.SEPTEMBER, 1)); System.out.println(p); Duration d = Duration.between(LocalDate.now(), LocalDate.of(2015, Month.SEPTEMBER, 1)); System.out.println(d); Assume that the local time on the system at the time this code is run is 2nd Sep 2015 1:00 AM. It will throw an exception at run time. The call to Duration.between will throw java.time.temporal.UnsupportedTemporalTypeException because LocalDate.now() does not have a time component, while Duration.between method needs Temporal arguments that have a time component Which functional interface(s) would you use if you need a function that always returns the same type as the type of its input(s)? UnaryOperator public interface UnaryOperator<T> extends Function<T,T> Represents an operation on a single operand that produces a result of the same type as its operand. This is a specialization of Function for the case where the operand and result are of the same type. BinaryOperator public interface BinaryOperator<T> extends BiFunction<T,T,T> Represents an operation upon two operands of the same type, producing a result of the same type as the operands. This is a specialization of BiFunction for the case where the operands and the result are all of the same type. This is a functional interface whose functional method is BiFunction.apply(Object, Object). 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(); } } The code will not compile. Remember that when you use a resource in try-with-resources, the resource must implement java.lang.AutoCloseable interface. In this case, although Device class contains the close() method required by this interface but it does not say that it implements AutoCloseable in its declaration. Therefore, compilation will fail. Complete the following pseudo code for the compute method of a RecursiveAction: compute(){ if( isSmallEnough(currentDataSet) ){ _________; //LINE 10 } else{ List<DataSet> list = _________; //LINE 13 List<RecursiveAction> subactions = //build MyRecursiveAction objects for each DataSet _________; //LINE 15 } } Assume that the following methods exist: processDirectly(DataSet) : processes the DataSet without forking splitDataSet(DataSet) : splits the DataSet into multiple smaller DataSet objects isSmallEnough(DataSet) : checks if the DataSet can be processed directly. processDirectly(currentDataSet); //Line 10 splitDataSet(currentDataSet); //Line 13 invokeAll(subactions); //Line 15 This is the general logic of how the fork/join frame work is used: 1. First check whether the task is small enough to be performed directly without forking. If so, perform it without forking. 2. If no, then split the task into multiple small tasks (at least 2) and submit the subtasks back to the pool using invokeAll(list of tasks). What will the following code fragment print? Path p1 = Paths.get("photos\\goa"); Path p2 = Paths.get("\\index.html"); Path p3 = p1.relativize(p2); System.out.println(p3); java.lang.IllegalArgumentException will be thrown Note that if one path has a root (for example, if a path starts with a // or c:) and the other does not, relativize cannot work and it will throw an IllegalArgumentException. What will the following code print? List<String> vowels = new ArrayList<String>(); vowels.add("a"); vowels.add("e"); vowels.add("i"); vowels.add("o"); vowels.add("u"); Function<List<String>, List<String>> f = list->list.subList(2, 4); f.apply(vowels); vowels.forEach(System.out::print); aeiou There is no problem with the code. The List.subList method returns a view backed by the original list. It doesn't change the existing list. Therefore, when you print the elements from the original list after calling subList, you will see all the elements of the original list. Consider the following code: class TaskBase { int getStatusCode(Object obj) throws NullPointerException { if(obj != null ) return 1; else return 0; } } class ParallelTask extends TaskBase { //override getStatusCode method. } Which of the following statements are valid? Overriding method can throw any RuntimeException. Overriding method cannot throw any checked exception. What will the following code print? Path p1 = Paths.get("c:\\temp\\test.txt"); Path p2 = Paths.get("report.pdf"); System.out.println(p1.resolve(p2)); c:\temp\test.txt\report.pdf Given: class Person{ String name; String dob; public Person(String name, String dob){ this.name = name; this.dob = dob; } } class MySorter { public int compare(Person p1, Person p2){ return p1.dob.compareTo(p2.dob); } } public class SortTest { public static int diff(Person p1, Person p2){ return p1.dob.compareTo(p2.dob); } public static int diff(Date d1, Date d2){ return d1.compareTo(d2); } public static void main(String[] args) { ArrayList<Person> al = new ArrayList<>(); al.add(new Person("Paul", "01012000")); al.add(new Person("Peter", "01011990")); al.add(new Person("Patrick", "01012002")); INSERT CODE HERE } } and the following lines of code: I java.util.Collections.sort(al, (p1, p2)>p1.dob.compareTo(p2.dob)); II java.util.Collections.sort(al, SortTest::diff); III java.util.Collections.sort(al, new MySorter()::compare); IV java.util.Arrays.sort(al, SortTest::diff); How many of the above lines can be inserted into the given code, independent of each other, to sort the list referred to by al? 3 Only the line java.util.Arrays.sort(al, SortTest::diff); will not work because Arrays.sort works on arrays not lists. If you had an array of Person objects, it would have been valid. Given: class ComplicatedTask extends RecursiveTask<Integer>{ int[] ia; int from; int to; static final int THRESHOLD = 3; public ComplicatedTask(int[] ia, int from, int to){ this.ia = ia; this.from = from; this.to = to; } public int transform(int t){ //this is a CPU intensive operation that //transforms t and returns the value } protected Integer compute() { if(from + THRESHOLD > to){ int sum = 0; for(int i = from; i<=to; i++){ sum = sum+transform(ia[i]); } return sum; } else{ int mid = (from+to)/2; ComplicatedTask newtask1 = new ComplicatedTask(ia, from, mid); ComplicatedTask newtask2 = new ComplicatedTask(ia, mid+1, to); newtask2.fork(); int x = newtask1.compute(); int y = newtask2.join(); return x+y; } } } Identify the correct statements about the above code. THRESHOLD should be increased if the cost of forking a new task dominates the cost of direct computation. There is a cost associated with forking a new task. If the cost of actually finshing the task without forking new subtasks is less, then there is not much benefit in breaking a task into smaller units. Therefore, a balance needs to be reached where the cost of forking is less than direct computation. THRESHOLD determines that level. THRESHOLD value can be different for different tasks. For example, for a simple sum of the numbers, you may keep THRESHOLD high, but for say computing the sum of factorial of each numbers, THRESHOLD may be low. The logic for computing mid should be such that it divides the task into two equal parts in terms of cost of computation. The whole objective is to divide the task such that multiple threads can compute it in parallel. Therefore, it is better if two sub tasks are equal in terms of cost of computation, otherwise, one thread will finish earlier than the other thereby reducing performance. What will the following code print? AtomicInteger ai = new AtomicInteger(); Stream<String> stream = Stream.of("old", "king", "cole", "was", "a", "merry", "old", "soul").parallel(); stream.filter( e->{ ai.incrementAndGet(); return e.contains("o"); }).allMatch(x->x.indexOf("o")>0); System.out.println("AI = "+ai); Any number between 1 to 8 2. Here, the stream consists of 8 elements. It is, therefore, possible for a JVM running on an eight core machine to split this stream into 8 streams (with one element each) and invoke the filter operation on each of them. If this happens, ai will be incremented 8 times. 3. It is also possible that the JVM decides not to split the stream at all. In this case, it will invoke the filter predicate on the first element (which will return true) and then invoke the allMatch predicate (which will return false because "old".indexOf("o") is 0). Since allMatch is a short circuiting terminal operation, it knows that there is no point in checking other elements because the result will be false anyway. Hence, in this scenario, ai will be incremented only once. 4. The number of pieces that the original stream will be split into could be anything between 1 and 8 and by applying the same logic as above, we can say that ai will be incremented any number of times between 1 and 8. 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 } } Which line is causing the problem? The enum definition contains an explicit constructor that takes a parameter. Therefore, the compiler will not provide a default no-args constructor for this enum. Hence, the declaration of MOCHA and LATTE will fail since they need a no-args constructor. It will compile if you add the following constructor: Coffee(){ } Consider the following program that computes the sum of all integers in a given array of integers: class ComplicatedTask extends RecursiveTask<Integer>{ int[] ia; int from; int to; static final int THRESHOLD = 3; public ComplicatedTask(int[] ia, int from, int to){ this.ia = ia; this.from = from; this.to = to; } protected void compute() { int sum = 0; if(from + THRESHOLD > to){ for(int i = from; i<=to; i++){ sum = sum+ia[i]; } } else{ int mid = (from+to)/2; ComplicatedTask newtask1 = new ComplicatedTask(ia, from, mid); ComplicatedTask newtask2 = new ComplicatedTask(ia, mid+1, to); newtask2.fork(); newtask1.compute(); newtask2.join(); } } } What changes must be done together so that it will work as expected? The compute method must be changed to return a value. The values returned by the newtask1 and newtask2 should be added and returned. What will the following code print when run? public class RunTest { public static volatile int counter = 0; static class RunnerDec implements Runnable{ public void run(){ for(int i=0;i<5000; i++){ counter--; } } } static class RunnerInc implements Runnable{ public void run(){ for(int i=0;i<5000; i++){ counter++; } } } public static void main(String[] args) { RunnerDec rd = new RunnerDec(); RunnerInc ri = new RunnerInc(); Thread t1 = new Thread(rd); Thread t2 = new Thread(ri); t1.start(); t2.start(); try{ t1.join(); t2.join(); }catch(Exception e){ e.printStackTrace(); } System.out.println(counter); } } It may print any number between -5000 to 5000. Which statements regarding the following code are correct? class Outer { private void Outer() { } protected class Inner { } } Constructor for Inner is protected. Given the following code: enum Title { MR("Mr. "), MRS("Mrs. "), MS("Ms. "); private String title; private Title(String s){ title = s; } public String format(String first, String last){ return title+" "+first+" "+last; } } //INSERT CODE HERE Identify valid code snippets .. (Assume that Title is accessible wherever required.) class TestClass{ void someMethod() { System.out.println(Title.MR.format("Rob", "Miller")); } } //OK class TestClass{ void someMethod() { System.out.println(MR.format("Rob", "Miller")); } } // Not OK Enum constants cannot be instantiated/created using the new keyword. Consider the following code: public class Test extends Thread { static Object obj = new Object(); static int x, y; public void run() { synchronized(obj) { for(;;) { x++; y++; System.out.println(x+" "+y); } } } public static void main(String[] args) { new Test().start(); new Test().start(); } } What will the above code print? It will keep on printing same values for x and y incrementing by 1 on each line. There are two threads created by the main method. However, when one of the threads enters run(), it acquires the lock on obj and enters into an infinite loop. Now, the second thread also enters run but has to wait to acquire the same lock since obj is a static field. So, in effect, only the thread that gets the lock first, keeps on running. The second thread never gets a chance. Therefore, the printed values are sequential, x and y are always printed as equal and they get incremented by 1 on each line. Consider the following program: import java.io.FileReader; import java.io.FileWriter; public class ClosingTest { public static void main(String[] args) throws Exception { try(FileReader fr = new FileReader("c:\\temp\\license.txt"); FileWriter fw = new FileWriter("c:\\temp\\license2.txt") ) { int x = -1; while( (x = fr.read()) != -1){ fw.write(x); } } } } The FileWriter object will always be closed before the FileReader object. Consider the following code: import java.io.*; public class TestClass { public static void main(String[] args) throws Exception { File f = new File("x"); //1 BufferedReader bfr1 = new BufferedReader(new FileReader(f)); //2 BufferedReader bfr2 = new BufferedReader( bfr1 ); //3 PrintWriter pw = new PrintWriter(new FileReader(f)); //4 } } Select the correct statements about the above program. //2 and //3 will compile without any error. 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); }); Stationery : 2.0 Food : 2.5 The natural order of enums is the order in which they are defined. It is not necessarily same as alphabetical order of their names. To customize the behavior of class serialization, the readObject and writeObject methods should be overridden. Identify the correct statements regarding the following program: class JerkyThread extends Thread { private int data = 0; private boolean done = false; public JerkyThread(int x){ super(); this.data = x; } public synchronized int getData(){ return data; } public synchronized boolean isDone(){ return done; } public synchronized void run() { data += data; done = true; } public static void main(String[] args) throws Exception { JerkyThread[] jta = new JerkyThread[3]; for(int i=0; i<3; i++) { jta[i] = new JerkyThread(i); jta[i].start(); } for(JerkyThread jt : jta) { if(jt.isDone()) System.out.println(jt.getData()); } } } 0 2 4 is a possible output. Observe that each JerkyThread has been given a unique value for data i.e. 0, 1, and 2. Now, once you start all the 3 threads, any of them may be scheduled to run any time. The main thread loop that prints out the values, prints out the values of thread 1, thread 2, and thread 3 in that sequence. At that time, those threads might be in any state: runnable, running, or finished. In any case, the values will either be same as the original data value or data+data. Thus, first value can only be 0 or 0. Second value can be 1 or 2, third value can be 2 or 4. Now, observe the line of code: if(jt.isDone()) System.out.println(jt.getData()); It prints value only if isDone() returns true. Otherwise, it prints nothing. isDone() returns true only if the statements data += data; and done = true; in the run() method of that instance have been executed. Thus, 0 2 2 is not a possible output although 0 2 is. PreparedStatement allows several additional SQL types such as BLOB and CLOB. PreparedStatement offers better performance when the same query is to be run multiple times with different parameter values. Consider the following code: class Bond { String ticker; double coupon; java.util.Date 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? Just have Bond class implement Serializable. Make bonds array transient in Portfolio and implement readObject(ObjectOutputStream os) and writeObject(ObjectOutputStream os) methods to read and write the state of Bond objects explicitly. In which of the following cases can the Console object be acquired? When the JVM is started from an interactive command line without redirecting the standard input and output streams. Consider the following classes... class Point { int x, y; } class ColoredPoint extends Point { int color; } class Test { static void test(ColoredPoint p, Point q) { System.out.println("(ColoredPoint, Point)"); } static void test(Point p, ColoredPoint q) { System.out.println("(Point, ColoredPoint)"); } public static void main(String[] args) { ColoredPoint cp = new ColoredPoint(); test(cp, cp); } } The above code will print (ColoredPoint, Point) when compiled and run. False This code produces an error at compile time. The problem is that there are two declarations of test that are applicable and accessible, and neither is more specific than the other. Therefore, the method invocation is ambiguous. If you add a third definition of test: static void test(ColoredPoint p, ColoredPoint q) { System.out.println("(ColoredPoint, ColoredPoint)"); } then it would be more specific than the other two, and the method invocation would no longer be ambiguous. A thread dies when the run( ) method ends. Given: class Person{ private String name; private int age; public Person(String name, int age){ this.name = name; this.age = age; } //getters/setters not shown } What will the following code print? List<Person> friends = Arrays.asList(new Person("Bob", 31), new Person("Paul", 32), new Person("John", 33)); double averageAge = friends.stream().filter(f->f.getAge()<30) .mapToInt(f->f.getAge()) .average().getAsDouble(); System.out.println(averageAge); It will throw an exception at runtime. The given code chains three operations to a stream. First, it filters out all the element that do not satisfy the condition f.getAge()<30, which means there will no element in the stream, second, it maps each Person element to an int using the mapping function f.getAge(). Since there is no element in the stream anyway, the stream remains empty. Finally, the average() method computes the average of all the elements, which is 0.0. However, there is a problem with this code. The average() method actually returns an OptionalDouble (and not Double). Since the stream contains no element and the average() method returns an OptionalDouble containing OptionalDouble.empty. Therefore, getAsDouble method throws a java.util.NoSuchElementException. To avoid this problem, instead of getAsDouble, you should use orElse(0.0). That way, if the OptionalDouble is empty, it will return 0.0. 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); 0 Notice that filter is an intermediate operation. It does not do anything until a terminal operation is invoked on the stream. Therefore, in this case, ai will remain 0. Consider the following code: Locale myLoc = new Locale("fr", "FR"); ResourceBundle rb = ResourceBundle.getBundle("appmessages", myLoc); //INSERT CODE HERE Which of the following lines of code will assign a ResourceBundle for a different Locale to rb than the one currently assigned? (Assume appropriate import statements) rb = ResourceBundle.getBundle("appmessages", new Locale("ch", "CH")); rb = ResourceBundle.getBundle("appmessages", Locale.CHINA); Replace XXX with a declaration such that the following code will compile without any error or warning. public void m1(XXX list) { Number n = list.get(0); } Replace XXX with a declaration such that the following code will compile without any error or warning. public void m1(XXX list) { Number n = list.get(0); } List<? extends Number> Given: Connection c = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", "app"); try(Statement stmt = c.createStatement();) { ResultSet rs = stmt.executeQuery("select * from STUDENT"); ResultSetMetaData rsmd = rs.getMetaData(); int cc = rsmd.getColumnCount(); while(rs.next()){ for(int i = 0; i<cc; i++){ System.out.print(rsmd.getColumnName(i)+" = "+rs.getObject(i+1)+", "); } System.out.println(); } } catch(SQLException e){ e.printStackTrace(); } What will the above code print? (Assume that there is data in Student table.) It will print an exception stack trace at run time. Since column indexing starts with 1, rsmd.getColumnName(0) will cause an exception. Other than this, there is no issue with the code. Assuming that the table student2 does not have any row, how many rows will be present in this table after the following code is executed? try (Connection c = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", "app");) { c.setAutoCommit(false); Statement stmt = c.createStatement(); int a1 = stmt.executeUpdate("insert into STUDENT2 values (1, 'aaa', 1.1)"); Savepoint sp1 = c.setSavepoint(); int a2 = stmt.executeUpdate("insert into STUDENT2 values (2, 'bbb', 2.1)"); c.rollback(); int a3 = stmt.executeUpdate("insert into STUDENT2 values (3, 'ccc', 3.1)"); c.setAutoCommit(true); int a4 = stmt.executeUpdate("insert into STUDENT2 values (4, 'ddd', 4.1)"); } catch (SQLException e) { e.printStackTrace(); } => 2 Consider the following code: public class AssertErrorTest { public void robustMethod(int[] intArray) throws AssertionError { int[] newIA = //get new array by processing intArray assert newIA != intArray; } } Which of the following declarations of robustMethod(int[] intArray) are valid in a subclass of the above class? => public void robustMethod(int[] intArray) => public void robustMethod(int[] intArray) throws Error => public void robustMethod(int[] intArray) throws RuntimeException java.util.function.Supplier is a functional interface and has only one method named get. It doesn't have getAsDouble. Therefore, this code will not compile. The following are complete contents of TestClass.java: class Book{ protected final int pages = 100; final void mA(){ System.out.println("In B.mA "+pages); } } class Encyclopedia extends Book{ private int pages = 200; //1 void mB(){ System.out.println("In E.mB "+pages); } void mA(){ //2 System.out.println("In E.mA "+pages); } } public class TestClass { public static void main(String[] args) { Book o1 = new Encyclopedia (); //3 Book o2 = new Book(); o1.mA(); //4 o1.mB(); //5 o2.mA(); } } Which lines will cause compilation to fail? => //2 and //5 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); => S1:50 S2:45 S3:40 Given the following code: public class Valuator { public AtomicInteger status = new AtomicInteger(0); public void valuate() { int oldstatus = status.get(); /* valid code here */ int newstatus = //determine new status //INSERT CODE HERE } } Assuming that an instance of this class is shared among multiple threads, you want to update the status to newstatus only if the oldstatus has not changed. Which of the following lines of code will you use? => status.compareAndSet(oldstatus, newstatus); compareAndSet(expectedValue, newValue) is meant exactly for this purpose. It first checks if the current value is same as the expected value and if so, updates to the new value. Which of the following statements are true regarding the try-with-resources statement? => Resources are closed in the reverse order of their creation. 1For example: try ( ZipFile resource1 = new ZipFile(zipFileName); BufferedWriter resource2 = Files.newBufferedWriter(path, charset) ){ ... } Here, resource1 is created before resource2 but resource2 will be closed before resource1. Closeable extends AutoCloseable. 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 = //code to create the list goes here Comparator<Book> c1 = (b1, b2)->b1.getGenre().compareTo(b2.getGenre()); //1 books.stream().sorted(c1.thenComparing(Book::getTitle)); //2 System.out.println(books); Identify the correct statements. => It will print the list as it is. 1. Manipulating a stream doesn't manipulate the backing source of the stream. Here, when you chain the sorted method to a stream, it returns a reference to a Stream that appears sorted. The original List which was used to create the stream will remain as it is. If you want to sort a List permanently, you should use one of the Collections.sort methods. 2. There is another issue with this code. Stream.sorted is an intermediate operation. It will not be executed until a terminal operation is invoked on the stream. Therefore, in this case, the sorted method will not even be invoked. You want to run Main.class [Assume that it belongs to the default package.] from the command line. It uses two packages good.* and bad.*. You want to disable assertions for all classes of bad.* as well as good.* but at the same time want to enable them for Main.class. Which of the following command lines will achieve the above? => java -ea:... -da:good... -da:bad... Main 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); => It will not compile. Remember that allMatch is a terminal operation that returns a boolean. You cannot chain any operation after that. If you had just this : Optional<String> ops = names.stream().parallel().findAny(); It could potentially print any name from the list because of .parallel(). 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); => {false=[11, 13, 15], true=[10, 12, 14]} Given: public class Book{ String isbn; String title; public Book(String isbn, String title){ this.isbn = isbn; this.title = title; } public int compareTo(Book b){ return this.isbn.compareTo(b.isbn); } //accessors not shown } and the following code snippet: List<Book> books = getBooksByAuthor("Ludlum"); Collections.sort(books, (b1, b2)->b1.getTitle().compareTo(b2.getTitle())); //1 Collections.sort(books); //2 Assuming that getBooksByAuthor is a valid method that returns a List of Books, which of the following statements is/are true? => Compilation failure at //2. For Collections.sort(List ) method to work, the elements of the passed List must implement Comparable interface. Here, Book does not implement Comparable and therefore this line will fail to compile. It is important to understand that compilation failure occurs because books is declared as List<Book>. If it were declared as just List, compilation would succeed and it would fail at run time with a ClassCastException. Given: Stream<Integer> strm1 = Stream.of(2, 3, 5, 7, 11, 13, 17, 19); //1 Stream<Integer> strm2 = strm1.filter(i->{ return i>5 && i<15; }); //2 strm2.forEach(System.out::print); //300 Which of the following options can be used to replace line at //2 without affecting the output? => Stream<Integer> strm2 = strm1.parallel().filter(i->i>5).filter(i->i<15).sequential(); Stream pipelines may execute either sequentially or in parallel. This execution mode is a property of the stream. Streams are created with an initial choice of sequential or parallel execution. (For example, Collection.stream() creates a sequential stream, and Collection.parallelStream() creates a parallel one.) This choice of execution mode may be modified by the BaseStream.sequential() or BaseStream.parallel() methods. It is not documented by Oracle exactly what happens when you change the stream execution mode multiple times in a pipeline. It is not clear whether it is the last change that matters or whether operations invoked after calling () parallel can be executed in parallel and operations invoked after calling sequential() will be executed sequentially. In either case, in the given line of code, the end result will be sequential. What will the following code print? import java.util.Optional; public class NewClass { public static Optional<String> getGrade(int marks){ Optional<String> grade = Optional.empty(); if(marks>50){ grade = Optional.of("PASS"); } else { grade.of("FAIL"); } return grade; } public static void main(String[] args) { Optional<String> grade1 = getGrade(50); Optional<String> grade2 = getGrade(55); System.out.println(grade1.orElse("UNKNOWN")); if(grade2.isPresent()){ grade2.ifPresent(x->System.out.println(x)); }else{ System.out.println(grade2.orElse("Empty")); } } } => UNKNOWN PASS Here are a few important things you need to know about Optional class: 1. Optional has a static method named of(T t) that returns an Optional object containing the value passed as argument. It will throw NullPointerException if you pass null. If you want to avoid NullPointerException, you should use Optional.ofNullable(T t) method. This will return Optional.empty if you pass null. 2. You cannot change the contents of Optional object after creation. Optional does not have a set method. Therefore, grade.of, although technically correct, will not actually change the Optional object referred to by grade. It will return a new Optional object containing the passed argument. 3. The orElse method returns the actual object contained inside the Optional or the argument passed to this method if the Optional is empty. It does not return an Optional object. Therefore, print(grade1.orElse("UNKNOWN")) will print UNKNOWN and not Optional[UNKNOWN]. 4. isPresent() returns true if the Optional contains a value, false otherwise. 5. ifPresent(Consumer ) executes the Consumer object with the value if the Optional contains a value. Not that it is the value contained in the Optional that is passed to the Consumer and not the Optional itself. Consider the following program: import java.util.*; class Book { private String title, isbn; public boolean equals(Object o){ return (o instanceof Book && ((Book)o).isbn.equals(this.isbn)); } // ... setters and getters for title and isbn } class BookStore { Map<Book, Integer> map = new HashMap<Book, Integer>(); int getNumberOfCopies(Book b){ return map.get(b); } public void addBook(Book b, int numberofcopies){ map.put(b, numberofcopies); } // ... other useful methods. } public class TestClass { static BookStore bs = new BookStore(); public static void main(String[] args) { Book b = new Book(); b.setIsbn("111"); bs.addBook(b, 10); System.out.println(bs.getNumberOfCopies(b)); b = new Book(); b.setIsbn("111"); System.out.println(bs.getNumberOfCopies(b)); } } What will it print when it is compiled and run? => It will compile without a warning and will throw an exception when run. => It will print 10. There are multiple concepts involved here: 1. Observe that Book class has overridden equals() method but hasn't overridden hashCode() method. The way equals method is coded here makes two Book objects equal if their isbn is equals. However, their hash code values will be different because Object class's hashCode method returns unique hashcode for every object. 2. In the main method, a Book object is stored in BookStore. The same Book object is being used to retrieve the numberofcopies value. Since the object that was stored in the Map and the object that was used to retrieve the value from the map are the same object, their hash codes will be the same and hence map will be able to find it among its name-value pairs. Thus, this will print 10. 3. Next, a new Book object is created. Note that its hash code will be different from the previously created book object. But as per equals() method of Book, they are equal because their isbn are same. When you try to use the new Book object to find the value, map will not find anything because of a different hash code. So map.get() will return null. 4. The return type of the method is an int (and not an Integer). But map.get always returns an object (not a primitive.) So auto-unboxing will try to convert null into an int, which will throw a NullPointerException. 5There is no warning at compilation because all the operations are valid. Which of the following options correctly makes use of java.util.concurrent.Callable? => public static class MyTask implements Callable<String>{ public String call() throws Exception { //do something return "Data from callable"; } } Given: Path p1 = Paths.get("c:\\a\\b\\c.java"); What will p1.getName(2).toString() return? => c.java A NavigableSet keeps the elements sorted. Which of the following lines will cause the compilation to fail? interface I { } public enum EnumA implements I { A, AA, AAA}; //1 class TestClass { public enum EnumB{ B, BB, BBB; public Object clone(){ return B; } //2 } public static enum EnumC{ C, CC, CCC }; public static enum EnumD extends EnumC{ DDD }; //3 public TestClass() { System.out.println(EnumC.CC.index()); //4 } public static void main(String[] args) { System.out.println(EnumC.valueOf("ccc")); //5 System.out.println(EnumC.CCC.name()); //6 } } => 2 java.lang.Enum (from which every enum extends implicitly), makes the clone method final. So you cannot override it. => 3 => 4 The correct method name is ordinal not index. EnumC.CC.ordinal() will return 1 in this case. 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{ Path p1 = Paths.get("c:\\temp\\test1.txt"); Path p2 = //LINE 10 - INSERT CODE HERE BufferedWriter bw = new BufferedWriter(new FileWriter(p2.toFile())); bw.write("hello"); bw.close(); } => p1.resolve("text2.txt"); //Not good. This will return "c:\temp\test1.txt\text2.txt", which is not what you want. The following is how resolve(String other) works: If the other parameter is an absolute path then this method trivially returns other. If other is an empty path then this method trivially returns this path. Otherwise this method considers this path to be a directory and resolves the given path against this path. In the simplest case, the given path does not have a root component, in which case this method joins the given path to this path and returns a resulting path that ends with the given path. Where the given path has a root component then resolution is highly implementation dependent and therefore unspecified. => p1.relativize("c:\\temp\\text2.txt"); //Not good. This is wrong for two reasons 1. relativize method does not take a String as an argument. It takes a Path object. 2. relativize method is meant to convert an absolute path into a relative path. But here, we want to convert a relative path to an absolute path. For example, p2 = p1.relativize(Paths.get("c:\\temp\\text2.txt")); will produce "..\text2.txt". => p1.resolveSibling("text2.txt"); //OK You already have the absolute path to test1.txt in p1. Further, it is given that test1.txt is in the same directory as text2.txt i.e. both the files are siblings. To open test2.txt, you need to determine the absolute path for text2.txt using the absolute path for test1.txt. In other words, you are trying to get the absolute path for a file that exists in the same directory as the original file. The method resolveSibling is meant exactly for this purpose. This will set p2 to c:\temp\text2.txt, which can then be used to create File object. You should go through the following JavaDoc API description for resolveSibling method. public Path resolveSibling(String other) or public Path resolveSibling(Path other) :Resolves the given path against this path's parent path. This is useful where a file name needs to be replaced with another file name. For example, suppose that the name separator is "/" and a path represents "dir1/dir2/foo", then invoking this method with the Path "bar" will result in the Path "dir1/dir2/bar". If this path does not have a parent path, or other is absolute, then this method returns other. If other is an empty path then this method returns this path's parent, or where this path doesn't have a parent, the empty path. => p1.relativize(Paths.get("text2.txt")); //Not ok This will thrown an IllegalArgumentException saying 'other' is different type of Path. This is because a relative path cannot be constructed if only one of the paths is an absolute path. Here, p1 is an absolute path (because it starts with a root) and p2 is a relative path. Given: class MyProcessor{ int value; public MyProcessor(){ value = 10; } public MyProcessor(int value){ this.value = value; } public void process(){ System.out.println("Processing "+value); } } What can be inserted in the code below so that it will print Processing 10? => Supplier<MyProcessor> supp = MyProcessor::new; MyProcessor mp = supp.get(); mp.process(); => Function<Integer, MyProcessor> f = MyProcessor::new; MyProcessor mp = f.apply(10); mp.process(); What will the following code print? ReentrantLock rlock = new ReentrantLock(); boolean f1 = rlock.lock(); System.out.println(f1); boolean f2 = rlock.lock(); System.out.println(f2); => It will not compile. Lock.lock() returns void. Lock.tryLock() returns boolean. Had the code been: ReentrantLock rlock = new ReentrantLock(); boolean f1 = rlock.tryLock(); System.out.println(f1); boolean f2 = rlock.tryLock(); System.out.println(f2); It would have printed: true true Note that ReentrantLock implements Lock. 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 ? => Replace code at //1 with .stream() //OK => Replace code at //3 with .parallelStream() //Not OK If you change stream to parallelStream, forEach method will print the elements in any order. You will need to change forEach to forEachOrdered as well if you make this change. Consider the following code: class A { A() { print(); } private void print() { System.out.println("A"); } } class B extends A { int i = Math.round(3.5f); public static void main(String[] args) { A a = new B(); a.print(); } void print() { System.out.println(i); } } What will be the output when class B is run ? => This program won't even compile. Note that print() is declared private in class A. So a.print() is not valid in class B's code as the class of 'a' is A. Which of the given command lines can be used so that the following code will print true? public class TestClass { public static void main(String[] args) { assert args.length == 1; System.out.println(args[1]); } } => java -ea TestClass true true // Not good. -ea will enable assertions and the statement assert args.length == 1 will fail because args is of length 2. So the next statement will not be executed and the program will end with an AssertionError. => java TestClass true true //OK Since there is no -ea switch in the command line, assertions will be disabled and the statement assert args.length == 1 will not be executed. The next statement will then print args[1] i.e. the second element of args array, which is true. 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); } => ac Which of the following sets of interface definitions are valid? => interface Measurement{ public default int getLength(){ return 0; } public static int getBreadth(){ return 0; } } interface Size extends Measurement{ public static final int UNIT = 100; public static int getLength(){ return 10;} } // Not good. getLength method in Size is invalid because a default method cannot be overridden by a static method. You can, however, redeclare a static method of a super interface as a default method in the sub interface. => interface Measurement{ public int getLength(); public static int getBreadth(){ return 0; } } interface Size extends Measurement{ } //OK => interface Measurement{ public default final int getUnit(){ return 100; } } interface Size extends Measurement{ public int getLength(); } //Not ok interface methods can never be declared final. 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? => 10.0 12.0 Remember that Double objects are immutable. Therefore, the first call to forEach does not change the elements in the original list on which the stream is based. It only replaces the elements of that stream with new ones. Therefore, when you call dlist.stream() the second time, a new stream is created and it has the same elements as the list i.e. 10.0 and 12.0. If it were a Stream of mutable objects such as StringBuilders and if you append something to the elements in the first forEach, that would change the original StringBuilder objects contained in the list. In that case, the second forEach will actually print the updated values. For example, the following code will indeed print ab and aab. List<StringBuilder> dList = Arrays.asList(new StringBuilder("a"), new StringBuilder("aa")); dList.stream().forEach(x->x.append("b")); dList.stream().forEach(x->System.out.println(x)); Which statements regarding the following code are correct? class A extends Thread { public void run() { System.out.println("Starting loop"); try{ Thread.sleep(10000); //1 sleep for 10 secs }catch(Exception e){ e.printStackTrace(); } System.out.println("Ending loop"); } } public class TestClass { public static void main(String args[]) throws Exception { A a = new A(); a.start(); Thread.sleep(1000); a.interrupt(); } } => It will run and MAY end without throwing any exception. Even though the thread is sleeping for 10 seconds and it is very probable that the main thread will execute and call a.interrupt() (which will cause the sleeping thread to receive an InterruptedException), this behavior cannot be guaranteed. It is possible, even though highly unlikely, that the sleeping thread will complete its 10 seconds sleep and the main thread may not get a chance to run and call a.interrupt() in those 10 seconds. In this case there won't be any exception. => It will run and will end without an InterruptedException if //1 is replaced with while(!isInterrupted()) { }; calling interrupt() will cause an InterruptedException ONLY if the thread on which interrupt() is called, is blocked on an invocation of the wait, join, or sleep, methods of this class. Given: BufferedReader bfr = new BufferedReader(new FileReader("c:\\temp\\pathtest\\a.java")); BufferedWriter bfw = new BufferedWriter(new FileWriter("c:\\temp\\pathtest\\b.java")); String line = null; while( (line=bfr.readLine()) != null ){ bfw.append(line); } //INSERT CODE HERE bfw.close(); Which of the following lines is required to be inserted in the code above so that content in b.java will be overwritten with the content in a.java? => None of the above. 1. BufferedWriter's append method = works same as the write(String) method. It doesn't really append the data to the end of the existing content. It overwrites the existing content. 2. The flush method flushes the stream and makes sure any data that is in the stream but is not written to the file yet, is written to the file. It does not close the stream. A call to flush is useful when you want to write the contents to the file but don't want to close the writer yet. 3. The close method flushes the stream and makes sure that all data is actually written to the file. Since the given code includes a call to close(), there is no need for a call to flush. Consider the following code: public class FileCopier { public static void copy(String records1, String records2) throws IOException { 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 (IOException | IndexOutOfBoundsException e) { e = new FileNotFoundException(); e.printStackTrace(); } } public static void main(String[] args) throws Exception { 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? => The program will not compile because the line e = new FileNotFoundException(); in catch block is invalid. The exception parameter in a multi-catch clause is implicitly final. Thus, it cannot be reassigned. Had there been only one exception in the catch clause (of type that is compatible with FileNotFoundException such as IOException or Exception, but not RuntimeException), it would have been valid. Consider the standard 'put' method of class HashMap. public Object put(Object key, Object value); => None of these. If a HashMap already contains an entry for the specified key, the element already in this dictionary for that key is returned after modifying the entry to contain the new element. There no such exception as DuplicateKeyException. HashMap allows both - the key and the value to be null. But Hashtable does not. What will the following code fragment print when compiled and run? Locale myloc = new Locale.Builder().setLanguage("hinglish").setRegion("IN").build(); //L1 ResourceBundle msgs = ResourceBundle.getBundle("mymsgs", myloc); Enumeration<String> en = msgs.getKeys(); while(en.hasMoreElements()){ String key = en.nextElement(); String val = msgs.getString(key); System.out.println(key+"="+val); } Assume that only the following two properties files (contents of the file is shown below the name of the file) are accessible to the code. 1. mymsgs_hinglish_US.properties okLabel=OK cancelLabel=Cancel 2. mymsgs_hinglish_UK.properties okLabel=YES noLabel=NO => It will throw an exception at run time. The code is trying to create a resource bundle for a specific locale i.e. hinglish_IN. To create this bundle, at least one of mymsgs_hinglish_IN.properties, mymsgs_hinglish.properties, and mymsgs.properties must be present in the classpath. Since none of these files is not available, the resource bundle cannot be created. An exception will therefore be thrown when you call getBundle(). Given: public class Book{ String isbn; String title; public Book(String isbn, String title){ this.isbn = isbn; this.title = title; } //INSERT CODE HERE } and this following code snippet: Object b1 = new Book("1111", "Thinking in Java"); Object b2 = new Book("1111", "Java in 24 hrs"); System.out.println(b1.equals(b2)); Which of the following implementations of the equals method will make the above code print true? => public boolean equals(Object b) throws NullPointerException{ return true; } This is undoubtedly the worst implementation for an equals method because it makes all the Book objects equals. However, it does satisfy the requirement of the question. You should think about what would be an appropriate implementation of the hashCode method if you use this code for the equals method. From a strictly OO perspective, which of the following code reuse techniques are used to aggregate features from multiple classes? => Inheritance => Composition To aggregate features of another class, you either extend that class (i.e. inheritance) or have an object of the other class in your class (i.e. composition). The following is an example of how composition is used for code reuse: public class Z{ private X x = new X(); private Y y = new Y(); public void mX(){ x.mX(); } public void mY(){ y.mY(); } public void mZ(){ x.mX(); y.mY(); } } The above class exposes three methods but it reuses the code for two methods by delegating the tasks to the methods of X and Y objects instead of writing the code for the same again. Similarly, in method mZ(), it uses the functionality already available in X and Y. Thus, it can be said that Z is composed of X and Y. Which of the following code fragments show syntactically correct usage of assertions? => public void assertTest(List v) { assert v.size() == 10 : v; } //OK Valid because <boolean_expression> : <any_expression_but_void> is satisfied. => public void assertTest(List v) { assert v != null : v = new ArrayList(); } //OK => public void assertTest(List v) { assert v != null : v == null; } //OK => public void assertTest(List v) { assert v.size() == 10 : v.clear(); } // Not OK Invalid because List.clear() returns void and boolean : void does not satisfy <boolean_expression> : <any_expression_but_void>, which is required for an assert statement. Which of the statements regarding the join() method of Thread class is correct? => The thread that calls the join() method, pauses until the other thread ends (i.e. finishes its run() method.) There is no need for any thread to hold any lock. 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? => appmessages_es_ES.properties is not present in CLASSPATH. Identify correct statements about Java Date and Time API. => Classes used to represent dates and times in java.time package are thread safe. All classess in java.time package such as classes for date, time, date and time combined, time zones, instants, duration, and clocks are immutable and thread-safe. Consider the following code snippet : public void readData(String fileName) throws Exception { try(FileReader fr1 = new FileReader(fileName)){ Connection c = getConnection(); //...other valid code } } Given that getConnection method throws ClassNotFoundException and that an IOException is thrown while closing fr1, which exception will be received by the caller of readData() method? => java.lang.ClassNotFoundException If an exception is thrown within the try-with-resources block, then that is the exception that the caller gets. But before the try block returns, the resource's close() method is called and if the close() method throws an exception as well, then this exception is added to the original exception as a supressed exception. Consider the following code: //Assume appropriate imports class Person{ String name; String dob; public Person(String name, String dob){ this.name = name; this.dob = dob; } } public class SortTest { public static void main(String[] args) { ArrayList<Person> al = new ArrayList<>(); al.add(new Person("Paul", "01012000")); al.add(new Person("Peter", "01011990")); al.add(new Person("Patrick", "01012002")); //INSERT CODE HERE for(Person a : al) System.out.println(a.name+" "+ a.dob); } } What can be inserted in the code so that it will sort the collection of Persons by Person's dob attribute? => Collections.sort(al, new Comparator<Person>(){ public int compare(Person o1, Person o2) { return o1.dob.compareTo(o2.dob); } }); When the class of the objects that you want to compare does not implement java.lang.Comparable interface (which has one method named compareTo(T t)), or when you want to compare the objects using some other comparison criteria than the one implemented by its compareTo method, you can use Collections.sort(List, java.util.Comparator) method. This method allows you to pass your own custom comparator to compare the objects. It has two methods: int compare(T o1, T o2) : Compares its two arguments for order. boolean equals(Object obj) : Indicates whether some other object is "equal to" this comparator. Identify the correct statement about i18n. => You should use Locale and formatter objects such as NumberFormat and DateFormat to generate locale specific output. => Using default locale for NumberFormat and DateFormat automatically ensures that the formatted text will be localized to the location setting of the machine on which the code is run. (Assuming that default locale hasn't been explicitly changed by any means.) When not passed to the getInstance() method, the default Locale is used, which is same as the one set by the operating system. If you want to change it, (for example, if you want to generate French format on a US machine), you must create a new Locale("fr", "FR") object and use the following methods to get an appropriate NumberFormat or DateFormat instance - NumberFormat: NumberFormat getInstance(Locale locale) DateFormat: DateFormat getDateInstance(int style, Locale locale) Note that DateFormat does not have getInstance(Locale locale) method. 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:\\a\\b\\c"); public static String getValue(){ String x = p1.getName(1).toString(); String y = p1.subpath(1,2).toString(); return x+" : "+y; } public static void main(String[] args) { System.out.println(getValue()); } } => b : b Remember the following points about Path.subpath(int beginIndex, int endIndex) 1. Indexing starts from 0. 2. Root (i.e. c:\) is not considered as the beginning. 3. name at beginIndex is included but name at endIndex is not. 4. paths do not start or end with \. Thus, if your path is "c:\\a\\b\\c", subpath(1,1) will cause IllegalArgumentException to be thrown. subpath(1,2) will correspond to b. subpath(1,3) will correspond to b/c. Remember the following 4 points about Path.getName() method : 1. Indices for path names start from 0. 2. Root (i.e. c:\) is not included in path names. 3. \ is NOT a part of a path name. 4. If you pass a negative index or a value greater than or equal to the number of elements, or this path has zero name elements, java.lang.IllegalArgumentException is thrown. It DOES NOT return null. Thus, for example, If your Path is "c:\\code\\java\\PathTest.java", p1.getRoot() is c:\ ((For Unix based environments, the root is usually / ). p1.getName(0) is code p1.getName(1) is java p1.getName(2) is PathTest.java p1.getName(3) will cause IllegalArgumentException to be thrown. 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? => The program will not compile because line //2 is invalid. The auto-closeable variables defined in the try-with-resources statement are implicitly final. Thus, they cannot be reassigned. Given that a method named Double getPrice(String id) exists and may potentially return null, about which of the following options can you be certain that a run time exception will not be thrown? => Optional<Double> price = Optional.ofNullable(getPrice("1111")); Double x = price.orElse(getPrice("2222")); => Optional<Double> price = Optional.ofNullable(getPrice("1111")); Double y = price.orElseGet(()->getPrice("333")); One advantage of CallableStatement is that it allows IN/OUT parameters. A CallableStatement is the only way for a JDBC program to execute stored procedures in the database if the procedure has in and out parameters. A PreparedStatement is used for SQL statements that are executed multiple times with different values. For example, if you want to insert several values into a table, one after another, it is a lot easier with PreparedStatement: ps = c.prepareStatement("INSERT INTO STUDENT VALUES (?, ?)"); //This is created only once //Once created, the PreparedStatement is compiled automatically. ps.setInt(1, 111); ps.setString(2, "Bob"); ps.executeUpdate(); //Now change the parameter values and execute again. ps.setInt(1, 112); ps.setString(2, "Cathy"); ps.executeUpdate(); A CallableStatement is meant for executing a stored procedure that has already been created in the database. For example: //computeMatrixForSales is a stored procedure that has already been created in the database. callableStatement = connection.prepareCall("{call computeMatrixForSales(?)}); callableStatement.setInt(1, 1000); callableStatement.executeUpdate(); A programmer wants to ensure that assertions are enabled before rest of the method is executed. He has written the following code: public void someMethod() { boolean enabled = false; assert enabled = true; assert enabled; ... rest of the code ... } Which of the following statements are correct regarding the above code? => It will not throw anything if assertions are disabled. If assertions are disabled, neither of the two assert lines will execute. So no exception will be thrown. This code should be written as: public void someMethod() { boolean enabled = false; assert enabled = true; if( !enabled ) throw new RuntimeException("Assertions should be enabled"); ... rest of the code ... } Which of the following statements are true regarding the Fork/Join framework? => The worker threads in the ForkJoinPool extend java.lang.Thread and are created by a factory. => One worker thread may steal work from another worker thread. You have to complete a big task that operates on a large array of integers. The task has to look at each element of the array and update that element. The new value of the element is generated by a utility class's static method, which takes in the existing value as a parameter and returns the new value. This method is computationally very intensive. What would be a good approach to solve this problem? => Subclass RecursiveAction and implement the compute() method that computes the new value but does not return anything. => Create a RecursiveAction that subdivides the task into two, then forks one of the tasks and computes another. This is a standard way of using the Fork/Join framework. You create a RecursiveTask or RecursiveAction (depending on where you need to return a value or not) and in that RecursiveTask, you subdivide the task into two equal parts. You then fork out one of the halfs and compute the second half. java.util.Locale allows you to do which of the following? => Provide country and language specific formatting for Dates. => Provide country specific formatting for Currencies. Given: String sentence1 = "Carpe diem. Seize the day, boys. Make your lives extraordinary."; String sentence2 = "Frankly, my dear, I don't give a damn!"; String sentence3 = "Do I look like I give a damn?"; List<String> sentences = Arrays.asList(sentence1, sentence2, sentence3); Which of the following options will create a stream containing all the words in the three sentences without repetition? => Stream<String> strm = sentences.stream() .flatMap(str->Stream.of(str.split("[ ,.!?\r\n]"))) .filter(s->s.length()>0) .distinct(); 1. The flatMap method replaces one element of a stream with elements of a new stream generated using the original element. Here, the original elements are the sentences. Each of these elements are replaced in the stream with the elements generated by applying str.split("[ ,.!?\r\n]", which basically converts the stream of sentences into a stream of words. 2. The stream is now filtered and only thoses elements where the length is greater than 0 are allowed to be in the stream. 3. Finally, distinct removes all the duplicates. 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(); } } => Device Opened Writing : TEST Device closed Device closed You have a file named customers.dat in c:\company\records directory. You want to copy all the lines in this file to another file named clients.dat in the same directory and you have the following code to do it: public static void writeData() { Path p1 = Paths.get("c:\\company\\records\\customers.dat"); //LINE 20 - INSERT CODE HERE try ( BufferedReader br = new BufferedReader(new FileReader(p1.toFile())); BufferedWriter bw = new BufferedWriter(new FileWriter(p2.toFile()))) { String line = null; while ((line = br.readLine()) != null) { bw.write(line); bw.newLine(); } }catch(Exception e){ e.printStackTrace(); } } Which of the following options can be inserted independent of each other at //LINE 20 to make it work? Assume that the current directory for the program when it runs is c:\code. => Path p2 = p1.resolveSibling("clients.dat"); You already have the absolute path to customers.dat in p1. Further, it is given that you want to copy the data to a file in the same directory i.e. both the files - old and new, are siblings. So, to open clients.dat, you need to determine the absolute path for clients.dat using the absolute path for customers.dat. In other words, you are trying to get the absolute path for a file that exists in the same directory as the original file. The method resolveSibling is meant exactly for this purpose. => Path p2 = Paths.get("c:", p1.subpath(0, 2).toString(), "clients.dat"); This is very straight forward. You should go through the JavaDoc API description for Path.subpath and Paths.get methods. You have a long running process that does computations in multiple steps and saves the values computed at each to the database. In some situations, the process may encounter a special condition and may be required to recompute the values starting from a certain step depending on the condition. What JDBC method call will you use to efficiently manage this requirement? (Assume that the variable names used in the statement below refer to valid objects of the type implied by their names.) => connection.rollback(savePoint); The SavePoint feature of JDBC is tailor made for this purpose. At the end of each step, the process can create a save point. Later on, when the process encounters the special condition, it can roll back the transaction up to any of the previous save point and continue from there, instead of rolling back the whole transaction and losing all the values. For example, connection.setAutoCommit(false); stmt.executeUpdate("update student set status=1"); \\1 SavePoint savePoint1 = connection.setSavePoint("step1done"); stmt.executeUpdate("update student set gpa=4.0"); \\2 if(special condition){ connection.rollback(savePoint1); } connection.commit(); //query 1 will be committed but query 2 will not be committed. Consider the following code fragment: public void m1() { ... assert value == 10 : null; } Which of the following statement is correct regarding the above code? (Assume that assertions are enabled.) => It will throw a AssertionError if value is not equal to 10. If the boolean expression is false, a java.lang.AssertionError is thrown. AssertionError extends from java.lang.Error. The second operand can be null but it cannot be void. In the above case, if value is not 10, it will throw new AssertionError(null). What will the following code print? Instant ins = Instant.parse("2015-06-25T16:43:30.00z"); ins.plus(10, ChronoUnit.HOURS); System.out.println(ins); => 2015-06-25T16:43:30Z java.time.Instant has several versions of plus and minus methods. However, remember that none of these methods change the Instant object itself. They return a new Instant object with the modification. In this case, it would return a new Instant object containing 2015-06-26T02:43:30Z. 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(); } => s = Files.find(Paths.get("c:\\temp\\pathtest"), Integer.MAX_VALUE, (p, a)->p.endsWith("test.txt")&& a.isRegularFile()); public static Stream<Path> find(Path start, int maxDepth, BiPredicate<Path,BasicFileAttributes> matcher, FileVisitOption... options) throws IOException Return a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file. Given: List<String> letters = Arrays.asList("j", "a", "v","a"); Which of the following code snippets will print JAVA? => UnaryOperator<String> uo = str->str.toUpperCase(); letters.replaceAll(uo); letters.forEach(System.out::print); => letters.forEach(letter->System.out.print(letter.toUpperCase())); => System.out.print(letters.stream().collect(Collectors.joining()).toUpperCase()); Consider the following program: public class TestClass extends Thread { private static int threadcounter = 0; public void run() { threadcounter++; System.out.println(threadcounter); } public static void main(String[] args) throws Exception { for(int i=0; i<10; i++) { synchronized(TestClass.class) { new TestClass().start(); } } } } Which of the following is correct regarding the execution of the given program? => Total of 10 numbers will be printed => The final value of threadcounter just before the program terminates may be less than 10. 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 { ExecutorService es = Executors.newSingleThreadExecutor(); Future<String> future = es.submit(new MyCallable()); System.out.println(future.get()); //1 es.shutdownNow(); //2 } } => DONE Remember that Future.get() will block until there is a value to return or there is an exception. Therefore, the program will block at line marked //1 and will print the return value of the given Callable i.e. "DONE" once it is done. If you don't want to block the code, you may use Future.isDone(), which returns a boolean without blocking. List<Runnable> shutdownNow() This method attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. This method does not wait for actively executing tasks to terminate. Use awaitTermination to do that. There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate. What is guaranteed by the JVM about threads? => It is usually the operating System, which decides which thread to run when and for how much time. => Threads in Java are usually System dependent. Assume that the following directory exists: c:\a\b\c A File object is created as follows: File f = new File("c:\\a\\b\\c\\d\\e"); Given that directories d and e do not exist under c, which of the following statements are correct? => f.mkdirs(); will create directory d under c and directory e under d. => f.getParentFile() will return a File Object representing c:\a\b\c\d getParent() returns a String and getParentFile() returns a File object. Consider the following code: public class TestOuter { public void myOuterMethod() { // 1 } public class TestInner { } public static void main(String[] args) { TestOuter to = new TestOuter(); // 2 } } Which of the following options correctly instantiates a TestInner object? => new TestInner(); at //1 Valid because 'this' instance of TestOuter is associated with TestInner object. => new TestOuter().new TestInner(); at //1 Which of the following are valid method implementations? => public void outputText(PrintWriter pw, String text){ pw.write(text); if(pw.checkError()) System.out.println("exception in writing"); } Note that none of the PrintWriter's methods throw any I/O exceptions because they supress the errors in writing and set an internal flag for error status instead. The checkError method returns true if there has been a problem in writing. => public void outputText(PrintWriter pw, String text){ pw.printf(text).print("success"); } PrintWriter has printf(Locale l, String format, Object... args) and printf(String format, Object... args) methods that allow you to format the input before printing. These methods return the same PrintWriter object so that you can chain multiple calls as shown in this option. 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? => Supplier<String> s = name::toUpperCase; val = s.get(); The functional method of the interface Supplier<T> is T get(). name::toUpperCase correctly implements this interface. It returns the value returned by calling name.toUpperCase. What will the following code print when compiled and run? interface Boiler{ public void boil(); public static void shutdown(){ System.out.println("shutting down"); } } interface Vaporizer extends Boiler{ //1 public default void vaporize(){ boil(); System.out.println("Vaporized!"); } } public class Reactor implements Vaporizer{ public void boil() { System.out.println("Boiling..."); } public static void main(String[] args) { Vaporizer v = new Reactor(); //2 v.vaporize(); //3 v.shutdown(); //4 } } Compilation failure at //4. Remember that static method of an interface can only be accessed by using the name of that interface. i.e. Boiler.shutdown() in this case. This is unlike static method of a class, which can be accessed using a subclass name or a variable name as well. What will the following code fragment print when compiled and run? Locale myloc = new Locale.Builder().setLanguage("en").setRegion("UK").build(); //L1 ResourceBundle msgs = ResourceBundle.getBundle("mymsgs", myloc); Enumeration<String> en = msgs.getKeys(); while(en.hasMoreElements()){ String key = en.nextElement(); String val = msgs.getString(key); System.out.println(key+" : "+val); } Assume that only the following two properties files (contents of the file is shown below the name of the file) are accessible to the code. 1. mymsgs.properties okLabel=OK cancelLabel=Cancel 2. mymsgs_en_UK.properties okLabel=YES noLabel=NO noLabel : NO okLabel : YES cancelLabel : Cancel mymsgs.properties is the base file for this resource bundle. Therefore, it will be loaded first. Since the language and region specific file is also present (_en_UK), it will also be loaded and the values in this file will be superimposed on the values of the base file. Remember that if there were another properties file named mymsgs_en.properties also present, then that file would have been loaded before mymsgs_en_UK.properties. Interface Runnable have only one method run: @FunctionalInterface public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); } Consider the following code : public class TestClass extends Thread { class Runner implements Runnable { public void run() { Thread[] t = new Thread[5]; for(int i=0; i<t.length; i++) System.out.println(t[i]); } } public static void main(String args[]) throws Exception { TestClass tc = new TestClass(); new Thread( tc.new Runner() ).start(); } } How many Thread objects are created by the above program when it is compiled and run? 2 Assertions can be enabled or disabled on a class by class basis. Which interfaces does java.util.NavigableMap extend directly or indirectly? java.util.Map java.util.SortedMap Consider the following code: interface Classic { int version = 1; public void read() ; } class MediaReader implements Classic{ int version = 2; public void read() { //Insert code here } } public class ReaderTest{ public static void main(String[] args) { MediaReader mr = new MediaReader(); mr.read(); } } What can be inserted in the code above so that it will print 1 when run? System.out.println(((Classic)this).version); Which of these statements concerning maps are true? All keys in a map are unique. //OK The Map interface extends the Collection interface. // Not OK What will the following program print when compiled and run? class Boo implements Serializable { transient int ti = 10; static int si = 20; } public class TestClass { public static void main(String[] args) throws Exception { Boo boo = new Boo(); boo.si++; System.out.println(boo.ti+" "+boo.si); FileOutputStream fos = new FileOutputStream("c:\\temp\\boo.ser"); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(boo); os.close(); FileInputStream fis = new FileInputStream("c:\\temp\\boo.ser"); ObjectInputStream is = new ObjectInputStream(fis); boo = (Boo) is.readObject(); is.close(); System.out.println(boo.ti+" "+boo.si); } } 10 21 0 21 Remember that transient fields and static fields are never serialized. Constructor, instance blocks, and field initialization of the class being deserialized are also not invoked. So, when boo is deserialized, the value of ti is set to 0. The class Boo is loaded as soon as the code refers to the class (here, it happens at Boo boo = new Boo(); ), and so the static int si is initialized to the value given in the class code i.e. 20 and then it is incremented to 21 because of boo.si++;. This part has nothing to do with serialization. So when you deserialize an instance of Boo, Boo.si is not affected and is not reset to 20. Therefore, if you run the program again with just the deserialization part, you will see that si is 20 and not 21. Given: public class Book{ private int id; private String title; //constructors and accessors not shown } Assuming that book is a reference to a valid Book object, which of the following code fragments correctly prints the details of the Book? Consumer<Book> c = b>System.out.println(b.getId()+":"+b.getTitle()); c.accept(book); In which of the following scenarios will you need to create an abstract class? You want to define common method signatures in the class but force subclasses to provide implementations for such methods. Which of the following elements is/are a must in a stream pipeline? a source a terminal operation 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.) Object obj = rb.getObject("key1"); String[] vals = rb.getStringArray("key2"); What will the following code fragment print? Path p1 = Paths.get("c:\\personal\\.\\photos\\..\\readme.txt"); Path p2 = Paths.get("c:\\personal\\index.html"); Path p3 = p1.relativize(p2); System.out.println(p3); ..\..\..\..\index.html Observe that if you append this path to p1, you will get p2. Therefore, this is the right answer. p1 + ..\..\..\..\index.html =>c:\\personal\\.\\photos\\..\\readme.txt + ..\..\..\..\index.html =>c:\\personal\\.\\photos\\.. + ..\..\..\index.html =>c:\\personal\\.\\photos + ..\..\index.html =>c:\\personal\\. + ..\index.html =>c:\\personal + index.html =>c:\\personal\index.html A ".." implies parent folder, therefore imagine that you are taking off one ".." from the right side of the plus sign and removing the last name of the path on the left side of the plus sign. You are using a RDBMS database from a company named Fandu Tech. It provides a JDBC 4.0 compliant driver implementation in class com.fandu.sql.Driver. Which of the following lines of code is/are required to get the driver loaded? None of the above. In JDBC 4.0, the drivers are loaded automatically based on the information provided by the driver's METAINF/services/java.sql.Driver file. Therefore, no java code in necessary to load the driver classes. Consider the following code: class A { byte getStatusCode(Object obj) throws NullPointerException { if(obj != null ) return 128; else return -1; } } class B extends A { //override getStatusCode method. } Which of the following statements are valid? class A will not compile. because 128 does not fit into a byte. Write down the command line switch that allows you to enable assertions for the system level classes [i.e. the classes that come bundled with the JDK]. esa, -esa, …. Given: class Course{ private String id; private String name; public Course(String id, String name){ this.id = id; this.name = name; } //accessors not shows } What will the following code print? List<Course> cList = Arrays.asList( new Course("803", "OCAJP 7"), new Course("808", "OCAJP 8"), new Course("809", "OCPJP 8") ); cList.stream().filter(c->c.getName().indexOf("8")>-1) .map(c->c.getId()) .collect(Collectors.joining("1Z0-")); cList.stream().forEach(c->System.out.println(c.getId())); 803 808 809 What changes will you do to apply the Singleton pattern to the following class? public class SpeedSensor { public SpeedSensor(){ } public double getSpeed(){ //code to sense and return speed } } Make SpeedSensor constructor private. Add a static variable of type SpeedSensor and a static method that returns that variable. What will the following code print? Path p1 = Paths.get("\\photos\\vacation"); Path p2 = Paths.get("\\yellowstone"); System.out.println(p1.resolve(p2)+" "+p1.relativize(p2)); \yellowstone ..\..\yellowstone Consider the following code: class A { } public class TestClass { public class A { public void m() { } } class B extends A { } public static void main(String args[]) { new TestClass().new A() { public void m() { } }; } } class created inside the main method is final. Because it is anonymous. Anonymous classes are implicitly final. Objects of class B cannot be created inside the main method just by doing "new B()" A programmer is writing a small component that processes a file line by line. The following is the code : //import statements not shown public class LineByLineProcessor { public void processLines(String fullFilePath) throws Exception { // declare and initialize "handle" here String str = null; while( (str = handle.readLine()) != null) { System.out.println("Processing line : "+str); } handle.close(); } } Which of the given options will declare and initialize handle appropriately? BufferedReader handle = new BufferedReader(new FileReader(fullFilePath)); BufferedReader handle = new BufferedReader(new FileReader( new File(fullFilePath))); Which statements regarding the following program are correct? class A extends Thread { static protected int i = 0; public void run() { for(; i<5; i++) System.out.println("Hello"); } } public class TestClass extends A { public void run() { for(; i<5; i++) System.out.println("World"); } public static void main(String args []) { Thread t1 = new A(); Thread t2 = new TestClass(); t2.start(); t1.start(); } } None of these. Notice that i is a static variable and there are 2 threads that are accessing it. None of the threads has synchronized access to the variable. So there is no guarantee which thread will access it when. Further, one thread might increment i while another is executing i<5. So it is possible that more than 5 words may be printed. For example, lets say i is 0 and thread1 starts first loop. It will print Hello. Now, before thread1 could do i++, thread2 might run and it will print "World" while i is still 0. We have added a few more statements to the above program to illustrate the behavior: class A extends Thread { static protected int i = 0; public void run() { for(; i<5; i++) { System.out.println("Hello "+i); try{ Thread.sleep(100); }catch(Exception e){} } } } public class TestClass extends A { public void run() { for(; i<5; i++) { System.out.println("World "+i); try{ Thread.sleep(100); }catch(Exception e){} } } public static void main(String args []) { Thread t1 = new A(); Thread t2 = new TestClass(); t2.start(); t1.start(); } } It prints the following: C:\temp>java TestClass World 0 Hello 0 World 1 Hello 2 World 3 Hello 4 What will the following code print when compiled and run? IntStream is1 = IntStream.range(1, 3); IntStream is2 = IntStream.rangeClosed(1, 3); IntStream is3 = IntStream.concat(is1, is2); Object val = is3.boxed().collect(Collectors.groupingBy(k>k)).get(3); System.out.println(val); [3] it will group the elements into a Map<Integer, List<Integer>> containing: {1=[1, 1], 2=[2, 2], 3=[3]} Streams support aggregate operations. In which of the following situations will you use composition? When you are trying to reuse functionality from multiple classes and your class already extends from a framework class. What will the following code print? Duration d = Duration.ofMillis(1100); System.out.println(d); d = Duration.ofSeconds(61); System.out.println(d); PT1.1S PT1M1S Given the following class: class Counter { public int startHere = 1; public int endHere = 100; public static void main(String[] args) { new Counter().go(); } void go() { // A Thread t = new Thread(a); t.start(); } } What block of code can you place at line A above so that this program will count from startHere to endHere? A. Runnable a = new Runnable() { public void run() { for (int i = startHere; i <= endHere; i++){ System.out.println(i); } } }; B. a implements Runnable { public void run() { for (int i = startHere; i <= endHere; i++){ System.out.println(i); } } }; C. Thread a = new Thread() { public void run() { for (int i = startHere; i <= endHere; i++){ System.out.println(i); } } }; A C Which of the following illustrates a good coding practice given that the database connection is to be reused? try(Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("select * from STUDENT"); ) { while(rs.next()){ //do something with the row } } //OK try(Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("select * from STUDENT"); ) { while(rs.next()){ //do something with the row } } catch(SQLException e){ } // Not OK An empty catch block is not a good coding practice. Statement stmt = null; ResultSet rs = null; try{ stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("select * from STUDENT"); while(rs.next()){ //do something with the row } } finally{ rs.close(); stmt.close(); } While not an entirely bad practice, it has a minor issue. If rs.close() throws an exception, stmt.close() will not be invoked. It is therefore always a good idea to use the auto close feature of the try-with-resources statement, which does not have this drawback. Consider the following class: public class IntPair { private int a; private int b; public void setA(int i){ this.a = i; } public int getA(){ return this.a; } public void setB(int i){ this.b = i; } public int getB(int b){ return b; } public boolean equals(Object obj) { return ( obj instanceof IntPair && this.a == ((IntPair) obj).a && this.b == ((IntPair) obj).b ); } public int hashCode() { //1 } } Which of the following options would be valid at //1? return a; //Not OK return a*b; //Not OK return a+b; //Not OK return b; //Not OK All of the above are valid. //OK The following is a partial code listing from an application: rs.moveToInsertRow(); rs.updateString(1, "111"); rs.updateString(2, "Java in 24 hours"); //INSERT CODE HERE Assuming that rs is a valid reference to an updatable ResultSet and that the result set contains only two String columns, what can be inserted in the code so that a new row is inserted in the database? rs.insertRow(); Consider the following subclass definition: public class SubClass extends SuperClass { int i, j, k; public SubClass( int m, int n ) { i = m ; j = m ; //1 public SubClass( int m ) { super(m ); } //2 } } Which of the following constructors MUST exist in SuperClass for SubClass to compile correctly? public SuperClass(int a) public SuperClass() A programmer has written the following code to ensure that the phone number is not null and is of 10 characters: public void processPhoneNumber(String number) { assert number != null && number.length() == 10 : "Invalid phone number"; ... } Which of the given statements regarding the above code are correct? This code will not work in all situations. It will not work if assertions are disabled. The given code is syntactically correct. You have just written a Java class named AssertTest.java that uses the assertion facility. Write down the syntax for compiling this program using Javac. [Do not write the classpath or any other switches, just use the one/ones that is/are absolutely needed. Start with: javac ...] Javac –source 1.4 AssertTest.java Given: public class ThreadSafety{ List<Student> sList = new ArrayList<Student>(); public Student getStudent(){ Student s = sList.remove(0); return s; } ...other irrelevant code } If two threads, T1 and T2, concurrently execute getStudent() method on the same ThreadSafety instance, which of the following are possible outcomes? (Assume that there are no nulls in the list.) T1 gets a Student object and T2 gets IndexOutOfBoundsException. If there is only one object in the list, it is possible that T1 gets the object, and when T2 tries to call remove(0), it gets IndexOutOfBoundsException because the list is now empty. Observe that in this situation, this is expected behavior. The exception is not because of T1 and T2 stepping on each other (though that might occur as well). T1 and T2 get two different instances of Student objects. This is an error free situation when both the threads are interleaved such that they do not impact each other. T1 removes an object and then T2 removes another object from the list. So both get a different object and there is no exception. Observe that a thread unsafe code does not necessarily break all the time. It may break at any time. Given: Instant now = Instant.now(); Instant now2 = //INSERT CODE HERE System.out.println(now2); Which of the following options can be inserted in the above code without causing any compilation or runtime errors? now.truncatedTo(ChronoUnit.DAYS); 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; int x = operate(fo.apply(20)); //2 System.out.println(x); //1 } } 15 The lambda expression a->b->a-b looks complicated but it is actually simple if you group it like this: a->(b->a-b); 1. IntFunction is a functional interface that takes an int and returns whatever it is typed to. Here, the IntFunction is typed to IntUnaryOperator. Therefore, IntFunction<IntUnaryOperator> will take in an int and return IntUnaryOperator. The general form of a lambda expression that captures IntFunction would be x->line of code that returns the correct return type i.e. IntUnaryOperator, in this case; where x is an int. Now, if you look at fo = a->b->a-b;, a is the argument variable of type int (because it is being used to capture IntFunction) and b->a-b forms the method body of the IntFunction. b>a-b must somehow return an IntUnaryOperator for fo = a->b->a-b; to work. 2. IntUnaryOperator is a functional interface that takes in an int and returns another int. It cannot be typed to anything else because both the input and the output are already defined to be int. The general form of a lambda expression that captures IntUnaryOperator would be y->line of code that returns an int; where y is an int. Now, in the case of b->a-b; you can see that b is the argument variable and a-b is the method body. For a-b to capture IntUnaryOperator, a must already be defined and it must be an int. Only then will a-b return an int (which is required to capture IntUnaryOperator). That is indeed the case because a is already defined as the argument variable of the encompassing lambda expression and is available for use within the method body of that expression. 3. So basically, when you call fo.apply(20), you are setting a to 20. Therefore, fo.apply(20) returns an IntUnaryFunction that returns 20-b, where b is the argument passed to the IntUnaryFunction. When you call iuo.applyAsInt(5); b is being set to 5. Therefore iuo.applyAsInt(5) will return 20-5 i.e. 15. Determine the output of this program: public class Color { int red, green, blue; Color() { Color(10, 10, 10); } Color(int r, int g, int b) { red = r; green = g; blue = b; } void printColor() { System.out.println("red: " + red + " green: " + green + " blue: " + blue); } public static void main(String[] args) { Color color = new Color(); color.printColor(); } } => A. Compiler error: cannot find symbol The compiler looks for the method Color() when it reaches this statement: Color(10, 10, 10);. The right way to call another constructor is to use the this keyword as follows: this(10, 10, 10);. class Circle { private int xPos, yPos, radius; public Circle(int x, int y, int r) { xPos = x; yPos = y; radius = r; } public boolean equals(Object arg) { if (arg == null) return false; if (this == arg) return true; if (arg instanceof Circle) { Circle that = (Circle) arg; if ((this.xPos == that.xPos) && (this.yPos == that.yPos) && (this.radius == that.radius)) { return true; } } return false; } } class TestCircle { public static void main(String[] args) { Set<Circle> circleList = new HashSet<Circle>(); circleList.add(new Circle(10, 20, 5)); System.out.println(circleList.contains(new Circle(10, 20, 5))); } } => It prints false (not true)! Why? The Circle class overrides the equals() method, but it doesn? override the hashCode() method. public class Circle { // define Point as an inner class within Circle class class Point { private int xPos; private int yPos; // you can provide constructor for an inner class like this public Point(int x, int y) { xPos = x; yPos = y; } // the inner class is like any other class - you can override methods here public String toString() { return "(" + xPos + "," + yPos + ")"; } } // make use of the inner class for declaring a field private Point center; private int radius; public Circle(int x, int y, int r) { // note how to make use of the inner class to instantiate it center = this.new Point(x, y); radius = r; } } Non-static inner class can't have static members(instatnces or methods): public class Test { public static void main(String[] args) { } static class A{ static int a; public static void a(){ System.out.println("aaa"); } } class B{ static int a; // Not OK public static void a(){ // Not OK System.out.println("aaa"); } } } Did you notice another feature in the getDescriptiveColor() method? Its argument is declared final. Even if you don? provide the final keyword, the compiler will treat is as effectively final?hat it means is you cannot assign to the variable that you are accessing in the local class. If you do so, you will get a compiler error: abstract class Shape { public static class Color { int m_red, m_green, m_blue; public Color() { this(0, 0, 0); } public Color(int red, int green, int blue) { m_red = red; m_green = green; m_blue = blue; } public String toString() { return " red = " + m_red + " green = " + m_green + " blue = " + m_blue; } // other color members elided } // other Shape members elided } class StatusReporter { // important to note that the argument "color" is declared final static Shape.Color getDescriptiveColor(final Shape.Color color) { // local class DescriptiveColor that extends Shape.Color class class DescriptiveColor extends Shape.Color { public String toString() { return "You selected a color with RGB values" + color; } } return new DescriptiveColor(); } public static void main(String[] args) { Shape.Color descriptiveColor = StatusReporter.getDescriptiveColor(new Shape.Color(0, 0, 0)); System.out.println(descriptiveColor); } } => If change: static Shape.Color getDescriptiveColor(Shape.Color color) { // local class DescriptiveColor that extends Shape.Color class class DescriptiveColor extends Shape.Color { public String toString() { return "You selected a color with RGB values" + color; } } color = null; // note this assignment will NOT compile return new DescriptiveColor(); } You can create a non-static local class inside a body of code. Interfaces cannot create local interfaces. public interface Test{ public default void test(){ class A{ void a(){ System.out.println("ads"); } } } public static void test1(){ interface A{ void a(){ System.out.println("ads"); } } } } You can apply the valueOf() and name() methods to the enum element to return the name of the enum element. If you declare an enum within a class, then it is by default static. If enumeration constants are from two different enumerations, the equals() method does not return true: public class Test { enum A { PHONG, NGO } enum B { PHONG, CUA } public static void main(String[] args) { // System.out.println(A.PHONG == B.PHONG); System.out.println(A.PHONG.equals(B.PHONG)); } } => False The static values() method in the Enum class returns an array of the enumeration constants when called on an enumeration type. Enumeration constants cannot be cloned. An attempt to do so will result in a CloneNotSupportedException. You cannot qualify default methods as synchronized or final. Static methods must have a method body and they are qualified using the static keyword. You cannot provide abstract keyword for static methods: Remember that you cannot override static methods in derived classes, so it? conceptually not possible to leave static methods abstract by not providing a method body. You cannot use default keyword for static methods because all default methods are instance methods. Listing 3-9. Diamond.java interface Interface1 { default public void foo() { System.out.println("Interface1's foo"); } } interface Interface2 { default public void foo() { System.out.println("Interface2's foo"); } } public class Diamond implements Interface1, Interface2 { public static void main(String[] args) { new Diamond().foo(); } } Error:(9, 8) java: class Diamond inherits unrelated defaults for foo() from types Interface1 and Interface2 In this case, resolve the conflict manually by using the super keyword within the Diamond class to explicitly mention which method definition to use: public void foo() { Interface1.super.foo(); } After this method definition is added in the Diamond class and executed, this program prints: Interface1's foo Listing 3-10. Diamond.java class BaseClass { public void foo() { System.out.println("BaseClass's foo"); } } interface BaseInterface { default public void foo() { System.out.println("BaseInterface's foo"); } } public class Diamond extends BaseClass implements BaseInterface { public static void main(String[] args) { new Diamond().foo(); } } => No compiler error in this case: the compiler resolves to the definition in the class and the interface definition is ignored. This program prints ?ase foo This can be considered as ?lass winsrule. For example, consider the Comparator interface that declares two abstract methods: @FunctionalInterface public interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); // other methods are default methods or static methods and are elided } This interface is a functional interface though it declares two abstract methods: compare() and equals() methods. How is it a functional interface when it has two abstract methods? Because equals() method signature matches from Object, and the compare() method is the only remaining abstract method, and hence the Comparator interface is a functional interface. How about this interface definition? @FunctionalInterface interface EqualsInterface { boolean equals(Object obj); } The compiler gives the error: “EqualsInterface is not a functional interface: no abstract method found in interface EqualsInterface Why? Since the method equals is from Object, it is not considered as a functional interface. class Shape { public Shape() { System.out.println("Shape constructor"); } public class Color { public Color() { System.out.println("Color constructor"); } } } class TestColor { public static void main(String[] args) { Shape.Color black = new Shape().Color(); // #1 } } => Compiler error: the method Color() is undefined for the type Shape You cannot instantiate an enum type using new. interface BaseInterface { default void foo() { System.out.println("BaseInterface's foo"); } } interface DerivedInterface extends BaseInterface { default void foo() { System.out.println("DerivedInterface's foo"); } } interface AnotherInterface { public static void foo() { System.out.println("AnotherInterface's foo"); } } public class MultipleInheritance implements DerivedInterface, AnotherInterface { public static void main(String[] args) { new MultipleInheritance().foo(); } } => C. The program prints: DerivedInterface? foo A default method can be overridden. Since DerivedInterface extends BaseInterface, the default method definition for foo is overridden in the DerivedInterface. Static methods do not cause conflicting definition of foo since they are not overridden, and they are accessed using the interface name, as in AnotherInterface.foo. Hence, the program compiles without errors. In the main method within MultipleInheritance class, the overridden foo method is invoked and hence the call resolves to foo method defined in DerivedInterface. public static void main(String[] args) { List list = new LinkedList(); list.add("First"); list.add("Second"); List<String> strList = list; // #1 for (Iterator<String> itemItr = strList.iterator(); itemItr.hasNext();) System.out.println("Item: " + itemItr.next()); List<String> strList2 = new LinkedList<>(); strList2.add("First"); strList2.add("Second"); List list2 = strList2; // #2 for (Iterator<String> itemItr = list2.iterator(); itemItr.hasNext();) System.out.println("Item: " + itemItr.next()); } => Item: First Item: Second Item: First Item: Second class Utilities { public static <T> void fill(List<T> list, T val) { for (int i = 0; i < list.size(); i++) list.set(i, val); } } class UtilitiesTest { public static void main(String[] args) { List<Integer> intList = new ArrayList<Integer>(); intList.add(10); intList.add(20); System.out.println("The original list is: " + intList); Utilities.fill(intList, 100); System.out.println("The list after calling Utilities.fill() is: " + intList); } } => The original list is: [10, 20] The list after calling Utilities.fill() is: [100, 100] public static void main(String[] args) { List<Number> intList = new ArrayList<>(); intList.add(new Integer(10)); // okay intList.add(new Float(10.4f)); // oops! System.out.println(intList); } => [10, 10.4] List<?> wildCardList = new ArrayList<Integer>(); //OK List<Object> numList = new ArrayList<Integer>(); // Not compile class WildCardUse { static void printList(List<?> list){ for(Object element: list) System.out.println("[" + element + "]"); } public static void main(String []args) { List<Integer> list = new ArrayList<>(); list.add(10); list.add(100); printList(list); List<String> strList = new ArrayList<>(); strList.add("10"); strList.add("100"); printList(strList); } } You can declare instance fields of type T, but not of static fields of type T. For example, class X<T> { T instanceMem; // okay static T statMem; // wrong usage - compiler error } It is not possible to have generic exception classes; as a result, the following will not compile: class GenericException<T> extends Throwable { } // wrong usage - compiler error // This program shows the usage of Iterator class TestIterator { public static void main(String[] args) { ArrayList<Integer> nums = new ArrayList<Integer>(); for (int i = 1; i < 10; i++) nums.add(i); System.out.println("Original list " + nums); Iterator<Integer> numsIter = nums.iterator(); while (numsIter.hasNext()) { numsIter.remove(); } System.out.println("List after removing all elements" + nums); } } => It prints the following: Original list [1, 2, 3, 4, 5, 6, 7, 8, 9] Exception in thread "main" java.lang.IllegalStateException at java.util.AbstractList$Itr.remove(AbstractList.java:356) at TestIterator.main(Main.java:12) Oops! What happened? The problem is that you haven? called next() before calling remove(). Checking hasNext() in the while loop condition, moving to the element using next(), and calling remove() is the correct idiom for removing an element. If you don? follow it correctly, you can get into trouble (i.e., you?l get IllegalStateException). Similarly, if you call remove() twice without sandwiching a next() between the statements, you?l get this exception. Let? fix this program by calling next() before calling remove(). Here is the relevant part of the code: Iterator<Integer> numsIter = nums.iterator(); while(numsIter.hasNext()) { numsIter.next(); numsIter.remove(); } System.out.println("List after removing all elements " + nums); It prints the list with no elements, as expected: List after removing all elements [] public static void main(String []args) { Double [] temperatureArray = {31.1, 30.0, 32.5, 34.9, 33.7, 27.8}; System.out.println("The original array is: " + Arrays.toString(temperatureArray)); List<Double> temperatureList = Arrays.asList(temperatureArray); temperatureList.set(0, 35.2); System.out.println("The modified array is: " + Arrays.toString(temperatureArray)); } => The original array is: [31.1, 30.0, 32.5, 34.9, 33.7, 27.8] The modified array is: [35.2, 30.0, 32.5, 34.9, 33.7, 27.8] The NavigableMap interface extends the SortedMap interface. The TreeMap class is the widely used class that implements NavigableMap. public class NavigableMapTest { public static void main(String[] args) { NavigableMap<Integer, String> examScores = new TreeMap<Integer, String>(); examScores.put(90, "Sophia"); examScores.put(20, "Isabella"); examScores.put(10, "Emma"); examScores.put(50, "Olivea"); System.out.println("The data in the map is: " + examScores); System.out.println("The data descending order is: " + examScores.descendingMap()); System.out.println("Details of those who passed the exam: " + examScores.tailMap(40)); System.out.println("The lowest mark is: " + examScores.firstEntry()); } } => It prints the following: The data in the map is: {10=Emma, 20=Isabella, 50=Olivea, 90=Sophia} The data descending order is: {90=Sophia, 50=Olivea, 20=Isabella, 10=Emma} Details of those who passed the exam: {50=Olivea, 90=Sophia} The lowest mark is: 10=Emma The Comparable interface has only one method compareTo(), which is declared as follows: int compareTo(Element that) Since you are implementing the compareTo() method in a class, you have this reference available. You can compare the current element with the passed Element and return an int value. What should the int value be? Well, here are the rules for returning the integer value: return 1 if current object > passed object return 0 if current object == passed object return -1 if current object < passed object class Student implements Comparable<Student> { String id; String name; Double cgpa; public Student(String studentId, String studentName, double studentCGPA) { id = studentId; name = studentName; cgpa = studentCGPA; } public String toString() { return " \n " + id + " \t " + name + " \t " + cgpa; } public int compareTo(Student that) { return this.id.compareTo(that.id); } } class ComparatorTest1 { public static void main(String[] args) { Student[] students = {new Student("cs011", "Lennon ", 3.1), new Student("cs021", "McCartney", 3.4), new Student("cs012", "Harrison ", 2.7), new Student("cs022", "Starr ", 3.7)}; System.out.println("Before sorting by student ID"); System.out.println("Student-ID \t Name \t CGPA (for 4.0) "); System.out.println(Arrays.toString(students)); Arrays.sort(students); System.out.println("After sorting by student ID"); System.out.println("Student-ID \t Name \t CGPA (for 4.0) "); System.out.println(Arrays.toString(students)); } } class CGPAComparator implements Comparator<Student> { public int compare(Student s1, Student s2) { return (s1.cgpa.compareTo(s2.cgpa)); } } class ComparatorTest2 { public static void main(String[] args) { Student[] students = {new Student("cs011", "Lennon ", 3.1), new Student("cs021", "McCartney", 3.4), new Student("cs012", "Harrison ", 2.7), new Student("cs022", "Starr ", 3.7)}; System.out.println("Before sorting by CGPA "); System.out.println("Student-ID \t Name \t CGPA (for 4.0) "); System.out.println(Arrays.toString(students)); Arrays.sort(students, new CGPAComparator()); System.out.println("After sorting by CGPA"); System.out.println("Student-ID \t Name \t CGPA (for 4.0) "); System.out.println(Arrays.toString(students)); } } Most classes have a natural order for comparing objects, so use Comparable interface in those cases. If you want to compare the objects other than the natural order or if there is no natural ordering present for your class type, then use the Comparator interface. Note that he List interface extends Iterable interface that has a default forEach method (this method was added in Java 8): public static void main(String []args) { List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); strings.forEach(string -> System.out.println(string)); } The Stream interface is the most important interface provided in the java.util.stream package. Stream operations can be ?hainedtogether to form a ?tream pipeline There are three parts in the stream pipeline (see Figure 4-2): Source: Create a stream (from a collection or an array or using Stream methods such as of() and generate()). Intermediate operations: Optional operations that can be chained together (such as map(), filter(), distinct(), and sorted() methods in the Stream interface). Terminal operations: Produce a result (such as sum(), collect(), forEach(), and reduce() methods in the Stream interface). Method[] objectMethods = Object.class.getMethods(); Stream<Method> objectMethodStream = Arrays.stream(objectMethods); IntStream.iterate(1, i -> i + 1).limit(5) // 1->5 We can also create streams using factories and builders. The of() method is a factory method in the Stream interface: Stream.of(1, 2, 3, 4, 5) Stream.of(new Integer[]{1, 2, 3, 4, 5}) Stream.builder().add(1).add(2).add(3).add(4).add(5).build(); The java.nio.file.Files class has lines() method that returns a Stream<String>. This code prints the contents of the file “FileRead.javain the current directory. Files.lines(Paths.get("./FileRead.java")).forEach(System.out::println); Here are some quick one-liners on how to use them. 1. The java.nio.file.Files class has lines() method that returns a Stream<String>. This code prints the contents of the file “FileRead.javain the current directory. Files.lines(Paths.get("./FileRead.java")).forEach(System.out::println); 2. The java.util.Pattern class has splitAsStream() method that returns a Stream<String>. This code splits the input string ?ava 8 streamsbased on whitespace and hence prints the strings ?ava and ?treamson the console. Pattern.compile(" ").splitAsStream("java 8 streams").forEach (System.out::println); 3. The java.util.Random class has ints() method that returns an IntStream. It generates an infinite stream of random integers; so to restrict the number of integers to 5 integers, we call limit(5) on that stream. new Random().ints().limit(5).forEach(System.out::println); 4. The String class has chars() method (newly introduced in Java 8 in CharSequence?n interface that String class implements). This method returns an IntStream (why IntStream? Remember that there is no equivalent char specialization for Streams). This code calls sorted() method on this stream, so the stream elements get sorted in ascending order. Because it is a stream of integers, this code uses "%c" to explicitly force the conversion from int to char. "hello".chars().sorted().forEach(ch -> System.out.printf("%c ", ch)); // prints e h l l o Stream.of(1, 2, 3) .peek(i -> System.out.printf("%d ", i)) .map(i -> i * i) .peek(i -> System.out.printf("%d ", i)) .count(); => This code prints: 1 1 2 4 3 9 Stream.of(1, 2, 3).parallel() .peek(i -> System.out.printf("%d ", i)) .map(i -> i * i) .peek(i -> System.out.printf("%d ", i)) .count(); => 2 4 3 9 1 1 There are many important terminal operations such as reduce(), collect(), findFirst(), findAny(), anyMatch(), allMatch(), and noneMatch() methods. We discuss these methods (and also the Optional<T> mentioned in this table) later in Chapter 6 on Stream API. Further, the IntStream, LongStream, and DoubleStream have methods such as sum(), min(), max(), and average() that operate on the stream of ints, longs, and doubles respectively. Object [] words = Pattern.compile(" ").splitAsStream("1 2 3 4 5").toArray(); System.out.println(Arrays.stream(words).mapToInt(str -> Integer.valueOf((String)str)).sum()); This program prints: 15 class UtilitiesTest { public static void main(String[] args) { List<Integer> intList = new LinkedList<>(); List<Double> dblList = new LinkedList<>(); System.out.println("First type: " + intList.getClass()); System.out.println("Second type:" + dblList.getClass()); } } => It prints the following: First type: class java.util.LinkedList Second type:class java.util.LinkedList Due to type erasure, after compilation both types are treated as same LinkedList type. Determine the behavior of this program: class LastError<T> { private T lastError; void setError(T t) { lastError = t; System.out.println("LastError: setError"); } } class StrLastError<S extends CharSequence> extends LastError<String> { public StrLastError(S s) {} void setError(S s) { System.out.println("StrLastError: setError"); } } class Test { public static void main(String []args) { StrLastError<String> err = new StrLastError<String>("Error"); err.setError("Last error"); } => It results in a compilation error It looks like the setError() method in StrLastError is overriding setError() in the LastError class. However, it is not the case. At the time of compilation, the knowledge of type S is not available. Therefore, the compiler records the signatures of these two methods as setError(String) in superclass and setError(S_extends_ CharSequence) in subclass—treating them as overloaded methods (not overridden). In this case, when the call to setError() is found, the compiler finds both the overloaded methods matching, resulting in the ambiguous method call error. Here is the error message Test.java:22: error: reference to setError is ambiguous, both method setError(T) in LastError and method setError(S) in StrLastError match err.setError("Last error"); ^ where T and S are type-variables: T extends Object declared in class LastError. S extends CharSequence declared in class StrLastError. functional interfaces defined in the java.util.function package based on your need. This functional interface also defines default methods named and() and or() that take a Predicate and return a Predicate. These methods have behavior similar to && and || operators. The method negate() returns a Predicate, and its behavior is similar to the ! operator. How are they useful? Here is a program that illustrates the use of and() method in Predicate interface (Listing 5-1). public class PredicateTest { public static void main(String[] args) { Predicate<String> nullCheck = arg -> arg != null; Predicate<String> emptyCheck = arg -> arg.length() > 0; Predicate<String> nullAndEmptyCheck = nullCheck.and(emptyCheck); String helloStr = "hello"; System.out.println(nullAndEmptyCheck.test(helloStr)); String nullStr = null; System.out.println(nullAndEmptyCheck.test(nullStr)); } } => true false public class RemoveIfMethod { public static void main(String[] args) { List<String> greeting = new ArrayList<>(); greeting.add("hello"); greeting.add("world"); greeting.removeIf(str -> !str.startsWith("h")); greeting.forEach(System.out::println); } } => It prints “hello” in the console it is possible, and here is the changed code: greeting.removeIf(((Predicate<String>) str -> str.startsWith("h")).negate()); A Consumer<T> “consumes” something: it takes an argument (of generic type T) and returns nothing (void). You can call accept() method on a Consumer object. Here is an example that uses the Consumer interface: Consumer<String> printUpperCase = str -> System.out.println(str.toUpperCase()); printUpperCase.accept("hello"); // prints: HELLO In this code, the lambda Function<String, Integer> strLength = str -> str.length(); System.out.println(strLength.apply("supercalifragilisticexpialidocious")); // prints: 34 The identity() function in Function just returns the passed argument without doing anything! Then what is its use? It is sometimes used for testing – when you write a piece of code that takes a Function and want to check if it works, you can call identity() because it doesn’t do anything. Here is an example: Arrays.stream("4, -9, 16".split(", ")) .map(Function.identity()) .forEach(System.out::println); In this code, the map(Function.identity()) does nothing; it just passes along the elements in the stream to the call forEach(System.out::println). Hence the code prints the elements as they are, i.e., the values 4, -9, and 16 in separate lines. class GenerateBooleans { public static void main(String[] args) { Random random = new Random(); Stream.generate(random::nextBoolean).limit(2).forEach(System.out::println); } } This program randomly prints two boolean values, for example, “true” and “false”. The generate() method in Stream interface is a static member that takes a Supplier as the argument: static <T> Stream<T> generate(Supplier<T> s) Here is a simple example that returns a value without taking anything as input: Supplier<String> currentDateTime = () -> LocalDateTime.now().toString(); System.out.println(currentDateTime.get()); Function<String, Integer> anotherInteger = Integer::new; System.out.println(anotherInteger.apply("100")); // this code prints: 100 ToIntFunction<T> int applyAsInt(T value) Operates on the passed generic type argument T and returns an int value ToLongFunction<T> long applyAsLong(T value) Operates on the passed generic type argument T and returns a long value ToDoubleFunction<T> double applyAsDouble(T value) Operates on the passed generic type argument T and returns an double value IntToLongFunction long applyAsLong(int value) Operates on the passed int type argument and returns a long value IntToDoubleFunction double applyAsDouble(int value) Operates on the passed int type argument and returns a double value LongToIntFunction int applyAsInt(long value) Operates on the passed long type argument and returns an int value LongToDoubleFunction double applyAsLong(long value) Operates on the passed long type argument and returns a double value DoubleToIntFunction int applyAsInt(double value) Operates on the passed double type argument and returns an int value DoubleToLongFunction long applyAsLong(double value) Operates on the passed double type argument and returns a long value IntConsumer void accept(int value) Operates on the given int argument and returns nothing LongConsumer void accept(long value) Operates on the given long argument and returns nothing DoubleConsumer void accept(double value) Operates on the given double argument and returns nothing ObjIntConsumer<T> void accept(T t, int value) Operates on the given generic type argument T and int arguments and returns nothing ObjLongConsumer<T> void accept(T t, long value) Operates on the given generic type argument T and long arguments and returns nothing ObjDoubleConsumer<T> void accept(T t, double value) Operates on the given generic type argument T and double arguments and returns nothing BooleanSupplier boolean getAsBoolean() Takes no arguments and returns a boolean value IntSupplier int getAsInt() Takes no arguments and returns an int value LongSupplier long getAsLong() Takes no arguments and returns a long value DoubleSupplier double getAsDouble() Takes no arguments and returns a double value BiPredicate<T, U> boolean test(T t, U u) Checks if the arguments match the condition and returns a boolean value as result BiConsumer<T, U> void accept(T t, U u) Operation that consumes two arguments but returns nothing BiFunction<T, U, R> R apply(T t, U u) Function that takes two argument and returns a result BiFunction<String, String, String> concatStr = (x, y) -> x + y; System.out.println(concatStr.apply("hello ", "world")); // prints: hello world In this example, the arguments and return type are same type, but they can be different, as in: BiFunction<Double, Double, Integer> compareDoubles = Double::compare; System.out.println(compareDoubles.apply(10.0, 10.0)); // prints: 0 BiPredicate<List<Integer>, Integer> listContains = List::contains; List aList = Arrays.asList(10, 20, 30); System.out.println(listContains.test(aList, 20)); // prints: true BiConsumer<List<Integer>, Integer> listAddElement = List::add; List aList = new ArrayList(); listAddElement.accept(aList, 10); System.out.println(aList); // prints: [10] Consider the following example. List<Integer> ell = Arrays.asList(-11, 22, 33, -44, 55); System.out.println("Before: " + ell); ell.replaceAll(Math::abs); System.out.println("After: " + ell); This code prints: Before: [-11, 22, 33, -44, 55] After: [11, 22, 33, 44, 55] This code uses replaceAll() method introduced in Java 8 that replaces the elements in the given List. The replaceAll() method takes a UnaryOperator as the sole argument: void replaceAll(UnaryOperator<T> operator) The replaceAll() method is passed with Math::abs method to it. Math has four overloaded methods for abs() method: abs(int) abs(long) abs(double) abs(float) Because the type is Integer, the overloaded method abs(int) is selected through type inference. UnaryOperator is a functional interface and it extends Function interface, and you can use the apply() method declared in the Function interface; further, it inherits the default functions compose() and andThen() from the Function interface. Similar to UnaryOperator that extends Function interface, there is a BinaryOperator that extends BiFunction interface. Primitive types versions of UnaryOperator interface IntUnaryOperator, LongUnaryOperator, and DoubleUnaryOperator are also provided as part of the java.util.function package. the interface java.util.stream.Stream<T>is not a functional interface–it has numerous abstract methods public class PredicateTest { public static void main(String []args) { Predicate<String> notNull = ((Predicate<String>)(arg -> arg == null)).negate(); // #1 System.out.println(notNull.test(null)); } } Print: False public class AndThen { public static void main(String []args) { Function<Integer, Integer> negate = (i -> -i), square = (i -> i * i), negateSquare = negate.compose(square); System.out.println(negateSquare.apply(10)); } } Print : -100. the negate.compose(square)calls square before calling negate. hence, for the given value 10, square results in 100, and when negated, it becomes -100. class ConsumerUse { public static void main(String []args) { ObjIntConsumer<String> charAt = (str, i) -> str.charAt(i); // #1 System.out.println(charAt.accept("java", 2)); // #2 } } this program results in a compiler error for the line marked with comment #2 ObjIntConsumeroperates on the given Stringargument strand intargument i and returns nothing. though the charAtmethod is declared to return the charat given index i, the acceptmethod in ObjIntConsumerhas return type void. since System. out.printlnexpects an argument to be passed, the call charAt.accept("java", 2) results in a compiler error because accept()method returns void. Optional<T> findFirst() Returns the first element from the stream; if there is no element present in the stream, it returns an empty Optional<T>object. Optional<T> findAny() Returns one of the elements from the stream; if there is no element present in the stream, it returns an empty Optional<T>object. Unlike the anymatch( ) method that returns false when the stream is empty, the allmatch( ) and nonematch( ) methods return true if the stream is empty! public static void main(String []args) { OptionalDouble temperature = DoubleStream.of(-10.1, -5.4, 6.0, -3.4, 8.9, 2.2) .filter(temp -> temp > 0).findFirst(); System.out.println("First matching temperature > 0 is " + temperature.getAsDouble()); } public static void selectHighestTemperature(Stream<Double> temperatures) { System.out.println(temperatures.max(Double::compareTo)); } Here is a call to this method: selectHighestTemperature(Stream.of(24.5, 23.6, 27.9, 21.1, 23.5, 25.5, 28.3)); This code prints: Optional[28.3] public static void selectHighestTemperature(Stream<Double> temperatures) { Optional<Double> max = temperatures.max(Double::compareTo); if(max.isPresent()) { // Line 1 System.out.println(max.get()); //Line 2 } //Line 3 } We can change line 1, 2,3 to: max.ifPresent(System.out::println); //OK: System.out::println is a Consumer. But not: max.ifPresent(System.out.println(max)); // Not compile: System.out.println is a void method, not Consumer => Not compile. There are many ways to create Optionalobjects. One way to create Optionalobjects is to use factory methods in Optionalclass, as in: Optional<String> empty = Optional.empty(); You can also use of()in Optionalclass: Optional<String> nonEmptyOptional = Optional.of("abracadabra"); However, you cannot pass nullto Optional.of()method, as in: Optional<String> nullStr = Optional.of(null); System.out.println(nullStr); // crashes with a NullPointerException This will result in throwing a NullPointerException. If you want to create an Optionalobject that has nullvalue, then you can instead use ofNullable()method: Optional<String> nullableStr = Optional.ofNullable(null); System.out.println(nullableStr); // prints: Optional.empty You can use orElse()or orElseThrow()methods, when these operations fail (i.e., the underlying Optionalhas a null value), as in: Optional<String> string = Optional.ofNullable(null); System.out.println(string.map(String::length).orElse(-1)); // The method orElse(Integer) This code prints -1 because the variable stringis an Optionalvariable that holds nulland hence the orElse()method executes and returns -1. Alternatively, you can throw an exception using the orElseThrow()method: Optional<String> string = Optional.ofNullable(null); System.out.println(string.map(String::length).orElseThrow(IllegalArgumentException::new)); Optional<String> string = Optional.ofNullable(null); System.out.println(string.map(String::length).orElseThrow(Exception::new));//Not compile Need try/catch or add throws declaration Optional<String> string = Optional.ofNullable(null); System.out.println(string.map(String::length).orElseThrow(NullPointerException::new)); //OK System.out.println(string.map(String::length).orElseThrow(ArrayIndexOutOfBoundsException::new)); //OK It is better to use DoubleStream and OptionalDouble, which are primitive type versions for double for Stream<T>and Optional<T>respectively. (The other two primitive type versions available are for int and long, named as OptionalIntand OptionalLongrespectively.) Stream<Integer> stream = Stream.of(1, 2, 3, 4); IntStream intStream = IntStream.of(9, 3, 4, 5, 6); System.out.println(stream.max()); // Compile failed System.out.println(intStream.max()); //OK public static void selectHighestTemperature(DoubleStream temperatures) { OptionalDouble max = temperatures.max(); max.ifPresent(System.out::println); } When invoked with the following call, selectHighestTemperature(DoubleStream.of(24.5, 23.6, 27.9, 21.1, 23.5, 25.5, 28.3)); We get the maximum value correctly printed on the console: 28.3 String[] string = "you never know what you have until you clean your room".split(" "); System.out.println(Arrays.stream(string).min(String::compareTo).get()); This program prints: clean Comparator<String> lengthCompare = (str1, str2) -> str1.length() - str2.length(); System.out.println(Arrays.stream(string).min(lengthCompare).get()); Important Data and Calculation Methods in IntStream, LongStream and DoubleStream Interfaces: int sum(): Returns the sum of elements in the stream; 0 in case the stream is empty. long count(): Returns the number of elements in the stream; 0 if the stream is empty. OptionalDouble average(): Returns the average value of the elements in the stream; an empty OptionalDouble value in case the stream is empty. OptionalInt min(): Returns the minimum integer value in the stream; an empty OptionalInt value in case the stream is empty. OptionalInt max(): Returns the maximum integer value in the stream; an empty OptionalInt value in case the stream is empty. IntSummaryStatistics summaryStatistics(): Returns an IntSummaryStatisticsobject that has sum, count, average, min, and maxvalues. IntStream intStream = IntStream.of(9, 3, 4, 5, 6); System.out.println(intStream.summaryStatistics().getAverage()); 5.4 String limerick = "There was a young lady named Bright " + "who traveled much faster than light " + "She set out one day " + "in a relative way " + "and came back the previous night "; IntSummaryStatistics wordStatistics = Pattern.compile(" ") .splitAsStream(limerick) .mapToInt(word -> word.length()) .summaryStatistics(); the mapToInt()method that returns an IntStream Stream<Integer> stream = Stream.of(1, 2, 3, 4); IntStream intStream = IntStream.of(9, 3, 4, 5, 6); System.out.println(stream.sum()); // Not compile System.out.println(intStream.sum()); //OK BinaryOperator<Integer> binOp = (x, y) -> x + y; BiFunction<Integer, Integer, Integer> biFunc = (x, y) -> x + y; System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(binOp)); //OK System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(0, binOp)); //OK System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(Integer::sum)); //OK System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(0, Integer::sum)); //OK System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(0, biFunc, Integer::sum)); //OK System.out.println(IntStream.of(1, 2, 3, 4, 5).reduce(binOp));//Not compile:need a IntBinaryOperator System.out.println(IntStream.of(1, 2, 3, 4, 5).reduce(0, binOp));//Not compile:need a IntBinaryOperator System.out.println(IntStream.of(1, 2, 3, 4, 5).reduce(Integer::sum)); //OK System.out.println(IntStream.of(1, 2, 3, 4, 5).reduce(0, Integer::sum)); //OK System.out.println(IntStream.of(1, 2, 3, 4, 5).reduce((x, y) -> x + y)); //OK System.out.println(IntStream.of(1, 2, 3, 4, 5).reduce(0, (x, y) -> x + y)); //OK Optional[15] 15 Optional[15] 15 15 OptionalInt[15] 15 OptionalInt[15] 15 In fact, the sum()method of IntStreamis internally implemented by calling reduce()method (in IntPipelineclass): @Override public final int sum() { return reduce(0, Integer::sum); } Stream<T> sorted(Comparator<? super T> comparator) List words = Arrays.asList("follow your heart but take your brain with you".split(" ")); Comparator<String> lengthCompare = (str1, str2) -> str1.length() - str2.length(); words.stream().distinct().sorted(lengthCompare).forEach(System.out::println); List words = Arrays.asList("follow your heart but take your brain with you".split(" ")); Comparator<String> lengthCompare = (str1, str2) -> str1.length() - str2.length(); words.stream().distinct().sorted(lengthCompare.thenComparing(String::compareTo)) .forEach(System.out::println); Map<String, Integer> nameLength = Stream.of("Arnold", "Alois", "Schwarzenegger") .collect(Collectors.toMap(name -> name, name -> name.length())); //OK Or: Map<String, Integer> nameLength = Stream.of("Arnold", "Alois", "Schwarzenegger") .collect(Collectors.toMap(Function.identity(), name -> name.length())); //OK String []string= "you never know what you have until you clean your room".split(" "); Arrays.stream(string).flatMap(word -> Arrays.stream(word.split(""))) .distinct() .forEach(System.out::print); List<List<Integer>> intsOfInts = Arrays.asList(Arrays.asList(1, 3, 5), Arrays.asList(2, 4)); intsOfInts.stream().flatMap(ints -> ints.stream()).sorted() .map(i -> i * i) .forEach(System.out::println); It also prints the squares of the values 1 to 5. public static void main(String []args) { IntStream temperatures = IntStream.of(-5, -6, -7, -5, 2, -8, -9); IntPredicate positiveTemperature = temp -> temp > 0; // #1 if(temperatures.anyMatch(positiveTemperature)) { // #2 int temp = temperatures .filter(positiveTemperature) .findAny() .getAsInt(); // #3 System.out.println(temp); } } Print: younevrkwhatilcm java.lang.IllegalStateException: stream has already been operated upon or closed public static void main(String []args) { boolean result = Stream.of("do", "re", "mi", "fa", "so", "la", "ti") .filter(str -> str.length() > 5) // #1 .peek(System.out::println) // #2 .allMatch(str -> str.length() > 5); // #3 System.out.println(result); } this program prints: true the predicate str -> str.length() > 5returns falsefor all the elements because the length of each string is 2. hence, the filter()method results in an empty stream and the peek()method does not print anything. the allMatch()method returns truefor an empty stream and does not evalute the given predicate. hence this program prints true. Stream<String> words = Pattern.compile(" ").splitAsStream("a bb ccc"); System.out.println(words.map(word -> word.length()).sum()); Compiler error: Cannot find symbol “sum” in interface Stream<Integer> public static void main(String args[]) { maxMarks(IntStream.of(52,60,99,80,76)); // #1 } public static void maxMarks(IntStream marks) { OptionalInt max = marks.max(); // #2 if(max.ifPresent()) { // #3 System.out.print(max.getAsInt()); } public static void main(String args[]){ Stream.of("eeny ","meeny ",null).forEach(StringToUpper::toUpper); } private static void toUpper(String str) { Optional <String> string = Optional.ofNullable(str); System.out.print(string.map(String::toUpperCase).orElse("dummy")); } this program prints: eeNY meeNY dummy// OK this program prints: Optional[eeNY] Optional[meeNY] Optional[dummy] // Bad String integerStr = "100"; Scanner consoleScanner = new Scanner(integerStr); System.out.println(consoleScanner.nextInt()); this program results in a compiler error in line marked with comment #3 If the method isPresent()were used instead of ifPresent()in this program, it will compile cleanly and print 99 on the console. 100 String integerStr = "ten"; // Line1 Scanner consoleScanner = new Scanner(integerStr); try{ System.out.println(consoleScanner.nextInt()); } catch (InputMismatchException ex){ System.out.println("EERROR"); } ERROR. If change line 1 become “” : program will throw: java.util.NoSuchElementException NoSuchElementExceptionis the base class of InputMismatchException Note how you combine the catch handlers together using the | (OR)operator here (the same operator you use for performing bit-wise ORoperation on integral values) for combining the catch clauses of NoSuchElementExceptionand IllegalStateException. Unlike the combined catch clauses for NoSuchElementExceptionand IllegalStateException, you cannot combine the catch clauses of NoSuchElementExceptionand InputMismatchException. As we’ve already discussed, NoSuchElementExceptionis the base class of InputMismatchException, and you cannot catch both of them in the multi-catch block. If you try compiling such a multicatch clause, you’ll get this compiler error: ScanInt5.java:11: error: Alternatives in a multi-catch statement cannot be related by subclassing } catch(InputMismatchException | NoSuchElementException exception) { // class ZipTextFile takes the name of a text file as input and creates a zip file // after compressing that text file. class ZipTextFile { public static final int CHUNK = 1024; // to help copy chunks of 1KB public static void main(String []args) { if(args.length == 0) { System.out.println("Pass the name of the file in the current directory to be zipped as an argument"); System.exit(-1); } String fileName = args[0]; // name of the zip file is the input file name with the suffix ".zip" String zipFileName = fileName + ".zip"; byte [] buffer = new byte[CHUNK]; // these constructors can throw FileNotFoundException try (ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(zipFileName)); FileInputStream fileIn = new FileInputStream(fileName)) { // putNextEntry can throw IOException zipFile.putNextEntry(new ZipEntry(fileName)); int lenRead = 0; // variable to keep track of number of bytes // successfully read // copy the contents of the input file into the zip file while((lenRead = fileIn.read(buffer)) > 0) { // both read and write methods can throw IOException zipFile.write (buffer, 0, lenRead); } // the streams will be closed automatically because they are // within try-with-resources statement } // this can result in multiple exceptions thrown from the try block; // use "suppressed exceptions" to get the exceptions that were suppressed! catch(Exception e) { System.out.println("The caught exception is: " + e); System.out.print("The suppressed exceptions are: "); for(Throwable suppressed : e.getSuppressed()) { System.out.println(suppressed); } } } } assert (i >= 0) : "impossible: i is negative!"; The program will run fine if the Boolean expression (i >= 0) evaluates to true. However, if it evaluates to false, the program will crash by throwing an AssertionError. public static void foo() { try { throw new ArrayIndexOutOfBoundsException(); } catch (ArrayIndexOutOfBoundsException oob) { RuntimeException re = new RuntimeException(); // Line 1 re.initCause(oob); throw re; } } public static void main(String[] args) { try { foo(); } catch (Exception re) { System.out.println(re.getClass()); } } Print: class java.lang.RuntimeException If change line 1 with: RuntimeException re = new RuntimeException(oob); Print: class java.lang.IllegalStateException in the expression new RuntimeException(oob);, the exception object oobis already chained to the RuntimeExceptionobject. the method initCause()cannot be called on an exception object that already has an exception object chained during the constructor call. hence, the call re.initCause(oob);results in initCause() throwing an IllegalStateException. class ExceptionTest { public static void foo() { try { throw new ArrayIndexOutOfBoundsException(); } catch(ArrayIndexOutOfBoundsException oob) { throw new Exception(oob); } } public static void main(String []args) { try { foo(); } catch(Exception re) { System.out.println(re.getCause()); } } } public static void fooThrower() throws FileNotFoundException { throw new FileNotFoundException(); } public static void barThrower() throws SQLException { throw new SQLException(); } public static void main(String []args) { try { fooThrower(); barThrower(); } catch(FileNotFoundException || SQLException multie) { System.out.println(multie); } } This program fails with compiler error(s) this program fails with compiler error(s): use “|” not “||” in catch statement. Consider the following class hierarchy from the package javax.security.auth.login and answer the questions: A. catch (AccountException | LoginException exception) // Bad B. catch (AccountException | AccountExpiredException exception) // Bad C. catch (AccountExpiredException | AccountNotFoundException exception) //OK d. catch (AccountExpiredException exception1 | AccountNotFoundException exception2) // Bad => For aand B, the base type handler is provided with the derived type handler, hence the multi-catch is incorrect. try { LoginException le = new AccountNotFoundException(); throw (Exception) le; } catch (AccountNotFoundException anfe) { System.out.println("In the handler of AccountNotFoundException"); } catch (AccountException ae) { System.out.println("In the handler of AccountException"); } catch (LoginException le) { System.out.println("In the handler of LoginException"); } catch (Exception e) { System.out.println("In the handler of Exception"); } When executed, which of the following statements will this code segment print: in the handler of AccountNotFoundException class AssertionFailure { public static void main(String []args) { try { assert false; } catch(RuntimeException re) { System.out.println("RuntimeException"); } catch(Exception e) { System.out.println("Exception"); } catch(Error e) { // LINE A System.out.println("Error" + e); } catch(Throwable t) { System.out.println("Throwable"); } } } This program is invoked from the command line as follows: java AssertionFailure does not print any output on console By default, assertions are disabled. if -ea(or the -enableassertionsoption to enable assertions), then the program would have printed "Error" since the exception thrown in the case of assertion failure is java.lang.AssertionError, which is derived from the Errorclass. import java.io.*; class ExceptionTest { public static void thrower() throws Exception { try { throw new IOException(); } finally { throw new FileNotFoundException(); } } public static void main(String []args) { try { thrower(); } catch(Throwable throwable) { System.out.println(throwable); } } } java.io.FilenotFoundexception if both the try block and finally block throw exceptions, the exception thrown from the try block will be ignored. the Instant class represents a Unix timestamp and internally uses longand int variables. Instantvalues are not very readable or usable by humans because the class does not support methods related to day, month, hours, and so on (in contrast, the Periodclass supports such methods). The new Java date and time API is provided in the java.time package. LocalDate is represented in the ISO-8601 calendar system in a year-month-day format (YYYY-MM-DD): for example, 2015-10-26. LocalDate valentinesDay = LocalDate.of(2016, Month.FEBRUARY, 14); System.out.println("Valentine's day is on: " + valentinesDay); assuming today’s date is 2015-10-26: long visaValidityDays = 180L; LocalDate currDate = LocalDate.now(); System.out.println("My Visa expires on: " + currDate.plusDays(visaValidityDays)); This code segment prints the following: My Visa expires on: 2016-04-23 Table 8-1. Important Methods in the LocalDate Class Method Short Description Example Code LocalDate now(Clock clock) LocalDate now(ZoneId zone) Returns a LocalDate object with the current date using the passed clock or zone argument // assume today's date is 26 Oct 2015 LocalDate.now(Clock.systemDefaultZone()); // returns current date as 2015-10-26 LocalDate.now(ZoneId.of("Asia/Kolkata")); // returns current date as 2015-10-26 LocalDate.now(ZoneId.of("Asia/Tokyo")); // returns current date as 2015-10-27 LocalDate ofYearDay(int year, int dayOfYear) Returns the LocalDate from the year and dayOfYear passed as arguments LocalDate.ofYearDay(2016,100); // returns date as 2016-04-09 LocalDate parse(CharSequence dateString) Returns the LocalDate from the dateString passed as the argument LocalDate.parse("2015-10-26"); // returns a LocalDate corresponding // to the passed string argument; hence it // returns date as 2015-10-26 LocalDate ofEpochDay(Long epochDay) Returns the LocalDate by adding the number of days to the epoch starting day (the epoch starts in 1970) LocalDate.ofEpochDay(10); // returns 1970 LocalTime currTime = LocalTime.now(); System.out.println("Current time is: " + currTime); When we executed it, it printed the following: Current time is: 12:23:05.072 System.out.println(LocalTime.of(18,30)); // prints: 18:30 Table 8-2. Important Methods in the LocalTime Class Method Short Description Example Code LocalTime now(Clock clock) LocalTime now(ZoneId zone) Returns a LocalTime object with the current time using the passed clock or zone argument LocalTime.now(Clock.systemDefaultZone()) // returns current time as 18:30:35.744 LocalDate.now(ZoneId.of("Asia/Tokyo"); // returns current time as 22:00:35.193 LocalTime ofSecondOfDay(long daySeconds) Returns the LocalTime from daySeconds passed as the argument (note that a 24-hour day has 86,400 seconds) LocalTime.ofSecondOfDay(66620); // returns 18:30:20 because // 66620 seconds have elapsed LocalDateTime dateTime = LocalDateTime.now(); System.out.println("Today's date and current time: " + dateTime); System.out.println("The date component is: " + dateTime.toLocalDate()); System.out.println("The time component is: " + dateTime.toLocalTime()); When we executed this code, it printed Today's date and current time: 2015-11-04T13:19:10.497 The date component is: 2015-11-04 The time component is: 13:19:10.497 public String test() throws MyException{ throw new MyException("Hi"); return "tESTT"; // Not compile. Need to remove } LocalDateTime localDateTime = LocalDateTime.now(); Instant instant = Instant.now(); System.out.println("LocalDateTime is: " + localDateTime + " \nInstant is: " + instant); When we executed this, it printed the following: LocalDateTime is: 2015-11-02T17:21:11.402 Instant is: 2015-11-02T11:51:11.404Z As you can see, the time value printed by LocalDateTime is different from the result of Instant. Why? Because we live in the Asia/Kolkata time zone, which is +05:30 hours from Greenwich time. LocalDateTime uses the default time zone, but Instant doesn’t. Duration.parse("P2DT10H30M") // returns a Duration object // with value PT58H30M The TemporalUnitinterface is part of the java.time.temporalpackage. Duration of(long amount, TemporalUnit unit) System.out.println(Duration.of(1, ChronoUnit.MINUTES).getSeconds()); // prints: 60 System.out.println(Duration.of(1, ChronoUnit.HOURS).getSeconds()); // prints:3600 System.out.println(Duration.of(1, ChronoUnit.DAYS).getSeconds()); // prints: 86400 System.out.println("My zone id is: " + ZoneId.systemDefault()); For our time zone, it printed this: My zone id is: Asia/Kolkata ZoneId AsiaKolkataZoneId = ZoneId.of("Asia/Kolkata"); LocalDate currentDate = LocalDate.now(); LocalTime currentTime = LocalTime.now(); ZoneId myZone = ZoneId.systemDefault(); ZonedDateTime zonedDateTime = ZonedDateTime.of(currentDate, currentTime, myZone); System.out.println(zonedDateTime); Here is the result: 2015-11-05T11:38:40.647+05:30[Asia/Kolkata] LocalDateTime dateTime = LocalDateTime.now(); ZoneId myZone = ZoneId.systemDefault(); ZonedDateTime zonedDateTime = dateTime.atZone(myZone); ZoneId myZone = ZoneId.of("Asia/Kolkata"); LocalDateTime dateTime = LocalDateTime.now(); ZonedDateTime zonedDateTime = dateTime.atZone(myZone); ZoneOffset zoneOffset = zonedDateTime.getOffset(); System.out.println(zoneOffset); It prints the following: +05:30 ZoneId singaporeZone = ZoneId.of("Asia/Singapore"); ZonedDateTime dateTimeInSingapore = ZonedDateTime.of( LocalDateTime.of(2016, Month.JANUARY, 1, 6, 0), singaporeZone); ZoneId aucklandZone = ZoneId.of("Pacific/Auckland"); ZonedDateTime sameDateTimeInAuckland = dateTimeInSingapore.withZoneSameInstant(aucklandZone); Duration timeDifference = Duration.between( dateTimeInSingapore.toLocalTime(), sameDateTimeInAuckland.toLocalTime()); System.out.printf("Time difference between %s and %s zones is %d hours", singaporeZone, aucklandZone, timeDifference.toHours()); Time difference between Asia/Singapore and Pacific/Auckland zones is 5 hours The DateTimeFormatterclass provides many predefined constants for formatting date and time values. Here is a list of a few such predefined formatters (with sample output values): • ISO_DATE(2015-11-05) • ISO_TIME(11:25:47.624) • RFC_1123_DATE_TIME(Thu, 5 Nov 2015 11:27:22 +0530) • ISO_ZONED_DATE_TIME(2015-11-05T11:30:33.49+05:30[Asia/Kolkata]) Here is a simple example that uses the predefined ISO_TIMEof type DateTimeFormatter: LocalTime wakeupTime = LocalTime.of(6, 0, 0); System.out.println("Wake up time: " + DateTimeFormatter.ISO_TIME.format(wakeupTime)); This printed the following: Wake up time: 06:00:00 DateTimeFormatter customFormat = DateTimeFormatter.ofPattern("dd MMM yyyy"); System.out.println(customFormat.format(LocalDate.of(2016, Month.JANUARY, 01))); Here is the result: 01 Jan 2016 Assume that you need to catch a flight from Singapore on January 1, 2016 at 6:00 a.m. The flight takes 10 hours to reach Auckland, New Zealand. Can you get the arrival time in Auckland? DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy hh.mm a"); // Leaving on 1st Jan 2016, 6:00am from "Singapore" ZonedDateTime departure = ZonedDateTime.of( LocalDateTime.of(2016, Month.JANUARY, 1, 6, 0), ZoneId.of("Asia/Singapore")); System.out.println("Departure: " + dateTimeFormatter.format(departure)); // Arrival on the same day in 10 hours in "Auckland" ZonedDateTime arrival = departure.withZoneSameInstant(ZoneId.of("Pacific/Auckland")) .plusHours(10); System.out.println("Arrival: " + dateTimeFormatter.format(arrival)); The < symbol in a format string supports relative index with which you can reuse the argument matched by the previous format specifier. For example, assuming console is a valid Consoleobject, the following code segment prints “10 a 12”: console.printf("%d %<x %<o", 10); // 10 – the decimal value, a – the hexadecimal value of 10, and // 12 – the octal value of 10 public static void main(String[] args) { char[] chars = {'a', 'b', 'c'}; String str = new String(chars); System.out.println("First:" + str); Arrays.fill(chars, ' '); // assign empty to chars str = new String(chars); System.out.println("Second: " + str); } Streams are ordered sequences of data. Java deals with input and output in terms of streams. the FileReader constructor will throw a FileNotFoundException. byte []magicNumber = {(byte) 0xCA, (byte)0xFE, (byte)0xBA, (byte)0xBE}; try (FileInputStream fis = new FileInputStream(fileName)) { // magic number is of 4 bytes – // use a temporary buffer to read first four bytes byte[] u4buffer = new byte[4]; // read a buffer full (4 bytes here) of data from the file if(fis.read(u4buffer) != -1) { // if read was successful // the overloaded method equals for two byte arrays // checks for equality of contents if(Arrays.equals(magicNumber, u4buffer)) { System.out.printf("The magic number for passed file %s matches that of a .class file", fileName); } else { System.out.printf("The magic number for passed file %s does not match that of a .class file", fileName); } } } catch(FileNotFoundException fnfe) { System.err.println("file does not exist with the given file name "); } catch(IOException ioe) { System.err.println("an I/O error occurred while processing the file"); } // write some data into a data file with hard-coded name "temp.data" try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("temp.data"))) { // write values 1 to 10 as byte, short, int, long, float and double // omitting boolean type because an int value cannot // be converted to boolean for(int i = 0; i < 10; i++) { dos.writeByte(i); dos.writeShort(i); dos.writeInt(i); dos.writeLong(i); dos.writeFloat(i); dos.writeDouble(i); } } catch(FileNotFoundException fnfe) { System.err.println("cannot create a file with the given file name "); System.exit(-1); // don't proceed – exit the program } catch(IOException ioe) { System.err.println("an I/O error occurred while processing the file"); System.exit(-1); // don't proceed – exit the program } // now, read the written data and print it to console try (DataInputStream dis = new DataInputStream(new FileInputStream("temp.data"))) { // the order of values to read is byte, short, int, long, float and // double since we've written from 0 to 10, // the for loop has to run 10 times for(int i = 0; i < 10; i++) { // %d is for printing byte, short, int or long // %f, %g, or %e is for printing float or double // %n is for printing newline System.out.printf("%d %d %d %d %g %g %n", dis.readByte(), dis.readShort(), dis.readInt(), dis.readLong(), dis.readFloat(), dis.readDouble()); } } catch(FileNotFoundException fnfe) { System.err.println("cannot create a file with the given file name "); } catch(IOException ioe) { System.err.println("an I/O error occurred while processing the file"); } // the DataOutputStream will auto-close, so don't have to worry about it } } // A simple class to illustrate object streams: fill a data structure, write it to a // temporary file and read it back and print the read data structure class ObjectStreamExample { public static void main(String []args) { Map<String, String> presidentsOfUS = new HashMap<>(); presidentsOfUS.put("Barack Obama", "2009 to --, Democratic Party, 56th term"); presidentsOfUS.put("George W. Bush", "2001 to 2009, Republican Party, 54th and 55th terms"); presidentsOfUS.put("Bill Clinton", "1993 to 2001, Democratic Party, 52nd and 53rd terms"); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.data"))) { oos.writeObject(presidentsOfUS); } catch(FileNotFoundException fnfe) { System.err.println("cannot create a file with the given file name "); } catch(IOException ioe) { System.err.println("an I/O error occurred while processing the file"); } // the ObjectOutputStream will auto-close, so don't have to worry about it try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.data"))) { Object obj = ois.readObject(); // first check if obj is of type Map if(obj != null && obj instanceof Map) { Map<?, ?> presidents = (Map<?, ?>) obj; System.out.println("President name \t Description"); for(Map.Entry<?, ?> president : presidents.entrySet()) { System.out.printf("%s \t %s %n", president.getKey(), president.getValue()); } } } catch(FileNotFoundException fnfe) { System.err.println("cannot create a file with the given file name "); } catch(IOException ioe) { System.err.println("an I/O error occurred while processing the file"); } catch(ClassNotFoundException cnfe) { System.err.println("cannot recognize the class of the object - is the file corrupted?"); } } } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); // OK BufferedReader br = new BufferedReader(System.in); String str = br.readLine() // Bad console.printf("%d %1$x %1$o", 16); this program prints: 16 10 20 FileInputStream findings = new FileInputStream("log.txt"); DataInputStream dataStream = new DataInputStream(findings); BufferedReader br = new BufferedReader(new InputStreamReader(dataStream)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); the br.close()statement will close the BufferedReaderobject and the underlying stream objects referred to by findingsand dataStream. the readLine()method invoked in the statement br.readLine()can throw an IOException; if this exception is thrown, br.close()will not be called, resulting in a resource leak. note that Garbage Collector will only collect unreferenced memory resources; it is the programmer’s responsibility to ensure that all other resources such as stream objects are released. public static void main(String[] args) { if(args.length != 2){ System.out.println("usage: FileCopy <source-path> <destination-path>"); System.exit(1); } Path pathSource = Paths.get(args[0]); Path pathDestination = Paths.get(args[1]); try { Files.copy(pathSource, pathDestination); System.out.println("Source file copied successfully"); } catch (IOException e) { e.printStackTrace(); } } Let’s execute it and see whether it works. D:\> java FileCopy FileCopy.java Backup.java Source file copied successfully Yes, it’s working. Try running it again with the same arguments: D:\OCPJP\programs\NIO2\src>java FileCopy FileCopy.java Backup.java java.nio.file.FileAlreadyExistsException: Backup.java at sun.nio.fs.WindowsFileCopy.copy(Unknown Source) [...stack trace elided...] Oops! What happened? When you try copying the file for the second time, you get a FileAlreadyExistsExceptionbecause the destination file already exists. What if you want to overwrite the existing file? The solution: you need to tell the copy()method that you would like to overwrite an existing file. In Listing 10-9, change copy()as follows: Files.copy(pathSource, pathDestination, StandardCopyOption.REPLACE_EXISTING); What if you try copying a directory? It will work, but remember that it will only copy the top-level directory, not the files/directories contained withinthat directory. If you copy a directory using the copy()method, it does not copy the files/directories contained in the source directory; you need to explicitly copy them to the destination folder A non-empty directory can be moved if moving the directory does not require moving the containing files/directories. For instance, moving a directory from one physical drive to another may be unsuccessful (an IOExceptionwill be thrown). If moving a directory is successful, then all the contained files/directories are also moved. You can specify move()as an atomic operation using the ATOMIC_MOVEcopy option. When you specify an atomic move, you are assured that either the move completes successfully or the source continues to be present. If move()is performed as a non-atomic operation and it fails while in process, the state of both files is unknown and undefined. In the case of a directory, the delete()method should be invoked on an empty directory; otherwise, the method will fail. In the case of a symbolic link, the link is deleted, not the target file of the link. The file you intend to delete must exist; Otherwise you get a NoSuchFileException. If you silently delete a file and do not want to be bothered with this exception, then you may use the deleteIfExists()method, which does not complain if the file does not exist and deletes the file if it exists. Files.list()method added in Java 8 to list all the files in the current directory try(Stream<Path> entries = Files.list(Paths.get("."))) { entries.forEach(System.out::println); } ./ListFiles.class ./ListFiles.java ... (rest of the output elided) Files.list(Paths.get(".")) .map(path -> path.toAbsolutePath()) .forEach(System.out::println); The result is as follows: D:\OCPJP\NIO2\src\ListFiles.class D:\OCPJP\NIO2\src\ListFiles.java ... (rest of the output elided) Note that the list()method does not recursively traverse the entries in the given Path. To recursively traverse the directories, you can use the Files.walk()method: Files.walk(Paths.get(".")).forEach(System.out::println); Files.walk(Paths.get(".")).forEach(System.out::println); . .\.classpath .\.project .\.settings Files.walk(Paths.get(".")).map(x -> x.toAbsolutePath()).forEach(System.out::println); D:\Study D:\Study D:\Study D:\Study Project\Workplaces\Test\. Project\Workplaces\Test\.\.classpath Project\Workplaces\Test\.\.project Project\Workplaces\Test\.\.settings try(Stream<Path> entries = Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS)) { long numOfEntries = entries.count(); System.out.printf("Found %d entries in the current path", numOfEntries); } Found 179 entries in the current path This code gives an arbitrary limit of 4 for the nesting depth as the second argument to the Files.walk() method. Files.lines()is a very convenient method to read the contents of a file: static Stream<String> lines(Path path) class Type { private static void processFile(String file) { try(Stream<String> lines = Files.lines(Paths.get(file))) { lines.forEach(System.out::println); } catch (IOException ioe) { System.err.println("IOException occurred when reading the file... exiting"); System.exit(-1); } } public static void main(String[] files) throws IOException { if (files.length == 0) { System.err.println("pass the name of the file(s) as argument"); System.exit(-1); } // process each file passed as argument Arrays.stream(files).forEach(Type::processFile); } } class FindFiles { public static void main(String []args) throws IOException { BiPredicate<Path, BasicFileAttributes> predicate = (path, attrs) -> attrs.isRegularFile() && path.toString().endsWith("class"); try(Stream<Path> entries = Files.find(Paths.get("."), 4, predicate)) { entries.limit(100).forEach(System.out::println); } } } This program prints long output, so it is not given here. This example used the limit()method on the Stream<Path>object to limit the number of entries processed when returned from the Files.find()method. The find()method takes the path to start searching from, the maximum depth to search, a BiPredicate, and an optional FileVisitOptionas arguments: static Stream<Path> find(Path path, int maxDepth, BiPredicate<Path,BasicFileAttributes> matcher, FileVisitOption... options) throws IOException In this example, you are looking for files that end with a classextension, and you limit the number of entries to 100 Iterator<Path> paths = aFilePath.iterator(); while(paths.hasNext()) { System.out.println("path element: " + paths.next()); } the program gets into an infinite loop, printing “path element: directory” forever. in the whileloop, you use iterator()to get a temporary iterator object. So, the call to next()on the temporary variable is lost, and the whileloop gets into an infinite loop. class RunnableImpl implements Runnable { public void run() { System.out.println("In run(); thread name is: " + Thread.currentThread().getName()); } public static void main(String args[]) throws Exception { Thread myThread = new Thread(new RunnableImpl()); myThread.start(); System.out.println("In main(); thread name is: " + Thread.currentThread().getName()); } } This program prints: In main(); thread name is: main In run(); thread name is: Thread-0 You cannot declare constructors synchronized; it will result in a compiler error. if they’re doing lots of work, but there is no progress made by either of the cars. This situation is called a livelock. The Path interface provides two methods to compare two Path objects: equals() and compareTo(). The equals() method checks the equality of two Path objects and returns a Boolean value, whereas compareTo() compares two Path objects character by character and returns an integer: 0 if both Path objects are equal; a negative integer if this path is lexicographically less than the parameter path; and a positive integer if this path is lexicographically greater than the parameter path. Path path1 = Paths.get("Test"); Path path2 = Paths.get("D:\\OCPJP\\programs\\NIO2\\Test"); // comparing two paths using compareTo() method System.out.println("(path1.compareTo(path2) == 0) is: " + (path1.compareTo(path2) == 0)); // comparing two paths using equals() method System.out.println("path1.equals(path2) is: " + path1.equals(path2)); // comparing two paths using equals() method with absolute path System.out.println("path2.equals(path1.toAbsolutePath()) is " path2.equals(path1.toAbsolutePath())); => (path1.compareTo(path2) == 0) is: false path1.equals(path2) is: false path2.equals(path1.toAbsolutePath()) is true => It first compares two paths using the compareTo() method, which compares paths character by character and returns an integer. In this case, because one path is a relative path and another one is an absolute path, you first expect to get a message that says the paths are not equal. => Then you compare both paths using equals(). The result is the same, which means even if the two Path objects are pointing to the same file/directory, it is possible for equals() to return false. You need to make sure both paths are absolute paths. => In the next step, you convert the relative path to an absolute path and then compare them using equals(). This time both paths match. Note that you use an escape character (\) in Paths.get("D:\\test\\testfile.txt"). In the path, if you gave D:\test, then \t would mean a tab character, and you’d get a java.nio.file.InvalidPathException when you ran the program. Path path = Paths.get(args[0]); try { Object object = Files.getAttribute(path, "creationTime", LinkOption.NOFOLLOW_LINKS); System.out.println("Creation time: " + object); object = Files.getAttribute(path, "lastModifiedTime", LinkOption.NOFOLLOW_LINKS); System.out.println("Last modified time: " + object); object = Files.getAttribute(path, "size", LinkOption.NOFOLLOW_LINKS); System.out.println("Size: " + object); object = Files.getAttribute(path, "dos:hidden", LinkOption.NOFOLLOW_LINKS); System.out.println("isHidden: " + object); object = Files.getAttribute(path, "isDirectory", LinkOption.NOFOLLOW_LINKS); System.out.println("isDirectory: " + object); } catch (IOException e) { e.printStackTrace(); } => Print: D:\> java FileAttributes FileAttributes.java Creation time: 2012-10-06T10:20:10.34375Z Last modified time: 2012-10-06T10:21:54.859375Z Size: 914 isHidden: false isDirectory: false => For example, if you type sized instead of size, you’ll get this exception: Exception in thread "main" java.lang.IllegalArgumentException: 'sized' not recognized [...stack trace elided...] Path path = Paths.get(args[0]); try { BasicFileAttributes fileAttributes = Files.readAttributes(path, BasicFileAttributes.class); System.out.println("File size: " + fileAttributes.size()); System.out.println("isDirectory: " + fileAttributes.isDirectory()); System.out.println("isRegularFile: " + fileAttributes.isRegularFile()); System.out.println("isSymbolicLink: " + fileAttributes.isSymbolicLink()); System.out.println("File last accessed time: " + fileAttributes.lastAccessTime()); System.out.println("File last modified time: " + fileAttributes.lastModifiedTime()); System.out.println("File creation time: " + fileAttributes.creationTime()); } catch (IOException e) { e.printStackTrace(); } => D:\>java FileAttributes2 FileAttributes2.java File size: 904 isDirectory: false isRegularFile: true isSymbolicLink: false File last accessed time: 2012-10-06T10:28:29.0625Z File last modified time: 2012-10-06T10:28:22.4375Z File creation time: 2012-10-06T10:26:39.1875Z import java.util.concurrent.CyclicBarrier; import java.util.concurrent.BrokenBarrierException; // The run() method in this thread should be called only when // four players are ready to start the game class MixedDoubleTennisGame extends Thread { public void run() { System.out.println("All four players ready, game starts \n Love all..."); } } // This thread simulates arrival of a player. // Once a player arrives, he/she should wait for other players to arrive class Player extends Thread { CyclicBarrier waitPoint; public Player(CyclicBarrier barrier, String name) { this.setName(name); waitPoint = barrier; this.start(); } public void run() { System.out.println("Player " + getName() + " is ready "); try { waitPoint.await(); // await for all four players to arrive } catch(BrokenBarrierException | InterruptedException exception) { System.out.println("An exception occurred while waiting... " + exception); } } } // Creates a CyclicBarrier object by passing the number of threads and the thread to run // when all the threads reach the barrier class CyclicBarrierTest { public static void main(String []args) { // a mixed-double tennis game requires four players; // so wait for four players // (i.e., four threads) to join to start the game System.out.println("Reserving tennis court \n" + "As soon as four players arrive, game will start"); CyclicBarrier barrier = new CyclicBarrier(4, new MixedDoubleTennisGame()); new Player(barrier, "G I Joe"); new Player(barrier, "Dora"); new Player(barrier, "Tintin"); new Player(barrier, "Barbie"); } } The program prints the following: Reserving tennis court As soon as four players arrive, game will start Player Dora is ready Player G I Joe is ready Player Tintin is ready Player Barbie is ready All four players ready, game starts Love all... ConcurrentHashMap Analogous to Hashtable, but with safe concurrent access and updates. ConcurrentSkipListMap Analogous to TreeMap, but provides safe concurrent access and updates. ConcurrentSkipListSet Analogous to TreeSet, but provides safe concurrent access and updates. CopyOnWriteArrayList Similar to ArrayList, but provides safe concurrent access. When the container is modified, it creates a fresh copy of the underlying array. CopyOnWriteArraySet A Setimplementation, but provides safe concurrent access and is implemented using CopyOnWriteArrayList. When the container is modified, it creates a fresh copy of the underlying array. Both ArrayListand CopyOnWriteArrayListimplement the Listinterface. There are three main differences between ArrayListand CopyOnWriteArrayList: • ArrayListis not thread-safe but CopyOnWriteArrayListis thread-safe. That means, it is unsafe to use ArrayListin contexts where multiple threads are executing (especially when some of the threads modify the container) but it is safe to use CopyOnWriteArrayListin this context. • Methods in ArrayListsuch as remove(), add(), and set()methods can throw java.util.ConcurrentModificationExceptionif another thread modifies the ArrayListwhen one thread is accessing it. However, it is safe to perform these operations from multiple threads in CopyOnWriteArrayList, and hence methods such as remove(), add(), and set()do not throw this exception. How? All the active iterators will still have access to the unmodified version of the container and hence they remain unaffected; if you try to create an iterator after the modification, you will get the iterator for the modified container. • You can get an iterator by calling the Iterator()method on a Listobject. If you call remove()method when the underlying container is modified, you may get a ConcurrentModificationException. However, you cannot call the remove() method on an Iteratorof a CopyOnWriteArrayList: it always throws the UnsupportedOperationException. public class ModifyingList { public static void main(String []args) { List<String> aList = new ArrayList<>(); aList.add("one"); aList.add("two"); aList.add("three"); Iterator listIter = aList.iterator(); while(listIter.hasNext()) { System.out.println(listIter.next()); aList.add("four"); } } } This program crashes by throwing java.util.ConcurrentModificationException. Why? Because the iterators of ArrayListare fail-fast; it fails by throwing ConcurrentModificationExceptionif it detects that the underlying container has changed when it is iterating over the elements in the container. public class COWList { public static void main(String []args) { List<String> aList = new CopyOnWriteArrayList<>(); aList.add("one"); aList.add("two"); aList.add("three"); Iterator listIter = aList.iterator(); while(listIter.hasNext()) { System.out.println(listIter.next()); aList.add("four"); } } } Now the program does not crash, it prints: one two three Observe that the element “four” added three times is not printed as part of the output. This is because the iterator still has access to the original (unmodified) container that had three elements. If you create a new iterator and access the elements, you will find that new elements have been added to aList.