0% found this document useful (1 vote)
3K views27 pages

Collections Linkedlist List Hashtest String Hashtest String: Import Java Import Java Import Java Public Class

The code defines an enum State with values ACTIVE, INACTIVE, and DELETED. Checking equality between enum values using == returns true, but using < is undefined for enums. The code compiles without exceptions and statements A, B, and C are true.

Uploaded by

khardemegha
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
3K views27 pages

Collections Linkedlist List Hashtest String Hashtest String: Import Java Import Java Import Java Public Class

The code defines an enum State with values ACTIVE, INACTIVE, and DELETED. Checking equality between enum values using == returns true, but using < is undefined for enums. The code compiles without exceptions and statements A, B, and C are true.

Uploaded by

khardemegha
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Given the code. What is the result? import java.util.Collections; import java.util.LinkedList; import java.util.

List; public class HashTest { private String str; public HashTest(String str) { this.str = str; } @Override public String toString() { return this.str; } public static void main(String args[]) { HashTest h1 = new HashTest("2"); String s1 = new String("1"); List<Object> list = new LinkedList<Object>(); list.add(h1); list.add(s1); Collections.sort(list); for (Object o : list) { System.out.print(o + " "); } } }

compilation fails. ==Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<Object>). The inferred type Object is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>

public class EmptyStringsTest { public static boolean isEmpty(String s) { return (s == null | s.length() == 0); } public static void main(String args[]) { if (isEmpty(null)) { System.out.print("empty "); } else { System.out.print("not_empty "); } } }

==You get a NullPointerException when you try to call a method using a variable that is null.

Simple example: String s = null; int len = s.length();

// NullPointerException because s is null

So you should check if the variable is null before calling any method on it, for example: int len; if (s == null) { len = 0; } else { len = s.length(); // safe, s is never null when you get here } Note that a NullPointerException is usually easy to solve. Carefully look at the stack trace of the exception, it tells you exactly in which line of your code the exception happens. Check what could benull in that line of code, and check if you're calling a method on something that might be null. Add a check (or prevent that the relevant thing can ever be null in another way).
link|improve this answer answered Jun 1 '10 at 14:23

Jesper

17.4k12050

class Small { public Small() { System.out.print("a "); super(); } } class Small2 extends Small { public Small2() { System.out.print("b "); super(); } } class Small3 extends Small2 { public Small3() { System.out.print("c "); super(); } } public class Test { public static void main(String args[]) { new Small3(); } } ==Constructor call must be the first statement in a constructor

class Hotel { public int bookings; public void book() { bookings++; } } public class SuperHotel extends Hotel { public void book() { bookings--; } public void book(int size) { book(); super.book(); bookings += size; } public static void main(String args[]) { Hotel hotel = new SuperHotel(); hotel.book(2); System.out.print(hotel.bookings); }

A) Compilation fails. B) An exception is thrown at runtime. C) 0 D) 1 E) 2 F) -1 ==Hotel hotel cannot be used to call book(int) as it is not present in Hotel
iven the code. What is the result? public class SomeClass { private int value = 1; public int getValue() { return value; } public void changeVal(int value) { value = value; } public static void main(String args[]) { int a = 2; SomeClass c = new SomeClass(); c.changeVal(a); System.out.print(c.getValue());

Given two classes. What should be inserted at the beginning of the class B to compile and run it correctly? // class A package mycompany; public class A { public static void doStuff() { System.out.println("doStuff"); } } // class B import mycompany.A.*; //or Import mycompany.A.doStuff; public class B { public static void main(String args[]) { doStuff(); } }

Which code, inserted inserted at line labeled "//some code goes her", allows the class Test to be compiled? class Util { public enum State{ACTIVE, DELETED, INACTIVE} } public class Test { public static void main(String args[]) { //some code goes here } }

A) State state = State.INACTIVE; B) State state = INACTIVE; C) Util.State state = Util.State.INACTIVE; D) State state = Util.INACTIVE;
Given the code. What is the result? public class Cruiser implements Runnable { public void run() { System.out.print("go"); } public static void main(String arg[]) { Thread t = new Thread(new Cruiser());

} }

