Questions and Answers. Q.3) asses is not part of Java's collection framework?explanation:

Size: px
Start display at page:

Download "Questions and Answers. Q.3) asses is not part of Java's collection framework?explanation:"

Transcription

1 Q.1) $ javac vector.java $ java vector 4 A. [3, 2, 6] B. [3, 2, 8] C. [3, 2, 6, 8] D. [3, 2, 8, 6] ANSWER : [3, 2, 8, 6] $ javac vector.java $ java vector [3, 2, 8, 6] Q.2) Which interface does java.util.hashtable implement? A. Java.util.Map B. Java.util.List C. Java.util.HashTable D. Java.util.Collection ANSWER : Java.util.Map Hash table based implementation of the Map interface. Q.3) asses is not part of Java's collection framework?explanation: A. Maps B. Array C. Stack D. Queue ANSWER : Queue Queue is not a part of collection framework. Q.4) Which of these methods can be used to delete the last element in a LinkedList object? A. remove() B. delete() C. removelast() D. deletelast() ANSWER : removelast() removelast() and removefirst() methods are used to remove elements in end and beginning of a linked list. Q.5) Which of these method can be used to increase the capacity of ArrayList object manually? A. Capacity() B. increasecapacity() C. increasecapacity() D. ensurecapacity() Page 1

2 ANSWER : ensurecapacity() When we add an element, the capacity of ArrayList object increases automatically, but we can increase it manually to specified length x by using function ensurecapacity(x); Q.6) Which of the following statements about the hashcode() method are incorrect? 1. The value returned by hashcode() is used in some collection classes to help locate objects. 2. The hashcode() method is required to return a positive int value. 3. The hashcode() method in the String class is the one inherited from Object. 4. Two new empty String objects will produce identical hashcodes. A. 1 and 2 B. 2 and 3 C. 3 and 4 D. 1 and 4 ANSWER : 2 and 3 (2) is an incorrect statement because there is no such requirement. (3) is an incorrect statement and therefore a correct answer because the hashcode for a string is computed from the characters in the string. Q.7) What is the output of this program? class Output ArrayList obj = new ArrayList(); obj.add("a"); obj.ensurecapacity(3); System.out.println(obj.size()); A. 1 B. 2 C. 3 D. 4 ANSWER : 1 Although obj.ensurecapacity(3); has manually increased the capacity of obj to 3 but the value is stored only at index 0, therefore obj.size() returns the total number of elements stored in the obj i:e 1, it has nothing to do with ensurecapacity(). $ javac Output.java $ java Output 1 Q.8) class Test1 public int value; public int hashcode() return 42; class Test2 Page 2

3 public int value; public int hashcode() return (int)(value^5); which statement is true? A. class Test1 will not compile. B. The Test1 hashcode() method is more efficient than the Test2 hashcode() method. C. The Test1 hashcode() method is less efficient than the Test2 hashcode() method. D. class Test2 will not compile. ANSWER : The Test1 hashcode() method is less efficient than the Test2 hashcode() method. The so-called "hashing algorithm" implemented by class Test1 will always return the same value, 42, which is legal but which will place all of the hash table entries into a single bucket, the most inefficient setup possible. Option A and D are incorrect because these classes are legal. Option B is incorrect based on the logic described above. Q.9) Which of these interface handle sequences? A. Set B. List C. Comparator D. Collection ANSWER : List A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for the following: Positional access : manipulates elements based on their numerical position in the list. This includes methods such as get, set, add, addall, and remove. Search : searches for a specified object in the list and returns its numerical position. Search methods include indexof and lastindexof. Iteration : extends Iterator semantics to take advantage of the list's sequential nature. The listiterator methods provide this behavior. Range-view : The sublist method performs arbitrary range operations on the list. Q.10) Which of these interface must contain a unique element? A. Set B. List C. Array D. Collection ANSWER : Set Set interface extends collection interface to handle sets, which must contain unique elements. Q.11) What is the output of this program? class Maps HashMap obj = new HashMap(); Page 3

4 obj.put("a", new Integer(1)); obj.put("b", new Integer(2)); obj.put("c", new Integer(3)); System.out.println(obj); A. A 1, B 1, C 1 B. A, B, C C. A-1, B-1, C-1 D. A=1, B=2, C=3 ANSWER : A=1, B=2, C=3 $ javac Maps.java $ java Maps A=1, B=2, C=3 Q.12) What is the output of this program? class vector Vector obj = new Vector(4,2); obj.addelement(new Integer(3)); obj.addelement(new Integer(2)); obj.addelement(new Integer(5)); obj.removeall(obj); System.out.println(obj.isEmpty()); A. 0 B. 1 C. true D. false ANSWER : true firstly elements 3, 2, 5 are entered in the vector obj, but when obj.removeall(obj); is executed all the elements are deleted and vector is empty, hence obj.isempty() returns true. $ javac vector.java $ java vector true Q.13) What is the output of this program? class Collection_Algos LinkedList list = new LinkedList(); list.add(new Integer(2)); list.add(new Integer(8)); list.add(new Integer(5)); list.add(new Integer(1)); Iterator i = list.iterator(); while(i.hasnext()) System.out.print(i.next() + " "); Page 4

5 A B C. 2 D ANSWER : $ javac Collection_Algos.java $ java Collection_Algos Q.14) What is the output of this program? class Output TreeSet t = new TreeSet(); t.add("3"); t.add("9"); t.add("1"); t.add("4"); t.add("8"); System.out.println(t); A. [1, 3, 5, 8, 9] B. [3, 4, 1, 8, 9] C. [9, 8, 4, 3, 1] D. [1, 3, 4, 8, 9] ANSWER : [1, 3, 4, 8, 9] TreeSet class uses set to store the values added by function add in ascending order using tree for storage $ javac Output.java $ java Output [1, 3, 4, 8, 9] Q.15) Which of these method is used add an element and corresponding key to a map? A. put() B. set() C. redo() D. add() ANSWER : put() Maps revolve around two basic operations, get() and put(). to put a value into a map, use put(), specifying the key and the value. To obtain a value, call get(), passing the key as an argument. The value is returned, Q.16) What is the output of this program? class Maps Page 5

6 A. [A, B, C] B. A, B, C C. 1, 2, 3 D. [1, 2, 3] HashMap obj = new HashMap(); obj.put("a", new Integer(1)); obj.put("b", new Integer(2)); obj.put("c", new Integer(3)); System.out.println(obj.keySet()); ANSWER : [A, B, C] keyset() method returns a set containing all the keys used in the invoking map. Here keys are characters A, B & C. 1, 2, 3 are the values given to these keys. $ javac Maps.java $ java Maps [A, B, C] Q.17) What is the output of this program? class Maps TreeMap obj = new TreeMap(); obj.put("a", new Integer(1)); obj.put("b", new Integer(2)); obj.put("c", new Integer(3)); System.out.println(obj.entrySet()); A. [A, B, C] B. [1, 2, 3] C. A=1, B=2, C=3 D. [A=1, B=2, C=3] ANSWER : [A=1, B=2, C=3] obj.entryset() method is used to obtain a set that contains the entries in the map. This method provides set view of the invoking map. $ javac Maps.java $ java Maps [A=1, B=2, C=3] Q.18) Which of these is true about unmodifiablecollection() method? A. unmodifiablecollection() returns a collection that cannot be modified. B. unmodifiablecollection() method is available only for List and Set. C. unmodifiablecollection() is defined in Collection class. D. None of the mentioned. ANSWER : unmodifiablecollection() method is available only for List and Set. unmodifiablecollection() is available for al collections, Set, Map, List etc. Page 6

