Constructor Overloading in Java

10:31 AM
Constructor are used to create the objects . new keyword always calls the  constructor of the class.

 Constructor name is always be the same as the name of the class .Generally in 99% code ,the name of the method is  different from the name of the class . But the problem arises  that method  too can have same name as the name of the class ( considered as bad coding practice)

Constructor example :

public class JavaBuff          // Class name                  
    {                                                                     
     public JavaBuff()            // Default Constructor   
       { } 
    public void JavaBuff()   //Valid but considered bad coding practice
      {}
} 

 If the name is same , then the only way we can differentiate between constructor and method , by looking at the return type .  Constructor never has a return type while method always has a return type .

               

 Points to ponder :


1.   While creating new object for the class ,every constructor calls the constructor of the superclass first , which is also known as constructor chaining . Internally , an implicit call to super() has been made ,unless the constructor invokes an overloaded constructor of the same class .

2.  Constructor can use any access modifier . Keep in mind that constructor can use private also .

3.  Constructor name should be same as the name of the class .

4.  Unlike methods , constructor do not have return types  .

5.  If one do not provide any constructor for the class ,then compiler put one implicitly in the code.
   
6. The default constructor is always no argument constructor .

7. If you have typed your constructor then , compiler do not provide the implicit constructor . So if you have overloaded the constructor , and also want to use the no arg constructor , then you need to write it by yourself in the code .

8. One cannot make a call to an instance method, or access an instance variable,
until after the super constructor runs.

9. Abstract classes always has constructor , and those constructors are called when a concrete (the class which implemented the abstract class) subclass is instantiated (creating an object).

10. Another important point is that interfaces do not have constructors .

11 . The first line in the constructor must be either call to super() or call to this() .Calls to this() and super() cannot be in the same constructor. You can have one or the other, but never both.

12. Every class, even an abstract class, has at least one constructor

13. Constructors are never inherited, thus they cannot be overridden.


Overloading a Constructor


Just like methods constructors can also be overloaded .Overloading a constructor means writing a multiple version of the constructor .

Continuing with  above example



public class JavaBuff          // Class name                
{                                                                    
    public JavaBuff()            //Default Constructor 1  
      { }  
    public  JavaBuff(int a , int b)   // Overloaded Constructor 2  
      { }
    public  JavaBuff(String x , String y)   // Overloaded Constructor 3  
      { }
 }


Constructor Overloading in Java Constructor Overloading in Java Reviewed by 13thGhost on 10:31 AM Rating: 5

Fail Fast Vs Fail Safe Iterator In Java

1:59 AM

Fail fast iterator while iterating through the collection , instantly throws Concurrent Modification Exception if there is structural modification  of the collection.

 Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.Any structural modification done to the iterator affects the copied data structure.


Fail Fast IteratorFail Safe Iterator
Throws ConcurrentModification Exception.Does not throws ConcurrentModification Exception.
Does not clone object .Clones objects.
No memory Overhead occurs.Memory Overhead occurs.
Examples:HashMap,Vector ,ArrayList, HashSet.Examples:CopyOnWriteArrayList,
ConcurrentHashMap

Concurrent Modification

When one or more thread is iterating over a collection, and in between if one thread changes the structure of the collection (either adding a element or by deleting a element or by updating a value  in the collection) is known as Concurrent Modification.

Fail-fast Iterator Example:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class FailFastExample
{
    
    
    public static void main(String[] args)
    {
        Map mapExample = new HashMap();
        mapExample.put("key1", "value1");
        mapExample.put("key2", "value2");
        mapExample.put("key3","value3");
        
        Iterator iterator = mapExample.keySet().iterator();
        
        while (iterator.hasNext())
        {
            System.out.println(mapExample.get(iterator.next()));
            mapExample.put("key4", "value4");
        }
        
    }
    
}


Output:
value1 Exception in thread "main" java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextEntry(Unknown Source) at java.util.HashMap$KeyIterator.next(Unknown Source) at FailFastExample.main(FailFastExample.java:20)

Fail-Safe Iterator Example:
import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;


public class FailSafeExample
{
    
    
    public static void main(String[] args)
    {
        ConcurrentHashMap mapExample = 
                               new ConcurrentHashMap();
        mapExample.put("key1", "value1");
        mapExample.put("key2", "value2");
        mapExample.put("key3","value3");
        
        Iterator iterator = mapExample.keySet().iterator();
        
        while (iterator.hasNext())
        {
            System.out.println(mapExample.get(iterator.next()));
            mapExample.put("key4", "value4");
        }
        
    }
    
}
Output:
value1
value2
value3
value4

