03 Nov
03Nov
      JVM (Java Virtual Machine)

JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed. It is a specification.

JVMs are available for many hardware and software platforms (so JVM is platform dependent).

There are three notions of the JVM: specification, implementation, and instance. The specification is a document that formally describes what is required of a JVM implementation. Having a single specification ensures all implementations are interoperable.

The JVM has instructions for the following groups of tasks:

  • Load and store Arithmetic Type conversion
  • Object creation and manipulation
  • Operand stack management (push / pop)
  • Control transfer (branching) Method invocation and return Throwing exceptions Monitor-based concurrency


   JDK (Java Development Kit)

The Java Development Kit (JDK) is an implementation of either one of the Java SE, Java EE or Java ME platforms[1] released by Oracle Corporation in the form of a binary product aimed at Java developers on Solaris, Linux, Mac OS X or Windows. The JDK includes a private JVM and a few other resources to finish the development of a Java Application.

The JDK has as its primary components a collection of programming tools, including:
  • appletviewer – this tool can be used to run and debug Java applets without a web browser
  • apt – the annotation-processing tool[4]
  • java – the loader for Java applications. This tool is an interpreter and can interpret the class files generated by the javac compiler. Now a single launcher is used for both development and deployment. The old deployment launcher, jre, no longer comes with Sun JDK, and instead it has been replaced by this new java loader.
  • javac – the Java compiler, which converts source code into Java bytecode



JRE (Java Runtime Environment)

JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime.

  JIT Compiler (Just In Time compiler)

Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

  ClassLoader

The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.

  Difference between Object oriented Programming Language and Object based programming Language

Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc. 

   Object oriented programming

Object-oriented programming (OOP) is a programming language model organized around objects.Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

   Advantages of bundling software components into objects

Bundling code into individual software objects provides a number of benefits, including:

  • Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
  • Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.
  • Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
  • Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
  Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic.

This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.

Inheritance

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Use of Inheritance

  • For Method Overriding (so runtime polymorphism can
    be achieved).
  • For Code Reusability.

Note: Multiple inheritance is not supported in java through class.

  Why multiple inheritance not supported in Java

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class

Can you use this() and super() both in a constructor?
No. Because super() or this() must be the first statement.
Object Cloning

The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

 Advantages of object.clone()

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning

Less processing task.

  Runtime Polymorphism

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time

In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

  Upcasting

When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:

class A{}  
class B extends A{}
A a=new B();//upcasting                              
 Java Runtime Polymorphism with data member
 Rule: Runtime polymorphism can't be achieved by data members.

Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data members. In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.

class Bike{  
int speedlimit=90;  
}  
class Honda3 extends Bike{  
int speedlimit=150;  

public static void main(String args[]){  
Bike obj=new Honda3();  
System.out.println(obj.speedlimit);//90  
}  
Output:90
 Binding

Connecting a method call to the method body is known as binding.

There are two types of Binding

  • static binding (also known as early binding).
  • dynamic binding (also known as late binding).

When type of the object is determined at compiled time(by the compiler), it is known as static binding. If there is any private, final or static method in a class, there is static binding.

 Serialization
 Serialization in java is a mechanism of writing the state of an object into a byte stream. It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.

The reverse operation of serialization is called deserialization. The String class and all the wrapper classes implements java.io.Serializable interface by default.

Advantage of Java Serialization

  • It is mainly used to travel object's state on the network (known as marshaling).
 Java Serialization with Aggregation (HAS-A Relationship)

If a class has a reference of another class, all the references must be Serializable otherwise serialization process will not be performed. In such case, NotSerializableException is thrown at runtime.

class Address{  
String addressLine,city,state;  
public Address(String addressLine, String city, String state) {  
this.addressLine=addressLine;  
this.city=city;  
this.state=state;  
}  
}  
import java.io.Serializable;  
public class Student implements Serializable{  
int id;  
String name;  
Address address;//HAS-A  
public Student(int id, String name) {  
this.id = id;  
this.name = name;  
}  
}                      

Since Address is not Serializable, you can not serialize the instance of Student class.

All the objects within an object must be Serializable.

 Java Serialization with Inheritance (IS-A Relationship)

If a class implements serializable then all its sub classes will also be serializable. Let's see the example given below:

import java.io.Serializable;  
class Person implements Serializable{  
int id;  
String name;  
Person(int id, String name) {  
this.id = id;  
this.name = name;  
}  
}  

class Student extends Person{  
String course;  
int fee;  
public Student(int id, String name, String course, int fee) {  
super(id,name);  
this.course=course;  
this.fee=fee;  
}  
}  

Now you can serialize the Student class object that extends thePerson class which is Serializable.Parent class properties are inherited to subclasses so if parent class is Serializable, subclass would also be.

java.io.Serializable interface

Serializable is a marker interface (has no body). It is just used to "mark" java classes which support a certain capability. It must be implemented by the class whose object you want to persist
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