7 Q.19) What is the output of this program? class Array int array[] = new int [5]; for (int i = 5; i > 0; i--) array[5 - i] = i; Arrays.sort(array); System.out.print(Arrays.binarySearch(array, 4)); A. 2 B. 3 C. 4 D. 5 ANSWER : 3 $ javac Array.java $ java Array 3 Q.20) Which of these class object can be used to form a dynamic array? A. ArrayList B. Map C. Vector D. Both a & b ANSWER : Both a & b Vectors are dynamic arrays, it contains many legacy methods that are not part of collection framework, and hence these methods are not present in ArrayList. But both are used to form dynamic arrays. Q.21) What is the output of this program? class Array int array[] = new int [5]; for (int i = 5; i > 0; i--) array[5-i] = i; Arrays.fill(array, 1, 4, 8); for (int i = 0; i < 5 ; i++) System.out.print(array[i]); A B C D ANSWER : array was containing 5,4,3,2,1 but when method Arrays.fill(array, 1, 4, 8) is called it fills the index location starting with 1 to 4 by value 8 hence array becomes 5,8,8,8,1. Page 7

8 $ javac Array.java $ java Array Q.22) What is the output of this program? class Collection_Algos LinkedList list = new LinkedList(); list.add(new Integer(2)); list.add(new Integer(8)); list.add(new Integer(5)); list.add(new Integer(1)); Iterator i = list.iterator(); Collections.reverse(list); while(i.hasnext()) System.out.print(i.next() + " "); A B C. 2 D ANSWER : Collections.reverse(list) reverses the given list, the list was 2->8->5->1 after reversing it became 1->5->8->2. $ javac Collection_Algos.java $ java Collection_Algos Q.23) Which collection class allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized? A. java.util.hashset B. java.util.linkedhashset C. java.util.list D. java.util.arraylist ANSWER : java.util.arraylist All of the collection classes allow you to grow or shrink the size of your collection. ArrayList provides an index to its elements. The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayList functionality and has synchronized methods; it is slower than ArrayList. Q.24) What is the output of this program? class vector Vector obj = new Vector(4,2); obj.addelement(new Integer(3)); obj.addelement(new Integer(2)); obj.addelement(new Integer(5)); System.out.println(obj.elementAt(1)); Page 8

9 A. 0 B. 3 C. 2 D. 5 ANSWER : 2 obj.elementat(1) returns the value stored at index 1, which is 2. $ javac vector.java $ java vector 2 Q.25) What is the output of this program? class Maps TreeMap obj = new TreeMap(); obj.put("a", new Integer(1)); obj.put("b", new Integer(2)); obj.put("c", new Integer(3)); System.out.println(obj.entrySet()); A. [A, B, C] B. [1, 2, 3] C. A=1, B=2, C=3 D. [A=1, B=2, C=3] ANSWER : [A=1, B=2, C=3] obj.entryset() method is used to obtain a set that contains the entries in the map. This method provides set view of the invoking map. $ javac Maps.java $ java Maps [A=1, B=2, C=3] Q.26) Which of these methods can be used to obtain set of all keys in a map? A. getall() B. getkeys() C. keyall() D. keyset() ANSWER : keyset() keyset() methods is used to get a set containing all the keys used in a map. This method provides set view of the keys in the invoking map. Q.27) Which of these return type of hasnext() method of an iterator? A. Integer B. Double C. Boolean Page 9

10 D. Collections Object ANSWER : Boolean hasnext() returns boolean values true or false. Q.28) Which of these method is used to change an element in a LinkedList Object? A. change() B. set() C. redo() D. add() ANSWER : redo() An element in a LinkedList object can be changed by first using get() to obtain the index or location of that object and the passing that location to method set() along with its new value. Q.29) What is Collection in Java? A. A group of objects B. A group of classes C. A group of interfaces D. None of the mentioned ANSWER : A group of objects A collection is a group of objects, it is similar to String Template Library (STL) of C++ programming language. Q.30) What will be the output of the program? public class Test public static void main (String args[]) String str = NULL; System.out.println(str); A. NULL B. Compile Error C. Code runs but no output D. Runtime Exception ANSWER : Compile Error Option B is correct because to set the value of a String variable to null you must use "null" and not "NULL". Q.31) Which of these interface is not a part of Java's collection framework? A. List B. Set C. SortedMap D. SortedList ANSWER : SortedList Page 10

11 SortedList is not a part of collection framework. Q.32) Which statement is true for the class java.util.arraylist? A. The elements in the collection are ordered. B. The collection is guaranteed to be immutable. C. The elements in the collection are guaranteed to be unique. D. The elements in the collection are accessed using a unique key. ANSWER : The elements in the collection are ordered. Yes, always the elements in the collection are ordered. Q.33) Which of the following are Java reserved words? 1. run 2. import 3. default 4. implement A. 1 and 2 B. 2 and 3 C. 3 and 4 D. 2 and 4 ANSWER : 2 and 3 (2) - This is a Java keyword (3) - This is a Java keyword (1) - Is incorrect because although it is a method of Thread/Runnable it is not a keyword (4) - This is not a Java keyword the keyword is implements Q.34) What will be the output of the program? public class Test public static void main (String[] args) String foo = args[1]; String bar = args[2]; String baz = args[3]; System.out.println("baz = " + baz); /* Line 8 */ And the command line invocation: > java Test red green blue A. baz = B. baz = null C. baz = blue D. Runtime Exception ANSWER : Runtime Exception When running the program you entered 3 arguments "red", "green" and "blue". When Page 11

12 dealing with arrays in java you must remember ALL ARRAYS IN JAVA ARE ZERO BASED therefore args[0] becomes "red", args[1] becomes "green" and args[2] becomes "blue". When the program entcounters line 8 above at runtime it looks for args[3] which has never been created therefore you get an ArrayIndexOutOfBoundsException at runtime. Q.35) Which of these classes implements Set interface? A. ArrayList B. HashSet C. LinkedList D. DynamicList ANSWER : HashSet HashSet and TreeSet implements Set interface where as LinkedList and ArrayList implements List interface. Q.36) Which of these method is used to change an element in a LinkedList Object? A. change() B. set() C. redo() D. add() ANSWER : redo() An element in a LinkedList object can be changed by first using get() to obtain the index or location of that object and the passing that location to method set() along with its new value. Q.37) x = 0; if (x1.hashcode()!= x2.hashcode() ) x = x + 1; if (x3.equals(x4) ) x = x + 10; if (!x5.equals(x6) ) x = x + 100; if (x7.hashcode() == x8.hashcode() ) x = x ; System.out.println("x = " + x); and assuming that the equals() and hashcode() methods are property implemented, if the output is "x = 1111", which of the following statements will always be true? A. x2.equals(x1) B. x3.hashcode() == x4.hashcode() C. x5.hashcode()!= x6.hashcode() D. x8.equals(x7) ANSWER : x3.hashcode() == x4.hashcode() By contract, if two objects are equivalent according to the equals() method, then the hashcode() method must evaluate them to be ==. Option A is incorrect because if the hashcode() values are not equal, the two objects must not be equal. Option C is incorrect because if equals() is not true there is no guarantee of any result from hashcode(). Option D is incorrect because hashcode() will often return == even if the two objects do Page 12