t.run(); t.run(); t.start();

A) Compilation fails. B) An exception is thrown at runtime. C) "go" is printed D) "gogogo" is printed E) "gogo" is printed
Given the code. What is the result if NullPointerException occurs at line 2? 1. try { 2. //some code goes here 3. } 4. catch (NullPointerException ne) { 5. System.out.print("1 "); 6. } 7. catch (RuntimeException re) { 8. System.out.print("2 "); 9. } 10. finally { 11. System.out.print("3"); 12. }

A) 1 B) 3 C) 1 3 D) 2 3 E) 1 2 3 F) 3 1
Given the code. What is the result? DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.US); Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, 2009); c.set(Calendar.MONTH, 6); c.set(Calendar.DAY_OF_MONTH, 1); String formattedDate = df.format(c.getTime()); System.out.println(formattedDate);

A) July 1, 2009 B) June 1, 2009 C) Compilation fails D) An exception is thrown at runtime


public class Cruiser { private int a = 0; public void foo() { Runnable r = new LittleCruiser(); new Thread(r).start(); new Thread(r).start(); } public static void main(String arg[]) { Cruiser c = new Cruiser(); c.foo(); } public class LittleCruiser implements Runnable { public void run() { int current = 0; for (int i = 0; i < 4; i++) { current = a; System.out.print(current + ", "); a = current + 2; } } } }

A) 0, 2, 4, 0, 2, 4, 6, 6, B) 0, 2, 4, 6, 8, 10, 12, 14, C) 0, 2, 4, 6, 8, 10, 2, 4,//can be D) 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14, E) 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,
Given the code. What is the result? import java.util.Arrays; public class HashTest { private String str; public HashTest(String str) {

this.str = str;

@Override public String toString() { return this.str; } public static void main(String args[]) { HashTest h1 = new HashTest("2"); String s1 = new String("1"); Object arr[] = new Object[2]; arr[0] = h1; arr[1] = s1; Arrays.sort(arr); for (Object o : arr) { System.out.print(o + " "); }

} }

A) "2 1" is printed. B) "1 2" is printed. C) Compilation fails.


Exception in thread "main" java.lang.ClassCastException: ArrayTest cannot be cast to java.lang.Comparable

D) An exception is thrown at runtime.

sort
public static void sort(Object[] a)

Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement theComparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array). This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort. The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance. Parameters: a - the array to be sorted. Throws:

- if the array contains elements that are not mutually comparable (for example, strings and integers). See Also:
ClassCastException Comparable

iven the code. What is the result? import java.util.HashSet; public class HashTest { private String str; public HashTest(String str) { this.str = str; } @Override public String toString() { return str; } @Override public int hashCode() { return this.str.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof HashTest) { HashTest ht = (HashTest) obj; return this.str.equals(ht.str); } return false; } public static void main(String args[]) { HashTest h1 = new HashTest("1"); HashTest h2 = new HashTest("1"); String s1 = new String("2"); String s2 = new String("2"); HashSet<Object> hs = new HashSet<Object>(); hs.add(h1); hs.add(h2); hs.add(s1); hs.add(s2); } } System.out.print(hs.size());

A) "4" is printed. B) "3" is printed.

C) "2" is printed. D) Compilation fails. E) An exception is thrown at runtime.


iven the code. What is the result? import java.util.HashSet; public class HashTest { private String str; public HashTest(String str) { this.str = str; } @Override public int hashCode() { return this.str.hashCode(); } @Override public boolean equals(Object obj) { return this.str.equals(obj); } public static void main(String args[]) { HashTest h1 = new HashTest("1"); HashTest h2 = new HashTest("1"); String s1 = new String("2"); String s2 = new String("2"); HashSet<Object> hs = new HashSet<Object>(); hs.add(h1); hs.add(h2); hs.add(s1); hs.add(s2); System.out.print(hs.size()); } }