 ObjectOutputStream class

The ObjectOutputStream class is used to write primitive data types and Java objects to an OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.

public ObjectOutputStream(OutputStream out) throws IOException {}creates an ObjectOutputStream that writes to the specified OutputStream.
 Important methods

MethodDescription
public final void writeObject(Object obj) throws IOException{}writes the specified object to the ObjectOutputStream.
public void flush() throws IOException {}flushes the current output stream.
public void close() throws IOException {}closes the current output stream.
 Java Serialization
In this example, we are going to serialize the object of Student class. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt.
import java.io.*;  
class Persist{  
public static void main(String args[])throws Exception{  
Student s1 =new Student(211,"ravi");  
FileOutputStream fout=new FileOutputStream("f.txt");  
ObjectOutputStream out=new ObjectOutputStream(fout);  
out.writeObject(s1);  
out.flush();  
System.out.println("success");  
}  
}                              
success
 Deserialization in java

public ObjectInputStream(InputStream in) throws IOException
{}
creates an ObjectInputStream that reads from the specified InputStream.

Deserialization is the process of reconstructing the object from the serialized state.It is the reverse operation of serialization.

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

 Important methods

MethodDescription
public final Object readObject() throws IOException, ClassNotFoundException{}reads an object from the input stream.
public void close() throws IOException {}closes ObjectInputStream.


  Example of Java Deserialization
 
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{  
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  
Student s=(Student)in.readObject();  
System.out.println(s.id+" "+s.name);  
in.close();  
   }  
}     

                     
211 ravi

 Java Serialization with static data member

If there is any static data member in a class, it will not be serialized because static is the part of class not object.
class Employee implements Serializable{  

int id;  
String name;  
static String company="SSS IT Pvt Ltd";   //it won't be serialized  
public Student(int id, String name) {  
this.id = id;  
this.name = name;  
}  
}                          


 Java Serialization with array or collection

Rule: In case of array or collection, all the objects of array or collection must be serializable. If any object is not serialiizable, serialization will be failed.

Externalizable

The Externalizable interface provides the facility of writing the state of an object into a byte stream in compress format. It is not a marker interface.

The Externalizable interface provides two methods:
  • public void writeExternal(ObjectOutput out) throws IOException
  • public void readExternal(ObjectInput in) throws IOException
 transient keyword

Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized. Let's take an example, I have declared a class as Student, it has three data members id, name and age. If you serialize the object, all the values will be serialized but I don't want to serialize one value, e.g. age then we can declare the age data member as transient.
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
transient int age;//Now it will not be serialized
public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}
}

 Static

The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

The static can be: 

  • variable (also known as class variable)
  • method (also known as class method)
  • block
  • nested class
 Static variable

If you declare any variable as static, it is known static variable.

  • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
  • The static variable gets memory only once in class area at the time of class loading.
 Advantage of static variable

It makes your program memory efficient (i.e it saves memory).
class Student{
int rollno;
String name;
String college="ITS";
}

Restrictions for static method

There are two main restrictions for the static method. They are:

  • The static method can not use non static data member or call non-static method directly.
  • this and super cannot be used in static context.
 Static Block
  • Is used to initialize the static data member.
  • It is executed before main method at the time of classloading.
    class A2{
    static{System.out.println("static block is invoked");}
    public static void main(String args[]){
    System.out.println("Hello main");
    }
    }
 this keyword

this is a reference variable that refers to the current object.

Following are the usage of this keyword

  • this keyword can be used to refer current class instance variable.
  • this() can be used to invoke current class constructor.
  • this keyword can be used to invoke current class method (implicitly)
  • this can be passed as an argument in the method call.
  • this can be passed as argument in the constructor call.
  • this keyword can also be used to return the current class instance.

If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity.


class Student10{
int id;
String name;

Student10(int id,String name){
id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){
Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
}
}

The above code results output as:

Output:0 null
 0 null

The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is better if you have many constructors in the class and want to reuse that constructor.

Rule: Call to this() must be the first statement in constructor.

  Multithreading

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

 Advantages of Java Multithreading
  • It doesn't block the user because threads are independent and you can perform multiple operations at same time.            
  • You can perform many operations together so it saves time.
  • Threads are independent so it doesn't affect other threads if exception occur in a single thread        
Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:

  • Process-based Multitasking(Multiprocessing)
  • Thread-based Multitasking(Multithreading)
Process-based Multitasking (Multiprocessing)

Each process have its own address in memory i.e. each process allocates separate memory area.

  • Process is heavyweight.
  • Cost of communication between the process is high.
  • Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.
Thread-based Multitasking (Multithreading)
  • Threads share the same address space.
  • Thread is lightweight.
  • Cost of communication between the thread is low.
Thread Life cycle

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

  • New
  • Runnable
  • Running
  • Non-Runnable(Blocked)
  • Terminated
 Life cycle of thread with images
 Chania

New :  The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

Runnable :   The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.

Running :  The thread is in running state if the thread scheduler has selected it.

Non-Runnable(Blocked) : This is the state when the thread is still alive, but is currently not eligible to run.

Terminated : A thread is in terminated or dead state when its run() method exits.

  Creating Thread