13 not evaluate to equals() being true. Q.38) Which of these is a method of ListIterator used to obtain index of previous element? A. previous() B. previousindex() C. back() D. goback() ANSWER : previousindex() previousindex() returns index of previous element. if there is no previous element then -1 is returned. Q.39) Which of these classes provide implementation of map interface? A. ArrayList B. HashMap C. LinkedList D. DynamicList ANSWER : HashMap AbstractMap, WeakHashMap, HashMap and TreeMap provide implementation of map interface. Q.40) Which of these interface is not a part of Java's collection framework? A. List B. Set C. SortedMap D. SortedList ANSWER : SortedList SortedList is not a part of collection framework. Q.41) What is the output of this program? class stack Stack obj = new Stack(); obj.push(new Integer(3)); obj.push(new Integer(2)); obj.pop(); obj.push(new Integer(5)); System.out.println(obj); A. [3, 5] B. [3, 2] C. [3, 2, 5] D. [3, 5, 2] ANSWER : [3, 5] push() and pop() are standard functions of the class stack, push() inserts in the stack and pop removes from the stack. 3 & 2 are inserted using push() the pop() is used which Page 13

14 removes 2 from the stack then again push is used to insert 5 hence stack contains elements 3 & 5. $ javac stack.java $ java stack [3, 5] Q.42) What will be the output of the program? public class Test private static int[] x; public static void main(string[] args) System.out.println(x[0]); A. 0 B. null C. Compile Error D. NullPointerException at runtime ANSWER : NullPointerException at runtime In the above code the array reference variable x has been declared but it has not been instantiated i.e. the new statement is missing, for example: private static int[]x = new int[5]; private static int[x] declares a static i.e. class level array. the "new" keyword is the word that actually creates said array. int[5] in association with the new sets the size of the array. so since the above code contains no new or size decalarations when you try and access x[0] you are trying to access a member of an array that has been declared but not intialized hence you get a NullPointerException at runtime. Q.43) Which of these interface declares core method that all collections will have? A. set B. EventListner C. Comparator D. Collection ANSWER : Collection Collection interfaces defines core methods that all the collections like set, map, arrays etc will have. Q.44) Which collection class allows you to associate its elements with key values, and allows you to retrieve objects in FIFO (first-in, first-out) sequence? A. java.util.arraylist B. java.util.linkedhashmap C. java.util.hashmap D. java.util.treemap ANSWER : java.util.linkedhashmap Page 14

15 LinkedHashMap is the collection class used for caching purposes. FIFO is another way to indicate caching behavior. To retrieve LinkedHashMap elements in cached order, use the values() method and iterate over the resultant collection. Q.45) Which of these methods is used to obtain an iterator to the start of collection? A. start() B. begin() C. iteratorset() D. iterator() ANSWER : iterator() To obtain an iterator to the start of the start of the collection we use iterator() method. Q.46) Which of these are legacy classes? A. Stack B. Hashtable C. Vector D. All of the mentioned ANSWER : All of the mentioned Stack, Hashtable, Vector, Properties and Dictionary are legacy classes. Q.47) What will be the output of the program? public static void main(string[] args) Object obj = new Object() public int hashcode() return 42; ; System.out.println(obj.hashCode()); A. 42 B. Runtime Exception C. Compile Error at line 2 D. Compile Error at line 5 ANSWER : 42 This code is an example of an anonymous inner class. They can be declared to extend another class or implement a single interface. Since they have no name you can not use the "new" keyword on them. In this case the annoynous class is extending the Object class. Within the you place the methods you want for that class. After this class has been declared its methods can be used by that object in the usual way e.g. objectname.annoymousclassmethod() Q.48) What will be the output of the program? package foo; import java.util.vector; /* Line 2 */ private class MyVector extends Vector Page 15

16 int i = 1; /* Line 5 */ public MyVector() i = 2; public class MyNewVector extends MyVector public MyNewVector () i = 4; /* Line 15 */ public static void main (String args []) MyVector v = new MyNewVector(); /* Line 19 */ A. Compilation will succeed. B. Compilation will fail at line 3. C. Compilation will fail at line 5. D. Compilation will fail at line 15. ANSWER : Compilation will fail at line 3. Option B is correct. The compiler complains with the error "modifier private not allowed here". The class is created private and is being used by another class on line 19. Q.49) What will be the output of the program? class H public static void main (String[] args) Object x = new Vector().elements(); System.out.print((x instanceof Enumeration)+","); System.out.print((x instanceof Iterator)+","); System.out.print(x instanceof ListIterator); A. Prints: false,false,false B. Prints: false,false,true C. Prints: false,true,false D. Prints: true,false,false ANSWER : Prints: true,false,false The Vector.elements method returns an Enumeration over the elements of the vector. Vector implements the List interface and extends AbstractList so it is also possible to get an Iterator over a Vector by invoking the iterator or listiterator method. Q.50) What will be the output of the program? public class Test private static float[] f = new float[2]; public static void main (String[] args) System.out.println("f[0] = " + f[0]); Page 16

17 A. f[0] = 0 B. f[0] = 0.0 C. Compile Error D. Runtime Exception ANSWER : f[0] = 0.0 The choices are between Option A and B, what this question is really testing is your knowledge of default values of an initialized array. This is an array type float i.e. it is a type that uses decimal point numbers therefore its initial value will be 0.0 and not 0 Q.51) Which class does not override the equals() and hashcode() methods, inheriting them directly from class Object? A. java.lang.string B. java.lang.double C. java.lang.stringbuffer D. java.lang.character ANSWER : java.lang.stringbuffer java.lang.stringbuffer is the only class in the list that uses the default methods provided by class Object. Q.52) Which of these methods is used to add elements in vector at specific location? A. add() B. set() C. AddElement() D. addelement() ANSWER : addelement() addelement() is used to add data in the vector, to obtain the data we use elementat() and to first and last element we use firstelement() and lastelement() respectively. Q.53) Which of these standard collection classes implements a dynamic array? A. AbstractList B. LinkedList C. ArrayList D. AbstractSet ANSWER : ArrayList ArrayList class implements a dynamic array by extending AbstractList class. Q.54) What is the output of this program? class Collection_iterators ListIterator a = list.listiterator(); if(a.previousindex()! = -1) while(a.hasnext()) System.out.print(a.next() + " "); else System.out.print("EMPTY"); Page 17

