Java_Level_5

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

What is thread?

A thread is a lightweight subprocess.It is a separate path of execution.It is called separate path of execution because each thread runs in a separate stack frame.

What is the difference between ArrayList and Vector?

ArrayList 1) ArrayList is not synchronized. 2) ArrayList is not a legacy class. 3) ArrayList increases its size by 50% of the array size. Vector 1) Vector is synchronized. 2) Vector is a legacy class. 3) Vector increases its size by doubling the array size.

What is the difference between ArrayList and LinkedList?

ArrayList 1) ArrayList uses a dynamic array. 2) ArrayList is not efficient for manipulation because a lot of shifting is required. 3) ArrayList is better to store and fetch data. LinkedList 1) LinkedList uses doubly linked list. 2) LinkedList is efficient for manipulation. 3) LinkedList is better to manipulate data.

What is ArrayList and HashMap ?

ArrayList and HashMap are two commonly used collection classes in Java. Even though both are the part of collection framework, the way they store and process the data is entirely different. In this post we will see the main differences between these two collections. ArrayList vs HashMap in Java 1) Implementation: ArrayList implements List Interface while HashMap is an implementation of Map interface. List and Map are two entirely different collection interfaces. 2) Memory consumption: ArrayList stores the elements value alone and internally maintains the indexes for each element. ArrayList<String> arraylist = new ArrayList<String>(); //String value is stored in array list arraylist.add("Test String"); HashMap stores key & value pair. For each value there must be a key associated in HashMap. That clearly shows that memory consumption is high in HashMap compared to the ArrayList. HashMap<Integer, String> hmap= new HashMap<Integer, String>(); //String value stored along with the key value in hash map hmap.put(123, "Test String"); 3) Order: ArrayList maintains the insertion order while HashMap doesnt. Which means ArrayList returns the list items in the same order in which they got inserted into the list. On the other side HashMap doesnt maintain any order, the returned key-values pairs are not sorted in any kind of order. 4) Duplicates: ArrayList allows duplicate elements but HashMap doesnt allow duplicate keys (It does allow duplicate values). 5) Nulls: ArrayList can have any number of null elements. HashMap allows one null key and any number of null values. 6) get method: In ArrayList we can get the element by specifying the index of it. In HashMap the elements is being fetched by specifying the corresponding key.

What is the difference between Collection and Collections?

Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.

What is the difference between Comparable and Comparator?

Comparable 1) Comparable provides only one sort of sequence. 2) It provides one method named compareTo(). 3) It is found in java.lang package. 4) If we implement Comparable interface, actual class is modified. Comparator 1) Comparator provides multiple sort of sequences. 2) It provides one method named compare(). 3) it is found in java.util package. 4) Actual class is not modified.

What is deadlock ?

Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread.

What is the difference between HashMap and Hashtable?

HashMap 1) HashMap is not synchronized. 2) HashMap can contain one null key and multiple null values. Hashtable 1) Hashtable is synchronized. 2) Hashtable cannot contain any null key or null value.

What is the difference between HashMap and TreeMap?

HashMap maintains no order but TreeMap maintains ascending order.

HashSet vs HashMap