There are two ways to create a thread:

  • By extending Thread class
  • By implementing Runnable interface
 Constructors of Thread class
  • Thread()
  • Thread(String name)
  • Thread(Runnable r)
  • Thread(Runnable r,String name)
 Common methods of thread

public void run(): is used to perform action for a thread

public void start()  starts the execution of the thread.JVM calls the run() method on the thread.

public void sleep(long miliseconds)  Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

public void join():  waits for a thread to die.

public int getPriority(): returns the priority of the thread.

public Thread currentThread() returns the reference of currently executing thread.

public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.

 Runnable interface

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().                        

public void run(): is used to perform action for a thread.

start() method of Thread class is used to start a newly created thread. It performs following tasks:

  • A new thread starts(with new callstack).
  • The thread moves from New state to the Runnable state.
  • When the thread gets a chance to execute, its target run() method will run.
  Extending Thread class
class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
}  
}  
Output:thread is running...
 Implementing Runnable Interface
class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  

public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
}  
}  
Output:thread is running...
 Thread Scheduler
  • Thread scheduler in java is the part of the JVM that decides which thread should run.
  • There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.Only one thread at a time can run in a single process.
    The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
Can a thread be started twice

No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

You can't call thread1.start();  and again thread1.start()

 Daemon Thread

Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

  • There are many java daemon threads running automatically e.g. gc, finalizer etc.
  • It is a low priority thread.
  • If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.
Abstraction

Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.

Abstract class and Method

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.                   

abstract class A{}

A method that is declared as abstract and does not have implementation is known as abstract method.

abstract void printStatus();//no body and abstract  
Abstract rules

An abstract class can have data member, abstract method, method body, constructor and even main() method. 

Rule: If there is any abstract method in a class, that class must be abstract.

Rule: If you are extending any abstract class that have abstract method, you must either provide the implementation of the method or make this class abstract.

D/B Abstraction and Encapsulation

Abstraction hides the implementation details whereas encapsulation wraps code and data into a single unit.

 Can you use abstract and final both with a method?

No, because abstract method needs to be overridden whereas you can't override final method.

Interface

Interface is a blueprint of a class that have static constants and abstract methods.It can be used to achieve fully abstraction and multiple inheritance.

Can you declare an interface method static?

No, because methods of an interface is abstract by default, and static and abstract keywords can't be used together.

 Can an Interface be final?

No, because its implementation is provided by another class.

Marker Interface

An interface that have no data member and method is known as a marker interface.For example Serializable, Cloneable etc.

Can we define private and protected modifiers for variables in interfaces

No, they are implicitly public.

Difference between abstract class and Interface

Abstract classInterface
An abstract class can have method body (non-abstract methods).Interface have only abstract methods.
An abstract class can have instance variables.An interface cannot have instance variables.
An abstract class can have constructor.Interface cannot have constructor.
An abstract class can have static methods.Interface cannot have static methods.
You can extends one abstract class.You can implement multiple interfaces

  !!! An object reference can be cast to an interface reference when the object implements the referenced interface

 Collections

Collections in java is a framework that provides an architecture to store and manipulate the group of objects.

All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

Collection represents a single unit of objects i.e. a group.

Framework
 
  • provides readymade architecture.
  • represents set of classes and interface.
  • is optional.
Collection Level

Iterator interface

Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:
  • public boolean hasNext() it returns true if iterator has more elements.
  • public object next() it returns the element and moves the cursor pointer to the next element.
  • public void remove() it removes the last elements returned by the iterator. It is rarely used.
ArrayList
  • Java ArrayList class uses a dynamic array for storing the elements.It extends AbstractList class and implements List
    interface.
  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList class maintains insertion order.
  • Java ArrayList class is non synchronized.
  • Java ArrayList allows random access because array works at the index basis.
  • In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.
LinkedList
  • Java LinkedList class uses doubly linked list to store the elements. It extends the AbstractList class and implements List and Deque interfaces.
  • Java LinkedList class can contain duplicate elements.
  • Java LinkedList class maintains insertion order.
  • Java LinkedList class is non synchronized.
  • In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
  • Java LinkedList class can be used as list, stack or queue.
 Difference between ArrayList and LinkedList

ArrayListLinkedList
ArrayList internally uses dynamic array to store the elements.LinkedList internally uses doubly linked list to store the elements.
Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memoryManipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.
ArrayList class can act as a list only because it implements List only.LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
ArrayList is better for storing and accessing data.LinkedList is better for manipulating data.

 List Interface

List Interface is the subinterface of Collection.It contains methods to insert and delete elements in index basis.It is a factory of ListIterator interface.

ListIterator interface
ListIterator Interface is used to traverse the element in backward and forward direction.

Commonly used methods of ListIterator Interface:

  • public boolean hasNext();
  • public Object next();
  • public boolean hasPrevious();
  • public Object previous();
ListIterator itr=al.listIterator();  
while(itr.hasNext()){ 
    System.out.println(itr.next());  
} 
 HashSet
 
  • uses hashtable to store the elements.It extends AbstractSet class and implements Set interface.
  • contains unique elements only.

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

hashset
TreeSet
  • contains unique elements only like HashSet. The TreeSet class implements NavigableSet interface that extends the SortedSet interface.
  • maintains ascending order.