18 A. 0 B. 1 C. -1 D. EMPTY ANSWER : EMPTY $ javac Collection_iterators.java $ java Collection_iterators EMPTY Q.55) Which is valid declaration of a float? A. float f = 1F; B. float f = 1.0; C. float f = "1"; D. float f = 1.0d; ANSWER : float f = 1F; Option B is incorrect because any literal number with a decimal point u declare the computer will implicitly cast to double unless you include "F or f" Option C is incorrect because it is a String. Option D is incorrect because "d" tells the computer it is a double so therefore you are trying to put a double value into a float variable i.e there might be a loss of precision. Q.56) What is the output of this program? class Arraylist ArrayList obj1 = new ArrayList(); ArrayList obj2 = new ArrayList(); obj1.add("a"); obj1.add("b"); obj2.add("a"); obj2.add(1, "B"); System.out.println(obj1.equals(obj2)); A. 0 B. 1 C. true D. false ANSWER : true obj1 and obj2 are an object of class ArrayList hence it is a dynamic array which can increase and decrease its size. obj.add(";x";) adds to the array element X and obj.add(1,";x";) adds element x at index position 1 in the list, Both the objects obj1 and obj2 contain same elements i:e A & B thus obj1.equals(obj2) method returns true. $ javac Arraylist.java $ java Arraylist Page 18

19 true Q.57) What is the output of this program? class Maps HashMap obj = new HashMap(); obj.put("a", new Integer(1)); obj.put("b", new Integer(2)); obj.put("c", new Integer(3)); System.out.println(obj.get("B")); A. 1 B. 2 C. 3 D. null ANSWER : 2 obj.get(";b";) method is used to obtain the value associated with key ";B";, which is 2. $ javac Maps.java $ java Maps 2 Q.58) What is the output of this program? class Collection_iterators LinkedList list = new LinkedList(); list.add(new Integer(2)); list.add(new Integer(8)); list.add(new Integer(5)); list.add(new Integer(1)); Iterator i = list.iterator(); Collections.reverse(list); Collections.shuffle(list); i.next(); i.remove(); while(i.hasnext()) System.out.print(i.next() + " "); A B C D ANSWER : i.next() returns the next element in the iteration. i.remove() removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next(). The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method. Page 19

20 $ javac Collection_iterators.java $ java Collection_iterators (output will be different on your system) Q.59) Which of these methods can be used to search an element in a list? A. find() B. get() C. sort() D. binaryserach() ANSWER : binaryserach() binaryserach() method uses binary search to find a specified value. This method must be applied to sorted arrays. Q.60) What is the output of this program? class Linkedlist LinkedList obj = new LinkedList(); obj.add("a"); obj.add("b"); obj.add("c"); obj.addfirst("d"); System.out.println(obj); A. [A, B, C] B. [D, B, C] C. [A, B, C, D] D. [D, A, B, C] ANSWER : [D, A, B, C] obj.addfirst('d') method is used to add 'D' to the start of a LinkedList object obj. $ javac Linkedlist.java $ java Linkedlist [D, A, B, C] Q.61) What is the output of this program? class Collection_Algos LinkedList list = new LinkedList(); list.add(new Integer(2)); list.add(new Integer(8)); list.add(new Integer(5)); list.add(new Integer(1)); Iterator i = list.iterator(); Collections.reverse(list); Collections.shuffle(list); while(i.hasnext()) System.out.print(i.next() + " "); Page 20

21 A B C D. Any random order ANSWER : Any random order shuffle : randomizes all the elements in a list. $ javac Collection_Algos.java $ java Collection_Algos (output will be different on your system) Q.62) Which of these classes implements Set interface? A. ArrayList B. HashSet C. LinkedList D. DynamicList ANSWER : HashSet HashSet and TreeSet implements Set interface where as LinkedList and ArrayList implements List interface. Q.63) What is the output of this program? class Collection_Algos LinkedList list = new LinkedList(); list.add(new Integer(2)); list.add(new Integer(8)); list.add(new Integer(5)); list.add(new Integer(1)); Iterator i = list.iterator(); Collections.reverse(list); Collections.sort(list); while(i.hasnext()) System.out.print(i.next() + " "); A B C D ANSWER : Explanation: Collections.sort(list) sorts the given list, the list was 2->8->5->1 after sorting it became 1->2->5->8. $ javac Collection_Algos.java $ java Collection_Algos Q.64) What is the output of this program? Page 21

22 class Bitset BitSet obj = new BitSet(5); for (int i = 0; i < 5; ++i) obj.set(i); obj.clear(2); System.out.print(obj); A. 0, 1, 3, 4 B. 0, 1, 2, 4 C. 0, 1, 2, 3, 4 D. 0, 0, 0, 3, 4 ANSWER : 0, 1, 3, 4 $ javac Bitset.java $ java Bitset 0, 1, 3, 4 Q.65) Which statement is true for the class java.util.hashset? A. The elements in the collection are ordered. B. The collection is guaranteed to be immutable. C. The elements in the collection are guaranteed to be unique. D. The elements in the collection are accessed using a unique key. ANSWER : The elements in the collection are guaranteed to be unique. Option C is correct. HashSet implements the Set interface and the Set interface specifies collection that contains no duplicate elements. Option A is wrong. HashSet makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. Option B is wrong. The set can be modified. Option D is wrong. This is a Set and not a Map. Q.66) What is the output of this program? class Array int array[] = new int [5]; for (int i = 5; i > 0; i--) array[5-i] = i; Arrays.fill(array, 1, 4, 8); for (int i = 0; i < 5 ; i++) System.out.print(array[i]); A B C Page 22

23 D ANSWER : array was containing 5,4,3,2,1 but when method Arrays.fill(array, 1, 4, 8) is called it fills the index location starting with 1 to 4 by value 8 hence array becomes 5,8,8,8,1. $ javac Array.java $ java Array Q.67) What is the output of this program? class vector Vector obj = new Vector(4,2); obj.addelement(new Integer(3)); obj.addelement(new Integer(2)); obj.addelement(new Integer(5)); obj.removeall(obj); System.out.println(obj.isEmpty()); A. 0 B. 1 C. true D. false ANSWER : true firstly elements 3, 2, 5 are entered in the vector obj, but when obj.removeall(obj); is executed all the elements are deleted and vector is empty, hence obj.isempty() returns true. $ javac vector.java $ java vector true Q.68) Which of these is Basic interface that all other interface inherits? A. Set B. Array C. List D. Collection ANSWER : Collection Collection interface is inherited by all other interfaces like Set, Array, Map etc. It defines core methods that all the collections like set, map, arrays etc will have Q.69) What is the numerical range of char? A. 0 to B. 0 to C to 255 D to ANSWER : 0 to Page 23