HashSet HashMap HashSet class implements the Set interface HashMap class implements the Map interface In HashSet we store objects(elements or values) e.g. If we have a HashSet of string elements then it could depict a set of HashSet elements: {Hello, Hi, Bye, Run} HashMap is used for storing key & value pairs. In short it maintains the mapping of key & value (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This is how you could represent HashMap elements if it has integer key and value of String type: e.g. {1->Hello, 2->Hi, 3->Bye, 4->Run} HashSet does not allow duplicate elements that means you can not store duplicate values in HashSet. HashMap does not allow duplicate keys however it allows to have duplicate values. HashSet permits to have a single null value. HashMap permits single null key and any number of null values. Similarities: 1) Both HashMap and HashSet are not synchronized which means they are not suitable for thread-safe operations unitl unless synchronized explicitly. This is how you can synchronize them explicitly: HashSet: Set s = Collections.synchronizedSet(new HashSet(...)); HashMap: Map m = Collections.synchronizedMap(new HashMap(...)); 2) Both of these classes do not guarantee that the order of their elements will remain constant over time. 3) If you look at the source code of HashSet then you may find that it is backed up by a HashMap. So basically it internally uses a HashMap for all of its operations. 4) They both provide constant time performance for basic operations such as adding, removing element etc. HashSet example import java.util.HashSet; class HashSetDemo{ public static void main(String[] args) { // Create a HashSet HashSet<String> hset = new HashSet<String>(); //add elements to HashSet hset.add("AA"); hset.add("BB"); hset.add("CC"); hset.add("DD"); // Displaying HashSet elements System.out.println("HashSet contains: "); for(String temp : hset){ System.out.println(temp); } } } Output: HashSet contains: AA BB CC DD HashMap example import java.util.HashMap; class HashMapDemo{ public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> hmap = new HashMap<Integer, String>(); //add elements to HashMap hmap.put(1, "AA"); hmap.put(2, "BB"); hmap.put(3, "CC"); hmap.put(4, "DD"); // Displaying HashMap elements System.out.println("HashMap contains: "+hmap); } } Output: HashMap contains: {1=AA, 2=BB, 3=CC, 4=DD}

What is the difference between HashSet and HashMap?

HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated.

What is the difference between HashSet and TreeSet?

HashSet maintains no order whereas TreeSet maintains ascending order.

HashTable

Hashtable doesnt preserve the insertion order, neither it sorts the inserted data based on keys or values. Which means no matter what keys & values you insert into Hashtable, the result would not be in any particular order. For example: Lets have a look at the below program and its output: import java.util.*; public class HashtableDemo { public static void main(String args[]) { Hashtable<Integer, String> ht= new Hashtable<Integer, String>(); ht.put(10, "Chaitanya"); ht.put(1, "Ajeet"); ht.put(11, "Test"); ht.put(9, "Demo"); ht.put(3, "Anuj"); // Get a set of the entries Set set = ht.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } } } Output: 10: Chaitanya 9: Demo 3: Anuj 1: Ajeet 11: Test As you can see that the output key-value pairs are in random order. Neither we got insertion order nor the values are sorted based on keys or values. The solution The are ways to sort Hashtable using Collections.list and Collections.sort, however best thing to do is use LinkedHashMap or TreeMap. Use LinkedHashMap: When you want to preserve the insertion order. Use TreeMap: When you want to sort the key-value pairs. Lets take the same example using LinkedHashMap and TreeMap: Using LinkedHashMap import java.util.*; public class LinkedHashMapDemo { public static void main(String args[]) { LinkedHashMap<Integer, String> lhm= new LinkedHashMap<Integer, String>(); lhm.put(10, "Chaitanya"); lhm.put(1, "Ajeet"); lhm.put(11, "Test"); lhm.put(9, "Demo"); lhm.put(3, "Anuj"); // Get a set of the entries Set set = lhm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } } } Output: 10: Chaitanya 1: Ajeet 11: Test 9: Demo 3: Anuj Voila!! We got the result in the insertion order. What if we want to get the result sorted? Use TreeMap. Refer below example: Use TreeMap import java.util.*; public class TreeMapDemo { public static void main(String args[]) { TreeMap<Integer, String> tm= new TreeMap<Integer, String>(); tm.put(10, "Chaitanya"); tm.put(1, "Ajeet"); tm.put(11, "Test"); tm.put(9, "Demo"); tm.put(3, "Anuj"); // Get a set of the entries Set set = tm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } } } Output: 1: Ajeet 3: Anuj 9: Demo 10: Chaitanya 11: Test As you can see, the output we got is sorted based on the keys.

What is the advantage of generic collection?

If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.

What is the advantage of Properties file?

If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage.

What is static synchronization?

If you make any static method as synchronized, the lock will be on the class not on object.

ArrayList

In this tutorial we will see how to copy and add all the elements of a list to ArrayList. In order to do that we will be using addAll method of ArrayList class. public boolean addAll(Collection c) It adds all the elements of specified Collection c to the end of the calling list. It throws NullPointerException if the specified Collection is null. Complete Example of Copying List elements to ArrayList package beginnersbook.com; import java.util.ArrayList; import java.util.List; public class ListToArrayListExample { public static void main(String a[]){ ArrayList<String> al = new ArrayList<String>(); //Adding elements to the ArrayList al.add("Text 1"); al.add("Text 2"); al.add("Text 3"); System.out.println("ArrayList Elements are: "+al); //Adding elements to a List List<String> list = new ArrayList<String>(); list.add("Text 4"); list.add("Text 5"); list.add("Text 6"); //Adding all lements of list to ArrayList using addAll al.addAll(list); System.out.println("Updated ArrayList Elements: "+al); } } Output: ArrayList Elements are: [Text 1, Text 2, Text 3] Updated ArrayList Elements: [Text 1, Text 2, Text 3, Text 4, Text 5, Text 6]

What is the difference between Iterator and Enumeration?

Iterator 1) Iterator can traverse legacy and non-legacy elements. 2) Iterator is fail-fast. 3) Iterator is slower than Enumeration. Enumeration 1) Enumeration can traverse only legacy elements. 2) Enumeration is not fail-fast. 3) Enumeration is faster than Iterator.