Fail Fast Vs Fail Safe Iterator In Java Fail Fast Vs Fail Safe Iterator In Java Reviewed by 13thGhost on 1:59 AM Rating: 5

String vs StringBuilder vs StringBuffer in Java

10:45 PM

String

String is immutable ( once created can not be changed )object . The object created as a
String is stored in the Constant String Pool.
Every immutable object in Java is thread safe ,that implies String is also thread safe . String
can not be used by two threads simultaneously.
String once assigned can not be changed.

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created
through StringBuffer is stored in the heap. StringBuffer has the same methods as the
StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread
safe .
Due to this it does not allow two threads to simultaneously access the same method . Each
method can be accessed by one thread at a time .
But being thread safe has disadvantages too as the performance of the StringBuffer hits due
to thread safe property . Thus StringBuilder is faster than the StringBuffer when calling the
same methods of each class.
String Buffer can be converted to the string by using toString() method.

StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer


StringBuilder

StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also
be modified . The main difference between the StringBuffer and StringBuilder is
that StringBuilder is also not thread safe.StringBuilder is fast as it is not thread safe .

StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
String vs StringBuilder vs StringBuffer in Java String vs StringBuilder vs StringBuffer in Java Reviewed by 13thGhost on 10:45 PM Rating: 5

Iterable interface in Java

10:22 PM
The Iterable Interface is defined in java.lang package. The Iterable interface is the super interface in collection framework. It is the root interface for all the collection classes. The Collection interface extends the Iterable interface. So,all the subclasses that implementing the Collection interface also implement the Iterable interface.
Implementing this interface allows an object to be the target of the enhanced “for each” statement. The for-each loop is used for iterating the collections. The Iterable Interface is implemented in collections classes where iterations comes in handy.
It contains only one abstract method that returns the iterator.

Iterator <T> iterator();
where T represents the type of elements returned by the iterator.

The iterator can be used to iterate the elements of the object implementing the Iterable interface.



import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IterableEample {
  public static void main(String[] args) {
    List<String> objectNames = new ArrayList<>();
    objectNames.add("alpha");
    objectNames.add("beta");
    objectNames.add("delta");
    
    System.out.println("Using for loop");
    for (int i = 0; i < objectNames.size(); i++) 
    {
        System.out.println("Name = " +objectNames.get(i));
    }
    
    System.out.println("Using for Iterator");
    // Second approch
    Iterator<String> iterator = objectNames.iterator();
    while (iterator.hasNext()) {
        System.out.println("Object Name = "+iterator.next());
    }
  }
}

Output:

Object Name = alpha
Object Name = beta
Object Name = delta


Iterable interface in Java Iterable interface in Java Reviewed by 13thGhost on 10:22 PM Rating: 5

Iterator vs ListIterator in Java

5:10 PM






IteratorListIterator
Can traverse all the collections including set, map, etc.It can be used to traverse only list type collection like ArrayList, LinkedList.
Iterates the collection only in the forward direction.Can iterate over the collection in forward as well as backward direction.
Cannot obtain indexes.Can obtain indexes.
No way to add new elements to the collection.You can add new elements to the collection.
Iterator cannot modify the elements during iteration.ListIterator can modify the elements in the collection using the set() method.
Iterator vs ListIterator in Java Iterator vs ListIterator in Java Reviewed by 13thGhost on 5:10 PM Rating: 5

Top 5 frequently asked questions on Iterator Interface in Java

5:06 PM

Q #1) What is the Iteration in Java?

Answer: An iteration is a process by which a code block is repeatedly executed until a given condition holds or doesn’t exist. Using iteration you can traverse through a sequence of elements or process the data.
Q #2) How many types of Iterators are there in Java?
Answer: Iterators are used to traverse through the collections in Java.
There are three types of iterators in Java:
  • Enumerators
  • Iterators
  • ListIterators