Queue Interface

The Queue interface basically orders the element in FIFO(First In First Out)manner.

Methods of Queue Interface :

  • public boolean add(object);
  • public boolean offer(object);
  • public remove();
  • public poll();
  • public element();
  • public peek();
 Map Interface

A map contains values based on the key i.e. key and value pair.Each pair is known as an entry.Map contains only unique elements.

Commonly used methods of Map interface:

  • public Object put(object key,Object value): is used to insert an entry in this map.
  • public void putAll(Map map):is used to insert the specified map in this map.
  • public Object remove(object key) is used to delete an entry for the specified key.
  • public Object get(Object key):is used to return the value for the specified key.
  • public boolean containsKey(Object key):is used to search the specified key from this map.
  • public boolean containsValue(Object value):is used to search the specified value from this map.
  • public Set keySet():returns the Set view containing all the keys.
  • public Set entrySet():returns the Set view containing all the keys and values.
 Entry

Entry is the subinterface of Map.So we will access it by Map.Entry name.It provides methods to get key and value.

Methods of Entry interface:

  • public Object getKey(): is used to obtain key.
  • public Object getValue():is used to obtain value
HashMap


  • A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It maintains no order.
HashMap
import java.util.*;  
class TestCollection13{  
public static void main(String args[]){  
HashMap hm=new HashMap();  
hm.put(100,"Amit");  
hm.put(101,"Vijay");  
hm.put(102,"Rahul");  
for(Map.Entry m:hm.entrySet()){  
       System.out.println(m.getKey()+" "+m.getValue());  
}  
 }  
}          
Output:102 Rahul
100 Amit
101 Vijay

HashSet contains only values whereas HashMap contains entry(key and value).

 LinkedHashMap
  • A LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It is same as HashMap instead maintains insertion order.
TreeMap
 
  • A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • It contains only unique elements.
  • It cannot have null key but can have multiple null values.
  • It is same as HashMap instead maintains ascending order.
Treemap
HashMapTreeMap
1) HashMap is can contain one null key.TreeMap can not contain any null key.
2) HashMap maintains no order.TreeMap maintains ascending order.
Hashtable
  • A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling the hashcode() method.A Hashtable contains values based on the key. Itimplements the Map interface and extends Dictionary class.
  • It contains only unique elements.
  • It may have not have any null key or value.
  • It is synchronized.
Difference between HashMap and HashTable

HashmapHashTable
HashMap is non synchronized. It is not-thread safe and can't
be shared between many threads without proper synchronization
code.
Hashtable is synchronized. It is thread-safe and can be
shared with many threads.
HashMap allows one null key and multiple null values.Hashtable doesn't allow any null key or value.
HashMap is a new class introduced in JDK 1.2.Hashtable is a legacy class.
HashMap is fast.Hashtable is slow.
We can make the HashMap as synchronizedHashtable is internally synchronized and can't be unsynchronized.
HashMap is traversed by Iterator.Hashtable is traversed by Enumerator and Iterator.
Iterator in HashMap is fail-fast.Enumerator in Hashtable is not fail-fast.
HashMap inherits AbstractMap class.Hashtable inherits Dictionary class.

Comparable Interface
 

Comparable interface is used to order the objects of user-defined class.This interface is found in java.lang package and contains only
one method named compareTo(Object).It provide only single sorting sequence i.e. you can sort the elements on based on single datamember
only.For instance it may be either rollno,name,age or anything else.

public int compareTo(Object obj): is used to compare the current object with the specified object.
We can sort the elements of:
  • String objects
  • Wrapper class objects
  • User-defined class objects

Error: String class and Wrapper classes implements the Comparable interface.So if you store the objects of string or wrapper classes, it will be Comparable.
 Comparator Interface

Comparator interface is used to order the objects of user-defined class.

This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).

It provides multiple sorting sequence i.e. you can sort the elements based on any data member. For instance it may be on rollno, name, age or anything else.

 public int compare(Object obj1,Object obj2): compares the first object with second object.
Method of Collections class for sorting List elements
public void sort(List list,Comparator c): is used to sort the elements of List by the given comparator.

 Difference between ArrayList and Vector

ArrayListVector
ArrayList is not synchronized.Vector is synchronized.
ArrayList increments 50% of current array size if number of element exceeds from its capacityVector increments 100% means doubles the array size if total number of element exceeds than its capacity.
ArrayList is not a legacy class, it is introduced in JDK 1.2.Vector is a legacy class.
ArrayList is fast because it is non-synchronized.Vector is slow because it is synchronized i.e. in multithreading environment, it will hold the other threads in runnable or non-runnable state until current thread releases the lock of object.
ArrayList uses Iterator interface to traverse the elements.Vector uses Enumeration interface to traverse the elements. But it can use Iterator also.

Vector
import java.util.*;      
class TestVector1{      
public static void main(String args[]){      
Vector v=new Vector();//creating vector  
v.add("umesh");//method of Collection  
v.addElement("irfan");//method of Vector  
v.addElement("kumar");  
//traversing elements using Enumeration  
Enumeration e=v.elements();  
while(e.hasMoreElements()){  
System.out.println(e.nextElement());  
}  
}       }                
umesh irfan kumar
Exception Handling