24 The char type is integral but unsigned. The range of a variable of type char is from 0 to or 0 to Java characters are Unicode, which is a 16-bit encoding capable of representing a wide range of international characters. If the most significant nine bits of a char are 0, then the encoding is the same as seven-bit ASCII. Q.70) What is the output of this program? class vector Vector obj = new Vector(4,2); obj.addelement(new Integer(3)); obj.addelement(new Integer(2)); obj.addelement(new Integer(5)); System.out.println(obj.capacity()); A. 2 B. 3 C. 4 D. 6 ANSWER : 4 $ javac vector.java $ java vector 4 Q.71) Suppose that you would like to create an instance of a new Map that has an iteration order that is the same as the iteration order of an existing instance of a Map. Which concrete implementation of the Map interface should be used for the new instance? A. TreeMap B. HashMap C. LinkedHashMap D. The answer depends on the implementation of the existing instance. ANSWER : LinkedHashMap The iteration order of a Collection is the order in which an iterator moves through the elements of the Collection. The iteration order of a LinkedHashMap is determined by the order in which elements are inserted. When a new LinkedHashMap is created by passing a reference to an existing Collection to the constructor of a LinkedHashMap the Collection.addAll method will ultimately be invoked. The addall method uses an iterator to the existing Collection to iterate through the elements of the existing Collection and add each to the instance of the new LinkedHashMap. Since the iteration order of the LinkedHashMap is determined by the order of insertion, the iteration order of the new LinkedHashMap must be the same as the interation order of the old Collection. Q.72) What is the output of this program? Page 24

25 class vector Vector obj = new Vector(4,2); obj.addelement(new Integer(3)); obj.addelement(new Integer(2)); obj.addelement(new Integer(5)); obj.removeall(obj); System.out.println(obj.isEmpty()); A. 0 B. 1 C. true D. false ANSWER : true firstly elements 3, 2, 5 are entered in the vector obj, but when obj.removeall(obj); is executed all the elements are deleted and vector is empty, hence obj.isempty() returns true. $ javac vector.java $ java vector true Q.73) Which of these is an incorrect form of using method max() to obtain maximum element? A. max(collection c) B. max(collection c, Comparator comp) C. max(comparator comp) D. max(list c) ANSWER : max(comparator comp) Explanation: It's illegal to call max() only with comparator, we need to give the collection to be serched into. Q.74) What is the output of this program? class Output HashSet obj = new HashSet(); obj.add("a"); obj.add("b"); obj.add("c"); System.out.println(obj + " " + obj.size()); A. ABC 3 B. [A, B, C] 3 C. ABC 2 D. [A, B, C] 2 ANSWER : [A, B, C] 3 Page 25

26 HashSet obj creates an hash object which implements Set interface, obj.size() gives the number of elements stored in the object obj which in this case is 3. $ javac Output.java $ java Output [A, B, C] 3 Q.75) What is the output of this program? class stack Stack obj = new Stack(); obj.push(new Integer(3)); obj.push(new Integer(2)); obj.pop(); obj.push(new Integer(5)); System.out.println(obj); A. [3, 5] B. [3, 2] C. [3, 2, 5] D. [3, 5, 2] ANSWER : [3, 5] push() and pop() are standard functions of the class stack, push() inserts in the stack and pop removes from the stack. 3 & 2 are inserted using push() the pop() is used which removes 2 from the stack then again push is used to insert 5 hence stack contains elements 3 & 5. $ javac stack.java $ java stack [3, 5] Q.76) Which two statements are true about comparing two instances of the same class, given that the equals() and hashcode() methods have been properly overridden? 1. If the equals() method returns true, the hashcode() comparison == must return true. 2. If the equals() method returns false, the hashcode() comparison!= must return true. 3. If the hashcode() comparison == returns true, the equals() method must return true. 4. If the hashcode() comparison == returns true, the equals() method might return true. A. 1 and 4 B. 2 and 3 C. 3 and 4 D. 1 and 3 ANSWER : 1 and 4 (1) is a restatement of the equals() and hashcode() contract. (4) is true because if the hashcode() comparison returns ==, the two objects might or might not be equal. (2) and (3) are incorrect because the hashcode() method is very flexible in its return values, and often two dissimilar objects can return the same hash code value. Q.77) Which of these methods can randomize all elements in a list? Page 26

27 A. rand() B. randomize() C. ambigous() D. shuffle() ANSWER : shuffle() shuffle : randomizes all the elements in a list. Q.78) Which interface provides the capability to store objects using a key-value pair? A. Java.util.Map B. Java.util.Set C. Java.util.List D. Java.util.Collection ANSWER : Java.util.Map An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. Q.79) Which of these method is used to reduce the capacity of an ArrayList object? A. trim() B. trimsize() C. trimtosize() D. trimtosize() ANSWER : trimtosize() trimtosize() is used to reduce the size of the array that underlines an ArrayList object. Q.80) Which of the following are true statements? 1. The Iterator interface declares only three methods: hasnext, next and remove. 2. The ListIterator interface extends both the List and Iterator interfaces. 3. The ListIterator interface provides forward and backward iteration capabilities. 4. The ListIterator interface provides the ability to modify the List during iteration. 5. The ListIterator interface provides the ability to determine its position in the List. A. 2, 3, 4 and 5 B. 1, 3, 4 and 5 C. 3, 4 and 5 D. 1, 2 and 3 ANSWER : 1, 3, 4 and 5 The ListIterator interface extends the Iterator interface and declares additional methods to provide forward and backward iteration capabilities, List modification capabilities, and the ability to determine the position of the iterator in the List. Q.81) Which of these methods deletes all the elements from invoking collection? A. clear() B. reset() C. delete() D. refresh() ANSWER : clear() clear() method removes all the elements from invoking collection. Page 27

28 Q.82) Which of these method is used to make all elements of an equal to specified value? A. add() B. fill() C. all() D. set() ANSWER : fill() fill() method assigns a value to all the elements in an array, in other words it fills the array with specified value. Q.83) What is the output of this program? class Linkedlist LinkedList obj = new LinkedList(); obj.add("a"); obj.add("b"); obj.add("c"); obj.removefirst(); System.out.println(obj); A. [A, B] B. [B, C] C. [A, B, C, D] D. [A, B, C] ANSWER : [B, C] $ javac Linkedlist.java $ java Linkedlist [B, C] Q.84) What is the output of this program? class Output ArrayList obj = new ArrayList(); obj.add("a"); obj.add("d"); obj.ensurecapacity(3); obj.trimtosize(); System.out.println(obj.size()); A. 1 B. 2 C. 3 D. 4 ANSWER : 2 trimtosize() is used to reduce the size of the array that underlines an ArrayList object. Page 28

29 $ javac Output.java $ java Output 2 Q.85) Which of these methods can convert an object into a List? A. SetList() B. ConvertList() C. singletonlist() D. CopyList() ANSWER : singletonlist() singletonlist() returns the object as an immutable List. This is a easy way to convert a single object into a list. This was added by Java 2.0. Q.86) /* Missing Statement? */ public class foo public static void main(string[]args)throws Exception java.io.printwriter out = new java.io.printwriter(); new java.io.outputstreamwriter(system.out,true); out.println("hello"); What line of code should replace the missing statement to make this program compile? A. No statement required. B. import java.io.*; C. include java.io.*; D. import java.io.printwriter; ANSWER : No statement required. The usual method for using/importing the java packages/classes is by using an import statement at the top of your code. However it is possible to explicitly import the specific class that you want to use as you use it which is shown in the code above. The disadvantage of this however is that every time you create a new object you will have to use the class path in the case "java.io" then the class name in the long run leading to a lot more typing Q.87) What is the output of this program? class Array int array[] = new int [5]; for (int i = 5; i > 0; i--) array[5 - i] = i; Arrays.sort(array); for (int i = 0; i < 5; ++i) System.out.print(array[i]);; A B C D Page 29