Q #3) How do I use an Iterator in Java?
Answer: In order to use the iterator to traverse through the collection, first, you have to get the iterator using the iterator() method of the specified collection.
Then you can use the hasNext() and next() methods of the iterator to get the element.
Q #4) Why Iterator is used instead of for loop?
Answer: Both the iterator as well as for loop is used to repeatedly execute a specific code block. But the main difference is that in for loop you cannot alter or modify the contents of the collection. Even if you attempt to modify it, it will throw concurrentModificationException. Using iterator you can remove an element from the collection.
Q #5) Why do we need Iterator in Java?
Answer: Iterator helps you to retrieve the elements in the collection or a container without the programmer having to know the internal structure or working of the collection. They are more elegant, consume less memory and also the programmer is spared of in writing lengthy code.
Secondly, the elements can be stored in the collection in any fashion but using an iterator, the programmer can retrieve them just like a list or any other sequence.

If you want to read more about iterator in Java, then click here. And to know the difference between iterator and iterable then click here.

Top 5 frequently asked questions on Iterator Interface in Java Top 5 frequently asked questions on Iterator Interface in Java Reviewed by 13thGhost on 5:06 PM Rating: 5

Iterable vs Iterator interfaces in Java.

10:50 AM

Iterable Interface

Iterator Interface

Represents a collection that can be traversed using foreach loop.Allows to iterate over some other collection.
The class that implements the iterable interface has to override iterator() method.hasNext() and next() methods of Iterator interface are to be overridden by class implementing it.
Does not store the current state.Stores the current state of iteration.
An instance of the iterator interface should be produced every time iterator() method is called.No such contract for iterator interface.
Moves only in the forward direction.Moves in the forward direction and subinterfaces like listIterator support bidirectional traversing.
Does not provide any method to modify the elements during iteration.Provides the remove method that can remove element when iteration is in progress.
Iterable vs Iterator interfaces in Java. Iterable vs Iterator interfaces in Java. Reviewed by 13thGhost on 10:50 AM Rating: 5

Iterator Interface in Java

10:48 AM
In Java, an Iterator is a construct that is used to traverse or step through the collection.
In order to use an Iterator, you need to get the iterator object using the iterator() method of the collection interface. Java Iterator is a collection framework interface and is a part of the java.util package. Using Java Iterator we can iterate through the collection of objects.
Java Iterator interface replaces the enumerator that was used earlier to step through some simple collections like vectors.The java.util.Iterator<E> interface provides for one-way traversal and java.util.ListIterator<E> provides two-way traversal.  Iterator<E> is a replacement for the older Enumeration class which was used before collections were added to Java.
The java.util.Iterator interface provides the following methods: 
  • boolean hasNext() - Returns true if the iteration has more elements.
  • E next() - Returns the next element in the iteration.
  • void remove() - Removes from the underlying collection the last element returned by the iterator (optional operation).
The java.util.Scanner class is an example of a class that implements the Iterator interface. 
java.util.Scanner s = new java.util.Scanner(new java.io.File("test.txt"));
while(s.hasNext()) { 
 System.out.println(s.next());
}

The major differences between Java Iterator and Enumerator are:

  • Considerable improvement in method names.
  • You can remove method elements from the collection that is being traversed using an iterator.
In the example below is the  example of Iterator interface .

import java.util.*;
public class ArrayListIteratorTest {
 public static void main(String[] args) {
  ArrayList al1 = new ArrayList();
  al1.add("one");al1.add("two");
  al1.add("three");
  Iterator i = al1.iterator();
  String l;
  while(i.hasNext()) {
   l = (String)i.next();
   System.out.println(l);
  }
 }
}

Output:
one
two
three


Iterator Interface in Java Iterator Interface in Java Reviewed by 13thGhost on 10:48 AM Rating: 5

Comparable vs Comparator interface in Java

9:35 PM


Comparable and Comparator both are interfaces and can be used to sort collection elements.
There are many differences between Comparable and Comparator interfaces that are mentioned as follows:

Comparable in JavaComparator in Java
Comparable interface is used to sort the objects with natural ordering.Comparator in Java is used to sort attributes of different objects.
Comparable interface compares “this” reference with the object specified.Comparator in Java compares two different class objects provided.
Comparable is present in java.lang package.

A Comparator is present in the java.util package.
Comparable affects the original class, i.e., the actual class is modified.Comparator doesn’t affect the original class
Comparable provides compareTo() method to sort elements.Comparator provides compare() method, equals() method to sort elements.

This question is one of the most frequently asked questions in interviews.
Comparable vs Comparator interface in Java Comparable vs Comparator interface in Java Reviewed by 13thGhost on 9:35 PM Rating: 5

HashMap in Java