What is the difference between Iterator and ListIterator?

Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction. Iterator 1) Iterator traverses the elements in forward direction only. 2) Iterator can be used in List, Set and Queue. ListIterator 1) ListIterator traverses the elements in backward and forward directions both. 2) ListIterator can be used in List only.

What is LinkedHashMap ?

JAVA COLLECTIONS LinkedHashMap is a Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). In last few tutorials we have discussed about HashMap and TreeMap. This class is different from both of them: HashMap doesnt maintain any order. TreeMap sort the entries in ascending order of keys. LinkedHashMap maintains the insertion order. Lets understand the LinkedHashMap with the help of an example: import java.util.LinkedHashMap; import java.util.Set; import java.util.Iterator; import java.util.Map; public class LinkedHashMapDemo { public static void main(String args[]) { // HashMap Declaration LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); //Adding elements to LinkedHashMap lhmap.put(22, "Abey"); lhmap.put(33, "Dawn"); lhmap.put(1, "Sherry"); lhmap.put(2, "Karon"); lhmap.put(100, "Jim"); // Generating a Set of entries Set set = lhmap.entrySet(); // Displaying elements of LinkedHashMap Iterator iterator = set.iterator(); while(iterator.hasNext()) { Map.Entry me = (Map.Entry)iterator.next(); System.out.print("Key is: "+ me.getKey() + "& Value is: "+me.getValue()+"\n"); } } } Output: Key is: 22& Value is: Abey Key is: 33& Value is: Dawn Key is: 1& Value is: Sherry Key is: 2& Value is: Karon Key is: 100& Value is: Jim As you can see the values are returned in the same order in which they got inserted.

What are List and Set ?

List and Set both are interfaces. They both extends Collection interface. 1) List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list. Set is an unordered collection, it doesnt maintain any order. There are few implementations of Set which maintains the order such as LinkedHashSet (It maintains the elements in insertion order). 2) List allows duplicates while Set doesnt allow duplicate elements. All the elements of a Set should be unique if you try to insert the duplicate element in Set it would replace the existing value. 3) List implementations: ArrayList, LinkedList etc. Set implementations: HashSet, LinkedHashSet, TreeSet etc. 4) List allows any number of null values. Set can have only a single null value at most. 5) ListIterator can be used to traverse a List in both the directions(forward and backward) However it can not be used to traverse a Set. We can use Iterator (It works with List too) to traverse a Set. 6) List interface has one legacy class called Vector whereas Set interface does not have any legacy class.

What is the difference between List and Set?

List can contain duplicate elements whereas Set contains only unique elements.

What is List, Set and Map ?

List, Set and Map are the interfaces which implements Collection interface. Here we will discuss difference between List Set and Map in Java. 1) Duplicity: List allows duplicate elements. Any number of duplicate elements can be inserted into the list without affecting the same existing values and their indexes. Set doesnt allow duplicates. Set and all of the classes which implements Set interface should have unique elements. Map stored the elements as key & value pair. Map doesnt allow duplicate keys while it allows duplicate values. 2) Null values: List allows any number of null values. Set allows single null value at most. Map can have single null key at most and any number of null values. 3) Order: List and all of its implementation classes maintains the insertion order. Set doesnt maintain any order; still few of its classes sort the elements in an order such as LinkedHashSet maintains the elements in insertion order. Similar to Set Map also doesnt stores the elements in an order, however few of its classes does the same. For e.g. TreeMap sorts the map in the ascending order of keys and LinkedHashMap sorts the elements in the insertion order, the order in which the elements got added to the LinkedHashMap. 4) Commonly used classes: List: ArrayList, LinkedList etc. Set: HashSet, LinkedHashSet, TreeSet, SortedSet etc. Map: HashMap, TreeMap, WeakHashMap, LinkedHashMap, IdentityHashMap etc. When to use List, Set and Map in Java? 1) If you do not want to have duplicate values in the database then Set should be your first choice as all of its classes do not allow duplicates. 2) If there is a need of frequent search operations based on the index values then List (ArrayList) is a better choice. 3) If there is a need of maintaining the insertion order then also the List is a preferred collection interface. 4) If the requirement is to have the key & value mappings in the database then Map is your best bet.

What is multithreading?

Multithreading is a process of executing multiple threads simultaneously. Its main advantage is: Threads share the same address space. Thread is lightweight. Cost of communication between process is low.

Is it possible to start a thread twice?

No, there is no possibility to start a thread twice. If we does, it throws an exception.

What is the difference between Set and Map?

Set contains values only whereas Map contains key and values both.

What is synchronization?

Synchronization is the capabilility of control the access of multiple threads to any shared resource.It is used: To prevent thread interference. To prevent consistency problem.

What is the purpose of Synchronized block?

Synchronized block is used to lock an object for any shared resource. Scope of synchronized block is smaller than the method.