Exception Handling is a mechanism to handle runtime errors.It is mainly used to handle checked exceptions.

Difference between Checked Exception and Unchecked Exception

1)Checked Exception :: The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException,SQLException etc. Checked exceptions are checked at compile-time.                

2)Unchecked Exception::The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at compile-time.

Is it necessary that each try block must be followed by a catch block

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.                  

finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort)

Difference between throw and throws

throw keywordthrows keyword
throw is used to explicitly throw an exception.throws is used to declare an exception.
checked exceptions can not be propagated with throw onlythrow only.checked exception can be propagated with throws.
throw is followed by an instance.throws is followed by class.
throw is used within the method.throws is used with the method signature.
You cannot throw multiple exceptionYou can declare multiple exception e.g. public void method()throws IOException,SQLException.
How many ways we can create the string object

There are two ways to create the string object, by string literal and by new keyword.

How many objects will be created in the following code
String s1="Welcome";  
String s2="Welcome";  
String s3="Welcome";  

Only one object.

Why java uses the concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

How many objects will be created in the following code?


String s = new String("Welcome");

Two objects, one in string constant pool and other in non-pool(heap).

What is the basic difference between string and stringbuffer object?

String is an immutable object. StringBuffer is a mutable object.

What is the difference between StringBuffer and StringBuilder ?

StringBuffer is synchronized whereas StringBuilder is not synchronized.

Garbage Collection

In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.    

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

Advantages of garbage collection

It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory

  • It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
How can an object be unreferenced
There are many ways
  • By nulling the reference
    Employee e=new Employee();  
    e=null;
  • By assigning a reference to another
    Employee e1=new Employee(); 
    Employee e2=new Employee(); 
    e1=e2;//now the first object referred by e1 is available for garbage collection  
  • By annonymous object:
        new Employee();  
finalize()

The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:            

The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

 gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

public static void gc(){}

Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.         

Neither finalization nor garbage collection is guaranteed.

Garbage collection sample program
public class TestGarbage1{  
public void finalize(){System.out.println("object is garbage collected");}  
public static void main(String args[]){  
TestGarbage1 s1=new TestGarbage1();  
TestGarbage1 s2=new TestGarbage1();  
s1=null;  
s2=null;  
System.gc();  
}  
}  
object is garbage collected
object is garbage collected

What is difference between final, finally and finalize?
  • final: final is a keyword, final can be variable, method or class.You, can't change the value of final variable, can't override final method, can't inherit final class             
  • finally: finally block is used in exception handling. finally block is always executed.             
  • finalize() method is used in garbage collection.finalize() method is invoked just before the object is garbage collected.The finalize() method can be used to perform any cleanup processing.             
Marker interface in Java?
It is an empty interface (no field or methods). Examples of marker interface are Serializable, Clonnable and Remote interface. All these interfaces are empty interfaces.
  1. Cloneable interface : Cloneable interface is present in java.lang package. There is a method clone() in Object class. A class that implements the Cloneable interface indicates that it is legal for clone() method to make a field-for-field copy of instances of that class.Invoking Object’s clone method on an instance of the class that does not implement the Cloneable interface results in an exception CloneNotSupportedException being thrown. By convention, classes that implement this interface should override Object.clone() method. 
  2. Serializable interface : Serializable interface is present in java.io package. It is used to make an object eligible for saving its state into a file. This is called Serialization.Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable.
  3. Remote interface : Remote interface is present in java.rmi package. A remote object is an object which is stored at one machine and accessed from another machine. So, to make an object a remote object, we need to flag it with Remote interface. Here, Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine.Any object that is a remote object must directly or indirectly implement this interface. RMI (Remote Method Invocation) provides some convenience classes that remote object implementations can extend which facilitate remote object creation.


Difference Between Abstract Class and Interfaces

Abstraction: Hiding the internal implementation of the feature and only showing the functionality to the users. i.e. what it works (showing), how it works (hiding). Both abstract class and interface are used for abstraction.

Abstract class vs Interface

  1. Type of methods: Interface can have only abstract methods. Abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also.
  2. Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-final variables.
  3. Type of variables: Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.
  4. Implementation: Abstract class can provide the implementation of interface. Interface can’t provide the implementation of abstract class.
  5. Inheritance vs Abstraction: A Java interface can be implemented using keyword “implements” and abstract class can be extended using keyword “extends”.
  6. Multiple implementation: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
  7. Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc.

One more use of marker interface in Java can be commenting. a marker interface called Thread Safe can be used to communicate other developers that classes implementing this marker interface gives thread-safe guarantee and any modification should not violate that. Marker interface can also help code coverage or code review tool to find bugs based on specified behavior of marker interfaces.

Again Annotations are better choice @ThreadSafe looks lot better than implementing ThraedSafe marker interface.

In summary marker interface in Java is used to indicate something to compiler, JVM or any other tool but Annotation is better way of doing same thing.