9:03 PM
Here is the list of methods available in HashMap class. I have also covered examples using these methods at the end of this post.
  1. void clear(): It removes all the key and value pairs from the specified Map.
  2. Object clone(): It returns a copy of all the mappings of a map and used for cloning them into another map.
  3. boolean containsKey(Object key): It is a boolean function which returns true or false based on whether the specified key is found in the map.
  4. boolean containsValue(Object Value): Similar to containsKey() method, however it looks for the specified value instead of key.
  5. Value get(Object key): It returns the value for the specified key.
  6. boolean isEmpty(): It checks whether the map is empty. If there are no key-value mapping present in the map then this function returns true else false.
  7. Set keySet(): It returns the Set of the keys fetched from the map.
  8. value put(Key k, Value v): Inserts key value mapping into the map. Used in the above example.
  9. int size(): Returns the size of the map – Number of key-value mappings.
  10. Collection values(): It returns a collection of values of map.
  11. Value remove(Object key): It removes the key-value pair for the specified key. Used in the above example.
  12. void putAll(Map m): Copies all the elements of a map to the another specified map.


import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Details {

   public static void main(String args[]) {

      /* This is how to declare HashMap */
      HashMap<Integer, String> hmap = new HashMap<Integer, String>();

      /*Adding elements to HashMap*/
      hmap.put(12, "Chaitanya");
      hmap.put(2, "Rahul");
      hmap.put(7, "Singh");
      hmap.put(49, "Ajeet");
      hmap.put(3, "Anuj");

      /* Display content using Iterator*/
      Set set = hmap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry mentry = (Map.Entry)iterator.next();
         System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
         System.out.println(mentry.getValue());
      }

      /* Get values based on key*/
      String var= hmap.get(2);
      System.out.println("Value at index 2 is: "+var);

      /* Remove values based on key*/
      hmap.remove(3);
      System.out.println("Map key and values after removal:");
      Set set2 = hmap.entrySet();
      Iterator iterator2 = set2.iterator();
      while(iterator2.hasNext()) {
          Map.Entry mentry2 = (Map.Entry)iterator2.next();
          System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
          System.out.println(mentry2.getValue());
       }

   }
}

The Output is :
key is: 49 & Value is: Ajeet
key is: 2 & Value is: Rahul
key is: 3 & Value is: Anuj
key is: 7 & Value is: Singh
key is: 12 & Value is: Chaitanya
Value at index 2 is: Rahul
Map key and values after removal:
Key is: 49 & Value is: Ajeet
Key is: 2 & Value is: Rahul
Key is: 7 & Value is: Singh
Key is: 12 & Value is: Chaitanya
HashMap in Java HashMap in Java Reviewed by 13thGhost on 9:03 PM Rating: 5

Comparator interface in Java

8:11 PM
Java Comparator interface is used to order the objects of a 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 sequences, i.e., we can sort the elements on the basis of any data member.

This interface is part of java.util package.



We can use Comparator interface in following situations.
  1. Sort the array or list of objects, but NOT in natural order.
  2. Sort the array or list of objects where we can not modify the object’s source code to implement Comparable interface.
  3. Sort same list or array of objects on different fields.
  4. Using group by sort on list or array of objects on different fields.



Employee.java


import java.time.LocalDate;
public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private String name;
    private LocalDate dob;
    //Getters and Setters
    @Override
    public String toString() {
      return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
    }
}


SortByName.java


import java.util.Comparator;
public class NameSorter implements Comparator<Employee>
{
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.getName().compareToIgnoreCase( e2.getName() );
    }
}



Its  use:
//import statements and pvsm
ArrayList<Employee> list = new ArrayList<>();     
list.add(new Employee(2, "Lokesh", LocalDate.now()));
list.add(new Employee(4, "Lokesh", LocalDate.now()));
list.add(new Employee(1, "Alex", LocalDate.now()));
list.add(new Employee(3, "Lokesh", LocalDate.now()));
list.add(new Employee(5, "Charles", LocalDate.now()));
Collections.sort(list, NameSorter);
System.out.println(list);

Output:

[
Employee [id=1, name=Alex, dob=2018-10-30],
Employee [id=2, name=Lokesh, dob=2018-10-30],
Employee [id=3, name=Lokesh, dob=2018-10-30],
Employee [id=4, name=Lokesh, dob=2018-10-30],
Employee [id=5, name=Charles, dob=2018-10-30],
]





Comparator interface in Java Comparator interface in Java Reviewed by 13thGhost on 8:11 PM Rating: 5

Recommended Posts

Powered by Blogger.