30 ANSWER : Arrays.sort(array) method sorts the array into 1,2,3,4,5. $ javac Array.java $ java Array Q.88) What will be the output of the program? TreeSet map = new TreeSet(); map.add("one"); map.add("two"); map.add("three"); map.add("four"); map.add("one"); Iterator it = map.iterator(); while (it.hasnext() ) System.out.print( it.next() + " " ); A. one two three four B. four three two one C. four one three two D. one two three four one ANSWER : four one three two TreeSet assures no duplicate entries; also, when it is accessed it will return elements in natural order, which typically means alphabetical. Q.89) What is the output of this program? class hashtable Hashtable obj = new Hashtable(); obj.put("a", new Integer(3)); obj.put("b", new Integer(2)); obj.put("c", new Integer(8)); obj.remove(new String("A")); System.out.print(obj); A. C=8, B=2 B. [C=8, B=2] C. A=3, C=8, B=2 D. [A=3, C=8, B=2] ANSWER : [C=8, B=2] $ javac hashtable.java $ java hashtable C=8, B=2 Q.90) What is the output of this program? Page 30

31 class Array int array[] = new int [5]; for (int i = 5; i > 0; i--) array[5 - i] = i; Arrays.sort(array); for (int i = 0; i < 5; ++i) System.out.print(array[i]);; A B C D ANSWER : Arrays.sort(array) method sorts the array into 1,2,3,4,5. $ javac Array.java $ java Array Page 31

1.Which four options describe the correct default values for array elements of the types indicated?

1.Which four options describe the correct default values for array elements of the types indicated? 1.Which four options describe the correct default values for array elements of the types indicated? 1. int -> 0 2. String -> "null" 3. Dog -> null 4. char -> '\u0000' 5. float -> 0.0f 6. boolean -> true

More information

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList This article discusses the main classes of Java Collection API. The following figure demonstrates the Java Collection framework. Figure

More information

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Inheritance Abstract classes Interfaces instanceof operator Nested classes Enumerations COUSE CONTENT Collections List Map Set Aggregate

More information

Generics. IRS W-9 Form

Generics. IRS W-9 Form Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]

More information

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering Readings and References Java Collections "Collections", Java tutorial http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Spring 2004 Software Engineering http://www.cs.washington.edu/education/courses/403/04sp/

More information

Java Collections Framework reloaded

Java Collections Framework reloaded Java Collections Framework reloaded October 1, 2004 Java Collections - 2004-10-01 p. 1/23 Outline Interfaces Implementations Ordering Java 1.5 Java Collections - 2004-10-01 p. 2/23 Components Interfaces:

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

CONTAİNERS COLLECTİONS

CONTAİNERS COLLECTİONS CONTAİNERS Some programs create too many objects and deal with them. In such a program, it is not feasible to declare a separate variable to hold reference to each of these objects. The proper way of keeping

More information

Collections Questions

Collections Questions Collections Questions https://www.journaldev.com/1330/java-collections-interview-questions-and-answers https://www.baeldung.com/java-collections-interview-questions https://www.javatpoint.com/java-collections-interview-questions

More information

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss The Collections API Mark Allen Weiss Lecture Objectives To learn how to use the Collections package in Java 1.2. To illustrate features of Java that help (and hurt) the design of the Collections API. Tuesday,

More information

Lecture 6 Collections

Lecture 6 Collections Lecture 6 Collections Concept A collection is a data structure actually, an object to hold other objects, which let you store and organize objects in useful ways for efficient access Check out the java.util

More information

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

27/04/2012. Objectives. Collection. Collections Framework. Collection Interface. Collection algorithm. Legacy collection Objectives Collection Collections Framework Concrete collections Collection algorithm By Võ Văn Hải Faculty of Information Technologies Summer 2012 Legacy collection 1 2 2/27 Collections Framework "Collection"

More information

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING)

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING) Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING) What is a Data Structure? Introduction A data structure is a particular way of organizing data using one or

More information

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff Collections by Vlad Costel Ungureanu for Learn Stuff Collections 2 Collections Operations Add objects to the collection Remove objects from the collection Find out if an object (or group of objects) is

More information

Java Collections Framework

Java Collections Framework Java Collections Framework Introduction In this article from my free Java 8 course, you will be given a high-level introduction of the Java Collections Framework (JCF). The term Collection has several

More information

Java Collections Framework. 24 April 2013 OSU CSE 1

Java Collections Framework. 24 April 2013 OSU CSE 1 Java Collections Framework 24 April 2013 OSU CSE 1 Overview The Java Collections Framework (JCF) is a group of interfaces and classes similar to the OSU CSE components The similarities will become clearly

More information

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the Answers 1) B 2) C 3) A 4) D 5) Non-static members 6) Static members 7) Default 8) abstract 9) Local variables 10) Data type default value 11) Data type default value 12) No 13) No 14) Yes 15) No 16) No

More information

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1 Topic #9: Collections CSE 413, Autumn 2004 Programming Languages http://www.cs.washington.edu/education/courses/413/04au/ If S is a subtype of T, what is S permitted to do with the methods of T? Typing

More information

USAL1J: Java Collections. S. Rosmorduc

USAL1J: Java Collections. S. Rosmorduc USAL1J: Java Collections S. Rosmorduc 1 A simple collection: ArrayList A list, implemented as an Array ArrayList l= new ArrayList() l.add(x): adds x at the end of the list l.add(i,x):

More information

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering Readings and References Java Collections References» "Collections", Java tutorial» http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Winter 2003 Software Engineering http://www.cs.washington.edu/education/courses/403/03wi/

More information

The Java Collections Framework. Chapters 7.5

The Java Collections Framework. Chapters 7.5 The Java s Framework Chapters 7.5 Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework Outline Introduction to the Java s Framework Iterators Interfaces,

More information

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know Organizing Data Data Structures that we know 17 Java Collections Generic Types, Iterators, Java Collections, Iterators Today: Arrays Fixed-size sequences Strings Sequences of characters Linked Lists (up

More information

Generics Collection Framework

Generics Collection Framework Generics Collection Framework Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Generics

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock) Lecture 15 Summary Collections Framework Iterable, Collections List, Set Map Collections class Comparable and Comparator 1 By the end of this lecture, you will be able to use different types of Collections

More information

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map Lecture 15 Summary Collections Framework Iterable, Collections List, Set Map Collections class Comparable and Comparator 1 By the end of this lecture, you will be able to use different types of Collections

More information

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data 1 JAVA PROGRAMMERS GUIDE LESSON 1 File: JGuiGuideL1.doc Date Started: July 10, 2000 Last Update: Jan 2, 2002 Status: proof DICTIONARIES, MAPS AND COLLECTIONS We have classes for Sets, Lists and Maps and

More information

d. If a is false and b is false then the output is "ELSE" Answer?