Are Static local variables allowed in Java?
Unlike C/C++, static local variables are not allowed in Java. For example, following Java program fails in compilation with error “Static local variables are not allowed” 


Static vs Dynamic binding in Java?

Static Binding: The binding which can be resolved at compile time by compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time .

Why binding of static, final and private methods is always a static binding? 
Static binding is better performance wise (no extra overhead is required). Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods is static.

Dynamic Binding: In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have same method . 


Covariant Return types in java
Before JDK 5.0, it was not possible to override  a method by changing the return type. When we override a parent class method, the name, argument types and return type of the overriding method in child class has to be exactly same as that of parent class method. Overriding method was said to be invariant with respect to return type.

Covariant return types

Java 5.0 onwards it is possible to have different return type for a overriding method in child class, but child’s return type should be sub-type of parent’s return type. Overriding method becomes variant with respect to return type.


HashMap
A map is an associative array data structures of key, value pairs.
Hashing: It is the transformation of a string of characters(Text) to a shorted fixed-length value that represents original string. A shorter values helps in indexing and faster searches.


How HashMap works in Java?
HashMap in Java works on hashing principle. It is a data structure which allows us to store object and retrieve it in constant time O(1) provided we know the key. In hashing, hash functions are used to link key and value in HashMap.
When we call put method, hashcode() method of the key object is called so that hash function of the map can find a bucket location to store value object, which is actually an index of the internal array, known as the table
When you want to retrieve the object, you call the get() method and again pass the key object. This time again key object generate same hash code (it's mandatory for it to do so to retrieve the object and that's why HashMap keys are immutable e.g. String) and we end up at same bucket location.
Since the internal array of HashMap is of fixed size, and if you keep storing objects, at some point of time hash function will return same bucket location for two different keys, this is called collision in HashMap. In this case, a linked list is formed at that bucket location and a new entry is stored as next node.

If we try to retrieve an object from this linked list, we need an extra check to search correct value, this is done by equals() method. Since each node contains an entry, HashMap keeps comparing entry's key object with the passed key using equals() and when it return true, Map returns the corresponding value.

Since searching inlined list is O(n) operation, in worst case hash collision reduce a map to linked list. This issue is recently addressed in Java 8 by replacing linked list to the tree to search in O(logN) time.

Read more: https://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html#ixzz5blJTU0Ax 


What will happen if two different objects have the same hashcode?
equals() and hashCode() contract  that two unequal objects in Java can have same hashcode.
Since hashcode is same, bucket location would be same and collision will occur in HashMap Since HashMap uses LinkedList to store object, this entry (object of Map.Entry comprise key and value )  will be stored in LinkedList.

after finding bucket location, we will call keys.equals() method to identify a correct node in LinkedList and return associated value object for that key in Java HashMap.

Using immutable, final object with proper equals() and hashcode() implementation would act as perfect Java HashMap  keys and improve the performance of Java HashMap  by reducing collision. Immutability also allows caching their hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g. Integer very good keys in Java HashMap.


What happens On HashMap in Java if the size of the HashMap  exceeds a given threshold defined by load factor?
If the size of the Map exceeds a given threshold defined by load-factor e.g. if the load factor is .75 it will act to re-size the map once it filled 75%. Similar to other collection classes like ArrayList,  Java HashMap re-size itself by creating a new bucket array of size twice of the previous size of HashMap and then start putting every old element into that new bucket array. This process is called rehashing because it also applies the hash function to find new bucket location.


Do you see any problem with resizing of HashMap in Java?
There is potential race condition exists while resizing HashMap in Java, if two thread at the same time found that now HashMap needs resizing and they both try to resizing. on the process of resizing of HashMap in Java, the element in the bucket which is stored in linked list get reversed in order during their migration to new bucket because Java HashMap  doesn't append the new element at tail instead it append new element at the head to avoid tail traversing. If race condition happens then you will end up with an infinite loop.


Why String, Integer and other wrapper classes are considered good keys?
String, Integer and other wrapper classes are natural candidates of HashMap key, and String is most frequently used key as well because String is immutable and final, and overrides equals and hashcode() method. Other wrapper class also shares similar property. Immutability is required, in order to prevent changes on fields used to calculate hashCode() because if key object returns different hashCode during insertion and retrieval than it won't be possible to get an object from HashMap.

Immutability is best as it offers other advantages as well like thread-safety, If you can  keep your hashCode same by only making certain fields final, then you go for that as well.


Can we use any custom object as a key in HashMap?
Of course you can use any Object as key in Java HashMap provided it follows equals and hashCode contract and its hashCode should not vary once the object is inserted into Map. If the custom object is Immutable than this will be already taken care because you can not change it once created.


How null key is handled in HashMap? Since equals() and hashCode() are used to store and retrieve values, how does it work in case of the null key?
The null key is handled specially in HashMap, there are two separate methods for that putForNullKey(V value) and getForNullKey(). Later is offloaded version of get() to look up null keys.  Null keys always map to index 0.  This null case is split out into separate methods for the sake of performance in the two most commonly used operations (get and put), but incorporated with conditionals in others. In short, equals() and hashcode() method are not used in case of null keys in HashMap.


