Core Java 2015

1. Which one of the following is NOT a reserved word in Java?
Answers:
• final
• private
• virtual
• public

2. Why is it important to override hashCode() when you override equals()?
Answers:
• equals() will throw an exception if hashCode() is not overridden as well.
• It is NOT important to override hashCode() when overriding equals().
• Overriding equals without hashCode breaks the contract of hashCode().
3. What is the issue with the following code? String s = ""; for(int i = 0; i < 1000000; i++) { s += Integer.toString(i); }
Answers:
• It will not compile.
• It will perform very slowly because strings are immutable.
• It will perform very slowly because Integer.toString() is slow.
• There are no issues with the above code.
4. Complete the sentence: One may extend a class from ...
Answers:
• Many classes through multiple inheritance
• Only one inner class
• Only one interface
• Only one non-final class
5. Which one of these lists contains only Java programming language keywords?
Answers:
• class, if, void, long, int, continue
• try, virtual, throw, final, volatile, transient
• byte, break, assert, switch, include
• strictfp, constant, super, implements, do
• goto, instanceof, native, finally, default, throws
6. How should you create a new class that maps keys to values, using the Java Collections Framework?
Answers:
• Extend the AbstractCollection class, thereby implementing the AbstractCollection interface
• Implement the Map interface, possibly by extending the AbstractMap class
• Implement both the Iterator and Array interfaces
• Implement the Queue, List, and Array interfaces
7. The Object.wait() method:
Answers:
• Resumes from waiting if notifyAll() is invoked for the object
• Resumes from waiting if notify() is invoked for the object
• Causes the current thread to wait
• Resumes from waiting if a specified amount of time has elapsed
8. A java class which extends another class is usually described with the word:
Answers:
• overloaded
• abstract
• subclass
• dynamic
9. Which of these are advantages of encapsulation in Java?
Answers:
• Encapsulated code is easy to change with new requirements
• All of these
• Encapsulation in Java makes unit testing easy
• Encapsulation reduces coupling of modules and increase cohesion inside a module
10. To document an API, which tool do you use?
Answers:
• documentcreate
• javadoc
• javaApi
• apicreate
11. If we want a class not to be overridden,the class must be done as
Answers:
• Class should be static
• Class should be final
• Class should public
• Class should be abstract
12. The "javac" command line tool is used to:
Answers:
• Convert java bytecode files into native executables
• Compile java source files into bytecode class files
• Compress collections of java class files into .jar archives
• Generate C headers and stubs for native methods
13. Which additional keyword may be used with try-catch blocks?
Answers:
• finally
• finish
• final
• finalize
14. The most reliable way to compare two Strings for equality is by:
Answers:
• Using the &= operator on the objects
• Using the == operator on the objects
• Using the == operator on the .value() of each object
• Using the .equals() or .compareTo() method of one object on the other
15. Java handles memory allocation and reuse using a process called:
Answers:
• Garbage Collection
• Buddy Blocks
• Manual Memory Management
• Virtual Memory
16. The part of a "try" block that is always executed is:
Answers:
• "enum"
• "finally"
• "if"
• "import"
17. To define a child class from the Parent class following is used:
Answers:
• class Child :: Parent
• class Child extends Parent
• class Child extends Public Parent
• class Child : Parent
18. What is an example of proper capitalization for a class name?
Answers:
• CAMELcase
• CamelCase
• camELCase
• camelcase
19. If a method or variable is marked as having the "private" access level, then it can only be accessed from:
Answers:
• Inside the same class or its parent class
• Inside the same class
• Inside the same class, or any of its superclasses
• Inside the same class, or a subclass
20. What is the most efficient way to concatenate a large number of strings in Java?
Answers:
• The + operator.
• The StringBuffer object.
21. Finally is used to....
Answers:
• ensure a block of code is executed when the JVM shuts down.
• ensure a block of code is executed only when try/catch completes without an exception
• ensure a block of code is always executed after a try/catch
• ensure a block of code is executed only when try/catch completes with an exception
22. Which of the following is a valid constructor signature?
Answers:
• public static className()
• static className()
• public void className()
• public className()
23. When you create a thread with the “new” operator – which one of the following statements is true about its state
Answers:
• it starts running immediately
• it is blocked until another thread calls notify()
• it is in “runnable” state
• it will be “runnable” when start() method is called
24. The Thread.sleep() method:
Answers:
• Causes all threads to suspend execution
• Suspends execution in synchronized methods only
• Causes the current thread to suspend execution
• Causes the hosted virtual machine to suspend all forms of execution
25. How can you stop your class from being inherited by another class?
Answers:
• It’s not possible.
• Declare the class as abstract.
• Declare the class as final.
• Declare the class default constructor as private.
26. Can an abstract class be a final class?
Answers:
• Yes
• No
27. What is the correct way to create an instance of a class?
Answers:
• ClassName varName = new ClassName(new ClassName);
• ClassName varName = new ClassName(arguments);
• ClassName varName => new ClassName();
• varName ClassName = new varName(arguments);
28. True of False? The strictfp keyword ensures that you get the same result on every platform if you perform operations in the floating point variable.
Answers:
• False
• True
29. Interfaces are useful for...
Answers:
• creating a design contract that encapsulates implementation
• implementing an abstract factory pattern
• reducing heap size
• making an abstract class concrete
30. Which of these is true?
Answers:
• An interface implements another interface and class
• A class implements and extends a class
• An interrface extends a class but implements another interface
• A class implements an interface but extends a class
31. How can we use the class or jar files kept on the network path, within our projects?
Answers:
• mentioning the file names in the Path
• by directly copying and including in the same folder as of the project
• Including the path and class /jar file name in the Classpath
• No the network files can not be used directly
• mentioning the Class /Jar file names during compilation only
32. What is auto boxing?
Answers:
• JVM conversion between primitive types and reference types
• JVM conversion of int to float values
• It doesn’t occur in Java, only in dynamically typed JVM languages like Groovy
• Automatic insertion of brackets by an IDE
33. The "java" command line tool is used to:
Answers:
• Load and execute java .class files
• Disassemble .class files back into readable source code
• Compile java source files into bytecode class files
• Compress collections of java class files into .jar archives
34. The Core Java platform provides many benefits to developers, including:
Answers:
• A purely functional programming language with a minimalist design philosophy
• A consistent programming interface across multiple hardware platforms
• Direct compilation to native code on most platforms
• Superior speed and performance compared to native code
35. What method should you always override when you have overridden the equals() method?
Answers:
• clone()
• toString()
• hashCode()
• wait()
36. JDBC addresses the issue of transactions.
Answers:
• True
• False
37. The "static" keyword marks something as:
Answers:
• No longer able to be subclassed or overloaded
• A constant variable whose value cannot be changed
• Not being mutable after initialization
• Belonging to a class, rather than a specific instance
38. The instanceof operator can be used to determine if an object is:
Answers:
• An instance of a subclass of a class
• An instance of a class
• (All of these)
• An instance of a class that implements a given interface
39. What are all the different types of access modifiers in Java
Answers:
• private, public
• private, protected, default, public
• protected, default, public
• private, protected, public
• private, default, public
40. What is the benefit of ConcurrentHashMap<K,V>?
Answers:
• Allows null to be used a key or value
• Supports locking the entire table in a way that prevents all access
• It maintains a list through all entries to retrieve data in the order it was inserted.
• All operations are thread-safe and retrieval operations do not entail locking
41. You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access that accomplishes this objective?
Answers:
• private
• public
• protected
• transient
42. When creating a user defined class for storing objects in a HashMap, which method(s) should be overridden?
Answers:
• The constructor method
• (You don't need override any methods)
• The equal() method
• The hashCode() method
• Both the equals() and hashCode() methods
43. When the == comparator is used on two objects, it checks to see if they:
Answers:
• Are references to exactly the same object
• Have the same value according to the .equals() method of the first object
• Evaluate to the same value
• Are instances of the same class
44. Java provides a class for mutable sequences of characters, called:
Answers:
• MutableString
• CharSequence
• StringBuffer
• String
45. What is the difference between a checked and unchecked exception?
Answers:
• An unchecked exception extends Throwable and a checked exception does not.
• A checked exception extends Throwable and an unchecked exception does not.
• Unchecked exceptions must be caught while checked do not need to caught
• Checked exceptions must be caught while unchecked do not need to caught
46. An "overloaded" method has what in common with one (or more) methods on the same class?
Answers:
• The same name
• The same number of parameters, regardless of type
• The same return type
• The same number and types of parameters
47. The List interface has which superinterfaces?
Answers:
• Set
• Collection
• Both Collection and Iterable
• Iterable
48. Calling System.gc() when using a modern JVM :
Answers:
• Directly and immediately disposes of all orphaned objects on the heap.
• Is especially important when programming for mobile or memory limited devices.
• Should be done after deleting several elements from a collection.
• Is the most straightforward and reliable way to perform memory management in Java.
• Does not necessarily force garbage collection to occur, and is not idiomatic java.
49. Which one of the following statements is true about Java Beans?
Answers:
• Java Beans cannot be used in server side programming, they are only used for Graphical User Interfaces.
• Java Beans are not permitted to create any threads
• All Java Beans must extend the java.bean base class
• Java Beans are user defined classes.
50. Which class/classes is/are thread safe among these?
Answers:
• StringBuilder
• String and StringBuffer
51. Which option is true for StringBuffer and StringBuilder
Answers:
• StringBuffer are not thread safe and StringBuilder are thread safe.
• StringBuffer are thread safe and StringBuilder are not thread safe
• StringBuffer and StringBuilder are thread safe.
• Neither StringBuffer nor StringBuilder are thread safe.
52. Which option is true for StringBuffer and StringBuilder
Answers:
• StringBuffer are not thread safe and StringBuilder are thread safe.
• StringBuffer are thread safe and StringBuilder are not thread safe
• StringBuffer and StringBuilder are thread safe.
• Neither StringBuffer nor StringBuilder are thread safe.
53. What is the output?  int[] xxx =  {10, 20};          List<String> list = new ArrayList<String>(10); list.add("01"); list.add("02");          System.out.println(xxx.length + ", " +list.size());
Answers:
• 2, 2
• Compile error
• 1, 2
• 2, 10
• 10, 2
54. What is a LinkedHashSet?
Answers:
• A hash set which preserves the order in which objects were inserted.
• A hash set with the performance of a linked list.
• A superclass of the HashSet object.
• A hash set which can easily be converted into a linked list.
55. Immutable objects are always...
Answers:
• memory efficient
• thread safe
• polymorphic
• serializable
56. A method without an access modifier (i.e. public, private, protected) is...
Answers:
• private
• protected
• package-private
• public
• static
57. In addition to CORBA, Core Java also supports network services using:
Answers:
• IPX / SPX Protocol
• Remote Object Access
• Remote Procedure Calls
• Remote Method Invocation
58. Java's automatic memory management:
Answers:
• Can be tuned using Virtual Machine settings
• Uses hardcoded settings inside each Virtual Machine, which should not be altered
• Can be configured to operate statically or dynamically at compile time
• Can be overriden using functions like alloc and dalloc
59. Java's String class is
Answers:
• Immutable, but can be subclassed
• Final, but creates mutable instances
• Mutable, and can be subclassed
• Final, with immutable instances
60. enum Example { ONE, TWO, THREE }    Which statement is true?
Answers:
• The expression (ONE < TWO) is guaranteed to be true and ONE.compareTo(TWO) is guaranteed to be less than one.
• The expressions (ONE == ONE) and ONE.equals(ONE) are both guaranteed to be true.
• The Example values cannot be used in a raw java.util.HashMap; instead, the programmer must use a java.util.EnumMap.
• The Example values can be used in a java.util.SortedSet, but the set will NOT be sorted because enumerated types do NOT implement java.lang.Comparable.
61. Which will compile successfully?
Answers:
• Object o = Old.get(new LinkedList<?>());
• Object o = Old.get(LinkedList());
• String s = Old.get(new LinkedList<String>());
• String s = (String)Old.get(new LinkedList<String>());
62. A class implementing a singleton pattern has...
Answers:
• no public constructors and static factory method and a non-static instance variables.
• public constructors instead of a static factory method and a static instance variable.
• no public constructors, a private static factory method, a static instance variable.
• no public constructors, a public static factory method, a static instance variable.
63. Which of the following is true about overloading vs overriding methods?
Answers:
• Final methods can be overriden, but not overloaded
• The argument list of overloaded methods must be of same data type (unlike overridden methods)
• Overloading happens at compile time, while overriding happens at runtime
• Overloading can arbitrarily change the access of a method, while overriding can only make it more restrictive
64. What is the result when this code is executed:    class One {    public One() { System.out.print(1); }    }    class Two extends One {    public Two() { System.out.print(2); }     }     class Three extends Two {    public Three() { System.out.print(3); }    }    public class Numbers{    public static void main( String[] argv ) { new Three(); }     }
Answers:
• 3
• 123
• 321
• 1
65. How do you convert int[]  to a ArrayList<Integer>?
Answers:
• Using toArrayList()
• Casting
• In a loop, creating new Integers.
• Using the static Arrays.asList method
66. What is a weak reference?
Answers:
• A reference to an object which may have been garbage collected when the object is asked for.
• A reference to an object that cannot be garbage collected.
• A reference to an object which is about to be garbage collected.
• A reference to an object which has been garbage collected.
67. Can the "main" method be overloaded
Answers:
• No
• Yes
68. How many objects are created: String s1="String"; String s2="String"; String s3="String";
Answers:
• Two
• None
• One
• Three
69. What Object would you use to represent currency ?
Answers:
• Currency
• Integer
• BigDecimal
• Double
70. What type should you use for floating point monetary calculations?
Answers:
• BigDecimal
• float
• byte
• double
71. What will be printed out if you attempt to compile and run the following code?  int i=9;  switch (i) {          default:          System.out.println("default ");                  case 0:          System.out.println("zero ");                  break;          case 1:                  System.out.println("one ");          case 2:          System.out.println("two ");  }
Answers:
• default zero
• no output displayed
• default
• error default clause not defined
72. After the following code fragment, what is the value in a? String s; int a; s = "Foolish boy."; a = s.indexOf("fool");
Answers:
• 1
• 0
• -1
• 4
• random value
73. public static void append(List list) { list.add("0042"); }    public static void main(String[] args) {    List<Integer> intList = new ArrayList<Integer>();    append(intList);    System.out.println(intList.get(0));    }      What is the result?
Answers:
• An exception is thrown at runtime.
• Compilation fails because of an error in line 14.
• 42
• 0042
• Compilation fails because of an error in line 13.
74. To create a single instance of a class, we can go with
Answers:
• (none of these)
• Static class
• Final class
• Abstract class
75. When must you override hashcode and equals method?
Answers:
• You should always do so as a matter of best practice
• For better performance when you want to use the object as a key in a HashMap
• When you want to serialize objects
• When you want to sort objects using Comparable
76. what is the output of following code? class A  {  int x=12; public static void main(String args[])  {  x++; System.out.println(x); } }
Answers:
• 12
• Compile time Error.
• Run time Error.
• 13
77. Anonymous inner classes have access to...
Answers:
• Any local variables in the containing scope
• Final, local variables in the containing scope
• Only variables passed into the constructor, and no variables in the containing class
• Only synchronized collections in the containing class
78. Which statement is true?
Answers:
• Any statement that can throw an Exception must be enclosed in a try block.
• catch(X x) can catch subclasses of X where X is a subclass of Exception.
• Any statement that can throw an Error must be enclosed in a try block.
• The Error class is a RuntimeException.
79. In your program, you need to read a zip file (myfile.zip) containing several other data files containing basic Java objects. Which of the following will allow you to construct a InputStream for the task?
Answers:
• new ZipInputStream(new FileInputStream(“myfile.zip”));
• new ObjectInputStream(new ZipInputStream( new FileInputStream((“myfile.zip”)));
• new DataInputStream(new FileInputStream(“myfile.zip”));
• new ZipInputStream(new ObjectInputStream(“myfile.zip”));
80. Does interrupt() always force all threads to terminate?
Answers:
• Yes, the thread gets to a predefined interruption point and stops
• No, if the interruption is not enabled for the thread, it will not terminate
• Yes, after interrupt() is called a thread terminates immediatelly
81. The documentation comment starts and ends with
Answers:
• /** and **/
• /** and */
• /* and **/
• /* and */
82. Float p = new Float(3.14f);    if (p > 3) {    System.out.print("p is bigger than 3. ");     }    else {    System.out.print("p is not bigger than 3. ");     }    finally {     System.out.println("Have a nice day.");     }      What is the result?
Answers:
• p is bigger than 3.
• p is bigger than 3. Have a nice day.
• Compilation fails.
• p is not bigger than 3. Have a nice day.
83. Which of the following statements about static inner classes is true?
Answers:
• A static inner class requires an instance of the enclosing class.
• A static inner class requires a static initializer.
• A static inner class has no reference to an instance of the enclosing class.
• A static inner class has access to the non-static members of the outer class.
84. All of the classes in the Java Collections Framework:
Answers:
• Have methods allowing them to be viewed as both Maps and Lists
• Involve data structures backed by Arrays
• Have methods to retrieve their data as an Array
• Allow elements to be added to the beginning or end of their internal List
85. Given the code: Integer i= new Integer("1"); if (i.toString() == i.toString()) System.out.println("Equal"); else System.out.println("Not Equal");
Answers:
• Compiler error
• Prints "Not Equal"
• None of the above
• Prints "Equal"
86. which statement is True ?
Answers:
• The notifyAll() method must be called from a synchronized context.
• The notify() method is defined in class java.lang.Thread.
• The notify() method causes a thread to immediately release its locks.
• To call wait(), an object must own the lock on the thread.
87. Which one of the following statements is true about threads in Java
Answers:
• the notify() method can only be called from inside a synchronized block or from a synchronized method
• the notify() method can not be called if your class extends Thread class, it can only be called if your class implements the “Runnable” interface
• the notify() must be called to wake up threads that have called wait() and notifyAll() must be called to wake up threads that have called join().
• the notify() method informs the Java Virtual Machine that it has finished executing
88. java.util.Collection is:
Answers:
• An abstract interface representing a group of objects, extended by Set and List
• An interface for iterable groups of objects
• An interface of non-destructive methods used by Set and List classes
• An abstract class representing a group of objects, extended by Set and List
89. A "blank" final variable (defined without an initial value):
Answers:
• Can be initialized later, but only in a single location
• Will raise an exception if its value is accessed or assigned at runtime
• Is illegal, and will cause an error at compile time
• Has a Null value, and will raise an exception if initialized or assigned later
90. LinkedBlockingQueue is useful for...
Answers:
• binary searches of a list of sorted objects
• a synchronized linked list
• implementing a stack
• implementing a producer consumer pattern
91. The keyword that ensures a field is coherently accessed by multiple threads is:
Answers:
• "native"
• "switch"
• "volatile"
• "synchronized"
92. ¿If the class X extends the class Y, wich of these is a polymorphic sentence?
Answers:
• Y y1 = (Y) new X(); y1.methodOfY();
• Y y1= new Y(); y1.methodOfX();
• Y y1= new X(); y1.methodOfY();
• Y y1= new X(); y1.methodOfX();
93. The TreeMap class is Java's implementation of which data structure?
Answers:
• Linked list
• B+ tree
• Red-Black tree
• B-tree
94. I would implement a LRU cache using only JDK classes by...
Answers:
• An ArrayList and binary search over the last accessed timestamp
• A Hashtable and iteration over all values that contain a last accessed timestamp.
• A LinkedList and binary search over the last accessed timestamp
• A TreeMap and iteration over values that containing a last accessed timestamp
95. Which code fragments correctly create and initialize a static array of int elements?
Answers:
• static final int[] a; static { a=new int[2]; a[0]=100; a[1]=200; }
• static final int a = { 100,200 };
• static final int[] a = new int[2]{ 100,200 };
• static final int[] a; static void init() { a = new int[3]; a[0]=100; a[1]=200; }
96. Which of the following are not a valid declarations?
Answers:
• float f = 1.2f;
• float f = (float)1.2;
• float f = 1.2;
• float f =1;
97. You need to keep a list of one million objects sorted at all times having 100 random inserts and delete per second. Reads from the list are always done in sorted order.  You would:
Answers:
• Use a HashMap to keep the list ordered at all times.
• Use a TreeMap for fast inserts and iterate over the list in order to re-sort it after each insert.
• Use a PriorityQueue to keep the list ordered at all times.
• Use a shell sort after each insert.
98. Livelock describes a situation in which two or more threads block each other, because:
Answers:
• Their actions are also responses to the actions of others, such that all are too busy to respond
• They are unable to gain access to shared resources, and cannot make any progress
• A call to Thread.sleep() has suspended the action on all threads in the VM
• Each are waiting on the other thread(s) before acting, such that no thread takes action
99. Which of the following is true about the Cloneable interface?
Answers:
• It changes the behavior of the protected clone method to give a field-by-field (reference) copy of the object.
• Is just a marker interface that does nothing.
• Creates an exact copy of the implementing class by calling its constructor.
• It provides a clone method that must be implemented.
100. You want to listen TCP connections on port 9000. How would you create the socket?
Answers:
• new Socket(9000);
• new ServerSocket(9000);
• new ServerSocket(“localhost”, 9000);
• new Socket(“localhost”, 9000);
101. The TreeMap and LinkedHashMap classes:
Answers:
• Enable iteration of a map's entries based on the insertion order of elements only.
• Enable iteration of a map's entries based either natural ordering of keys OR natural ordering of values - depending on the arguments sent to the constructor.
• Enable iteration of a map's entries based on natural ordering of keys only.
• Enable iteration of a map's entries in a deterministic order.
102. public class Test{ public static void main(String [] arg){ int x=10; if(x++ > 10 && x++ == 12){ ++x; } System.out.println(x); } }  What is the Output of this code?
Answers:
• 10
• 13
• 11
• 12
103. A Guarded Block is a concurrency idiom in which:
Answers:
• A condition is polled before the execution of a code block can proceed
• A block of code will only ever be executed in synchronized mode
• A block of code is protected by an intrinsic lock obtained from a specific Object or Class
• All statements in a block of code are guaranteed to be executed completely, or not at all
104. What's the output of following error ?  class A {   public Number getNumber(){       return 1;   } }  class B extends A {      public int getNumber(){       return 2;   } }   public class Main{       public static void main(String []args){         A a = new B();         System.out.println(a.getNumber());      } }
Answers:
• 1
• RuntimeError
• Compilation error
• 2
105. A class may extend:
Answers:
• Only one interface
• Only one non-final class
• Only one inner class
• Many classes through multiple inheritance
106. What is the difference between a checked and unchecked exception?
Answers:
• An unchecked exception extends Throwable and a checked exception does not.
• Unchecked exceptions must be caught while checked do not need to be caught
• Checked exceptions must be caught while unchecked do not need to be caught
• A checked exception extends Throwable and an unchecked exception does not.
107. What is the name of the method used to start a thread execution?
Answers:
• resume();
• init();
• run();
• start();
108. Java variables are passed into methods as:
Answers:
• Pass-by Value
• Pass-by Reference
• Neither
109. What is @Override annotation used for?
Answers:
• It makes compiler check that method is really overridden
• It just makes your code easier to read
• It makes method virtual
110. What is the correct syntax for importing java.util.Scanner?
Answers:
• import.java.util.scanner;
• import java.util.Scanner;
• import.java.util.scanner.
• import. java.util.Scanner;
111. What is the output?      public static void main(String[] args) {         int x=10;         if(x++ > 9 && x++ == 12){             ++x;         }         System.out.println(x);     }
Answers:
• 11
• 12
• 13
• 10
112. What will be the output of this code?  class Main {    static abstract class Base {                  protected Base() {                       init();                 }                                  abstract void init(); }                   static class Child extends Base {                 private final int value;                           public Child() {                           value = 5;                  }                                  @Override                public void init() {                      System.out.println("value = " + value);              }       }                public static void main(String[] args) {                  Child c = new Child();       } }
Answers:
• Runtime exception
• Compilation error
• value = 5
• value = 0

No comments:

Post a Comment