d. If a is false and b is false then the output is ELSE Answer? Intermediate Level 1) Predict the output for the below code: public void foo( boolean a, boolean b) if( a ) System.out.println("A"); if(a && b) System.out.println( "A && B"); if (!b ) System.out.println(

More information

Lecture 4. The Java Collections Framework

Lecture 4. The Java Collections Framework Lecture 4. The Java s Framework - 1 - Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework - 2 - Learning Outcomes From this lecture you should

More information

Data Structures. COMS W1007 Introduction to Computer Science. Christopher Conway 1 July 2003

Data Structures. COMS W1007 Introduction to Computer Science. Christopher Conway 1 July 2003 Data Structures COMS W1007 Introduction to Computer Science Christopher Conway 1 July 2003 Linked Lists An array is a list of elements with a fixed size, accessed by index. A more flexible data structure

More information

Class 32: The Java Collections Framework

Class 32: The Java Collections Framework Introduction to Computation and Problem Solving Class 32: The Java Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To introduce you to the data structure classes that come

More information

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1 COMP209 Object Oriented Programming Container Classes 3 Mark Hall List Functionality Types List Iterator Adapter design pattern Adapting a LinkedList to a Stack/Queue Map Functionality Hashing Performance

More information

Model Solutions. COMP 103: Test April, 2013

Model Solutions. COMP 103: Test April, 2013 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 40 minutes

More information

Collections Framework: Part 2

Collections Framework: Part 2 Collections Framework: Part 2 Computer Science and Engineering College of Engineering The Ohio State University Lecture 18 Collection Implementations Java SDK provides several implementations of Collection

More information

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description java.lang Interface Iterable Type Parameters: T - the type of elements returned by the iterator Iterator iterator() Returns an iterator over a set of elements of type T. java.util Interface Iterator

More information

Collections (Java) Collections Framework

Collections (Java) Collections Framework Collections (Java) https://docs.oracle.com/javase/tutorial/collections/index.html Collection an object that groups multiple elements into a single unit. o store o retrieve o manipulate o communicate o

More information

9/16/2010 CS Ananda Gunawardena

9/16/2010 CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

CS Ananda Gunawardena

CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

5/23/2015. Core Java Syllabus. VikRam ShaRma

5/23/2015. Core Java Syllabus. VikRam ShaRma 5/23/2015 Core Java Syllabus VikRam ShaRma Basic Concepts of Core Java 1 Introduction to Java 1.1 Need of java i.e. History 1.2 What is java? 1.3 Java Buzzwords 1.4 JDK JRE JVM JIT - Java Compiler 1.5

More information

1)Write a program on inheritance and check weather the given object is instance of a class or not?