A) "4" is printed. B) "3" is printed. C) "2" is printed. D) Compilation fails. E) An exception is thrown at runtime.
Given the code. What is true about it? (Choose all that apply)

enum State{ACTIVE, INACTIVE, DELETED}

A) State.ACTIVE == State.ACTIVE is true B) State.ACTIVE == State.INACTIVE is false C) State.ACTIVE.equals(State.ACTIVE) is true D) State.ACTIVE < State.INACTIVE is true// this operation is undefined for State
Given the code. What is the result? 1. public static void main(String args[]) { 2. Object myObj = new String[]{"one", "two", "three"} { 3. for (String s : (String[])myObj) System.out.print(s + "."); 4. } 5. }

A) one.two.three. B) Compilation fails because of an error at line 2 C) Compilation fails because of an error at line 3
Which three will compile without exception? (Choose three)

D) An exception is thrown at runtime.

A) private synchronized SomeClass a; B) void book() { synchronized () {} } C) public synchronized void book() {} D) public synchronized(this) void book() {} E) public void book() { synchronized(Cruiser.class) {} } F) public void book() {synchronized(a){}}
public static void main(String args[]) { try { String arr[] = new String[10]; arr = null; arr[0] = "one"; System.out.print(arr[0]); } catch(NullPointerException nex) { System.out.print("null pointer exception");

} catch(Exception ex) { System.out.print("exception"); } } null pointer exception

Given the code. Which line of code marks the earliest point that an object referenced by myInt becomes a candidate for garbage collection? 1 public void doStuff() { 2 Integer arr[] = new Integer[5]; 3 for (int i = 0; i < arr.length; i++) { 4 Integer myInt = new Integer(i); 5 arr[i] = myInt; 6 } 7 System.out.println("end"); 8 }

A) Line 4 B) Line 5 C) Line 6 D) Line 7 At line 8


Because each time a new myInt is created it's reference is assigned to one of the array references). More specifically the answer should be Line 8??what say??yeah it's not given in option..but still it should have been given then..

Given the code. What is the result? public class TryMe { public static void printB(String str) { System.out.print(Boolean.valueOf(str) ? "true" : "false"); } public static void main(String args[]) { printB("tRuE"); printB("false"); } }

A) "truefalse" is written. B) "falsefalse" is written. C) "truetrue" is written. D) Compilation fails.

E) An exception is thrown at runtime.


When comparing java.io.BufferedWriter to java.io.FileWriter, which capability exist as a method in only one of the two? Andy ribbell Hr 9085595343 7327899906

A) Closing the stream B) flushing the stream C) writing to the stream D) marking a location in the stream E) writing a line separator to the stream
Given the code. What is the result? public class TrickyNum<X extends Number> { private X x; public TrickyNum(X x) { this.x = x; } private double getDouble() { return x.doubleValue(); } public static void main(String args[]) { TrickyNum<Integer> a = new TrickyNum<Integer>(new Integer(1)); System.out.print(a.getDouble()); }

A) Compilation fails. B) An exception is thrown at runtime. C) "1.0" is printed. D) "1" is printed.


iven the code. What is the result? public class Hotel {

private static void book() { System.out.print("book"); } public static void main(String[] args) { Thread.sleep(1); book(); } }

A) Compilation fails. B) An exception is thrown at runtime. C) "book" is printed. D) The code executes normally, but nothing is printed.
ive a piece of code. What is true? public void waitForSomething() { SomeClass o = new SomeClass(); synchronized (o) { o.wait(); o.notify(); } }