Java ArrayList and HashMap Performance Improvement in JDK 7
when you create empty ArrayList, without specifying any initial capacity i.e. by using new ArrayList(), Java creates an Object array of default size 10 to hold objects. This memory is allocated eagerly, even before you have added any object
ArrayList and HashMap with size zero in JDK 1.7.0_40 update.


Difference Between HashTable and HashMap?
Though both Hashtable and HashMap are data-structure based upon hashing and implementation of Map interface, the main difference between them is that HashMap is not thread-safe but Hashtable is thread-safe. Which means you cannot use HashMap in multi-threaded Java application without external synchronization.

  1. The HashMap class is roughly equivalent to Hashtable, except that it is non-synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
  2. One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap can not be shared between multiple threads without proper synchronization. Java 5 introduces ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.
  3. Another significant difference between HashMap vs Hashtable is that Iterator in the HashMap is  a fail-fast iterator  while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally  by adding or removing any element except Iterator's own remove() method.
  4. One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment. So if you don't need synchronization and HashMap are only used by one thread, it outperforms Hashtable in Java.
  5. HashMap does not guarantee that the order of the map will remain constant over time.


Syncronization
Synchronized means only one Thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a Hashtable will have to acquire a lock on the object while others will wait for the lock to be released.


Fail-Safe
2) Fail-safe is relevant from the context of iterators. If an Iterator or ListIterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.


3) Structurally modification means deleting or inserting element which could effectively change the structure of the map.

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);


What is the difference between poll() and remove() method of Queue interface?
Though both poll() and remove() method from Queue is used to remove the object and returns the head of the queue, there is a subtle difference between them. If Queue is empty() then a call to remove() method will throw Exception, while a call to poll() method returns null. By the way, exactly which element is removed from the queue depends upon queue's ordering policy and varies between different implementation, for example, PriorityQueue keeps the lowest element as per Comparator or Comparable at head position.


What is the difference between fail-fast and fail-safe Iterators?
Fail-fast Iterators throws ConcurrentModificationException when one Thread is iterating over collection object and other thread structurally modify Collection either by adding, removing or modifying objects on underlying collection. They are called fail-fast because they try to immediately throw Exception when they encounter failure. On the other hand fail-safe Iterators works on copy of collection instead of original collection


How do you remove an entry from a Collection? and subsequently what is the difference between the remove() method of Collection and remove() method of Iterator, which one you will use while removing elements during iteration?
Collection interface defines remove(Object obj) method to remove objects from Collection. List interface adds another method remove(int index), which is used to remove object at specific index. You can use any of these method to remove an entry from Collection, while not iterating. Things change, when you iterate. Suppose you are traversing a List and removing only certain elements based on logic, then you need to use Iterator's remove() method. This method removes current element from Iterator's perspective. If you use Collection's or List's remove() method during iteration then your code will throw ConcurrentModificationException. That's why it's advised to use Iterator remove() method to remove objects from Collection.


What is the difference between Synchronized Collection and Concurrent Collection?
Java 5 has added several new Concurrent Collection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue etc.

Java Also provided a way to get Synchronized copy of collection e.g. ArrayList, HashMap by using Collections.synchronizedMap() Utility function.One Significant difference is that Concurrent Collections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and Synchronization.


What is the difference between Iterator and Enumeration?
Iterator duplicate functionality of Enumeration with one addition of remove() method and both provide navigation functionally on objects of Collection.Another difference is that Iterator is more safe than Enumeration and doesn't allow another thread to modify collection object during iteration except remove() method and throwsConcurrentModificaitonException.


HashSet
HashSet is built on top of HashMap. If you look at source code of java.util.HashSet class, you will find that that it uses a HashMap
.
When you call add() method of HashSet, it put entry in HashMap . Since keys are unique in a HashMap, it provides uniqueness guarantee of Set interface.


What do you need to do to use a custom object as a key in Collection classes like Map or Set?
If you are using any custom object in Map as key, you need to override equals() and hashCode() method, and make sure they follow their contract. On the other hand if you are storing a custom object in Sorted Collection e.g. SortedSet or SortedMap, you also need to make sure that your equals() method is consistent to compareTo() method, otherwise that collection will not follow there contacts e.g. Set may allow duplicates.


When do you use ConcurrentHashMap in Java? 

ConcurrentHashMap is better suited for situation where you have multiple readers and one

Writer or fewer writers since Map gets locked only during the write operation. If you have an equal number of reader and writer than ConcurrentHashMap will perform in the line of Hashtable or synchronized HashMap.


What is the difference between Set and List in Java?
Set doesn't allowed duplicate while List does and List maintains insertion order while Set doesn't.


How do you Sort objects on the collection?
This Collection interview question serves two purpose it not only test an important programming concept Sorting but also utility class like Collections which provide several methods for creating synchronized collection and sorting. Sorting is implemented using Comparable and Comparator in Java and when you call Collections.sort() it gets sorted based on the natural order specified in compareTo() method while Collections.sort(Comparator) will sort objects based on compare() method of Comparator.