1)Write a program on inheritance and check weather the given object is instance of a class or not? 1)Write a program on inheritance and check weather the given object is instance of a class or not? class A class B extends A class C extends A class X A a1=new B(); if(a1 instanceof B) System.out.println(

More information

Strings and Arrays. Hendrik Speleers

Strings and Arrays. Hendrik Speleers Hendrik Speleers Overview Characters and strings String manipulation Formatting output Arrays One-dimensional Two-dimensional Container classes List: ArrayList and LinkedList Iterating over a list Characters

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Object-Oriented Programming with Java

Object-Oriented Programming with Java Object-Oriented Programming with Java Recitation No. 2 Oranit Dror The String Class Represents a character string (e.g. "Hi") Explicit constructor: String quote = "Hello World"; string literal All string

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 8 : Collections Lecture Contents 2 Why collections? What is a collection? Non-generic collections: Array & ArrayList Stack HashTable

More information

Advanced Programming Generics Collections

Advanced Programming Generics Collections Advanced Programming Generics Collections The Context Create a data structure that stores elements: a stack, a linked list, a vector a graph, a tree, etc. What data type to use for representing the elements

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University C O P Y R I G H T S 2 0 1 5 E O M, H Y E O N S A N G A L L R I G H T S R E S E R V E D - Containers - About Containers

More information

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException VERSION A CSC 1351: Final Name: 1 Interfaces, Classes and Inheritance 2 Basic Data Types (arrays, lists, stacks, queues, trees,...) 2.1 Does the following code compile? If it does not, how can it be fixed?

More information

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections Course Name: Advanced Java Lecture 8 Topics to be covered Collections Introduction A collection, sometimes called a container, is simply an object that groups multiple elements into a single unit. Collections

More information

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani The Collection Framework Collection: an aggregate that can hold a varying number of elements Interface:

More information

Get started with the Java Collections Framework By Dan Becker

Get started with the Java Collections Framework By Dan Becker Get started with the Java Collections Framework By Dan Becker JavaWorld Nov 1, 1998 COMMENTS JDK 1.2 introduces a new framework for collections of objects, called the Java Collections Framework. "Oh no,"

More information

Overview of Java s Support for Polymorphism

Overview of Java s Support for Polymorphism Overview of Java s Support for Polymorphism Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt

More information

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Readings List Implementations Chapter 20.2 Objectives Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Additional references:

More information

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures Collections CSE 143 Java Collections Most programs need to store and access collections of data Collections are worth studying because... They are widely useful in programming They provide examples of

More information

What is the Java Collections Framework?

What is the Java Collections Framework? 1 of 13 What is the Java Collections Framework? To begin with, what is a collection?. I have a collection of comic books. In that collection, I have Tarzan comics, Phantom comics, Superman comics and several

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 4: Generic Type and Collections Stéphane Airiau Université Paris-Dauphine Lesson 4: Generic Type and Collections (Stéphane Airiau) Java 1 Linked List 1 public class Node

More information

PIC 20A Collections and Data Structures

PIC 20A Collections and Data Structures PIC 20A Collections and Data Structures Ernest Ryu UCLA Mathematics Last edited: March 14, 2018 Introductory example How do you write a phone book program? Some programmers may yell hash table! and write

More information

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help Overview Package Class Use Tree Deprecated Index Help PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes SUMMARY: NESTED FIELD CONSTR METHOD DETAIL: FIELD CONSTR METHOD Página 1 de 30 Java TM 2 Platform

More information

Standard ADTs. Lecture 19 CS2110 Summer 2009

Standard ADTs. Lecture 19 CS2110 Summer 2009 Standard ADTs Lecture 19 CS2110 Summer 2009 Past Java Collections Framework How to use a few interfaces and implementations of abstract data types: Collection List Set Iterator Comparable Comparator 2

More information

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 36. Collections Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Arrays Class Interface Collection and Class Collections ArrayList Class Generics LinkedList Class Collections Algorithms

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Collections Framework Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi 1 Today The java.util.arrays class Java Collection Framework java.util.collection

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Collections Framework Today The java.util.arrays class Java Collection Framework java.util.collection interface java.util.list interface java.util.arraylist

More information

Collection Framework Collection, Set, Queue, List, Map 3

Collection Framework Collection, Set, Queue, List, Map 3 Collection Framework Collection, Set, Queue, List, Map 3 1 1. Beginner - What is Collection? What is a Collections Framework? What are the benefits of Java Collections Framework? 3 2. Beginner - What is

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

CS11 Java. Winter Lecture 8

CS11 Java. Winter Lecture 8 CS11 Java Winter 2010-2011 Lecture 8 Java Collections Very powerful set of classes for managing collections of objects Introduced in Java 1.2 Provides: Interfaces specifying different kinds of collections

More information

ArrayList. Introduction. java.util.arraylist

ArrayList. Introduction. java.util.arraylist ArrayList Introduction In this article from my free Java 8 course, I will be giving you a basic overview of the Java class java.util.arraylist. I will first explain the meaning of size and capacity of

More information

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p. A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p. 9 Classes and Objects p. 11 Creating Objects p. 12 Static or

More information

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code

More information

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( ) Review CSE 143 Java Hashing Want to implement Sets of objects Want fast contains( ), add( ) One strategy: a sorted list OK contains( ): use binary search Slow add( ): have to maintain list in sorted order

More information

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS T E W H A R E W Ā N A N G A O T E Student ID:....................... Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2015 TRIMESTER 2 COMP103 INTRODUCTION

More information

EXAMINATIONS 2016 TRIMESTER 2

EXAMINATIONS 2016 TRIMESTER 2 T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2016 TRIMESTER 2 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

More information

A simple map: Hashtable

A simple map: Hashtable Using Maps A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable, use: table.put(key, value); To retrieve a value from

More information

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc.

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc. Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com 2 Disclaimer & Acknowledgments Even though Sang Shin is a full-time employee

More information

Fundamental language mechanisms

Fundamental language mechanisms Java Fundamentals Fundamental language mechanisms The exception mechanism What are exceptions? Exceptions are exceptional events in the execution of a program Depending on how grave the event is, the program

More information

List... NOTE We use List as illustrative example of collections Study the others from textbook!

List... NOTE We use List as illustrative example of collections Study the others from textbook! List... NOTE We use List as illustrative example of collections Study the others from textbook! 25 What is a List? A List is an ordered Collection (sometimes called a sequence) Lists may contain duplicate

More information

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Model Solutions COMP 103: Test

More information

Java Language Features

Java Language Features Java Language Features References: Object-Oriented Development Using Java, Xiaoping Jia Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From

More information

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14 MINI-MAX USING TREES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 Spring 2014 2 Important Dates. April 10 --- A4 due (Connect 4, minimax, trees) April 15 --- A5 due (Exercises on different topics,

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Wrapper classes. Wrapper classes Java Collections Engi- 5895 Hafez Seliem Wrapper classes Provide a mechanism to wrap primitive values in an object so that the primitives can be included in activities reserved for objects, like as being

More information

Java Collections. Engi Hafez Seliem

Java Collections. Engi Hafez Seliem Java Collections Engi- 5895 Hafez Seliem Wrapper classes Provide a mechanism to wrap primitive values in an object so that the primitives can be included in activities reserved for objects, like as being

More information

CS 307 Final Spring 2010

CS 307 Final Spring 2010 Points off 1 2 3 4 5 Total off Net Score CS 307 Final Spring 2010 Name UTEID login name Instructions: 1. Please turn off your cell phones. 2. There are 5 questions on this test. 3. You have 3 hours to

More information

Tha Java Programming Language

Tha Java Programming Language Tha Java Programming Language Kozsik Tamás (2000-2001) kto@elte.hu http://www.elte.hu/~k to/ III. Arrays, collections and other baseclasses Some of the baseclasses Object String StringBuffer Integer, Double,...

More information

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 1. JIT meaning a. java in time b. just in time c. join in time d. none of above CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 2. After the compilation of the java source code, which file is created

More information

Yes, it changes each time simulateonestep is invoked.

Yes, it changes each time simulateonestep is invoked. Exercise 10.1 Yes, the number of foxes changes. However, note that although this has a high probability of happening, it is not guaranteed to and will ultimately depend upon the initial state of the simulation.

More information

Section Lists and Sets

Section Lists and Sets Section 10.2 Lists and Sets IN THE PREVIOUS SECTION, we looked at the general properties of collection classes in Java. In this section, we look at some specific collection classes and how to use them.

More information

EPITA Première Année Cycle Ingénieur. Atelier Java - J2

EPITA Première Année Cycle Ingénieur. Atelier Java - J2 EPITA Première Année Cycle Ingénieur marwan.burelle@lse.epita.fr http://www.lse.epita.fr Plan 1 2 A Solution: Relation to ML Polymorphism 3 What are Collections Collection Core Interface Specific Collection

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 7 : Collections Lecture Contents 2 Why collections? What is a collection? Non-generic collections: Array & ArrayList Stack HashTable

More information

Computer Science II (Spring )

Computer Science II (Spring ) Computer Science II 4003-232-01 (Spring 2007-2008) Week 5: Generics, Java Collection Framework Richard Zanibbi Rochester Institute of Technology Generic Types in Java (Ch. 21 in Liang) What are Generic

More information

Lecture 16: Case Study: The Java Collections API

Lecture 16: Case Study: The Java Collections API Lecture 16: Case Study: The Java Collections API You can t be a competent Java programmer without understanding the crucial parts of the Java library. The basic types are all in java.lang, and are part

More information

Software 1 with Java. Recitation No. 6 (Collections)

Software 1 with Java. Recitation No. 6 (Collections) Software 1 with Java Recitation No. 6 (Collections) Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 2

More information

Outline. iterator review iterator implementation the Java foreach statement testing

Outline. iterator review iterator implementation the Java foreach statement testing Outline iterator review iterator implementation the Java foreach statement testing review: Iterator methods a Java iterator only provides two or three operations: E next(), which returns the next element,

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 8 : Collections Lecture Contents 2 Why collections? What is a collection? Non-generic collections: Array & ArrayList Stack HashTable

More information

Points To Remember for SCJP

Points To Remember for SCJP Points To Remember for SCJP www.techfaq360.com The datatype in a switch statement must be convertible to int, i.e., only byte, short, char and int can be used in a switch statement, and the range of the

More information

Generics and collections

Generics and collections Generics From JDK 1.5.0 They are similar to C++ templates They allow to eliminate runtime exceptions related to improper casting (ClassCastException) Traditional approach public class Box { private Object

More information

Interfaces, collections and comparisons

Interfaces, collections and comparisons תכנות מונחה עצמים תרגול מספר 4 Interfaces, collections and comparisons Interfaces Overview Overview O Interface defines behavior. Overview O Interface defines behavior. O The interface includes: O Name

More information

MODULE 6q - Exceptions

MODULE 6q - Exceptions MODULE 6q - Exceptions THE TRY-CATCH CONSTRUCT Three different exceptions are referred to in the program below. They are the ArrayIndexOutOfBoundsException which is built-into Java and two others, BadLuckException

More information

Generic classes & the Java Collections Framework. *Really* Reusable Code

Generic classes & the Java Collections Framework. *Really* Reusable Code Generic classes & the Java Collections Framework *Really* Reusable Code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers

More information

Abstract Data Types (ADTs) Queues & Priority Queues. Sets. Dictionaries. Stacks 6/15/2011

Abstract Data Types (ADTs) Queues & Priority Queues. Sets. Dictionaries. Stacks 6/15/2011 CS/ENGRD 110 Object-Oriented Programming and Data Structures Spring 011 Thorsten Joachims Lecture 16: Standard ADTs Abstract Data Types (ADTs) A method for achieving abstraction for data structures and

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information