Why not use for(int i=0; i< v.size();i++){}?

For loops are expensive to the processor when the collection reaches large sizes, as many operations are done just to compute the first line:

For Loop

  1. int i = 0 is an assignment and creation (2 operations)
  2. i get size, check value of i, and compare (3 operations)
  3. i++ gets i then adds 1 to it [++i is only 2 operations] this one (3 operations)
  4. 7/8 operations in total, each time the loop runs through

While Loop

  1. where an enumeration or iterator uses a while(){}
  2. while(v.hasNext()) has next true or false (1 operation)
  3. while(v.hasMoreElements()) has more true or false (1 operation)
  4. Only one operation per repeat of this loop

Iterator
Iterator is the interface and found in the java.util package.It has three methods

  1. hasNext()
  2. next()
  3. remove()

Enumeration
Enumeration is also an interface and found in the java.util package .An enumeration is an object that generates elements one at a time. It is used for passing through a collection, usually of unknown size.The traversing of elements can only be done once per creation.

It has following methods

  1. hasMoreElements()
  2. nextElement()

An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework.Iterators differ from enumerations by allowing the caller to remove elements from the underlying collection during the iteration.

HashMap vs HashTable

  1. HashMap is non synchronized and not thread safe.On the other hand, HashTable is thread safe and synchronized.
  2. Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.
  3. Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not.if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator’s own remove method , then the iterator will throw ConcurrentModification Exception.
    Structural modification means adding or removing elements from the Collection object (here hashmap or hashtable) . Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast.
  4. Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable in single threaded environment.

Similarities Between HashMap and Hashtable

  1. Insertion Order :Both HashMap and Hashtable does not guarantee that the order of the map will remain constant over time. Instead use LinkedHashMap, as the order remains constant over time.
  2. Map interface :Both HashMap and Hashtable implements Map interface .
  3. Put and get method :Both HashMap and Hashtable provides constant time performance for put and get methods assuming that the objects are distributed uniformly across the bucket.
  4. Internal working :Both HashMap and Hashtable works on the Principle of Hashing . We have already discussed how hashmap works in java .

When to use HashMap and Hashtable?
Single Threaded Application
HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications .

Multi Threaded Application
We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 . Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multithreaded application prefer ConcurrentHashMap instead of Hashtable.

An instance is eligible for garbage collection when null is assigned to it. These are choices made by the JVM implementer.

class Animal 
{
    public static void main(String[] args) 
    {
        Animal lion = new Animal();
        System.out.println("Main is completed.");
    }

    protected void finalize() {
        System.out.println("Rest in Peace!");
    }
}

During compilation process as an optimization technique the Java compiler can choose to assign null value to an instance, so that it marks that instance can be evicted.

In the above class, lion instance is never uses beyond the instantiation line. So the Java compiler as an optimzation measure can assign lion = null just after the instantiation line. So, even before SOP’s output, the finalizer can print ‘Rest in Peace!’. We cannot prove this deterministically as it depends on the JVM implementation and memory used at runtime.

Being an automatic process, programmers need not initiate the garbage collection process explicitly in the code. System.gc() and Runtime.gc() are hooks to request the JVM to initiate the garbage collection process.

When we are writing a performance benchmark we may call System.gc() in between runs

Just before evicting an instance and reclaiming the memory space, the Java garbage collector invokes the finalize() method of the respective instance so that the instance will get a chance to free up any resources held by it. Though there is a guarantee that the finalize() will be invoked before reclaiming the memory space, there is no order or time specified. The order between multiple instances cannot be predetermined, they can even happen in parallel. Programs should not pre-mediate an order between instances and reclaim resources using the finalize() method.Any uncaught exception thrown during finalize process is ignored silently and the finalization of that instance is cancelled.

Final Example]

  1. Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed.
  2. Final is a keyword.
class FinalEg
{
   public static void main(String[] args) 
   {
      final int x = 600;
      x = 400;// Compile Time Error
    }
}

Finally Example

  1. Finally is used to place important code, it will be executed whether exception is handled or not.
  2. Finally is a block.
class FinallyEg
{
	public static void main(String[] args) 
	{
		try {
			int x = 500;
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			System.out.println("finally block is executed");
		}
	}
}

Finalize Example

  1. Finalize is used to perform clean up processing just before object is garbage collected.
  2. Finalize is a method.
class FinalizeEg 
{
	public void finalize() 
        {
	   System.out.println("finalize called");
	}

	public static void main(String[] args) 
        {
		FinalizeExample f1 = new FinalizeExample();
		FinalizeExample f2 = new FinalizeExample();
		f1 = null;
		f2 = null;
		System.gc();
	}
}

Difference between throw and throws in Java

void doCalc() throws ArithmeticException
{  
   .
   .
   throw new ArithmeticException("sorry");  
}  

throw

  1. Java throw keyword is used to explicitly throw an exception.
  2. Checked exception cannot be propagated using throw only.
  3. Throw is followed by an instance.
  4. Throw is used within the method.
  5. You cannot throw multiple exceptions.

throws

  1. Java throws keyword is used to declare an exception.
  2. Checked exception can be propagated with throws.
  3. Throws is followed by class.
  4. Throws is used with the method signature.
  5. You can declare multiple exceptions e.g.
    public void method()throws IOException,SQLException.