What is NavigableMap in Java? What is a benefit over Map?
NavigableMap Map was added in Java 1.6, it adds navigation capability to Map data structure. It provides methods like lowerKey() to get keys which is less than specified key, floorKey() to return keys which is less than or equal to specified key, ceilingKey() to get keys which is greater than or equal to specified key and higherKey() to return keys which is greater specified key from a Map. It also provide similar methods to get entries e.g. lowerEntry(), floorEntry(), ceilingEntry() and higherEntry(). Apart from navigation methods, it also provides utilities to create sub-Map e.g. creating a Map from entries of an exsiting Map like tailMap, headMap and subMap. headMap() method returns a NavigableMap whose keys are less than specified, tailMap() returns a NavigableMap whose keys are greater than the specified and subMap() gives a NavigableMap between a range, specified by toKey to fromKey.  


Which one you will prefer between Array and ArrayList for Storing object and why?
Though ArrayList is also backed up by array, it offers some usability advantage over array in Java. Array is fixed length data structure, once created you can not change it's length. On the other hand, ArrayList is dynamic, it automatically allocate a new array and copies content of old array, when it resize. Another reason of using ArrayList over Array is support of Generics. Array doesn't support Generics, and if you store an Integer object on a String array, you will only going to know about it at runtime, when it throws ArrayStoreException. On the other hand, if you use ArrayList, compiler and IDE will catch those error on the spot. So if you know size in advance and you don't need re-sizing than use array, otherwise use ArrayList.


Can we replace Hashtable with ConcurrentHashMap? 
Yes we can replace Hashtable with ConcurrentHashMap and that's what suggested in Java documentation of ConcurrentHashMap. but you need to be careful with code which relies on locking behavior of Hashtable. Since Hashtable locks whole Map instead of a portion of Map, compound operations like if(Hashtable.get(key) == null) put(key, value) works in Hashtable but not in concurrentHashMap. instead of this use putIfAbsent() method of ConcurrentHashMap


What is CopyOnWriteArrayList, how it is different than ArrayList and Vector?
CopyOnWriteArrayList is new List implementation introduced in Java 1.5 which provides better concurrent access than Synchronized List. better concurrency is achieved by Copying ArrayList over each write and replace with original instead of locking. Also CopyOnWriteArrayList doesn't throw any ConcurrentModification Exception. Its different than ArrayList because its thread-safe and ArrayList is not thread-safe and it's different than Vector in terms of Concurrency. CopyOnWriteArrayList provides better Concurrency by reducing contention among readers and writers.


Why ListIterator has added() method but Iterator doesn't or Why to add() method is declared in ListIterator and not on Iterator. 
ListIterator has added() method because of its ability to traverse or iterate in both direction of the collection. it maintains two pointers in terms of previous and next call and in a position to add a new element without affecting current iteration.


When does ConcurrentModificationException occur on iteration?  
When you remove object using Collection's or List's remove method e.g. remove(Object element) or remove(int index), instead of Iterator's remove() method than ConcurrentModificationException occurs. As per Iterator's contract, if it detect any structural change in Collection e.g. adding or removing of the element, once Iterator begins, it can throw ConcurrentModificationException.  Here are some tips to avoid ConcurrentModification in Java.


Difference between Set, List and Map Collection classes?
java.util.Set, java.util.List and java.util.Map defines three of most popular data structure support in Java. Set provides uniqueness guarantee i.e.g you can not store duplicate elements on it, but it's not ordered. On the other hand List is an ordered Collection and also allowes duplicates. Map is based on hashing and stores key and value in an Object called entry. It provides O(1) performance to get object, if you know keys, if there is no collision. Popular impelmentation of Set is HashSet, of List is ArrayList and LinkedList, and of Map are HashMap, Hashtable and ConcurrentHashMap. Another key difference between Set, List and Map are that Map doesn't implement Collection interface, while other two does.


New Features in Java 7
1. Type Inference in Generics :

Prior JDK 7, you type more to specify types on both left and right hand side of object creation expression, but now it only needed on left hand side, 

2. String in switch :

Before JDK 7, only integral types can be used as selector for switch-case statement. In JDK 7, you can use a String object as the selector. For example,


3. Automatic Resource Management:
Before JDK 7, we need to use a finally block, to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly, for example while reading files and streams, we need to close them into finally block, which result in lots of boiler plate and messy code.

Now in Java 7, you can use try-with-resource feature to automatically close resources, which implements AutoClosable and Closeable interface e.g. Streams, Files, Socket handles, database connections etc. JDK 7 introduces a try-with-resources statement, which ensures that each of the resources in try(resources) is closed at the end of the statement by calling close() method of AutoClosable. Now same example in Java 7 will look like below, a much concise and cleaner code :



4. Underscore in String literals
In JDK 7, you could insert underscore(s) '_' in between the digits in an numeric literals (integral and floating-point literals) to improve readability. This is especially valuable for people who uses large numbers in source files, may be useful in finance and computing domains. For example,








Comments
* The email will not be published on the website.
I BUILT MY SITE FOR FREE USING