What about the daemon threads?

The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads.

What is the default size of load factor in hashing based collection?

The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

Why we override equals() method?

The equals method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property. For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method.

What does the hashCode() method?

The hashCode() method returns a hash code value (an integer number). The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same. But, it is possible that two hash code numbers can have different or same keys.

What does join() method ?

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

What is the difference between notify() and notifyAll() ?

The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.

Can we make the user thread as daemon thread if thread is started?

The shutdown hook is basically a thread i.e. invoked implicitely before JVM shuts down. So we can use it perform clean up resource.

What is the Difference between HashMap and Hashtable?

This is one of the frequently asked interview questions for Java/J2EE professionals. HashMap and Hashtable both classes implements java.util.Map interface, however there are differences in the way they work and their usage. Here we will discuss the differences between these classes. HashMap vs Hashtable 1) HashMap is non-synchronized. This means if its used in multithread environment then more than one thread can access and process the HashMap simultaneously. Hashtable is synchronized. It ensures that no more than one thread can access the Hashtable at a given moment of time. The thread which works on Hashtable acquires a lock on it to make the other threads wait till its work gets completed. 2) HashMap allows one null key and any number of null values. Hashtable doesnt allow null keys and null values. 3) HashMap implementation LinkedHashMap maintains the insertion order and TreeMap sorts the mappings based on the ascending order of keys. Hashtable doesnt guarantee any kind of order. It doesnt maintain the mappings in any particular order. 4) Initially Hashtable was not the part of collection framework it has been made a collection framework member later after being retrofitted to implement the Map interface. HashMap implements Map interface and is a part of collection framework since the beginning. 5) Another difference between these classes is that the Iterator of the HashMap is a fail-fast and it throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except iterators own remove() method. In Simple words fail-fast means: When calling iterator.next(), if any modification has been made between the moment the iterator was created and the moment next() is called, a ConcurrentModificationException is immediately thrown. Enumerator for the Hashtable is not fail-fast. For e.g. HashMap: HashMap hm= new HashMap(); .... .... Set keys = hm.keySet(); for (Object key : keys) { //it will throw the ConcurrentModificationException here hm.put(object & value pair here); } Hashtable: Hashtable ht= new Hashtable(); .... ..... Enumeration keys = ht.keys(); for (Enumeration en = ht.elements() ; en.hasMoreElements() ; en.nextElement()) { //No exception would be thrown here ht.put(key & value pair here); } When to use HashMap and Hashtable? 1) As stated above the main difference between HashMap & Hashtable is synchronization. If there is a need of thread-safe operation then Hashtable can be used as all its methods are synchronized but its a legacy class and should be avoided as there is nothing about it, which cannot be done by HashMap. For multi-thread environment I would recommend you to use ConcurrentHashMap (Almost similar to Hashtable) or even you can make the HashMap synchronized explicitly (Read here..). 2) Synchronized operation gives poor performance so it should be avoided until unless required. Hence for non-thread environment HashMap should be used without any doubt.

What is hash-collision in Hashtable and how it is handled in Java?

Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision.

What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

When should we interrupt a thread?

We should interrupt a thread if we want to break out the sleep or wait state of a thread.

How to synchronize List, Set and Map elements?

Yes, Collections class provides methods to make List, Set or Map elements as synchronized: public static List synchronizedList(List l){} public static Set synchronizedSet(Set s){} public static SortedSet synchronizedSortedSet(SortedSet s){} public static Map synchronizedMap(Map m){} public static SortedMap synchronizedSortedMap(SortedMap m){}

Can Java object be locked down for exclusive use by a given thread?

Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

What is difference between wait() and sleep() method?

wait() 1) The wait() method is defined in Object class. 2) wait() method releases the lock. sleep() 1) The sleep() method is defined in Thread class. 2) The sleep() method doesn't releases the lock.

Can we call the run() method instead of start()?

yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching between the threads.


Kaugnay na mga set ng pag-aaral

NUR 212 EAQ - Chapter 49: Endocrine Problems

View Set

Quiz 4 Information Security Fundamentals

View Set

Project 3.2.2 Small and Large Intestines

View Set

Substance Use Disorders: Understanding Disorders

View Set

PHS 112 Chapter 4 Homework Study Guide

View Set

Lesson 8-E: Genitourinary-Renal-Reproductive Systems

View Set

Chapter 20 Eating Disorders, ch 20 NCLEX questions, Mental Health Final Ch 20, Ch 20 PrepUs: Eating Disorders, Ch. 20 Eating Disorders M.C., Mental Health, Eating disorders prepU, Chapter 20 Mental, Chapter 20: Eating Disorders

View Set

(Ch.1 ) Fundementals of nursing terms and Nclex questions

View Set