A) This code may throw an InterruptedException B) This code may throw an IllegalStateException C) This code may throw a TimeOutException D) Reversing the ofrer of o.wait() and o.notify() will cause this method to complete normally.
Compilation fails. Unhandled exception type InterruptedException.
Run after adding throws or try catch Given the code. What is the result? public class SomeClass { private Integer value = 1; public Integer getValue() { return value; } public void changeVal(Integer value) { value = new Integer(3); } public static void main(String args[]) { Integer a = new Integer(2);

} }

SomeClass c = new SomeClass(); c.changeVal(a); System.out.print(a);

A) "1" is printed B) "2" is printed C) Compilation fails D) An exception is thrown at runtime


hat apply) import java.util.*; class Empty { } class Extended extends Empty { } public class TryMe { public static void doStuff1(List<Empty> list) { // some code } public static void doStuff2(List list) { // some code } public static void doStuff3(List<? extends Empty> list) { // some code } public static void main(String args[]) { List<Empty> list1 = new LinkedList<Empty>(); List<Extended> list2 = new LinkedList<Extended>(); // more code here } }

A) doStuff1(list1); B) doStuff2(list2); C) doStuff2(list1); D) doStuff3(list1); E) doStuff3(list2); F) doStuff1(list2);

Given: d is a valid, non-null java.util.Date object df is a valid, non-null java.text.DateFormat object set to the current locale. What outputs the current locale's country name and the appropriate version of date?

A) Locale l = Locale.getDefault(); System.out.println(l.getDisplayCountry() + " " + df.format(d)); B) Locale l = Locale.getLocale(); System.out.println(l.getDisplayCountry()); C) Locale l = Locale.getLocale(); System.out.println(l.getDisplayCountry() + " " + df.setDateFormat(d)); D) Locale l = Locale.getDefault(); System.out.println(l.getDisplayCountry() + " " + df.setDateFormat(d));
Given the code. What is the result? import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class TryMe { public static void main(String args[]) { List list = new LinkedList<String>(); list.add("one"); list.add("two"); list.add("three"); Collections.reverse(list); Iterator iter = list.iterator(); for (Object o : iter) { System.out.print(o + " "); }

} }

A) "three two one " is printed B) "one two three " is printed C) Nothing is printed

D) Compilation fails E) An exception is thrown at runtime


Given the code. What is the result? class Hotel { public void book() throws Exception { throw new Exception(); } } public class SuperHotel extends Hotel { public void book() { System.out.print("booked"); } public static void main(String args[]) { Hotel h = new SuperHotel(); h.book(); } }

A) An exception is thrown at runtime. B) Compilation fails. C) The code runs without any output. D) "boked" is printed.
Given two classes defined in two different files. What is required at line marked "//some code goes here" to process the method doStuff() of a class A? // The first file package pack1; public class ClassA { public static void doStuff() { System.out.println("doStuff"); } } // The second file package pack2; public class ClassB { public static void main(String args[]) { //some code goes here } }

A) ClassA.doStuff(); B) pack1.ClassA.doStuff();

C) doStuff(); D) It is impossible to use the method doStuff() in the class B. E) import pack1.A.*; doStuff();

Complete the class that maps Strings to Integers. import java.util.*; public class StringToInteger { HashMap <String, Integer> hm = new HashMap<String, Integer>(); public void add( String a, Integer b) { hm.put(a, b); } public Collection<String> getKeys() { return hm.keySet(); } public Collection<Integer> getValues() { return hm.values(); } public static void main(String args[]) { StringToInteger si = new StringToInteger(); si.add("one", 1); si.add("two", 2); System.out.println(si.getKeys()); System.out.println(si.getValues());

} }

<Integer, String> Set<String> Set<Integer>

Given the code. What is the output? public class Test { int a = 10; public void doStuff(int a) {

a += 1; System.out.println(++a); } public static void main(String args[]) { Test t = new Test(); t.doStuff(3); }

A) 4 B) 5 C) 12 D) 11
Given the code. What is true? public class Room { public int roomNr; private Date beginDtm; private Date endDttm; public void book(int roomNr, Date beginDttm, Date endDttm) { this.roomNr = roomNr; this.beginDtm = beginDttm; this.endDttm = endDttm; }

A) The code demonstrates polymorphism. B) The class is fully encapsulated. C) The variable roomNr breaks encapsulation. D) Variables beginDttm and endDttm break polymorphism. E) The method book breaks encapsulation.
Given the code. What is the result? public class Hotel { private static void book() { System.out.print("book"); } public static void main(String[] args) throws InterruptedException { Thread.sleep(1); book(); }

A) Compilation fails. B) An exception is thrown at runtime. C) "book" is printed D) The code executes normally, but nothing is printed.
Given the code. What is the result? import java.util.HashSet; public class HashTest { private String str; public HashTest(String str) { this.str = str; } public static void main(String args[]) { HashTest h1 = new HashTest("1"); HashTest h2 = new HashTest("1"); String s1 = new String("2"); String s2 = new String("2"); HashSet<Object> hs = new HashSet<Object>(); hs.add(h1); hs.add(h2); hs.add(s1); hs.add(s2); System.out.print(hs.size()); } }

A) "4" is printed. B) "3" is printed. C) "2" is printed. D) Compilation fails.


What is true? (Choose three)

A) A method with the same signature as a private final method in class Z can be implemented in a subclass of Z. B) A final method in class Z can be abstract if and only if Z is abstract.

C) A protected method in class Z can be overriden by any subclass of Z. D) A private static method can be called only within other static methods in class Z. E) A non-static public final method in class Z can be overriden in any subclass of Z. F) A public static method in class Z can be called by a subclass of Z without explicitly referencing the class Z.
Given the code. What is the result? public class TrickyNum<X extends Object> { private X x; public TrickyNum(X x) { this.x = x; } private double getDouble() { return x.doubleValue(); } public static void main(String args[]) { TrickyNum<Integer> a = new TrickyNum<Integer>(new Integer(1)); System.out.print(a.getDouble()); }

A) Compilation fails. B) An exception is thrown at runtime. C) "1.0" is printed. D) "1" is printed.


What do you need to do to correct compilation errors? (Select two) public class Creature { private int legCount; private int wingCount; public Creature(int legCount) { this.legCount = this.legCount; this.wingCount = 0; } public String toString() { return "legs=" + this.legCount + " wings=" + wingCount; }

public class Animal extends Creature {

public Animal(int legCount) { this.wingCount = 0; } }

A) insert a call to super() into Creature constructor. B) insert a call to super() into Animal constructor. C) insert a call to this() into Animal constructor. D) insert a call to super(legCount) into Animal constructor. E) change the wingCount variable in the class Creature to protected. F) change the string "this.wingCount = 0" in the class Animal to "super.wingCount = 0"
Give the code. What is the result? class Hotel { public int bookings; public void book() { bookings++; } } public class SuperHotel extends Hotel { public void book() { bookings--; } public void book(int size) { book(); super.book(); bookings += size; } public static void main(String args[]) { SuperHotel hotel = new SuperHotel(); hotel.book(2); System.out.print(hotel.bookings); }

A) Compilation fails. B) An exception is thrown at runtime. C) 0 D) 1

E) 2 F) -1
Given the code. What is the output? public class Test { int a = 10; public void doStuff(int a) { a += 1; System.out.println(a++); } public static void main(String args[]) { Test t = new Test(); t.doStuff(3); } }

A) 11 B) 12 C) 4 D) 5
Given the code. What is the result? import java.util.Collections; import java.util.LinkedList; public class TryMe { public static void main(String args[]) { LinkedList<String> list = new LinkedList<String>(); list.add("BbB1"); list.add("bBb2"); list.add("bbB3"); list.add("BBb4"); Collections.sort(list); for (String str : list) { System.out.print(str + ":"); } } }

A) "BbB1:bBb2:bbB3:BBb4:" is printed. B) "BBb4:bbB3:bBb2:BbB1:" is printed. C) "BBb4:BbB1:bBb2:bbB3:" is printed.

D) "bbB3:bBb2:BbB1:BBb4:" is printed E) Compilation fails. F) An exception is thrown at runtime.


Given the code. What is the result? import java.io.*; public class Hotel implements Serializable { private Room room = new Room(); public static void main(String[] args) { Hotel h = new Hotel(); try { FileOutputStream fos = new FileOutputStream("Hotel.dat"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(h); oos.close(); } catch(Exception ex) { ex.printStackTrace(); } }

class Room { }

A) Compilation fails. B) An instance of Hotel is serialized. C) An instance of Hotel and an instance of Room are both serialized. D) An exception is thrown at runtime.
Given the code. What is the result? public static void main(String args[]) { String str = null; if (str.length() == 0) { System.out.print("1"); } else if (str == null) { System.out.print("2"); } else { System.out.print("3"); } }

A) Compilation fails. B) "1" is printed.

C) "2" is printed. D) "3" is printed. E) An exception is thrown at runtime.


Given the code. What is the result? import java.util.*; public class TryMe { public static void main(String args[]) { Queue<String> q = new PriorityQueue<String>(); q.add("3"); q.add("1"); q.add("2"); System.out.print(q.poll() + " "); System.out.print(q.peek() + " "); System.out.print(q.peek()); } }

A) 1 2 3 B) 3 2 1 C) 1 2 2 D) 3 1 1 E) 2 3 3 F) 1 1 2
Given the code. What is the result? public class SomeClass { private int value = 1; public void printVal(int value) { System.out.print(value); } public static void main(String args[]) { int a = 2; SomeClass c = new SomeClass(); c.printVal(a); }

A) "1" is printed

B) "2" is printed C) Compilation fails D) An exception is thrown at runtim


iven the code. What is the result? public class Cruiser implements Runnable { public static void main(String[] args) { Thread a = new Thread(new Cruiser()); a.start(); System.out.print("Begin"); a.join(); System.out.print("End");

public void run() { System.out.print("Run"); } }

A) Compilation fails. B) An exception is thrown at runtime. C) "BeginRunEnd" is printed. D) "BeginEndRun" is printed. E) "BeginEnd" is printed.
Given the code. What is the result? public class Test { private static void doStuff(String str) { int var = 4; if (var == str.length()) { System.out.print(str.charAt(var--) + " "); } else { System.out.print(str.charAt(0) + " "); } } public static void main(String args[]) { doStuff("abcd"); doStuff("efg"); doStuff("hi"); } }

A) Compilation fails.

B) An exception is thrown at runtime. C) d e h D) d f i E) c f i F) c e h

Which piece of code will allow this class to be correctly serialzed and desirialized? Drag and drop the correct fragment. import java.io.*; public class Car implements Serializable { public int speeds; public int wheels; private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeInt(speeds); oos.writeInt(wheels); } private void readObject(ObjectInputStream ois) throws IOException { speeds = ois.readInt(); wheels = ois.readInt(); } } ois.defaultReadObject(); this = ois.defaultReadObject(); wheels = ois.readInt(); speeds = ois.readInt();

Given: System.out.printf("Pi = %f and E = %b", Math.PI, Math.E). Place values where they would appear in the output Pi = 3.141593 and E = true 3 2 2.718282 false

Which three statements concerning the use of the java.io.Serializable interface are true? (Choose three)

A) object from classes tha use aggregation cannot be serialized. B) An object serialized on one JVM can be deserialized on a different JVM. C) The values in fields with the volatile modifier will not survive serialization and deserialization. D) The values in field with the transient modifier will not survive serialization and deserialization. E) It is legal to serialize an object of a type that has a supertype that does not implement java.io.Serializable

You might also like