Category Archives: Java

Apache Tika Introduction


Apache Tika provides generic API for all document type content detection, analysis and content extraction from multiple file formats. Tika internally uses various documents parsers to extract metadata and structured text content from the various file types. For Example PDF, Spreadsheet, text file, images, etc.

Tika latest version 1.22 released on 1st Aug 2019 by Apache software foundation. Tika completely has written in Java and supports cross-platform.

Tika Version History

Year Development
2006 The idea of Tika was proposed in front of the Lucene Project Management Committee.
2006 The concept of Tika and its benefits in the Jackrabbit project was discussed.
2007 Tika entered into Apache.
2008 Both 0.1 and 0.2 Versions were released and Tika graduated from the incubator to the Lucene sub-project.
2009 This year Tika Versions 0.3, 0.4, and 0.5 were released.
2010 Both 0.6 and 0.7 Version was released and Tika graduated into the top-level Apache project.
2011 Tika 1.0 was released with book “Tika in Action” was also released in the same year.
2019 Tika 1.22 was release for additional CSV and HWP files type.

Why Tika?

As per https://filext.com/, there are around 25k to 50K file extensions (Structured and Non Structured) and these are growing day by day. To deal with so many types of format Tika provides universal Java API to support around 1400 file types that cover most common and popular formats.

Tika provides content extraction, metadata extraction, and language identification capabilities. Tika written in Java, still used by other languages also by calling restful services and CLI tools.

Where to use Apache Tika?

  • Search Engine: Tika uses the search engine to create search indexing for text in digital documents.
  • Document Analysis: Analysis of the documents like images, pdf to do analysis based on extract content.
  • Digital Asset Management (DAM): It’s used with an organization where maintains a library of documents, images, videos, ebooks, drawings to classify based on common features.
  • Content Analysis: Analyse the content from the web site and care of user’s interest like amazon shows movies, products based on the user’s visit. Machine learning based on content.

Features of Tika

  • Unified parser Interface: Tika internally uses best suitable parser libraries within a single parser interface. Due to this feature Tika, reduce the burden of developer from the burden of selecting the suitable parser library and use it according to the file type encountered.
  • Low memory usage: Tika consumes fewer memory resources, therefore, it is easily embedded with Java applications. We can also use Tika within the application which runs on platforms with fewer resources like mobile PDA.
  • Fast processing: Tika can quickly extract and detect content from applications.
  • Flexible metadata: Tika understands all type of metadata models which are used to define files.
  • Parser integration: Tika supports various parser libraries available for each document type in the same application.
  • MIME-type detection: Tika can extract and detect content from all MIME types.
  • Language detection: Tika includes language identification feature, therefore it can be used in documents based on language type in multilingual websites.
Advertisements

Java: Collection Framework Introduction


A collection is an object (also called container) to deal with a group of objects or elements as a single unit. These objects called as elements of Collection. Collections are used to perform operations like the store, retrieve, manipulate, communicate and aggregate.

A collection can have a different type of data. Based on data can decide the type collection data structure.

  • Homogeneous
  • Heterogeneous
  • Unique
  • Duplicate

See Also: 

Real-life Example of Collection

Here are some real-life examples of collections:

  • LinkedList: Your web page visiting history.
  • LinkedList: Train Coaches are connected to each other.
  • LinkedList: Our brain, when we remember something memory follow association because of one memory link to another.  This way recall in sequence.
  • Stack & LinkedList: Stack of Plates or Towel at the party. The top plate always picks first.
  • Queue & LinkedList: Queue/line of the person standing on the railway ticket window or for food in the mess.
  • A classroom is a collection of students.
  • A money bank is a collection of coins.
  • A school bag is a collection of books.

Why need collection?

There are four ways in Java to store values by JVM.

1:Variable approach

If we need to handle one, two or three or fewer numbers of values then the variable approach is a good bit if need to deal with so many objects like 5000 then variable approach have some drawback:

  • The limitation of a variable is that it can store only one value at a time.
  • Readability and reusability of the code will be down.
  • JVM will take more time for the execution.

2: Using a class object approach

Using a class object, we can store multiple “fixed” numbers of values of different types. For example, suppose we are creating a class named Person.

class Person{
String Name ;
int age ;
}

If you create the object of Person class like this

Person p1=new Person(); // So can you think how many values can store in this person object?

The answer is only two i.e name and age. but if you will want to store the third value, it will not possible.

3: Using an array object approach

Array improved the readability of code, by using a single variable for a huge number of values but there are various problems and limitations with the array.


Student[] st=new Student[5000];
  1. Array allow to store only homogeneous data type.
  2. Array is static and fixed in length size.
  3. Array concept help with standard data structure, but when need to deal with the sorting of objects, search for a specific item, etc.

4: Collection Object:

By using a collection object, we can store the same or different data without any size limitation.

What is a Framework in Java?

A framework is a set of several classes and interfaces which provide a readymade architecture.

What is a Collections Framework?

A collection framework provides a unified readymade architecture for storing and manipulating a group of objects. All collections frameworks contain the following:

  • Interfaces: Interfaces generally forms a hierarchy and allow collections object to be manipulated independently of the details of their representation.
  • Implementations: Provides a concrete representation by data structure and implementation of  collections interfaces.
  • Algorithms: The methods that perform useful operations, such as searching and sorting, on objects that implement collection interfaces.

Benefits of Collections Framework

Collections Framework provides lots of benefits:

  • Reduces programming effort: The Collections framework provides useful data structures and algorithms so that developers can concentrate on programming logic only.
  • Increases program performance and quality: Collections Framework provides high-quality data structures and algorithms implementations for good performance. These collections interface APIs are interchangeable so that easily tuned by switching collection implementations.
  • Allows interoperability among unrelated APIs: These data structures are interchangeable so that choose data structure and algorithms according to requirement.
  • Reduces effort to learn and to use new APIs: Most of APIs are common for collections framework because of the inherent Collection interface. only some APIs need to remember that are specific to the data structure.
  • Reduces effort to design new APIs: If new data structure and algorithm change create polymorphism of API and change the internal algorithm of APIs.
  • Fosters software reuse: If new data structure added use standard APIs so that easy to learn for developers.

References

Java : Collection Framework Hierarchy


All the classes and interfaces of the collection framework are in java.util package. This hierarchy for the collection framework specifically mentioned the class and interface with respect to each type.

Java Collection Framework Hierarchy

Iterable Interface

The Iterable interface is the root interface for all the collection classes because the Collection interface extends the Iterable interface, therefore, all the subclasses of Collection interface also implement the Iterable interface.

The iterable interface contains only one abstract method.

  • Iterator iterator(): It returns the iterator over the elements of type T.

Iterator Interface

The iterator interface provides the facility of iterating the elements in a forward direction only.
For more detail: Java: Iterator Interface methods and Examples

Collection Interface

The Collection interface builds the foundation for the Collection framework. The collection interface is one of the interfaces which is implemented by all the Collection framework classes. It provides common methods to implement by all the subclasses of collection interfaces.
For more detail: Java: Collection Interface methods and Examples

List Interface

List interface is the subtype/child interface of the Collection interface. It stores objects/elements in list type data structure in ordered form and also allowed duplicate values.

Implementation classes for List interface are ArrayList, LinkedList, Vector, and Stack.

For Example: To instantiate List Interface with Implementation classes follow:


List  list1= new ArrayList();  
List  list2 = new LinkedList();  
List  list3 = new Vector();  
List  list4 = new Stack();

For more detail: Java: List Interface methods and Examples

ArrayList Class

The ArrayList implements the List interface. It’s having the following features:

  • ArrayList uses a dynamic array data structure to store objects and elements.
  • ArrayList allows duplicate objects and elements.
  • ArrayList maintains the insertion order.
  • ArrayList is non-synchronized.
  • ArrayList elements/objects can be accessed randomly.

For more detail: Java: ArrayList Interface methods and Examples

LinkedList Class

LinkedList implements the List interface. It’s having the following features:

  • LinkedList uses a doubly linked list data structure to store elements.
  • LinkedList allowed storing the duplicate elements.
  • LinkedList maintains the insertion order.
  • LinkedList is not synchronized.
  • LinkedList manipulation is fast because no shifting is required.

For more detail: Java: LinkedList Class methods and Examples

Vector Class

Vector Class implements List interface. It’s having the following features:

  • Vector is similar to the ArrayList class.
  • Vector class uses data structure as a dynamic array to store the data elements.
  • Vector is synchronized.
  • Vector contains many methods that are not the part of Collection Framework.

For more detail: Java: Vector Class methods and Examples

Stack Class

The Stack is the subclass of the Vector class. It’s having the following features:

  • Stack implements the Vector data structure with the (LIFO)last-in-first-out.
  • Stack contains all of the methods of the Vector class.
  • Stack also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its features.

For more detail: Java: Stack Class methods and Examples

Queue Interface

Queue Interface extends the Collection interface. It’s having the following features:

  • Queue interface maintains the FIFO (first-in-first-out) order.
  • Queue can be defined as an ordered list that is used to hold the elements which are about to be processed.
  • Queue interface implemented by the various classes like PriorityQueue, Deque, and ArrayDeque.

Queue interface can be instantiated as:

Queue q1 = new PriorityQueue();  
Queue q2 = new ArrayDeque();  

For more detail: Java: Queue Interface methods and Examples

Here are detail about classes which implements Queue Interface.

PriorityQueue

The PriorityQueue class implements the Queue interface.

  • PriorityQueue holds the elements or objects which are to be processed by their priorities.
    PriorityQueue doesn’t allow null values to be stored in the queue.

For more detail: Java: PriorityQueue Class methods and Examples

Deque Interface

Deque stands for the double-ended queue which allows us to perform the operations at both ends.interface extends the Queue interface.

  • Deque extends the Queue interface.
  • Deque allows remove and add the elements from both the side.
Deque d = new ArrayDeque(); 

For more detail: Java: Deque Interface methods and Examples

ArrayDeque Class

ArrayDeque class implements the Deque interface.

  • ArrayDeque facilitates us to use the Deque.
  • ArrayDeque allows add or delete the elements from both the ends.
  • ArrayDeque is faster than ArrayList and has no capacity restrictions.

For more detail: Java: ArrayQueue Class methods and Examples

Set Interface

Set Interface extends Collection Interface and present in java.util package.

  • Set doesn’t allow duplicate elements or objects.
  • Set store elements in an unordered way.
  • Set allows only one null value.
  • Set is implemented by HashSet, LinkedHashSet, and TreeSet.

We can create an instantiation of Set as below:

Set s1 = new HashSet();  
Set s2 = new LinkedHashSet();  
Set s3 = new TreeSet();

For more detail: Java: Set Interface methods and Examples

HashSet

HashSet class implements Set Interface. It’s having the following features:

  • HashSet internally uses data structure like a hash table for storage.
  • HashSet uses hashing technique for storage of the elements.
  • HashSet always contains unique items.

For more detail: Java: HashSet Class methods and Examples

LinkedHashSet

LinkedHashSet class implements Set Interface. It’s having the following features:

  • LinkedHashSet store items in LinkedList.
  • LinkedHashSet store unique elements.
  • LinkedHashSet maintains the insertion order.
  • LinkedHashSet allows null elements.

For more detail: Java: LinkedHashSet Class methods and Examples

SortedSet Interface

SortedSet Interface extends Set Interface. It’s having the following features:

  • SortedSet provides a total ordering on its elements.
  • SortedSet elements are arranged in the increasing (ascending) order.
  • SortedSet provides additional methods that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

SortedSet set = new TreeSet();  

For more detail: Java: SortedSet Interface methods and Examples

TreeSet Class

TreeSet class implements the SortedSet interface.  It’s having the following features:

  • TreeSet uses a tree data structure for storage.
  • TreeSet also contains unique elements.
  • TreeSet elements access and retrieval time is quite fast.
  • TreeSet elements stored in ascending order.

For more detail: Java: TreeSet Class methods and Examples

Map Interface

In the collection framework, a map contains values on the basis of key and value pair. This pair is known as an entry. A map having the following features:

  • Map contains unique keys.
  • Map allows duplicate values.
  • Map is useful to search, update or delete elements on the basis of a key.
  • Map is the root interface in Map hierarchy for Collection Framework.
  • Map interface is extended by SortedMap and implemented by HashMap, LinkedHashMap.
  • Map implementation classes HashMap and LinkedHashMap allow null keys and values but TreeMap doesn’t allow null key and value.
  • Map can’t be traversed, for traversing needs to convert into the set using method keySet() or entrySet().

For more detail: Java: Map Class methods and Examples

HashMap Class

HashMap class implements Map interface. It’s having following features:

  • HashMap uses data structure as a Hash Table.
  • HashMap store values based on keys.
  • HashMap contains unique keys.
  • HashMap allows duplicate values.
  • HashMap doesn’t maintain order.
  • HashMap class allows only one null key and multiple null values.
  • HashMap is not synchronized.
  • HashMap initial default capacity is 16 elements with a load factor of 0.75.

For more detail:

LinkedHashMap Class

LinkedHashMap class extends the HashMap class. It’s having the following features:

  • LinkedHashMap contains values based on the key.
  • LinkedHashMap contains unique elements.
  • LinkedHashMap may have one null key and multiple null values.
  • LinkedHashMap is not synchronized.
  • LinkedHashMap maintains the insertion order.
  • LinkedHashMap default initial capacity is 16 with a load factor of 0.75.

For more detail: Java: LinkedHashMap Class methods and Examples

TreeMap Class

TreeMap class implements the SortedMap interface. it’s having the following features:

  • TreeMap uses data structure as red-black tree.
  • TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • TreeMap contains only unique elements.
  • TreeMap doesn’t allow null keys and values.
  • TreeMap is not synchronized.
  • TreeMap maintains an ascending order.

For more detail: Java: TreeMap Class methods and Examples

HashTable Class

Hashtable class implements a Map interface and extends Dictionary class to store key and values as pairs. It’s having the following features:

  • HashTable store values as an array of the list where each list is known as a bucket of the node(key and value pair).
  • HashTable class is in java.util package.
  • Hashtable contains unique elements.
  • Hashtable doesn’t allow null key or value.
  • Hashtable is synchronized.
  • Hashtable initial default capacity is 11 whereas the load factor is 0.75.

For more detail: Java: HashTable Class methods and Examples

See Also:

Java: Arrays vs Collections


In Java, Arrays and Collections both are to deal with a group of objects but there are lots of differences in terms of data structure or performing operations.

Here are some most common differences:

Difference between Arrays & Collections

Arrays Collections
Arrays is having fixed-length.. Collections are growable in nature i.e increase or decrease.
Arrays are not recommended in terms of memory concerns. Collections use different data structures and recommended to use with respect to memory.
Arrays are used with respect to performance. Collections are not recommended to use with respect to performance.
Arrays can store only homogeneous (same type) of data. Collections can hold both homogeneous and heterogeneous elements.
Arrays do not have a single API. Collections having big list of methods.
Arrays can work with primitives and object types. Collections can hold only objects but not with primitive. If you pass as primitive internally convert to object.
See Also: Array & Arrays Class Examples See Also: Collection Framework and Examples

Java: EnumSet Class


Java EnumSet class is the specialized Set implementation for use with enum types. It inherits AbstractSet class and implements the Set interface.

EnumSet class hierarchy

The hierarchy of EnumSet class is given in the figure given below.
EnumSet

EnumSet class declaration

Let’s see the declaration for java.util.EnumSet class.

public abstract class EnumSet<E extends Enum> extends AbstractSet implements Cloneable, Serializable  

Methods of Java EnumSet Class

Method Description
static <E extends Enum> EnumSet allOf(Class elementType) It is used to create an enum set containing all of the elements in the specified element type.
static <E extends Enum> EnumSet copyOf(Collection c) It is used to create an enum set initialized from the specified collection.
static <E extends Enum> EnumSet noneOf(Class elementType) It is used to create an empty enum set with the specified element type.
static <E extends Enum> EnumSet of(E e) It is used to create an enum set initially containing the specified element.
static <E extends Enum> EnumSet range(E from, E to) It is used to create an enum set initially containing the specified elements.
EnumSet clone() It is used to return a copy of this set.

Example :EnumSet

import java.util.*;
enum days {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumSetExample {
  public static void main(String[] args) {
    Set set = EnumSet.of(days.TUESDAY, days.WEDNESDAY);
    // Traversing elements
    Iterator iter = set.iterator();
    while (iter.hasNext())
      System.out.println(iter.next());
  }
}

Output :


TUESDAY
WEDNESDAY

Java EnumSet Example: allOf() and noneOf()

import java.util.*;
enum days {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumSetExample {
  public static void main(String[] args) {
    Set set1 = EnumSet.allOf(days.class);
      System.out.println("Week Days:"+set1);
      Set set2 = EnumSet.noneOf(days.class);
      System.out.println("Week Days:"+set2);
  }
}

Output :


Week Days:[SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
Week Days:[]

Java: ArrayList Vs Vector Class


java.util.ArrayList and java.util.Vector both implements List interface and maintains insertion order. It’s having many differences as below:

ArrayList vs Vector

ArrayList Vector
ArrayList is not synchronized. Vector is synchronized.
ArrayList increases 50% of the current array size if the number of elements exceeds its capacity. Vector increase 100% means doubles the array size when the total number of elements exceeds 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 a multithreading environment, it holds the other threads in the runnable or non-runnable state until the current thread releases the lock of the object.
ArrayList uses the Iterator interface to traverse the elements. A Vector can use the Iterator interface or Enumeration interface to traverse the elements.
See Also:ArrayList Class See Also:Java: Vector Class

ArrayList Example: traversing by the iterator

import java.util.*;
class ArrayListExample{
 public static void main(String args[]){    

  //creating arraylist of String
  List al=new ArrayList();
 //adding objecta in arraylist
  al.add("Saurabh");
  al.add("Mahesh");
  al.add("Jonny");
  al.add("Anil");
  //traverse elements using Iterator
  Iterator itr=al.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
 }
}

Output

Saurabh
Mahesh
Jonny
Anil

Vector Example: Traversing by Enumerator

import java.util.*;
class VectorExample{
 public static void main(String args[]){
  Vector v=new Vector();//creating vector
  v.add("Umrao");//method of Collection
  v.addElement("Isha");//method of Vector
  v.addElement("Kush");
  //traverse elements using Enumeration
  Enumeration e=v.elements();
  while(e.hasMoreElements()){
   System.out.println(e.nextElement());
  }
 }
}

Output

Umrao
Isha
Kush

Java : Non Primitive Data Types


Non-primitive data types are also called as reference types because they refer to objects.

Examples:  Strings, Arrays, Classes, Interface, etc. are non-primitive type.

Note: Non-primitive data type also called a User Defined Type when declaring an object with Classes and Interfaces names.

See Also: Java: Primitive Type Size and Default Value

Primitive Vs Non-Primitive

These are the main difference between primitive and non-primitive data types:

  • Primitive types are predefined in Java. While Non-primitive types are created by the programmer and is not defined by Java (except for String).
  • Non-primitive types also be used to call methods to perform certain operations, while primitive types cannot.
  • The primitive type has always had value, while non-primitive types can be null.
  • The primitive type starts with a lowercase letter, while non-primitive types start with an uppercase letter.
  • The primitive type size depends on the data type, while non-primitive types have all the same size.

Java: How HashSet Work?


A Set interface represents a group of unique elements arranged like an array. When we try to pass the duplicate element that is already available in the Set, then it will not store into the Set.

HashSet class

HashSet class implemnets Set interface and extends AbstractSet class.A HashSet class uses Hash Map internally for storing elements by using hashing technique.HashSet store unique elements and does not guarantee the order of elements.

Suppose, you want to create a HashSet to store a group of Strings, then create the HashSet object as:


HashSet hs=new HashSet();  

Where is the generic type parameter to represent HashSet allows only String type objects.

HashSet default constructor create instance of initial capacity 16 and capacity may increase automatically when number of elements reach to load factors. For uniqueness of object generate key as hashcode value. HashSet class doesn’t have method to retrieve object of Instance only way is retrieve object by iteration.

Note: To set your own capacity and loadfactor for HashSet. you can use below constructor.


HashSet hs=new HashSet(int capacity, float loadfactor);  

Here, loadfactor determines when number of elements in HashSet reach to that capacity limit increase capacity internally.the point where the capacity of HashSet would be increased internally.
The initial default capacity of HashSet is 16. The default load factor is 0.75. then 16*0.75=12 when no of elements reach to 12 increase capacity of HashSet to store more elements.

Example HashSet:

import java.util.HashSet;
import java.util.Iterator;

public class HashSetExample1 {
	public static void main(String[] args) {
      HashSet countries=new HashSet();
      countries.add("India");
      countries.add("Pakistan");
      countries.add("China");
      countries.add("Nepal");
      countries.add("Afganistan");
      countries.add("Canada");
      countries.add("Brazil");
      countries.add("Canada");
      countries.add("Brazil");
      countries.add("Thailand");
      countries.add("Malasia");
      countries.add("Russia");
      countries.add("London");
      countries.add("Switzerand");
      //Till that point threshold/capacity value is 12
      System.out.println("Countries Name:"+countries);
      System.out.println("Total Countries:"+countries.size());
      //Duplicate elements not allowed
      System.out.println("Add Dubai:"+countries.add("Dubai"));
      System.out.println("Add Dubai :"+countries.add("Dubai"));//return false when duplicate
      //After adding 13th element Threshold/capacity reach to 24 just double
      System.out.println("Countries Name:"+countries);
      System.out.println("Total Countries:"+countries.size());

     //iteration of Hashset elements
      System.out.println("\n\nPrint Countries by for each:");
      for(String country:countries)
      {
    	 System.out.println(country);
      }

      System.out.println("\n\nPrint Countries by for iterator:");
      Iterator it=countries.iterator();
      while(it.hasNext())
      {
    	  System.out.println(it.next());
      }

	}
}

Output


Countries Name:[Canada, Pakistan, China, Malasia, Brazil, London, Afganistan, Thailand, Nepal, Switzerand, India, Russia]
Total Countries:12
Add Dubai:true
Add Dubai :false
Countries Name:[Malasia, Thailand, Dubai, India, Russia, Canada, Pakistan, China, Brazil, London, Afganistan, Nepal, Switzerand]
Total Countries:13


Print Countries by for each:
Malasia
Thailand
Dubai
India
Russia
Canada
Pakistan
China
Brazil
London
Afganistan
Nepal
Switzerand


Print Countries by for iterator:
Malasia
Thailand
Dubai
India
Russia
Canada
Pakistan
China
Brazil
London
Afganistan
Nepal
Switzerand

In this example we have added duplicate values as Dubai in HashSet. When added it first time by add method return true because Dubai was not in HashSet. When added again return false because it was already added.

How HashSet work?

Now question comes how HashSet, add() method returns true and false. When you will open HashSet implementation of the add() method in Java APIs i.e. rt.jar, you will see the following code in it:

public class HashSet&ltE> extends AbstractSet
{
private transient HashMap map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public HashSet()
{
map = new HashMap();
}
public boolean add(E e)
{
return map.put(e, PRESENT)==null;
}
}

In this HashSet, add(object) methods use HashMap delegated to put(key, value) internally. Where key is the object added on HashSet and value is constant object as PRESENT in java.util.HashSet.

When we create HashSet Object, internally create an object of HashMap. As we know in HashMap each key is unique so, When we call add(E e) method this passing object set as key of HashMap and dummy object (new Object()) which is referred by Object reference PRESENT pass as value.

In HashMap put(key, value):

  • If the Key is unique and added then it will return null
    If the Key is duplicate, then map will return the old value of the key.

Let consider above example, when add country as countries.add(“Dubai”), java internally call HashMap put(“Dubai”,PRESENT) method to add element in map.

public boolean add(E e)
{
return map.put(e, PRESENT==null);
}

If the method map.put(key, value) returns null, then the method map.put(e, PRESENT)==null will return true internally, and the element added to the HashSet.
If the method map.put(key, value) returns the old value of the key, then the method map.put(e, PRESENT)==null will return false internally, and the element will not add to the HashSet.

As per given implementation when country “Dubai” added first time put() method return as null because “Dubai” not added before (unique) then add method return true. But when “Dubai” added again put() method will return old object and add method will return false on that case because of duplicate.

Retrieving Object from the HashSet

We use iterator() method of HashSet to retrieve objects. Internally HashSet iterator method called map.keySet().iterator() method.

public Iterator iterator()
{
return map.keySet().iterator();
}

Java: Collections Class Methods and Examples


java.util.Collections class extends Object class. Collections also called as utility class is used exclusively with static methods that operate on or return collections.

Points to remember

  • Collection class supports polymorphic to operate on collections.
  • Collection class throws a NullPointerException if passing objects are null.

Collections Declaration

public class Collections extends Object 

Collections Class Methods

Methods Descriptions
static boolean addAll() Adds all of the specified elements to the given collection.
static Queue asLifoQueue() Returns a view of a Deque as a LIFO(Last in first out) Queue.
static int binarySearch() Searches the list for the specified object and returns their index position in a sorted list.
static Collection checkedCollection() Returns a dynamically type safe view of the given collection.
static List checkedList() Returns a dynamically type safe view of the given list.
static Map checkedMap() Returns a dynamically type safe view of the given map.
static NavigableMap checkedNavigableMap() Returns a dynamically type safe view of the given navigable map.
static NavigableSet checkedNavigableSet() Returns a dynamically type safe view of the given navigable set.
static Queue checkedQueue() Returns a dynamically type safe view of the given queue.
static Set checkedSet() Returns a dynamically type safe view of the given set.
static SortedMap checkedSortedMap() Returns a dynamically type safe view of the given sorted map.
static SortedSet checkedSortedSet() Returns a dynamically type safe view of the given sorted set.
static void copy() Copy all the elements from one list into a another list.
static boolean disjoint() Returns true if the two specified collections have no common elements.
static Enumeration emptyEnumeration() Get an enumeration that has no elements.
static Iterator emptyIterator() Get an Iterator that has no elements.
static List emptyList() Get a List that has no elements.
static ListIterator emptyListIterator() Get a List Iterator that has no elements.
static Map emptyMap() Returns an empty map which is immutable.
static NavigableMap emptyNavigableMap() Returns an empty navigable map which is immutable.
static NavigableSet emptyNavigableSet() Get an empty navigable set which is immutable in nature.
static Set emptySet() Get the set that has no elements.
static SortedMap emptySortedMap() Returns an empty sorted map which is immutable.
static SortedSet emptySortedSet() Get the sorted set that has no elements.
static Enumeration enumeration() Get the enumeration over the specified collection.
static void fill() Replace all of the elements of the specified list with the specified elements.
static int frequency() Get the number of elements in the specified collection equal to the given object.
static int indexOfSubList() Get the starting index position of the first occurrence of the specified target list within the specified source list. It returns -1 if there is no elements found in the specified list.
static int lastIndexOfSubList() Get the starting index position of the last occurrence of the specified target list within the specified source list. It returns -1 if there is no elements found in the specified list.
static ArrayList list() Get an array list containing the elements returned by the specified enumeration in the order in which they are returned by the enumeration.
static > T max() Get the maximum value of the given collection, according to the natural ordering of its elements.
static > T min() Get the minimum value of the given collection, according to the natural ordering of its elements.
static List nCopies() Get an immutable list consisting of n copies of the specified object.
static Set newSetFromMap() Return a set backed by the specified map.
static boolean replaceAll() Replace all occurrences of one specified value in a list with the other specified value.
static void reverse() Reverse the order of the elements in the given list.
static Comparator reverseOrder() Get the comparator that imposes the reverse of the natural ordering of elements on a collection of objects which implement the Comparable interface.
static void rotate() Rotate the elements in the specified list by a given distance.
static void shuffle() Randomly reorders the specified list elements using a default randomness.
static Set singleton() Get an immutable set which contains only the specified object.
static List singletonList() Get an immutable list which contains only the specified object.
static Map singletonMap() Get an immutable map, mapping only the specified key to the specified value.
static >void sort() Sort the elements presents in the specified list of collection in ascending order.
static void swap() Swap the elements at the specified positions in the given list.
static Collection synchronizedCollection() Get a synchronized (thread-safe) collection backed by the given collection.
static List synchronizedList() Get a synchronized (thread-safe) collection backed by the given list.
static Map synchronizedMap() Get a synchronized (thread-safe) map backed by the given map.
static NavigableMap synchronizedNavigableMap() Get a synchronized (thread-safe) navigable map backed by the given navigable map.
static NavigableSet synchronizedNavigableSet() Get a synchronized (thread-safe) navigable set backed by the given navigable set.
static Set synchronizedSet() Get a synchronized (thread-safe) set backed by the given set.
static SortedMap synchronizedSortedMap() Get a synchronized (thread-safe) sorted map backed by the given sorted map.
static SortedSet synchronizedSortedSet() Get a synchronized (thread-safe) sorted set backed by the given sorted set.
static Collection unmodifiableCollection() Get an unmodifiable view of the given collection.
static List unmodifiableList() Get an unmodifiable view of the given list.
static Map unmodifiableMap() Get an unmodifiable view of the given map.
static NavigableMap unmodifiableNavigableMap() Get an unmodifiable view of the given navigable map.
static NavigableSet unmodifiableNavigableSet() Get an unmodifiable view of the given navigable set.
static Set unmodifiableSet() Get an unmodifiable view of the given set.
static SortedMap unmodifiableSortedMap() Get an unmodifiable view of the given sorted map.
static SortedSet unmodifiableSortedSet() Get an unmodifiable view of the given sorted set.

Collections Example : Add elements in list

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsExample1 {

	public static void main(String[] args) {
		 List list = new ArrayList();
	        list.add("C");
	        list.add("C++");
	        list.add("Python");
	        list.add("Lisp");
	        list.add("Java Script");
	        System.out.println("Initial collection value:"+list);
	        //add some more element in collection
	        Collections.addAll(list, "Servlet","JSP");
	        System.out.println("After adding elements collection value:"+list);
	        String[] strArr = {"C#", "Closure",".Net"};
	        //add some more elements
	        Collections.addAll(list, strArr);
	        System.out.println("After adding array collection value:"+list);
	}

}

Output :


Initial collection value:[C, C++, Python, Lisp, Java Script]
After adding elements collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP]
After adding array collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP, C#, Closure, .Net]

Collections Example :max()

import java.util.*;

public class CollectionsExample2 {
	public static void main(String a[]) {
		List list = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Max element from the collection: " + Collections.max(list));
	}
}

Output :


Max element from the collection: 90

Output:

Collections Example :min()

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsExample3 {
	public static void main(String a[]) {
		Listlist = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Min element from the collection: " + Collections.min(list));
	}
}

Output :


Min element from the collection: 2

Java: EnumMap Class Methods and Examples


java.util.EnumMap class inherits Enum and AbstractMap classes. It’s special type of Map for enum keys.

EnumMap Declaration

public class EnumMap,V> extends AbstractMap implements Serializable, Cloneable  
  • K: Represent as key in Map of type Enum
  • V:Represent as value with respect to K.

Constructors of EnumMap

Constructor Description
EnumMap(Class keyType) Create an empty enum map with the given key type.
EnumMap(EnumMap m) Create an enum map with the same key type as the given enum map.
EnumMap(Map m) Create an enum map initialized from the given map.

Methods of EnumMap

Method Description
clear() Clear all the mapping from the map.
clone() Copy the mapped value of one map to another map as sallow cloning.
containsKey() Check whether a given key is present in this map or not.
containsValue() Check whether one or more key is associated with a specified value or not.
entrySet() Create a set of keys/elements contained in the EnumMap.
equals() Compare two maps keys for equality.
get() Get the mapped value with respect to given key.
hashCode() Get the hashcode value of the EnumMap.
keySet() Return the set of the keys contained in the map.
size() Get count of the size of the EnumMap.
Values() Create a collection view of the values contained in this map.
put() Associate the given value with the specified key in this EnumMap.
putAll() Copy all the mappings from one EnumMap to another new EnumMap.
remove() Remove the mapping for the given key from EnumMap if the given key exist in EnumMap.

EnumMap Example : insert elements and traverse

import java.util.*;

public class EnumMapExample1 {
	// create an enum for keys
	public enum Days {
		Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
	};

	public static void main(String[] args) {

		// Insert elements in map
		EnumMap map = new EnumMap(Days.class);
		map.put(Days.Monday, "1");
		map.put(Days.Wednesday, "3");
		map.put(Days.Friday, "5");
		map.put(Days.Sunday, "7");
		// traverse map
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Monday 1
Wednesday 3
Friday 5
Sunday 7

EnumMap Example: insert objects and traverse

import java.util.EnumMap;
import java.util.Map;
class Magzine {
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}    

public class EnumMapWithObjectsExample {
	// Creating enum of keys
	public enum Key {
		One, Two, Three
	};

	public static void main(String[]args){
EnumMap map = new EnumMap(Key.class);
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzines to Map
		map.put(Key.One, m1);
		map.put(Key.Two, m2);
		map.put(Key.Three, m3);
		// Traversing EnumMap
		for (Map.Entry entry : map.entrySet()) {
			Magzine m = entry.getValue();
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


21 The Sun Sy Sunfranchy The Sun Company 8
22 Glimmer Trains Unknown Glimmer Train Press 4
23 Crazy horse Brett Lot College of Charleston 6

Java: Map Interface Methods and Examples


In the collection framework, a map contains values on the basis of key and value pairs. This pair is known as an entry.

Points to Remember

  • Map contains unique keys.
  • Map allows duplicate values.
  • Map is useful to search, update or delete elements on the basis of a key.
  • Map is the root interface in the Map hierarchy for Collection Framework.
  • Map interface is extended by SortedMap and implemented by HashMap, LinkedHashMap.
  • Map implementation classes HashMap and LinkedHashMap allow null keys and values but TreeMap doesn’t allow null key and value.
  • Map can’t be traversed, for transversing needs to convert into the set using method keySet() or entrySet().

See Also:

Methods of Map Interface

Method Description
put(Object key, Object value) This method used to insert an entry on the map.
void putAll(Map map) This method inserts the specified map in the map.
V putIfAbsent(K key, V value) This method inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key) This method used to delete an entry for the specified key.
boolean remove(Object key, Object value) This method removes the specified values with the associated specified keys from the map.
Set keySet() It returns the Set view containing all the keys.
Set<Map.Entry> entrySet() It returns the Set view containing all the keys and values.
void clear() It is used to reset the map.
V compute(K key, BiFunction remappingFunction) This method computes a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) This method computes its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) This method computes a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value)  if some value equal to the value exists within the map then return true, else return false.
boolean containsKey(Object key) if some key equal to the key exists within the map return true, else return false.
boolean equals(Object o) It is used to compare the specified Object values with the Map.
void forEach(BiConsumer action) Mentioned action will perform for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key) Returns the object that contains the value with respect to the key.
V getOrDefault(Object key, V defaultValue) Returns the value with respect to key is mapped, or defaultValue if the map contains no mapping for the key.
int hashCode() It returns the hash code value for the Map
boolean isEmpty() Check if the map not having any element Returns true if the map is empty or false.
V merge(K key, V value, BiFunction remappingFunction) If the given key is not mapped with a value or with null, associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value with respect to the key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value with respect to the key.
void replaceAll(BiFunction function) It replaces each entry’s value with the given function on that entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection of the values contained in the map.
int size() Returns the number of elements in the map.

Map.Entry Interface

Entry is the subinterface of Map. So we will be accessed by Map.Entry name. It returns a collection-view of the map, whose elements are of this class. It provides methods to get key and value.

Methods of Map.Entry interface

Method Description
K getKey() It is used to obtain a key.
V getValue() It is used to obtain value.
int hashCode() It is used to obtain hashCode.
V setValue(V value) It is used to replace the value corresponding to this entry with the specified value.
boolean equals(Object o) It is used to compare the specified object with the other existing objects.
static ,V> Comparator<Map.Entry> comparingByKey() It returns a comparator that compare the objects in natural order on key.
static Comparator<Map.Entry> comparingByKey(Comparator cmp) It returns a comparator that compare the objects by key using the given Comparator.
static <K,V extends Comparable> Comparator<Map.Entry> comparingByValue() It returns a comparator that compare the objects in natural order on value.
static Comparator<Map.Entry> comparingByValue(Comparator cmp) It returns a comparator that compare the objects by value using the given Comparator.

Map Example: Legacy Style without Generics

import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
    Map map=new HashMap();
    //Adding elements to map
    map.put(1,"Anuj");
    map.put(5,"Raghav");
    map.put(2,"Jitendra");
    map.put(3,"Anuj");
    //Traversing Map Entry
	//Converting to Set so that we can traverse
    Set set=map.entrySet();
    Iterator itr=set.iterator();
    while(itr.hasNext()){
        //Type cast to Map.Entry so that we can get key and value separately
        Map.Entry entry=(Map.Entry)itr.next();
        System.out.println(entry.getKey()+" "+entry.getValue());
    }
}
}

Output :


1 Anuj
2 Jitendra
5 Raghav
3 Anuj

Map Example: With Generics

import java.util.*;
class MapExample2{
 public static void main(String args[]){
  Map map=new HashMap();
  map.put(20,"Anuj");
  map.put(21,"Virendra");
  map.put(22,"Raghav");
  //Elements can traverse in any order
  for(Map.Entry m:map.entrySet()){
   System.out.println(m.getKey()+" "+m.getValue());
  }
 }
}

Output :


22 Raghav
20 Anuj
21 Virendra

Map Example: comparingByKey() in ascending and descending order

import java.util.*;
class MapExample3{
 public static void main(String args[]){
Map map=new HashMap();
      map.put(20,"Anuj");
      map.put(21,"Virendra");
      map.put(22,"Raghav"); 

	  //ascending order
      //Returns a Set view of the mappings contained in this map
      map.entrySet()
      //Returns a sequential Stream with this collection as its source
      .stream()
      //Sorted according to the provided Comparator
      .sorted(Map.Entry.comparingByKey())
      //Performs an action for each element of this stream
      .forEach(System.out::println);  

	  //descending oder
	  //Returns a Set view of the mappings contained in this map
      map.entrySet()
      //Returns a sequential Stream with this collection as its source
      .stream()
      //Sorted according to the provided Comparator
      .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
      //Performs an action for each element of this stream
      .forEach(System.out::println);
 }
}

Output :


20=Anuj
21=Virendra
22=Raghav

Map Example: comparingByValue() in ascending and descending Order

import java.uti
class MapExample5{
 public static void main(String args[]){
Map map=new HashMap();
      map.put(20,"Anuj");
      map.put(21,"Virendra");
      map.put(22,"Raghav");  

	  //ascending order 

      //Returns a Set view of the mappings contained in this map
      map.entrySet()
      //Returns a sequential Stream with this collection as its source
      .stream()
      //Sorted according to the provided Comparator
      .sorted(Map.Entry.comparingByValue())
      //Performs an action for each element of this stream
      .forEach(System.out::println);  

	  //descending order

	  //Returns a Set view of the mappings contained in this map
     map.entrySet()
     //Returns a sequential Stream with this collection as its source
     .stream()
     //Sorted according to the provided Comparator
     .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
     //Performs an action for each element of this stream
     .forEach(System.out::println);
 }
}

Output :


20=Anuj
22=Raghav
21=Virendra

21=Virendra
22=Raghav
20=Anuj

Java: TreeMap Class Methods and Examples


Java.util.TreeMap implements SortedMap interface and provides an efficient way to storing key-value pairs in sorted order. TreeMap implements the NavigableMap interface and extends AbstractMap class.

Points to Remember

  • TreeMap uses data structure as a red-black tree.
  • TreeMap contains values based on the key.
  • TreeMap contains only unique elements.
  • TreeMap cannot have a null key but can have multiple null values.
  • TreeMap is not synchronized.
  • TreeMap maintains an ascending order.

TreeMap Declaration

public class TreeMap extends AbstractMap implements NavigableMap, Serializable,Cloneable
  • K: Represent as key in Map
  • V: Represent as value with respect to K.

See Also:

What is the difference between HashMap and TreeMap?

HashMap TreeMap
HashMap can contain one null key. TreeMap cannot contain any null key.
HashMap maintains no order. TreeMap maintains an ascending order.

Constructors of TreeMap

Constructor Description
TreeMap() This constructor uses to create an empty treemap that will be sorted using the natural order of its key.
TreeMap(Comparator comparator) This constructor uses to an empty tree-based map that will be sorted using the comparator comp.
TreeMap(Map m) It is used to initialize a treemap with the entries from m, which will be sorted using the natural order of the keys.
TreeMap(SortedMap m) This constructor uses to initialize a treemap with the entries from the SortedMap sm, which will be sorted in the same order as sm.

Methods of TreeMap

Method Description
Map.Entry ceilingEntry(K key) It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key.
K ceilingKey(K key) It returns the least key, greater than the specified key or null if there is no such key.
void clear() It removes all the key-value pairs from a map.
Object clone() It returns a shallow copy of TreeMap instance.
Comparator comparator() It returns the comparator that arranges the key in order, or null if the map uses the natural ordering.
NavigableSet descendingKeySet() This method returns a reverse order NavigableSet view of the keys contained in the map.
NavigableMap descendingMap() It returns the specified key-value pairs in descending order.
Map.Entry firstEntry() It returns the key-value pair having the least key.
Map.Entry floorEntry(K key) It returns the greatest key, less than or equal to the specified key, or null if there is no such key.
void forEach(BiConsumer action) It performs the mention action for each entry in the map until all entries processed or the action throws an exception.
SortedMap headMap(K toKey) It returns the key-value pairs whose keys are strictly less than toKey.
NavigableMap headMap(K toKey, boolean inclusive) It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey.
Map.Entry higherEntry(K key) It returns the least key strictly greater than the given key, or null if there is no such key.
K higherKey(K key) It is used to return true if map contains a mapping for the specified key.
Set keySet() It returns the set of keys exist in the map.
Map.Entry lastEntry() It returns the key-value pair having the greatest key, or null if there is no such key.
Map.Entry lowerEntry(K key) It returns a key and value mapping associated with the greatest key less than the given key or null if there is no such key.
K lowerKey(K key) It returns from map  the greatest key strictly less than the given key, or null if there is no such key.
NavigableSet navigableKeySet() It returns a NavigableSet view of the keys contains in this map.
Map.Entry pollFirstEntry() It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
Map.Entry pollLastEntry() It removes and returns a key and value mapping associated with the greatest key in this map, or null if the map is empty.
V put(K key, V value) It inserts the specified value with respect to key in the map.
void putAll(Map map) It is used to copy all the key-value pair from one map to another map.
V replace(K key, V value) It replaces the value with respect to key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value with respect to key.
void replaceAll(BiFunction function) It replaces each entry’s value with the result of invoking the mentioned function on all entries have been processed or the function throw an exception.
NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) It returns key and value pairs whose keys match with in range fromKey to toKey.
SortedMap subMap(K fromKey, K toKey) It returns key and value pairs whose keys range match fromKey, inclusive, to toKey, exclusive.
SortedMap tailMap(K fromKey) It returns key and value pairs whose keys are greater than or equal to fromKey.
NavigableMap tailMap(K fromKey, boolean inclusive) It returns key and value pairs whose keys are greater than (o equal to, if inclusive is true) fromKey.
boolean containsKey(Object key) It returns true if the map contains a mapping with respect to  key.
boolean containsValue(Object value) It returns true if the map find one or more keys to the specified value.
K firstKey() It is used to return the first find lowest key currently in this sorted map.
V get(Object key) It is used to return the value to which the map maps the specified key.
K lastKey() It is used to return the last highest key currently in the sorted map.
V remove(Object key) It removes the key and value pair of the specified key from the map.
Set entrySet() It returns a set of the mappings contained in the map.
int size() It returns the number of key-value pairs that exists in the hashtable.
Collection values() It returns a collection  of values contained in the map.

TreeMap Example : insert and traverse elements

import java.util.Map;
import java.util.TreeMap;

class TreeMapExample1{
	 public static void main(String args[]){
	   TreeMap&lt;Integer,String&gt; map=new TreeMap&lt;Integer,String&gt;();
	      map.put(20,"Anuj");
	      map.put(22,"Ravi");
	      map.put(21,"Virendra");
	      map.put(23,"Raghav");    

	      for(Map.Entry m:map.entrySet()){
	       System.out.println(m.getKey()+" "+m.getValue());
	      }
	 }
	}

Output :


20 Anuj
21 Virendra
22 Ravi
23 Raghav

TreeMap Example : remove() elements

import java.util.*;

public class TreeMapExample2 {
	public static void main(String args[]) {
		TreeMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		System.out.println("\nBefore invoking remove() method");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		map.remove(22);
		System.out.println("\nAfter invoking remove() method");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :



Before invoking remove() method
20 Anuj
21 Virendra
22 Ravi
23 Raghav

After invoking remove() method
20 Anuj
21 Virendra
23 Raghav

Treemap Example : with NavigableMap

import java.util.*;
import java.util.NavigableMap;
import java.util.TreeMap;

class TreeMapExample3 {
	public static void main(String args[]) {
		NavigableMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");

		// Maintains descending order
		System.out.println("\ndescendingMap: " + map.descendingMap());
		// Returns key-value pairs whose keys are less than or equal to the
		// specified key.
		System.out.println("\nheadMap: " + map.headMap(22, true));
		// Returns key-value pairs whose keys are greater than or equal to the
		// specified key.
		System.out.println("\ntailMap: " + map.tailMap(22, true));
		// Returns key-value pairs exists in between the specified key.
		System.out.println("\nsubMap: " + map.subMap(20, false, 22, true));
	}
}

Output :


descendingMap: {23=Raghav, 22=Ravi, 21=Virendra, 20=Anuj}

headMap: {20=Anuj, 21=Virendra, 22=Ravi}

tailMap: {22=Ravi, 23=Raghav}

subMap: {21=Virendra, 22=Ravi}

TreeMap Example : SortedMap()

import java.util.*;
import java.util.SortedMap;
import java.util.TreeMap;

class TreeMapExample4 {
	public static void main(String args[]) {
		SortedMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		// Returns key-value pairs whose keys are less than the specified key.
		System.out.println("\nheadMap: " + map.headMap(22));
		// Returns key-value pairs whose keys are greater than or equal to the
		// specified key.
		System.out.println("\ntailMap: " + map.tailMap(22));
		// Returns key-value pairs exists in between the specified key.
		System.out.println("\nsubMap: " + map.subMap(20, 22));
	}
}

Output :


headMap: {20=Anuj, 21=Virendra}

tailMap: {22=Ravi, 23=Raghav}

subMap: {20=Anuj, 21=Virendra}

TreeMap Example : with objects

import java.util.*;
class Magzine{
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}
import java.util.Map;
import java.util.TreeMap;

public class HashtableExampleWithObjects {
	public static void main(String[] args) {
		// Creating map of Magzine
		Map&lt;Integer, Magzine&gt; table = new TreeMap&lt;Integer, Magzine&gt;();
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzine to map
		table.put(1, m1);
		table.put(2, m2);
		table.put(3, m3);
		// Traversing map
		for (Map.Entry&lt;Integer, Magzine&gt; entry : table.entrySet()) {
			int key = entry.getKey();
			Magzine m = entry.getValue();
			System.out.println("\nId: "+key + " Details:");
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

 

Java: Collections Utility Class Methods and Examples


java.util.Collections class inherits Object class. The Collections utility class is used exclusively with static methods that operate on or return collections.

Points to remember

  • Collections class supports the polymorphic to operate on collections.
  • Collections class throws a NullPointerException if passing objects are null.

See Also:

Collections Declaration

public class Collections extends Object 

Collections Utility Class Methods

Method Descriptions
static boolean addAll() It is used to adds all of the specified element to the specified collection.
static Queue asLifoQueue() It returns a view of a Deque as a Last-in-first-out (LIFO) Queue.
static int binarySearch() It searches the list for the specified object and returns its position in a sorted list.
static Collection checkedCollection() It is used to returns a dynamically typesafe view of the specified collection.
static List checkedList() It is used to returns a dynamically typesafe view of the specified list.
static Map checkedMap() It is used to returns a dynamically typesafe view of the specified map.
static NavigableMap checkedNavigableMap() It is used to returns a dynamically typesafe view of the specified navigable map.
static NavigableSet checkedNavigableSet() It is used to returns a dynamically typesafe view of the specified navigable set.
static Queue checkedQueue() It is used to returns a dynamically typesafe view of the specified queue.
static Set checkedSet() It is used to returns a dynamically typesafe view of the specified set.
static SortedMap checkedSortedMap() It is used to returns a dynamically typesafe view of the specified sorted map.
static SortedSet checkedSortedSet() It is used to returns a dynamically typesafe view of the specified sorted set.
static void copy() It is used to copy all the elements from one list into another list.
static boolean disjoint() It returns true if the two specified collections have no elements in common.
static Enumeration emptyEnumeration() It is used to get an enumeration that has no elements.
static Iterator emptyIterator() It is used to get an Iterator that has no elements.
static List emptyList() It is used to get a List that has no elements.
static ListIterator emptyListIterator() It is used to get a List Iterator that has no elements.
static Map emptyMap() It returns an empty map that is immutable.
static NavigableMap emptyNavigableMap() It returns an empty navigable map that is immutable.
static NavigableSet emptyNavigableSet() It is used to get an empty navigable set which is immutable in nature.
static Set emptySet() It is used to get the set that has no elements.
static SortedMap emptySortedMap() It returns an empty sorted map which is immutable.
static SortedSet emptySortedSet() It is used to get the sorted set that has no elements.
static Enumeration enumeration() It is used to get the enumeration over the specified collection.
static void fill() It is used to replace all of the elements of the specified list with the specified elements.
static int frequency() It is used to get the number of elements in the specified collection equal to the specified object.
static int indexOfSubList() It is used to get the starting position of the first occurrence of the specified target list within the specified source list. It returns -1 if there is no such occurrence in the specified list.
static int lastIndexOfSubList() It is used to get the starting position of the last occurrence of the specified target list within the specified source list. It returns -1 if there is no such occurrence in the specified list.
static ArrayList list() It is used to get an array list containing the elements returned by the specified enumeration in the order in which they are returned by the enumeration.
static > T max() It is used to get the maximum value of the given collection, according to the natural ordering of its elements.
static > T min() It is used to get the minimum value of the given collection, according to the natural ordering of its elements.
static List nCopies() It is used to get an immutable list consisting of n copies of the specified object.
static Set newSetFromMap() It is used to return a set backed by the specified map.
static boolean replaceAll() It is used to replace all occurrences of one specified value in a list with the other specified value.
static void reverse() It is used to reverse the order of the elements in the specified list.
static Comparator reverseOrder() It is used to get the comparator that imposes the reverse of the natural ordering on a collection of objects which internally implement the Comparable interface.
static void rotate() It is used to rotate the elements in the specified list by a given distance.
static void shuffle() It is used to randomly reorders the specified list elements using default randomness.
static Set singleton() It is used to get an immutable set that contains only the specified object.
static List singletonList() It is used to get an immutable list that contains only the specified object.
static Map singletonMap() Use to get an immutable map, mapping only the specified key to the specified value.
static >void sort() It is used to sort the elements present in the specified list of the collection in ascending order.
static void swap() It is used to swap the elements at the specified positions in the specified list.
static Collection synchronizedCollection() It is used to get a synchronized (thread-safe) collection backed by the specified collection.
static List synchronizedList() It is used to get a synchronized (thread-safe) collection backed by the specified list.
static Map synchronizedMap() It is used to get a synchronized (thread-safe) map backed by the specified map.
static NavigableMap synchronizedNavigableMap() It is used to get a synchronized (thread-safe) navigable map backed by the specified navigable map.
static NavigableSet synchronizedNavigableSet() It is used to get a synchronized (thread-safe) navigable set backed by the specified navigable set.
static Set synchronizedSet() It is used to get a synchronized (thread-safe) set backed by the specified set.
static SortedMap synchronizedSortedMap() It is used to get a synchronized (thread-safe) sorted map backed by the specified sorted map.
static SortedSet synchronizedSortedSet() It is used to get a synchronized (thread-safe) sorted set backed by the specified sorted set.
static Collection unmodifiableCollection() It is used to get an unmodifiable view of the specified collection.
static List unmodifiableList() It is used to get an unmodifiable view of the specified list.
static Map unmodifiableMap() It is used to get an unmodifiable view of the specified map.
static NavigableMap unmodifiableNavigableMap() It is used to get an unmodifiable view of the specified navigable map.
static NavigableSet unmodifiableNavigableSet() It is used to get an unmodifiable view of the specified navigable set.
static Set unmodifiableSet() It is used to get an unmodifiable view of the specified set.
static SortedMap unmodifiableSortedMap() It is used to get an unmodifiable view of the specified sorted map.
static SortedSet unmodifiableSortedSet() It is used to get an unmodifiable view of the specified sorted set.

See Also:

Collections Example : Add elements in list

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsExample1 {

	public static void main(String[] args) {
		 List list = new ArrayList();
	        list.add("C");
	        list.add("C++");
	        list.add("Python");
	        list.add("Lisp");
	        list.add("Java Script");
	        System.out.println("Initial collection value:"+list);
	        //add some more element in collection
	        Collections.addAll(list, "Servlet","JSP");
	        System.out.println("After adding elements collection value:"+list);
	        String[] strArr = {"C#", "Closure",".Net"};
	        //add some more elements
	        Collections.addAll(list, strArr);
	        System.out.println("After adding array collection value:"+list);
	}

}

Output :


Initial collection value:[C, C++, Python, Lisp, Java Script]
After adding elements collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP]
After adding array collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP, C#, Closure, .Net]

Collections Example :max()

import java.util.*;

public class CollectionsExample2 {
	public static void main(String a[]) {
		List list = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Max element from the collection: " + Collections.max(list));
	}
}

Output :


Max element from the collection: 90

Output:

Collections Example :min()

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsExample3 {
	public static void main(String a[]) {
		List list = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Min element from the collection: " + Collections.min(list));
	}
}

Output :


Min element from the collection: 2

Java: LinkedHashMap Class Methods and Examples


LinkedHashMap class extends the HashMap class and implements Map Interface to store values in key and value pairs.

Points to Remember

  • LinkedHashMap class is in java.util package.
  • LinkedHashMap uses data structure Hashtable and LinkedList implementation of the Map interface.
  • LinkedHashMap contains values based on the key.
  • LinkedHashMap contains unique elements.
  • LinkedHashMap class may have one null key and multiple null values.
  • LinkedHashMap is not synchronized.
  • LinkedHashMap maintains the insertion order.
  • LinkedHashMap initial default capacity is 16 with a load factor of 0.75.

LinkedHashMap Declaration


public class LinkedHashMap extends HashMap implements Map  
  • K: Here K represent Key of Map
  • V: Here V represents value in the Map with respect to K.

Constructors of LinkedHashMap class

Constructor Description
LinkedHashMap() This is the default LinkedHashMap constructor.
LinkedHashMap(int capacity)  Use to initialize a LinkedHashMap with the given capacity.
LinkedHashMap(int capacity, float loadFactor) Use to initialize both the capacity and the load factor.
LinkedHashMap(int capacity, float loadFactor, boolean accessOrder) Use to initialize both the capacity and the load factor with specified ordering mode.
LinkedHashMap(Map m) Use to initialize the LinkedHashMap with the elements from the given Map class m.

Methods of LinkedHashMap class

Method Description
V get(Object key) It returns the value object map to the specified key.
void clear() It removes all the key-value pairs from a map.
boolean containsValue(Object value) It returns true if one or more keys to the specified value.
Set<Map.Entry> entrySet() It returns a Set view of the mappings contained in the map.
void forEach(BiConsumer action) It performs the given action on each entry in the map until all entries have been processed or any action throws an exception.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped or defaultValue if this map contains no mapping for the key.
Set keySet() It returns a Set view of the keys contained in the map
protected boolean removeEldestEntry(Map.Entry eldest) It returns true on removing its eldest entry.
void replaceAll(BiFunction function) It replaces each entry’s value in map with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection values() It returns a Collection view of the values contained in this map.

LinkedHashMap Example : insert items and traverse

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample4 {

	public static void main(String args[]) {

		Map hm = new LinkedHashMap();

		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");

		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}

}

Output :


20 Anuj
21 Virendra
22 Raghav

LinkedHashMap Example : Key-Value pair

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample1 {

	public static void main(String args[]) {
		Map map = new LinkedHashMap();
		map.put(20, "Anuj");
		map.put(21, "Virendra");
		map.put(22, "Raghav");
		// Fetching key from LinkedHashMap
		System.out.println("Keys: " + map.keySet());
		// Fetching value from LinkedHashMap
		System.out.println("Values: " + map.values());
		// Fetching key-value pair from LinkedHashMap
		System.out.println("Key-Value pairs: " + map.entrySet());
	}

}

Output :


Keys: [20, 21, 22]
Values: [Anuj, Virendra, Raghav]
Key-Value pairs: [20=Anuj, 21=Virendra, 22=Raghav]

LinkedHashMap Example : remove()

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample2 {

	public static void main(String args[]) {
		Map map = new LinkedHashMap();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		System.out.println("Before remove: " + map);
		// Remove value for key 22
		map.remove(22);
		System.out.println("After remove: " + map);
	}

}

Output :


Before remove: {20=Anuj, 22=Ravi, 21=Virendra, 23=Raghav}
After remove: {20=Anuj, 21=Virendra, 23=Raghav}

LinkedHashMap Example : getOrDefault()

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample3 {

	public static void main(String args[]) {
		Map map = new LinkedHashMap();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		// Here it will retrieve values for key 21 and 25
		// if values not find out in HashTable then return default value
		System.out.println(map.getOrDefault(21, "Not Found"));
		System.out.println(map.getOrDefault(25, "Not Found"));
	}
}

Output :


Virendra
Not Found

LinkedHashMap Example : with objects

import java.util.*;
class Magzine{
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}
public class LinkedHashMapExampleWithObjects {
	public static void main(String[] args) {
		// Creating map of Magzine
		Map map = new LinkedHashMap();
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzine to map
		map.put(1, m1);
		map.put(2, m2);
		map.put(3, m3);
		// Traversing map
		for (Map.Entry entry : map.entrySet()) {
			int key = entry.getKey();
			Magzine m = entry.getValue();
			System.out.println("\nId: "+key + " Details:");
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

Java: HashTable Class Methods and Examples


The hashtable class implements a Map interface and extends Dictionary Class to store key and values as pairs.

Hashtable is an array of the list where each list is known as a bucket of the node (key and value pair). The position of the node is identified by calling the hashcode() method on key.

Points to remember

  • Hashtable class is in java.util package.
  • Hashtable contains unique elements.
  • Hashtable doesn’t allow null key or value.
  • Hashtable is synchronized.
  • Hashtable initial default capacity is 11 whereas the load factor is 0.75.

See Also:

Hashtable class declaration

Let’s see the declaration for java.util.Hashtable class.


public class Hashtable extends Dictionary implements Map, Cloneable, Serializable  
  • K: Represent as key in Map
  • V: Represent as value with respect to K.

Constructors of java.util.Hashtable class

Constructor Description
Hashtable() It creates an empty hashtable having the initial default capacity and load factor.
Hashtable(int capacity) It accepts an integer parameter and creates a hash table that contains a specified initial capacity.
Hashtable(int capacity, float loadFactor) It is used to create a hash table having the specified initial capacity and loadFactor.
Hashtable(Map t) It creates a new hash table with the same mappings as the given Map.

Methods of java.util.Hashtable class

Method Description
void clear() Use to reset the hash table.
Object clone() It returns a shallow copy of the Hashtable.
V compute(K key, BiFunction remappingFunction) It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
Enumeration elements() It returns an enumeration of the values in the hash table.
Set<Map.Entry> entrySet() It returns a set view of the mappings contained in the map.
boolean equals(Object o) Use to compare the specified Object with the Map.
void forEach(BiConsumer action) It performs the action for each entry in the map until all entries have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue) This method returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
int hashCode() It returns the hash code value for the Map
Enumeration keys() This method returns an enumeration of the keys in the hashtable.
Set keySet() It returns a Set view of the keys contained in the map.
V merge(K key, V value, BiFunction remappingFunction) If the specified key is not found in hashTable then associates it with the given non-null value.
V put(K key, V value) It inserts the specified value with the specified key in the hash table.
void putAll(Map t)) It is used to copy all the key-value pairs from the map to the hashtable.
V putIfAbsent(K key, V value) If the specified key is not already associated with a value (or is mapped to null) in Hashtable then insert key and value.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys from the hashtable.
V replace(K key, V value) This method replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) This method replaces the old value with the new value for a specified key.
void replaceAll(BiFunction function) This method replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
String toString() It returns a string representation of the Hashtable object.
Collection values() It returns a collection view of the values contained in the map.
boolean contains(Object value) This method returns true if some value equal to the value exists within the hash table, else return false.
boolean containsValue(Object value) This method returns true if some value equal to the value exists within the hash table, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the key exists within the hash table, else return false.
boolean isEmpty() This method returns true if the hash table is empty; returns false if it contains at least one key.
protected void rehash() It is used to increase the size of the hash table and rehashes all of its keys.
V get(Object key) This method returns the object value associated with the key.
V remove(Object key) It is used to remove the key and its value. This method returns the value associated with the key.
int size() This method returns the number of entries in the hash table.

HashTable Example : add() key and value

import java.util.*;

public class HashTableExample1 {

	public static void main(String args[]) {
		Hashtable hm = new Hashtable();

		//add values in hash table
		hm.put(20, "Anuj");
		hm.put(22, "Ravi");
		hm.put(21, "Virendra");
		hm.put(23, "Raghav");

		//print all values from HashTable
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


21 Virendra
20 Anuj
23 Raghav
22 Ravi

HashTable Example : remove()

import java.util.Hashtable;

public class HashTableExample2 {

	public static void main(String args[]) {
		Hashtable map = new Hashtable();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		System.out.println("Before remove: " + map);
		// Remove value for key 22
		map.remove(22);
		System.out.println("After remove: " + map);
	}

}

Output :


Before remove: {21=Virendra, 20=Anuj, 23=Raghav, 22=Ravi}
After remove: {21=Virendra, 20=Anuj, 23=Raghav}

Hashtable Example : getOrDefault()

import java.util.Hashtable;

public class HashTableExample3 {

	public static void main(String args[]) {
		Hashtable map = new Hashtable();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		// Here it will retrieve values for key 21 and 25
		// if values not find out in HashTable then return default value
		System.out.println(map.getOrDefault(21, "Not Found"));
		System.out.println(map.getOrDefault(25, "Not Found"));
	}
}

Output :


Virendra
Not Found

Hashtable Example : putAbsent()

import java.util.*;
class HashtableExample4{
 public static void main(String args[]){
   Hashtable map=new Hashtable();
     map.put(20,"Anuj");
     map.put(22,"Ravi");
     map.put(21,"Virendra");
     map.put(23,"Raghav");
     System.out.println("Initial Map: "+map);
     //insert value in hashtable only when not exist
     map.putIfAbsent(24,"Gaurav");
     System.out.println("Updated Map: "+map);
     //insert value in hashtable only when not exist
     map.putIfAbsent(21,"Virendra");
     System.out.println("Updated Map: "+map);
 }
}

Output :


Initial Map: {21=Virendra, 20=Anuj, 23=Raghav, 22=Ravi}
Updated Map: {21=Virendra, 20=Anuj, 24=Gaurav, 23=Raghav, 22=Ravi}
Updated Map: {21=Virendra, 20=Anuj, 24=Gaurav, 23=Raghav, 22=Ravi}

Hashtable Example : with Objects

import java.util.*;
class Magzine{
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}    

public class HashtableExampleWithObjects {
	public static void main(String[] args) {
		// Creating map of Magzine
		Map table = new Hashtable();
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzine to map
		table.put(1, m1);
		table.put(2, m2);
		table.put(3, m3);
		// Traversing map
		for (Map.Entry entry : table.entrySet()) {
			int key = entry.getKey();
			Magzine m = entry.getValue();
			System.out.println("\nId: "+key + " Details:");
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Java: Hashmap Working


What is Hashing?

Hashing is technique of converting an object into an integer value. For example hashcode() method always return int value. We can also override hashcode() method and implement own logic to get hashcode value.

Note : The integer value helps in indexing and faster searches.

What is HashMap

HashMap is a one type of collection in Java collection framework to store values in key and value pair. HashMap uses hashing technique for storing values. HashMap uses internal data structure as array and LinkedList for storing key and values. HashMap contains an array of nodes, and node presented by a class with respect to key.

See Also : Java: HashMap Class Methods and Examples

Contract between equals() and hashcode() method

Before discussing internal working of HashMap, need to understand hashCode() and equals() method contract in detail.

  • equals(): it’s Object class method to check the equality of two objects by comparing key, whether they are equal or not. It can be overridden.
  • hashCode(): it’s also object class methods which return memory reference of object in integer form. This value received from the hashcode() method is used as the bucket number or address of element inside Map. Hashcode value of null Key is 0.

If you override the equals() method, then it is mandatory to override the hashCod() method.

See Also: Java : java.lang.Object Class & Methods

Buckets: is an Array of the node, where each node has a data structure like a LinkedList. More than one node can use same bucket and may be different in capacity.

Working of HashMap

Insert Key, Value pair in HashMap

We use put() method to insert the Key and Value pair in the HashMap. The default capacity of HashMap is 16 (0 to 15).

Example: In the following example, we want to insert six (Key, Value) pair in the HashMap.

HashMap map = new HashMap();
map.put("Ankur", 35);
map.put("Saurabh", 36);
map.put("Gaurav", 32);
map.put("Raghav", 29);
map.put("Rajendra", 40);
map.put("Shailesh", 33);

When we call the put() method, then it calculates the hash code of the Key i.e “Ankur” hashcode is 63412443. Now to store the Key and value pair in memory, we have to calculate the index based on below formulae.

HashMap Representataion.jpg

Calculating Index Formulae:


Index = hashcode(Key) & (n-1)  
Where n is the size of the array.

Hence the index value for Ankur and others are as below:
Calculate Index for “Ankur”
Index = 63412443& (16-1) = 11
Calculate Index for “Saurabh”
Index = -758033668& (16-1) = 12
Calculate Index for “Gaurav”
Index = 2125849484& (16-1) = 12
Calculate Index for “Raghav”
Index = -1854623835& (16-1) = 5
Calculate Index for “Rajendra”
Index = 201412911& (16-1) = 15
Calculate Index for “Shailesh”
Index = -687212437& (16-1) = 11

The key “Ankur” calculated index value is 11. This key and value pair store in one of the node of HashMap.

Hash Collision

Hash Collisions occured when two or more keys are calculating index as same value.

From above calculated index value, keys “Ankur and “Shailesh” both index value is 11 having hash collision. Similarly for “Saurabh” and “Gaurav” having index value 12. In this case, equals() method compare both Keys are equal or not. If Keys are equal, replace the value with the current value. Otherwise, linked this node object (key and value pair) to the existing node object through the LinkedList.

Similarly, we will store the other keys with respect to below index positions.

HashMap get() method to retrieve values

HashMap get(Key) method is used to retrieve value by Key. This method calculate index position based on key hashcode value and capacity of hashmap and fetch result. If no matching key find out will return result as value null.

Suppose we have to fetch the Key “Ankur.” The following method will be called.


map.get(new Key("Ankur"));

It generates the hash code as 63412443. Now calculate the index value of 63412443 by using index formula. The index value will be 11. get() method search for the index value 11. It compares the given key value sequentially in bucket with respect to index position 11. If any equal key find out in bucket will return value object with respect to that key otherwise finally return null if not no match find out.

Let’s fetch another Key “Raghav.” The hash code of the Key “Raghav” is -1854623835. The calculated index value of -1854623835 is 5. Go to index 5 of the array and compare the first element’s Key with the given Key “Raghav”. It return the value object for match key.

Java: HashMap Class Methods and Examples


java.util.HashMap class inherits AbstractMap class and implements the Map interface. HashMap values store on the basis of key and value pair where each pair is known as an Entry.

  • K: It’s the type of Key in HashMap
  • V: It’s a type of value with respect to Key.

HashMap Class Declaration


public class HashMap extends implements Map, Cloneable, Serializable  

See Also:

Points to Remember:

  • HashMap uses data structure as a Hash Table.
  • HashMap store values based on keys.
  • HashMap contains unique keys.
  • HashMap allows duplicate values.
  • HashMap doesn’t maintain order.
  • HashMap class allows only one null key and multiple null values.
  • HashMap is not synchronized.
  • HashMap initial default capacity is 16 elements with a load factor of 0.75.

HashMap Representataion

Difference between HashSet and HashMap

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

HashMap Class Constructors

Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map m) It is used to initialize the hash map by using the elements of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float loadFactor) It is used to initialize both the capacity and load factor of the hash map by using its arguments.

HashMap Class Methods

Method Description
void clear() Use to remove all of the mappings from this map.
boolean isEmpty() Use to return true if this map contains no key-value mappings.
Object clone() Use to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Set entrySet() Use to return a collection view of the mappings contained in this map.
Set keySet() Use to return a set view of the keys contained in this map.
V put(Object key, Object value) Use to insert an entry in the map.
void putAll(Map map) Use to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value in the map only when  specified key is not already specified.
V remove(Object key) Use to delete an entry for the specified key.
boolean remove(Object key, Object value) removes the  values with the associated specified keys from the map.
V compute(K key, BiFunction remappingFunction) Use to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) Use to compute its value using the given mapping function, if the specified key is not mapped with a value or null, and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) Use to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value) It returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key) It returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o) Use to compare the specified Object with the Map.
void forEach(BiConsumer action) Added in Java 8 to  performs the given action for each entry in the map  or the action throws an exception.
V get(Object key) This method returns the object that contains the value associated with respect to key.
V getOrDefault(Object key, V defaultValue) Added in Java 8. It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
boolean isEmpty() It returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction remappingFunction) If the specified key is not already associated with a value or is associated with null then associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value with respect to specified key.
boolean replace(K key, V oldValue, V newValue) Replaces the old value with the new value with respect to specified key.
void replaceAll(BiFunction function) It replaces each entry’s value with entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection of the values contained in the map.
int size() It returns the count of number of entries in the map.

Example: add elements

Here, you will learn different ways to insert elements.

import java.util.*;

class HashMapExample1 {
	public static void main(String args[]) {
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		System.out.println("Initial hash map elements: " + hm );
		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");

		System.out.println("\nAfter invoking put() method");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}

		hm.putIfAbsent(23, "Gaurav");
		System.out.println("\nAfter invoking putIfAbsent() method");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		HashMap map = new HashMap();
		map.put(24, "Ravi");
		map.putAll(hm);
		System.out.println("\nAfter invoking putAll() method ");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Initial hash map elements: {}

After invoking put() method
20 Anuj
21 Virendra
22 Raghav

After invoking putIfAbsent() method
20 Anuj
21 Virendra
22 Raghav
23 Gaurav

After invoking putAll() method 
20 Anuj
21 Virendra
22 Raghav
23 Gaurav
24 Ravi

HashMap Example : remove()

Here you will see different ways to remove elements from HashMap

import java.util.*;
import java.util.HashMap;

public class HashMapExample2 {
	public static void main(String args[]) {
		HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(20, "Anuj");
		map.put(21, "Virendra");
		map.put(22, "Raghav");
		map.put(23, "Gaurav");
		System.out.println("Initial hash map elements: " + map);
		// key-based removal
		map.remove(20);
		System.out.println("\nUpdated hash map  elements: " + map);
		// value-based removal
		map.remove(21);
		System.out.println("\nUpdated hash map  elements: " + map);
		// key-value pair based removal
		map.remove(22, "Raghav");
		System.out.println("\nUpdated hash map  elements: " + map);
	}
}

Output :


Initial hash map elements: {20=Anuj, 21=Virendra, 22=Raghav, 23=Gaurav}

Updated hash map  elements: {21=Virendra, 22=Raghav, 23=Gaurav}

Updated hash map  elements: {22=Raghav, 23=Gaurav}

Updated hash map  elements: {23=Gaurav}

HashMap Example : replace()

Here you will see different ways to replace() elements in HashMap

import java.util.*;

class HashMapExample3 {
	public static void main(String args[]) {
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");
		System.out.println("Initial hash map elements:");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replace(22, "Gaurav");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replace(21, "Virendra", "Ravi");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replaceAll((k, v) -> "Anuj");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Initial hash map elements:
20 Anuj
21 Virendra
22 Raghav

Updated hash map elements:
20 Anuj
21 Virendra
22 Gaurav

Updated hash map elements:
20 Anuj
21 Ravi
22 Gaurav

Updated hash map elements:
20 Anuj
21 Anuj
22 Anuj

HashMap Example: Objects handling

import java.util.*;
public class Magzine {
	int id;
	String name,author,publisher;
	int quantity;
	public Magzine(int id, String name, String author, String publisher, int quantity) {
	    this.id = id;
	    this.name = name;
	    this.author = author;
	    this.publisher = publisher;
	    this.quantity = quantity;
	}    

}
public class MapExample {
import java.util.HashMap;
import java.util.Map;

public class HashMapWithObjectsExample {

	public static void main(String[] args) {
	    //Creating map of Magzines
	    Map<Integer,Magzine> map=new HashMap<Integer,Magzine>();
	    //Creating Books
	    Magzine m1=new Magzine(21,"The Sun","Sy Sunfranchy","The Sun Company",8);
	    Magzine m2=new Magzine(22,"Glimmer Trains","Unknown","Glimmer Train Press",4);
	    Magzine m3=new Magzine(23,"Crazy horse","Brett Lot","College of Charleston",6);
	    //Adding Magzines to map
	    map.put(1,m1);
	    map.put(2,m2);
	    map.put(3,m3);  

	    //Traversing map
	    for(Map.Entry<Integer,Magzine> entry:map.entrySet()){
	        int key=entry.getKey();
	        Magzine m=entry.getValue();
	        System.out.println("\nMagzine "+key+" Details:");
	        System.out.println(m.id+" "+m.name+" "+m.author+" "+m.publisher+" "+m.quantity);
	    }
	}
}

Output :



Magzine 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Magzine 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Magzine 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

References

Java: Difference between HashMap and Hashtable


HashMap and Hashtable both implements Map interface and used to store data in key and value pairs. Both use hashing techniques to get unique keys.

Apart from some similarities, there are many differences between HashMap and Hashtable classes as follows:

java.util.HashMap java.util.HashTable
HashMap class introduced in JDK 1.2. Hashtable is a legacy class.
HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.
HashMap is traversed by Iterator. Hashtable is traversed by the Enumerator and Iterator.
Hashmap, Iterator is fail-fast. Hashtable, Enumerator is not fail-fast.
HashMap is not synchronized and not-thread safe. Hashtable is synchronized and thread safe.
HashMap can be synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can’t be unsynchronized.
HashMap class allows only one null key and multiple null values. Hashtable doesn’t allow any null key or value.
HashMap is fast. Hashtable is slow.

For more detail:

 

Java: Unmodifiable Collection Methods and Example


In Collection Framework, to make collection type object as unmodifiable java.Util.Collections class provides static methods to make these object as unmodifiable.

Collections Class Unmodifiable Methods

static Collection
unmodifiableCollection(Collection<? extends T> c)
Returns an unmodifiable view of the specified collection.
static List
unmodifiableList(List<? extends T> list)
Returns an unmodifiable view of the specified list.
static <K,V> Map<K,V>
unmodifiableMap(Map<? extends K,? extends V> m)
Returns an unmodifiable view of the specified map.
static <K,V> NavigableMap<K,V>
unmodifiableNavigableMap(NavigableMap<K,? extends V> m)
Returns an unmodifiable view of the given map.
static NavigableSet
unmodifiableNavigableSet(NavigableSet s)
Returns an unmodifiable view of the given navigable set.
static Set
unmodifiableSet(Set<? extends T> s)
Returns an unmodifiable view of the given set.
static <K,V> SortedMap<K,V>
unmodifiableSortedMap(SortedMap<K,? extends V> m)
Returns an unmodifiable view of the given map.
static SortedSet
unmodifiableSortedSet(SortedSet s)
Returns an unmodifiable view of the given  set.

Example: Synchronized Collections

In this example creating the blank type of collection and making it Unmodified. You can assign the same with collection objects.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;

public class CollectionUnmodifiedExample {

	public static void main(String[] args) {
		Collection c = new ArrayList();
	    Collections.unmodifiableCollection(c);
	    Collections.unmodifiableList(new ArrayList());
	    Collections.unmodifiableMap(new HashMap());
	    Collections.unmodifiableSet(new HashSet());
	}

}

References

Java: Synchronized Collection Methods and Examples


In Collection Framework, only some of the classes are thread-safe or synchronized. If you need to work on a multi-threaded environment then you have to convert these non-synchronized type classes to Synchronized type collection.

Synchronized Collection

These are the classes only are synchronized:

  • Vector
  • HashTable

As a solution java.util.Collections class provides some static methods to make them Synchronized.

Collections Class Synchronized Methods

All these methods are static:

Collection synchronizedCollection(Collection c) Returns a synchronized collection.
List synchronizedList(List list) Returns a synchronized list.
Map<K,V>
synchronizedMap(Map<K,V> m)
Returns a synchronized map .
NavigableMap<K,V>
synchronizedNavigableMap(NavigableMap<K,V> m)
Returns a synchronized navigable map.
NavigableSet synchronizedNavigableSet(NavigableSet s) Returns a synchronized navigable set .
static Set synchronizedSet(Set s) Returns a synchronized set .
SortedMap<K,V>
synchronizedSortedMap(SortedMap<K,V> m)
Returns a synchronized sorted map .
SortedSet
synchronizedSortedSet(SortedSet s)
Returns a synchronized sorted set.

Example: Synchronized Collections

In this example creating the blank type of collection and making it Synchronized. You can assign the same with collection objects.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CollectionSunchronizationExample {

	public static void main(String[] args) {
		Collection c = Collections.synchronizedCollection(new ArrayList());
	    List list = Collections.synchronizedList(new ArrayList());
	    Set s = Collections.synchronizedSet(new HashSet());
	    Map m = Collections.synchronizedMap(new HashMap());

	}

}

References

Java: Properties Class Methods and Examples


java.util.Properties class is a subclass of HashTable. Properties class store values in key and value pairs both as String.

We can define our properties by properties (extension as .properties) or by Properties class. The main benefit of define properties in the properties file. If something needs to change then don’t need to recompile the Java Class.

Method of Properties Class

public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key, String value) sets the property in the properties object.
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStream os, String comment) writes the properties in the OutputStream object.
storeToXML(OutputStream os, String comment) writers the properties in the writer object for generating the XML document.
public void storeToXML(Writer w, String comment, String encoding) writers the properties in the writer object for generating an XML document with the specified encoding.

Example: Create Properties File

import java.io.FileWriter;
import java.util.Properties;

public class CreateProprtiesFile {

	public static void main(String[] args) throws Exception {
		Properties p = new Properties();
		//append properties in class as key and value
		p.setProperty("name", "Saurabh Gupta");
		p.setProperty("email", "FacingIssuesOnIT@gmail.com");

		//Write in properties file
		p.store(new FileWriter("myinfo.properties"),
				"FacingIssuesOnIT Properties Example");
	}
}

Output

Properties file creation

Example: Read Properties File

In this example, you will learn to read properties from the file.

import java.io.FileReader;
import java.util.Properties;

public class ReadPropertiesFile {

	public static void main(String[] args) throws Exception{
		//Read properties file
		 FileReader reader=new FileReader("myinfo.properties");   

		    Properties p=new Properties();
		    //Load file as properties
		    p.load(reader);   

		    //retrieve value of property one by one
		    System.out.println(p.getProperty("name"));
		    System.out.println(p.getProperty("email"));
	}

}

Output


Saurabh Gupta
FacingIssuesOnIT@gmail.com

Example : Print System Level Properties

import java.util.Map;
import java.util.Properties;

public class PrintSystemProperties {

	public static void main(String[] args) throws Exception{   

		//Get all properties from System class
		Properties properties=System.getProperties(); 

		//Print all System level properties
		System.out.println("Your Machine Properties :\n");
		for(Map.Entry entry:properties.entrySet())
		{
			System.out.println(entry.getKey()+" = "+entry.getValue());
		}

	}

}

Output


Your Machine Properties :

java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.8.0_73\jre\bin
java.vm.version = 25.73-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) 64-Bit Server VM
file.encoding.pkg = sun.io
user.country = US
user.script = 
sun.java.launcher = SUN_STANDARD
sun.os.patch.level = 
java.vm.specification.name = Java Virtual Machine Specification
user.dir = F:\Workspace-Learning\Session8Examples
java.runtime.version = 1.8.0_73-b02
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = C:\Program Files\Java\jdk1.8.0_73\jre\lib\endorsed
os.arch = amd64
java.io.tmpdir = C:\Users\SAURAB~1\AppData\Local\Temp\
line.separator = 

java.vm.specification.vendor = Oracle Corporation
user.variant = 
os.name = Windows 10
sun.jnu.encoding = Cp1252
java.library.path = C:\Program Files\Java\jdk1.8.0_73\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_73/bin/server;C:/Program Files/Java/jre1.8.0_73/bin;C:/Program Files/Java/jre1.8.0_73/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Git\cmd;%JAVA_HOME%\bin;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Users\Saurabh Gupta\Desktop;;.
java.specification.name = Java Platform API Specification
java.class.version = 52.0
sun.management.compiler = HotSpot 64-Bit Tiered Compilers
os.version = 10.0
user.home = C:\Users\Saurabh Gupta
user.timezone = 
java.awt.printerjob = sun.awt.windows.WPrinterJob
file.encoding = Cp1252
java.specification.version = 1.8
java.class.path = C:\Program Files\Java\jdk1.8.0_73\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\zipfs.jar;F:\Workspace-Learning\Session8Examples\bin
user.name = Saurabh Gupta
java.vm.specification.version = 1.8
sun.java.command = collections.properties.PrintSystemProperties
java.home = C:\Program Files\Java\jdk1.8.0_73\jre
sun.arch.data.model = 64
user.language = en
java.specification.vendor = Oracle Corporation
awt.toolkit = sun.awt.windows.WToolkit
java.vm.info = mixed mode
java.version = 1.8.0_73
java.ext.dirs = C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
sun.boot.class.path = C:\Program Files\Java\jdk1.8.0_73\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_73\jre\classes
java.vendor = Oracle Corporation
file.separator = \
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
sun.io.unicode.encoding = UnicodeLittle
sun.cpu.endian = little
sun.desktop = windows
sun.cpu.isalist = amd64

Java 8: Lambda Expression


Java 8 introduced lambda expression to move toward functional programming. A lambda expression is an anonymous function that doesn’t have a name and doesn’t belong to any class.

Where to use the Lambda Expression

A lambda expression can only be used where the type they are matched against is a single abstract method(SAM) interface or functional interface.

To use a lambda expression, you can either create your own functional interface or use the predefined functional interface provided by Java.

Example of a pre-defined interface: Runnable, callable, ActionListener, etc.

Pre Java 8: Use anonymous inner classes.
Post-Java 8: Now use lambda expression instead of anonymous inner classes.

Points to remember

  • Lambda expression is also known as a closure that allows us to treat functionality as a method arguments (passing functions around) or treat code as data.
  • Lambda expression concept was first introduced in the LISP programming language.
  • Lambda expression is used to provide an implementation of a functional interface or Single Method Interface.
  • Lambda expression treated as a function so the compiler does not create .class file.
  • Lambda expression doesn’t need to define a method again for implementation.
  • Lambda expression benefit is less coding.

Java Lambda expression Syntax

To create a lambda expression, On the left side of the symbol lambda operator(->) specify input parameters (if there are any), and on the right side place the expression or block of statements.


 (parameter_list) -> {function_body}

For example, the lambda expression (x, y) -> x + y specifies that lambda expression takes two arguments x and y and returns the sum of these.

Note:

  • Optional type declaration: No need to declare the data type of a parameter. The compiler can inference the data type from the value of the parameter.
  • The optional parenthesis around parameter: No needs to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  • Optional curly braces: For a single line of the statement, No need to use curly braces in the expression body.
  • Optional return keyword: The compiler automatically returns the value if the body has a single expression statement to return the value. Curly braces are required to indicate that expression statement returns a value.

Here is some Lamda expression example according to a number of arguments.

No Argument Syntax


()->{
//write some statemnet here
}

One Argument Syntax


(arg1)->{
//write some statemnet here
}

Two Argument Syntax


(arg1,arg2)->{
//write some statemnet here
}

Method vs Lambda Expression in Java

A function (or method) in Java has four main parts:
1. Name
2. Parameter list
3. Body
4. return type.

A lambda expression has these main parts:
Lambda expression only has a parameter list and body.
1. No name – Lambda expression is an anonymous function that doesn’t have a name.
2. Parameter list
3. Body – This is the main part of the function where implementation is written.
4. No return type – Don’t need to write a return statement explicitly. The compiler is able to infer the return type by checking the code.

Example 1: Lambda Expression with a predefined functional interface

In this thread, execution example consider both ways legacy and lambda expression to implement the run method and start threads.

public class PredefinedFunctionalInterfaceExample {
public static void main(String[] args) {

// Implementing Runnable using anonymous class (legacy way)
Runnable runnable1 = new Runnable() {
@Override
public void run() {
System.out.println("Thread name : " + Thread.currentThread().getName());
}
};
Thread thread1 = new Thread(runnable1);

// Implementing Runnable using Lambda expression because Runnable having
// only one abstarct method run()
Runnable runnable2 = () -&amp;amp;gt; {
System.out.println("Thread name : " + Thread.currentThread().getName());
};
Thread thread2 = new Thread(runnable2);

// Start Threads
thread1.start();
thread2.start();
}
}

Example 2: lambda Expression with your own functional interface

In this example, define the functional interface “YourFunctionalInterface” definition by the lambda expression for arguments (a,b). When we call the functional interface method with the argument (120,100) then it will make reference to the given definition of FunctionalInterface and return the result as 220.

@FunctionalInterface
interface YourFunctionalInterface
{
 public int addValues(int a, int b);
}

public class CalculateClass {

   public static void main(String args[]) {
        // lambda expression
    YourFunctionalInterface sum = (a, b) -&amp;amp;gt; a + b;
        System.out.println("Result: "+sum.addValues(120, 100));
    }
}

Output


Result: 220

Example 3: Lambda Expression with no arguments

@FunctionalInterface
interface MyFunctionalInterface {
//abstarct method with no argument
public String sayWelcome();
}
public class LambdaExpressionExample {
public static void main(String args[]) {
//No argument lambda expression
MyFunctionalInterface msg = () -> {
return "Welcome to Facing Issues on IT !!";
};
System.out.println(msg.sayWelcome());
}
}

Output


Welcome to Facing Issues on IT !!

Example 4: Lambda Expression for Collection Iteration

import java.util.*;
public class LambdaExpressionLoopExample{
public static void main(String[] args) {
List list=new ArrayList();
list.add("Saurabh");
list.add("Gaurav");
list.add("Bharti");
list.add("Herry");
list.add("Henry");
list.forEach(
// lambda expression for list iteration
(names)->System.out.println(names)
);
}
}

Output


Saurabh
Gaurav
Bharti
Herry
Henry

Note:

  1. As you can see from these examples lambda expression used less code.
  2. Lambda expression is backward compatible so we can enhance our existing API when migrating to Java 8.

References

Java 8: Optional for handling NULL


Java 8 introduces a new class called java.util.Optional to overcome the headache of NullPointerException. Optional class is a type of container of optional single value that either contains a value or doesn’t (it is then said to be “empty”).

The optional class having lots of methods to deal with different cases:

Create Optional Object

Create Optional Object : Empty


Optional optionalObj=Optional.empty();

Create Optional Object: Non-Null
Optional.of() method throw NullPointerException if passing object reference is null.


YourClass yourObj=new YourClass();
Optional optionalObj=Optional.of(yourObj);

Create Optional Object: Allowed Null
Optional.ofNullable() method allowed null reference in Optional object container.


YourClass yourObj=null;
Optional optionalObj=Optional.ofNullable(yourObj);

Check Optional Object for value present

Optional.isPresent() method return boolean true/false based on any value present in Optional container.


if(optionalObj.isPresent())
{
//do something
}

Optional Object for value

if Optional.isPresent() method return true then we get value from Optional object by get() method. If value is not exist in Optional object and trying to call get() method then throw exception as NoSuchElementException


if(optionalObj.isPresent())
{
YourClass yourObj=optionalObj.get();
}

Set Optional Object default value and actions

We can use Optional.orElse() method which provide default value if Optional object is empty.


YourClass yourObj=optionalObj.orElse(new YourClass("defaut"));
</pre We can use Optional.orElseThrow() method which instread of returning default value if Optional empty , throw an exception:

YourClass yourObj = optionalObj.orElseThrow(IllegalStateException::new);

Example 1

In this example, covered all the above case.


import java.util.Optional;
public class OptionalExamples {

	public static void main(String args[]) {
		OptionalExamples java8Tester = new OptionalExamples();
	      Integer value1 = null;
	      Integer value2 = new Integer(25);

	      //Optional.ofNullable - allows passed parameter to be null.
	      Optional<Integer> firstParam = Optional.ofNullable(value1);

	      //Optional.of - throws NullPointerException if passed parameter is null
	      Optional<Integer> secondParam = Optional.of(value2);
	      System.out.println(java8Tester.sum(firstParam,secondParam));
	   }

	   public Integer sum(Optional<Integer> a, Optional<Integer> b) {
	      //Optional.isPresent - checks the value is present or not

	      System.out.println("First parameter is present: " + a.isPresent());
	      System.out.println("Second parameter is present: " + b.isPresent());

	      //Optional.orElse - returns the value if present otherwise returns
	      //the default value passed.
	      Integer value1 = a.orElse(new Integer(0));

	      //Optional.get - gets the value, value should be present
	      Integer value2 = b.get();
	      return value1 + value2;
	   }

}

Output


First parameter is present: false
Second parameter is present: true
25

Example 2

public class OptionalExaple2

	public static void main(String[] args) {
		Optional<String> completeName = Optional.ofNullable(null);
		// The isPresent() method returns true if this instance of Optional has
		// non-null value and false otherwise.
		System.out.println("Complete Name is set? " + completeName.isPresent());
		// The orElseGet() method provides the fallback mechanism in case
		// Optional has null value by accepting the function to generate the
		// default one.
		System.out.println("Complete Name: " + completeName.orElseGet(() -> "[Unknown]"));
		// The map() method transforms the current Optional’s value and returns
		// the new Optional instance.
		System.out.println(completeName.map(s -> "Hey " + s + "!").orElse("Hey Unknown!"));

		Optional<String> firstName = Optional.of("Saurabh");
		System.out.println("First Name is set? " + firstName.isPresent());
		// The orElse() method is similar to orElseGet() but instead of function
		// it accepts the default value.
		System.out.println("First Name: " + firstName.orElseGet(() -> "[Unknown]"));
		System.out.println(firstName.map(s -> "Hey " + s + "!").orElse("Hey Unnknown!"));
		System.out.println();

	}

}

Output


Complete Name is set? false
Complete Name: [Unknown]
Hey Unknown!
First Name is set? true
First Name: Saurabh
Hey Saurabh!

References

 

Java 8: Base64 Encoding and Decoding


In Java 8 added new class Base64 for encryption and decryption. It supports three types encoding and decoding:

  • Simple
  • URL
  • MIME

Note: Passing a null argument to a method of this class will cause a NullPointerException to be thrown.

Simple

Uses “The Base64 Alphabets” lying in A-Za-z0-9+/ for encoding and decoding. The encoder does not add any line feed/line separate character in output and decoder rejects all characters out of the Base 64 alphabet.

Example: Simple Encoding and Decoding

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64s {

	public static void main(String[] args) {
    final String text = "Facing Issues On IT in Java 8!";

        final String encoded = Base64.getEncoder().encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
        System.out.println("After Encoding:"+ encoded );

        final String decoded = new String(Base64.getDecoder().decode( encoded ),StandardCharsets.UTF_8 );
        System.out.println("After Decoding:"+ decoded );
	}
}

Output


After Encoding:RmFjaW5nIElzc3VlcyBPbiBJVCBpbiBKYXZhIDgh
After Decoding:Facing Issues On IT in Java 8!

URL

Uses “URL and Filename safe Base64 Alphabet” lying in A-Za-z0-9+_ for encoding and decoding. The encoder does not add any line feed/line separater character in output and decoder rejects all characters out of the Base 64 alphabet.

Example: URL Encoding and Decoding

import java.util.Base64;

public class Base64URLExample {

	public static void main(String[] args) {
		String originalUrl = "https://www.google.co.in/?gfe_rd=cr&ei=dzbFV&gws_rd=ssl#q=java";
		String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes());
		System.out.println("After Encoding:"+ encodedUrl );

		byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl);
		String decodedUrl = new String(decodedBytes);
		System.out.println("After Decoding:"+ decodedUrl );
	}

}

Output


After Encoding:aHR0cHM6Ly93d3cuZ29vZ2xlLmNvLmluLz9nZmVfcmQ9Y3ImZWk9ZHpiRlYmZ3dzX3JkPXNzbCNxPWphdmE=
After Decoding:https://www.google.co.in/?gfe_rd=cr&ei=dzbFV&gws_rd=ssl#q=java

MIME

Uses “The Base64 Alphabet” lying in lying in A-Za-z0-9+/ for encoding and decoding. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return ‘\r’ followed immediately by a linefeed ‘\n’ as the line separator. No line separator is added to the end of the encoded output. All line separators or other characters not found in the base64 alphabet table are ignored in decoding operation.

Example: MIME Encoding and Decoding

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.UUID;

public class Base64Mime {

	public static void main(String[] args) {

		try {
			StringBuilder stringBuilder = new StringBuilder();
			// Lets generate some mime input to encode
			for (int i = 0; i < 10; ++i) {
				stringBuilder.append(UUID.randomUUID().toString());
			}

			byte[] mimeBytes = stringBuilder.toString().getBytes("utf-8");
			String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);
			System.out.println("Base64 Encoded String (MIME) :" + mimeEncodedString);

			byte[] decodedBytes = Base64.getMimeDecoder().decode(mimeEncodedString);
			String decodedMime = new String(decodedBytes);
			System.out.println("Base64 Decoded String (MIME) :" + decodedMime);

		} catch (UnsupportedEncodingException e) {
			System.out.println("Error :" + e.getMessage());
		}
	}

}

Output


Base64 Encoded String (MIME) :YWY1MWRkMDAtNjg0MC00MDE4LTk5YWYtMDE4NTFhYmZkYzA3M2Q0MjU1YjMtNDFiOS00ZmZmLTky
NjktYzc5YjU2Mzg4OGMyM2IzZTAyN2QtNzhkMC00YzRiLTg3MzgtZWFiMmI3OTdlNmVlMzdmYzQ3
ZDItYmI2Zi00NmVjLThlYTQtOWUwYWJlODA0M2IwN2I1NzIxNjUtNzJjZC00ODhmLWJkMWUtOWVl
NGI3YTc5M2NmZjczMjU1MDItMzIyNC00Mjc1LWI2MjQtNTcxZTU3ZmZkZjVhNTdiMmM4NTgtMzFi
Yi00ZjNlLWI5MWYtZWJkNjc5ODlkOTA2NDQ4MDZiZDQtOWM4Zi00NjJlLWI1ZWUtODZiNWM0MTJm
MmVjM2JmMjFjMDAtNjUwYi00ZjE0LWI5ZTUtOTY2YjE2NjUzMWQxMGJhYTIzMTAtOTFmMy00OGYz
LTg1ZTgtZmU3OTEyMjNhODc3
Base64 Decoded String (MIME) :af51dd00-6840-4018-99af-01851abfdc073d4255b3-41b9-4fff-9269-c79b563888c23b3e027d-78d0-4c4b-8738-eab2b797e6ee37fc47d2-bb6f-46ec-8ea4-9e0abe8043b07b572165-72cd-488f-bd1e-9ee4b7a793cff7325502-3224-4275-b624-571e57ffdf5a57b2c858-31bb-4f3e-b91f-ebd67989d90644806bd4-9c8f-462e-b5ee-86b5c412f2ec3bf21c00-650b-4f14-b9e5-966b166531d10baa2310-91f3-48f3-85e8-fe791223a877

References

Java 8: Arrays Parallel Processing


Java 8 added lots of new methods to allow parallel processing for arrays. The most frequently used one is parallelSort() which may speed up the arrays sorting on multicore machines.

Java 8 new methods for Arrays

  • Arrays.parallelSetAll(): Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
  • Arrays.parallelSort(): Sorts the specified array into ascending numerical order.
  • Arrays.parallelPrefix(): Cumulates, in parallel, each element of the given array in place, using the supplied function.

Example: Arrays Parallel Processing

In this example uses method parallelSetAll() to fill up arrays with 25000 random values.
After that, the apply parallelSort() on these arrays values. Here you can see the output of the initial 10 values before and after sorting.

public class ParallelArrays {

	public static void main(String[] args) {
		    long[] arrayOfLong = new long [ 25000 ];
            //Fill long array with random numbers parallelly
	        Arrays.parallelSetAll( arrayOfLong,index -> ThreadLocalRandom.current().nextInt( 1000000 ) );
			//Print initial 10 values of array
            System.out.println("Before Sorting:Print initial 10 values of array");
	        Arrays.stream( arrayOfLong ).limit( 10 ).forEach(i -> System.out.print( i + " " ) );
	        System.out.println();
			//Parallel Sort Array Values
	        Arrays.parallelSort( arrayOfLong );
			//Print initial 10 values of array
			System.out.println("After Sorting:Print initial 10 values of array");
	        Arrays.stream( arrayOfLong ).limit( 10 ).forEach(i -> System.out.print( i + " " ) );
	        System.out.println();
	}

}

Output


Before Sorting:Print initial 10 values of array
164965 546280 269106 800751 338598 862392 358814 206345 611726 788465 
After Sorting: Print initial 10 values of array
4 13 87 93 94 145 203 281 319 397

References

Java 8 : Nashorn JavaScript Engine


Java 8 introduced a new Nashorn Javascript Engine to replace existing Rhino. Nashorn Javascript engine provides 2 to 10 times better performance and it directly compiles the code in memory and passes the bytecode to JVM. Nashorn JavaScript Engine enhanced version of javax.script.ScriptEngine and follows the same set of rules, permitting for Java and JavaScript interoperability.

Points to remember

  • Use jjs command to run Javascript through Nashhorn Engine.
  • The class name for the Nashorn Javascript engine is jdk.nashorn.api.scripting.NashornScriptEngine.

Exmaple: Nashorn JavaScript Engine

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class NashornEngineTest {

	public static void main(String[] args) {
		try {
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("JavaScript");

			System.out.println(engine.getClass().getName());
			System.out.println("Result:"
					+ engine.eval("function increment() { return 1; }; increment() + 1;"));
		} catch (ScriptException ex) {
			ex.printStackTrace();
		}

	}

}

Output


jdk.nashorn.api.scripting.NashornScriptEngine
Result:2.0

References

Java 8:Named Parameters in Reflection


With Java 8 reflection API added method to get parameters name of the method. For that, you need to make some compile-time configuration as pass the compiler flag: javac -parameters.

In this example, you will difference in reflection API output with and without named parameter configuration.

Example: Named Parameter Reflection API

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class NamedParameterExample {

	public static void main(String[] args) throws Exception {

		for(Method method :NamedParameterExample.class.getDeclaredMethods()) {
			System.out.println("\nMethod :"+method.getName()+" Parameters are :");
			for (final Parameter parameter : method.getParameters()) {
				System.out.println("Parameter: " + parameter.getName());
			}
		}
	}

	public static void printValues()
	{
		//Some statement here
	}

	public static int addOperation(int A, int b)
	{
		return A+b;
	}

	public static int substractionOperation(int param1 , int param2)
	{
		return param1-param2;
	}
}

Output: Without Configuration for the named parameter


Method :main Parameters are :
Parameter: arg0

Method :printValues Parameters are :

Method :addOperation Parameters are :
Parameter: arg0
Parameter: arg1

Method :substractionOperation Parameters are :
Parameter: arg0
Parameter: arg1

Output: With Configuration for the named parameter



Method :main Parameters are :
Parameter: args

Method :printValues Parameters are :

Method :addOperation Parameters are :
Parameter: A
Parameter: b

Method :substractionOperation Parameters are :
Parameter: param1
Parameter: param2

Eclipse Configuration for Named Parameter

Go to Window Tab -> Preferences -> Compiler -> Select Checkbox for “Store Information about method parameters (usable via reflection)”.
As shown in the below screen.

Java 8 named parameter eclipse setting

Console Configuration for Named Parameter

On time on compile with javac pass additional configuration as javac -parameters “class name”.

Maven Configuration for Named Parameter

On section of the maven-compiler-plugin:


<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId> 
  <version>3.1</version>
  <configuration> 
       <compilerArgument>-parameters</compilerArgument>
       <source>1.8</source> 
       <target>1.8</target> 
  </configuration>
</plugin>

Java 8: Reflection API to get Repeatable Annotation Detail


Java 8, introduced some new reflection APIs to retrieve annotation related information from different elements types like classes, interfaces, method, type, etc.

Reflection API provides new method getAnnotionByType() to return array of repeating annotations type.

Pre-requisite: Java: Annotations

In previous post Java 8: Repeatable Annotations you have learned about the creation and implementation of repeatable annotation. Let’s take one more example of repeatable annotation and see how to get annotation detail by Java reflection APIs.

Example: Retrieve Annotation Detail by Reflection API

As repeating annotations should themselves annotated with @Repeatable(Filetrs.class) annotation. Here Filters is just a holder of Filter’s annotations. The filterable interface defined Filter annotation two times with different values.

import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public class RepeatingAnnotations {
	@Target(ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
	public @interface Filters {
		Filter[] value();
	}

	@Target(ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
	@Repeatable(Filters.class)
	public @interface Filter {
		String value();
	};

	@Filter("filter1")
	@Filter("filter2")
	public interface Filterable {
	}

	public static void main(String[] args) {

	    /**
		*Here reflection API Class.getAnnotationsByType() returns
		*array of applied annotations
		*/
		for (Filter filter : Filterable.class
				.getAnnotationsByType(Filter.class)) {
			System.out.println(filter.value());
		}
	}

}

Output


filter1
filter2

Java 8: Repeatable Annotations


In Java 8 introduced repeatable annotation so that same annotation can be used multiple time on the same declaration and type use. For example, create a custom annotation to implement as repeatable annotation.

Pre-Requisite : Java: Annotations Tutorial

See also: Java 8: Reflection API to get Repeatable Annotation Detail

Create Custom Repeatable Annotation

import java.lang.annotation.Repeatable;
@Repeatable(Schedules.class)
public @interface Schedule {
String dayOfMonth() default "first";
String dayOfWeek() default "Mon";
int hour() default 2;
}

Create an array of repeatable annotation


package com.common.annotations;
public @interface Schedules {
Schedule[] value();
}

Use of repeatable annotation


package com.common.annotations;
import java.util.Date;
public class RepeatableAnnotationExample {
    public static void main(String[] args) {

    } 

@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour=23)
   public void doPeriodicCleanup() {
     System.out.println("Clean up started at :"+new Date());
   }
}

Java 8: StringJoiner Class


In java 8, introduced a new class StringJoiner to join more than one strings with the specified delimiter. This class also provides prefix and suffix to the final delimited String. We can also set default text value if no values added for string joined.

Constructors

  • StringJoiner(CharSequence delimiter): Constructs a StringJoiner with a delimiter, with no prefix or suffix.
  • StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): Constructs a StringJoiner with delimiter on values and add prefix and suffix on the final value.

Example 1: StringJoiner with delimiter (:)

Here in this example defined StringJoiner with a delimiter (:) to separate values, use StringJoiner.setEmptyValue() method to default value if not data added. Use StringJoiner.add() method to add values on StringJoiner.

import java.util.StringJoiner;

public class StringJoinerExample {

	public static void main(String[] args) {
		// Passing Hyphen(:) as delimiter
        StringJoiner myFriends = new StringJoiner(":");
        myFriends.setEmptyValue("No Friends Found");
        System.out.println("Friends Detail : When no data added");
        System.out.println(myFriends);
        // Joining multiple strings by using add() method
        myFriends.add("Saurabh");
        myFriends.add("Gaurav");
        myFriends.add("Raghav");
        myFriends.add("Shailesh");
        myFriends.add("Ankur");                 

        System.out.println("Friends Detail : After data added");
        // Displaying the output String with delimiter :
        System.out.println(myFriends);
	}

}

Output


Friends Detail : When no data added
No Friends Found
Friends Detail : After data added
Saurabh:Gaurav:Raghav:Shailesh:Ankur

Example 2: StringJoiner with a delimiter (:), prefix, and suffix

In this example, defined StringJoiner with a delimiter for values, prefix, and suffix for final delimited String.

import java.util.StringJoiner;

public class StringJoinerPrefixSuffixExample {

	public static void main(String[] args) {
		// Passing colon (:) as delimiter , prefix ({) and suffix (})
        StringJoiner myFriends = new StringJoiner(":","{","}"); 

        myFriends.setEmptyValue("No Friends Found");
        System.out.println("Friends Detail : When no data added");
        System.out.println("Friends Detail :"+myFriends);
        // Joining multiple strings by using add() method
        myFriends.add("Saurabh");
        myFriends.add("Gaurav");
        myFriends.add("Raghav");
        myFriends.add("Shailesh");
        myFriends.add("Ankur");
        System.out.println("Friends Detail : After data added");
        // Displaying the output String with delimiter :
        System.out.println(myFriends);
	}

}

Output


Friends Detail : When no data added
Friends Detail :No Friends Found
Friends Detail : After data added
{Saurabh:Gaurav:Raghav:Shailesh:Ankur}

Example 3: Merge StringJoiner 1 with a delimiter (:), StringJoiner 2 with a delimiter (,)

We can use StringJoiner.merge() method to merge the values of two StringJoiner. Here also use StringJoiner.length() method which returns the length of the final delimited String.

import java.util.StringJoiner;

public class StringJoinerMergeExample {

	public static void main(String[] args) {
	   // Passing Hyphen(:) as delimiter
        StringJoiner myFriends = new StringJoiner(":");
        // Joining multiple strings by using add() method
        myFriends.add("Saurabh");
        myFriends.add("Gaurav");
        myFriends.add("Raghav");
        myFriends.add("Shailesh");
        myFriends.add("Ankur");                 

        System.out.println("Friends Detail 1: After data added");
        // Displaying the output String with delimiter :
        System.out.println(myFriends); 

     // Passing Hyphen(:) as delimiter
        StringJoiner myFriends1 = new StringJoiner(",");
        // Joining multiple strings by using add() method
        myFriends1.add("Saurabh1");
        myFriends1.add("Gaurav1");
        myFriends1.add("Raghav1");
        myFriends1.add("Shailesh1");
        myFriends1.add("Ankur1");                 

        System.out.println("Friends Detail 2: After data added");
        // Displaying the output String with delimiter :
        System.out.println(myFriends1); 

        //Merge StringJoiner
        myFriends1.merge(myFriends);
        System.out.println("Result after merge Friends Detail 1 & 2:");
        System.out.println(myFriends1);

        //Length of String Joiner
        System.out.println(myFriends1.length());

	}

}

Output


Friends Detail 1: After data added
Saurabh:Gaurav:Raghav:Shailesh:Ankur
Friends Detail 2: After data added
Saurabh1,Gaurav1,Raghav1,Shailesh1,Ankur1
Result after merge Friends Detail 1 & 2:
Saurabh1,Gaurav1,Raghav1,Shailesh1,Ankur1,Saurabh:Gaurav:Raghav:Shailesh:Ankur
78

References

Java 8: Functional Interface


“An interface having exactly one abstract method is called Function Interface. Along with one abstract method can have any number of default and static methods.”

Points to Remember

  • This is also called as Single Abstract Method Interfaces or SAM Interfaces.
  • The default method having implementation is not considered as an abstract method.
  • An interface declares an abstract method overriding one of the public methods of java.lang.Object is not considered as an abstract method because any implementation of the interface will have an implementation from java.lang.Object or elsewhere.
  • If you declare an interface with @FunctionalInterface then the annotated interface must satisfy the requirements of a functional interface, if not match requirement will get the compile-time issue.

Note: Compiler will treat an interface as a functional interface if fulfilling conditions of Functional interface regardless of whether or not declared with @FunctionalInterface annotation.

Where to use Functional Interface

  • Functional Interface uses to represent Lambda Expressions.

Create your own functional interface

We can create our own Functional Interface by using @FunctionalInterface or Define interface having only one abstract method.

@FunctionalInterface
interface YourFunctionalInterface
{
 public int addValues(int a, int b);
}

Use of Functional Interface

We can use our own functional interface as above or predefined interface also such as Runnable, ActionListener, Comparator, etc. all these having a single abstract method.

Example: Use your own functional interface

In this example, define the functional interface “YourFunctionalInterface” definition by the lambda expression for arguments (a,b). When we call the functional interface method with the argument (120,100)  then it will make reference to the given definition of FunctionalInterface and return the result as 220.

public class CalculateClass {

   public static void main(String args[]) {
        // lambda expression
    YourFunctionalInterface sum = (a, b) -> a + b;
        System.out.println("Result: "+sum.addValues(120, 100));
    }
}

Output


Result: 220

Example: Use a predefined functional interface

In this thread, execution example consider both ways legacy and lambda expression to implement the run method and start threads.

public class PredefinedFunctionalInterfaceExample {
public static void main(String[] args) {

// Implementing Runnable using anonymous class (legacy way)
Runnable runnable1 = new Runnable() {
@Override
public void run() {
System.out.println("Thread name : " + Thread.currentThread().getName());
}
};
Thread thread1 = new Thread(runnable1);

// Implementing Runnable using Lambda expression because Runnable having
// only one abstarct method run()
Runnable runnable2 = () -> {
System.out.println("Thread name : " + Thread.currentThread().getName());
};
Thread thread2 = new Thread(runnable2);

// Start Threads
thread1.start();
thread2.start();
}
}

References

Java : Data Types


Java is a strictly-typed programming language. It means all variable names must be declared with Data Type before its use. Each variable with Data Type specifies allowed values and size allocated to it.

Java allowed two types of data types:

  1. Primitive data types: These are the most basic data type in Java, used to the building blocks of manipulation. These 8 are the primitive data types: boolean, char, byte, short, int, long, float and double.
  2. Non-primitive data types: The non-primitive data types are predefined or user-defined Classes, Interfaces, and Arrays.

Except for primitive type all other data type variables are non-primitive type.

See Also: Java : Primitive Types size and default value

Java Data Types

 

Java : Program Execution


Java is a high level programming language. To run a java program (.java file) first need to compile by javac compiler that convert java code to byte code (.class file). Machine language for JVM is byte code that is same for all type JVM machines (i.e OS). After running java command, JVM executes the byte code gennerated by compiler and produce output.

For Example : Byte code generated on windows machine can be run on Mac or Linux OS and vice versa.

Java program exceution

JVM makes java portable (write once, run anywhere) and platform independent. Because each operating system has different JVM, however the machine language is byte code output they produce after execution of byte code is same across all operating systems.

See Also: JDK, JRE, JIT,SDK, JVM Introduction

 

JDK, JRE, JIT,SDK, JVM Introduction


JDK (Java  Development Kit)

JDK (Java Development Kit) is a superset of JRE (Java Runtime Environment), it contains everything that JRE has along with development tools such as compiler, debugger, etc.

JDK Java development Kit
Java Development Kit

See Also: Java: Program Execution

JRE (Java Runtime Environment)

JRE (Java Runtime Environment) provides the environment in which the JVM (Java Virtual Machine) runs. JRE contains JVM, class libraries, and other files excluding development tools such as compiler and debugger.

It means, you can run the code in JRE but you can’t develop and compile the code in JRE.

JDK and JRE Formulae

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) runs the program by using class, libraries, and files provided by JRE. JVM able to run a program written in Java and other languages also that are compiled to Java byte code. For Example Jython, Jruby, Closure, Apache, Groovy, Kotlin, etc.

JVM Architecture

Now discussed terminology used for JVM.

Class Loader

The class loader reads the .class file and saves the byte code in the method area.

Method Area

Method area holds class level information of .class file. JVM jave only one method area which is shared among all the classes.

Heap

Heap is a JVM memory part where objects are allocated. JVM creates an object for each .class Class file.

Stack

The stack is  JVM memory part but unlike Heap, it is used for storing temporary variables i.e method parameters.

PC Registers

PC Registers use to keeps the track of which instruction has been executed and which one is going to be executed. Because instructions are executed by threads, each thread has a separate PC register.

JIT Compiler

The JIT also called a Just-In-Time compiler. It used when a method is called. The JIT compiles the bytecode of that called method into native machine code. When a method has been compiled in native machine code, the JVM calls the compiled code of that method directly instead of interpreting it.

Native Method Stack

A native method used to access the runtime data areas of the virtual machine.

Native Method interface

It enables java code to call or be called by native applications wiritten in C or C++. Native applications are programs in low-level language that is specific to the hardware and OS of a system.

Garbage collection

Garbage Collection use for automatic memory management by JVM. It destroys unreferenced objects from Heap so that allocates more memory for new objects.

JDK Architecture & API’s Details

In this figure, you will get an idea of how these libraries and API’s are distributed on different levels.

JDK APIs Architecture

Difference between API and Methods

API (Application Programming Interface) interfaces that the rest of the world sees and can use. A Method can be part of the public interface or not. But an API executes a set of methods.

In java, APIs provide through the interface which is really a set of public methods. An API has contract like tells about method signatures and return type.

For Example List API’s provide different method signature and expected result as return type so that you can use according to your convenience.

Difference between JDK and SDK

JDK(Java Development Kit) is an extended subset of a SDK (Software Development Kit).

  • JDK includes tools for developing, debugging and monitoring of Java Program. It mainly responsible for the writing and running of Java programs.
  • SDK is composed of extra software related to a Web application or mobile application etc. such as Application Server, Documentation, Debuggers, Code Samples, Tutorials, GlassFish server, MySQL and IDE Netbeans.

Now, Oracle strongly suggests using the term JDK to refer to the Java SE Development Kit. The Java EE SDK is now available with or without the JDK, by which they specifically mean the Java SE 7 JDK.

See Also: Java Versions History

 

Java: final Vs finally Vs finalize


Here is a list of key differences between final, finally and finalize:

final

  • final is keyword
  • final is use with class, method, and variables
  • A final class can not be instantiated.
  • A final method can not be overridden.
  • A final variable can not be re-assigned.

final Example

A final variable can not be re-assigned.

final variable example
Final Variable can be reassigned

A final class can not be subclassed.

Final Class Example
Final class can not be subclassed

A final method can not be overridden.

Final method Example
final method can not be overloaded

finally

  • finally is keyword
  • finally block is used in exception handling that follows try block.
  • finally block of code always executes, whether an exception occurred or not. It’s used to run clean-type resources.
  • After java 7+ by using try-resources with files make finally as optional.

finally Example

In this example, you will see finally block executes, whether an exception occurred or not.

public class TesFinally {
   public static void main(String[] args) {

      try{
         int a = 20;
         int b = 0;
         int result = a/b;
      }catch(Exception e){
         System.out.println("Exception occured: "+ e.getMessage());
      }
      finally{
         System.out.println("Finally Exceuted.");
      }
   }
}

Output


Exception occured: / by zero
Finally Executed.

finalize

  • finalize is an object class method
  • finalize() method is called just before the object is destroyed or garbage collected.
  • finalize() method is used to clean up object resources before destroy.
  • If finalize() method call Explicitly, then it will be executed just like a normal method but the object won’t be deleted/destroyed.

See Also: Java: Garbage Collection Finalize() Method Example And Uses

finalize Example

In this example first calling finalize() method manually by test object which will behave as a normal method. For checking how Garbage collector call finalize() method setting test as null make object as unreferenced to make eligible for garbage collection. Here calling System.gc() to request JVM to call the garbage collector method. Now it’s up to JVM to call Garbage Collector or not. Usually, JVM calls Garbage Collector when there is not enough space available in the Heap area or when the memory is low.

public class FinalizeMethodTest {

    public static void main(String[] args) {
        FinalizeMethodTest test=new FinalizeMethodTest();
        //manually calling finalize method is call like normal method
        test.finalize();

        //unreferenced object to make eligible for garbage collector
        test=null;

        //Requesting JVM to call Garbage Collector method
        System.gc();

        System.out.println("Main Method Completed !!");
    }
    @Override
     public void finalize()
        {
            System.out.println("finalize method overriden");
        }
}

Output


finalize method overriden
Main Method Completed !!
finalize method overriden

Here finalize() method calls two times one for manually another by garbage collector for cleaning up this test object.

 

Java: do-while loop


The Java do-while loop is a control flow statement, used to iterate a part of the program several times. this loop is preferred when the number of iteration is not fixed and you must have to execute the loop at least once.

In the do-while loop, statements inside will be executed at least once because the condition is checked after the loop body.

See Also: Java: Types of Looping Statements

Syntax:


do{  
//code to be executed  
}while(condition); 

Flow chart of do-while loop

do while loop flow chart

Example: Prints Even numbers between 1 to 20.

The same example writes in for and while loop also in a different way.

public class DoWhileLoopExample {
    public static void main(String[] args) {
    int i=1;
    System.out.println("Even numbers between 1 to 20:");
    do{
      if(i%2==0)
      {
      // If modulus of number after devision 2 is 0 then even number
      System.out.println(i);
       }
      i++;
      while(i<=20);
}
}

Output:


Even nmbers between 1 to 20 :
2
4
6
8
10
12
14
16
18
20

Java Infinitive do-while Loop

If you pass true or condition satisfied always as true in the do-while loop, it will be execute infinitive times.

Syntax:


do{  
//code to be executed  
}while(true);

Example: do-while infinite loop

public class DoWhileInfiniteLoopExample {
public static void main(String[] args) {
    do{
        System.out.println("FacingissuesOnIT");
    }while(true);
}
}

Output:


FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
.................
..............
............

ctrl+c

Note: Use press ctrl+c to exit from the program otherwise that will continue the print “FacingIssuesOnIT” statement.

Java: while loop


The Java while loop is a control flow statement, used to iterate a part of the program several times. It preferred when the number of iteration is not fixed.

See Also: Java: Types of Looping Statements

Syntax:


while(condition){  
//code to be executed  
}

Flow chart for while loop

while loop flow chart

Example: Print even numbers between 1 to 20.

This is the same example written in for loop also in the previous post.

class WhileLoopExample {
public static void main(String[] args) {
   System.out.println("Even Numbers between 1 to 20 :");
   int i=1;
   while(i<=20){
     // If modulus of number after devision 2 is 0 then even number
     if (i % 2 == 0) {
            System.out.println(i);
       }
      i++;
     }
   }
}

Output:


Even Numbers between 1 to 20 :
2
4
6
8
10
12
14
16
18
20

Java Infinitive While Loop

If you pass true or condition satisfied always as true in the while loop, it will be execute infinitive times.

Syntax:


while(true){  
//code to be executed  
}  

Example: while infinite loop

public class WhileExample2 {
public static void main(String[] args) {
    while(true){
        System.out.println("FacingIssuesOnIT”);
    }
}
}

Output:


FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
.................
..............
............

ctrl+c

Note: Use press ctrl+c to exit from the program otherwise that will continue the print “FacingIssuesOnIT” statement.

Java : for loop


The for loop in Java is a control flow statement used to iterate a part of the program several times. It’s most preferred when the number of the iteration is fixed.

In for loop are used in three ways :

  1. Simple For Loop
  2. Enhanced For Loop or For-each
  3. Labeled For Loop

Java Simple For Loop

In java, simple for loop is the same as C/C++. It consists of four parts:

Syntax


for(initialization;condition;increment/decrement){  
// code to be executed 
}
  • Initialization (Optional): It is the initialization condition which is executed once when the loop starts. We can initialize the variable or use an already initialized variable.
  • Condition (Optional): It is executed each time to test the condition of the loop. It return boolean values true or false but continues execution depend on until the condition is true.
  • Statement: The statement inside the loop is executed each time until the second condition is false.
  • Increment/Decrement (Optional): It increments or decrements the intialization variable value.

For Loop Flow Chart

for loop flow chart

Example:

Program to print even numbers between 1 to 20

public class SimpleForLoopExample {

	public static void main(String[] args) {
		System.out.println("Even Numbers between 1 to 20 :");
		for (int i = 1; i <= 20; i++) {
			// If modulus of number after devision 2 is 0 then even number
			if (i % 2 == 0) {
				System.out.println(i);
			}
		}
	}
}

Output


Even Numbers between 1 to 20 :
2
4
6
8
10
12
14
16
18
20

Java Nested For Loop

If we have a loop inside a loop that is called as nested loop. For each iteration of outer loop inner loop executes completely.

Example:
Print table for 1 to 10

public class NestedForLoop {

	public static void main(String[] args) {
     for(int i=1;i<=10;i++)
     {
    	 for(int j=1;j<=10;j++)
    	 {
    		System.out.printf("%-3d",(i*j)) ;
    	 }
    	 System.out.println();
     }

	}
}

Output:


1  2  3  4  5  6  7  8  9  10 
2  4  6  8  10 12 14 16 18 20 
3  6  9  12 15 18 21 24 27 30 
4  8  12 16 20 24 28 32 36 40 
5  10 15 20 25 30 35 40 45 50 
6  12 18 24 30 36 42 48 54 60 
7  14 21 28 35 42 49 56 63 70 
8  16 24 32 40 48 56 64 72 80 
9  18 27 36 45 54 63 72 81 90 
10 20 30 40 50 60 70 80 90 100

Java for-each Loop (Java 5+)

The for-each loop is used to traverse object type like array or collection. Java for-each loop is easier than simple for loop because not required to increase or decrese indexes for accessing collections values.

Java for-each loop works on elements basis not index and returns element one by one in the defined variable.

Syntax:


for(Type var:array){  
//code to be executed  
}

Example:

public class ForEachLoopExample {
public static void main(String[] args) {
    //Declaring an array
    int numArr[]={10,20,30,40,50};
    //Print array by using for-each loop
    for(int i:numArr){
        System.out.println(i);
    }
}
}

Output

10
20
30
40
50

Java Labeled For Loop

By using labeled for loop can define a name of loop by using label before the for loop. It’s useful when nested for loop need to break/continue specific for loop.

Usually, break and continue keywords breaks/continues the innermost for loop only.

Syntax:


labelname:  
for(initialization;condition;incr/decr){  
//code to be executed  
}  

Example:

public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}

Output:


1 1
1 2
1 3
2 1

If you use break bb;, it will break inner loop only which is the default behavior of any loop.

public class LabeledForExample2 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
}
}

Output:


1 1
1 2
1 3
2 1
3 1
3 2
3 3

Java Infinitive For Loop

If you use two semicolons ;; in the for loop, it will be infinitive for loop.

Syntax:


for(;;){
//code to be executed
}

Example:

//Java program to demonstrate the use of infinite for loop
//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println("infinitive loop");
}
}
}

Output:


infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
Now, you need to press ctrl+c to exit from the program.

Java: Program execution from Command Line and Eclipse with Arguments.


In the previous post First Java “Hello World” Program, you got some basic understanding for starting a Java Program. In this post, you will learn about to execute a Java Program from Eclipse and Commandline. Here consider both the case by passing with and without arguments to the main method().

Points to Remember

These are some points that need keep in mind while passing arguments from the eclipse or command line.

  • When you need to pass more than one argument. These values separated by spaces.
  • If passing an argument String value having space make sure to pass in the double quote (” “). For Example: “Saurabh Gupta”.
  • Always check for the length of  main() method argument otherwise you may get ArrayIndexOutOfBoundException if trying to access index beyond passed arguments.

Execute Java Program from Eclipse without Arguments

When your program not required any argument to pass in main() methods follow these steps to execute a program.

For Example :

public class TestProgram {

	public static void main(String[] args) {
		System.out.println("Hello World ! ");
	}
}

Output


Hellow World !
  • Step 1: Go to the Java Class file  “TestProgram”.java.
  • Step 2: Right-click on the file select option as  “Run As” -> “Java Application”.
  • Step 3: You will see the output in the console tab.

Execute Java Program from Eclipse with Arguments

When your program required arguments to pass in the main() method follow these steps to execute a program.

For Example:

In this program, main() method required three arguments to print for “First Name “, “Last Name ” and “Full Name”.

public class TestProgram {

	public static void main(String[] args) {
		System.out.println("Hello World ! ");

		System.out.println("Number of argument passed :"+args.length);
		//Check for number of argument passed from command line
		if (args != null && args.length == 3) {
			System.out.println("First Name :" + args[0]);
			System.out.println("Last Name :" + args[1]);
			System.out.println("Full Name :" + args[2]);
		}
	}
}

Output


Hello World ! 
Number of argument passed :3
First Name :Saurabh
Last Name :Gupta
Full Name :Saurabh Gupta
  • Step 1: Go to the Java Class file  “TestProgram”.java.
  • Step 2: Right-click on the file select option as  “Run As” -> “Run Configuration”.
  • Step 3: You will get pop up, Go to the “Arguments” tab pass arguments in the “Program Arguments” section as mentioned in the below screen for this example.
  • Step 4: Click on the Run Button.
  • Step 3: You will see the output in the console tab.

Eclipse Arguments Passing to java program

ss

ss

Java Program run from command line.jpg

 

 

ss

java program run commandline with argument

First Java “Hello World” Program


First Java “Hello World” Program

Here is the first Java program “Hello World” program for basic understanding about the Java Syntax and execution of a program.

public class HelloWorldFirstProgram {
    public static void main(String[] args) {
	    // Prints the string to the console.
        System.out.println("Hello World!");
    }
}

Output


Hello World !

See Also :

Explanation about each keyword

public: The keyword public is access modifier that denotes a method can be called from code in other classes, or that a class may be used by classes outside the class hierarchy.

static: The keyword static with method main() indicate a static method, which is associated with only class and not with the specific instance of the class. That can be called by class name.

void: The keyword void indicates that the main method does not return any value to the caller.
main method: The main method is a java launcher method, that is used to call by JVM to pass control to the program for execution.

See Also :

System.out.println

System.out.println is one of the most frequent statements used by java programmers for debugging purpose and prints logs in the console.

  • The System is the class defined public
  • Out is the public static object of System class of type PrintStream.
  • println() is a method of PrintSteam class as String.

See Also: Java: System.out Vs System.in Vs System.err classes and methods.

 

Java: System.out Vs System.in Vs System.err classes and methods.


The java.lang.System class, having three static members (in, out and err) that pre-initialize at JVM startup that’s what no need to initialize. These classes also known as Stream classes.

Out of these System.out is most frequent use by programmers to write output on the console.

System Stream Classes

Here is a list of System Stream classes objects:

  • System.in
  • System.out
  • System.err

System.in

System.in is an InputStream type object which is typically connected to the keyboard input of console programs.

Note: It’s generally used often, Mainly used by beginner-level programmers to insert input from the keyboard. Because when you consider for application-level data is commonly passed to program by:

  • Command-line arguments
  • Configuration files
  • Application GUI

See Also:

System.out

System.out is a PrintStream type used to outputs the data to the console.

Note: It’s the most frequent used Stream object to print out of the program and for debugging about the flow and values.

System.err

System.err is a PrintStream type mainly used to output an error texts to console.

Note: Some of IDE like eclipse show System.err output in the console in red color so that you can easily see error messages.

Example for System .in, System.out and System.err

In this example, you will see, How to insert value to a program by the keyboard by System.in. Output to console by System.out and for any error print by System.err.

System in out and Err Example
Example System.in, System.out and System.err

Output

System in out err result

Exchanging System Streams

By default System Stream class is to console, but we can also change System Streams by programmatical configuration for each type so that InputStream for System.in or OutputStream for System.out or System.err will read and write to the new stream.

  • System.setIn() : This method use to change input stream.
  • System.setOut() : This method use to change output stream.
  • System.setErr() : This method use to change error output stream.

See Also:

System.out Stream Change

In the below example, out will be got to the given file instead of default OutputStream as Console.

OutputStream output = new FileOutputStream("c:\\output\\FacingIssuesOnIT_logs.txt");
PrintStream printOut = new PrintStream(output);

//This method will change output stream.
System.setOut(printOut);

Java : Types of Statements


A java method body is a series of one or more statements. In a java programming language, a statement is a basic unit of execution which follows the syntax of the language and includes one or more clauses.

Note: All statements except blocks terminated by a semicolon(;).

Type of Java Statements

Java supports three different types of statements:

Blocks

A block is a series of zero or more statements between a matching set of open and close curly braces.  For example :

  • The bodies of methods and switch statements are blocks.
  • The bodies of if, for, while, and do-while statements may also be blocks.
  • You can also simply create a new block inside another block by enclosing code within curly braces. A block contained within another block is itself a statement of the outer block.
  • Blocks that contain no statements are called an empty block.

Example of Statements

At the high level below are some examples of statements. You can get more detail about each type of statement in the corresponding link.

Java Block and Types of Statements
Java Block and Types of Statements

References

 

Java : Control Flow Statements


Statements in java source code generally executed from top to bottom, in the order they appear. However, with control-flow statements, that order can be interrupted to implement decision making, branching or looping so that the Java program can run particular blocks of code based on certain conditions. Control flow statements categorize as below:

See Also: Type of Statements in Java

Java : Looping Statements


Programming language loops are control flow statements used when need to execute a set of instructions repeatedly when some conditions become true. There are three types of loops in java.

for loop

The for loop is used to iterates a part of the programs multiple times. It’s most preferred to use when the number of iteration is fixed.

For Detail Information follow: Java: for loop

Syntax


for(initialization;condition;increment/decrement){  
// code to be executed 
}

Example

//for loop
for(int i=1; i<=15; i++){
System.out.println(i);
}

The syntax for infinitive loop

for(;;){
//code to be executed
}

while loop

The while loop is used to executes a part of the programs repeatedly on the basis of given boolean condition. It’s most preferred when the number of the iteration is not fixed.

For Detail Information follow: Java: while loop

Syntax


while(condition){  
//code to be executed 
}

Example

//while loop
int i=1;
while(i<=10){
System.out.println(i);
i++;
}

The syntax for infinitive loop

while(true){
//code to be executed
}

do-while loop

The do-while loop is used to executes a part of the programs at least once and the further execution depends upon the given boolean condition. It’s preferred when the number of iteration is not fixed and you must have to execute the loop at least once.

For Detail Information follow: Java: do-while loop

Syntax

     
do{  
//code to be executed  
}while(condition); 

Example

//do-while loop
int i=1;
do{
System.out.println(i);
i++;
}while(i<=15);

The syntax for infinitive loop

do{
//code to be executed
}while(true);

Setup Java/JDK and Eclipse On Window & Linux


Before creating the Java project, the first thing is to check to JDK installed or not in your machine.

How to check Java version in your machine?

Window

  • Go to search
  • Type cmd and enter or search for Command prompt
  • You will see a black screen for the command prompt as below.
  • Type java -version to get detail about it.

Linux

  • On the current screen type command as java -version to get detail about it.

Java Version Check.jpg

The above screen is for the case when java is installed on your screen. If JDK/JRE is not installed on your machine then you will get a message like “Java is not recognized as an internal-external command.”

How to setup Java from Initial?

If JDK/JRE is not set up in your machine then follow below steps:

Download JDK from this siteDownload JDK Latest Version

Windows

  • After downloading click on the .exe file to install
  • Follow all steps as the next button and continue as long as a process not complete.
  • Default download location for Java will be  “C:\Program Files\Java\jdkVerXYZ”

Java JDK Directory

To access Java from command prompts or IDE need to configure environment variables as JAVA_HOME and Path. The value of JAVA_HOME would be home directory path where JDK installed and Path would be (JAVA_HOME/bin)

Follow these steps to configure the environment variables

  • Go to Computer ->right click-> Properties -> Advance System Settings->System Variable
  • or Go to search type ENV and click on enter.
  • Enter that value of JAVA_HOME as below
Java_Home
Set JAVA_HOME

 

 

 

 

  • Set the Path by appending at last as below %JAVA_HOME%/bin;

Java Path Settings

  • Follow the above steps to check Java versions.

Linux 

  • Download JDK and untar it.
  • Go to your home directory/ sudo directory and set JAVA_HOME and Path in .bashrc file as below:

export JAVA_HOME=/opt/app/<installation directory>/jdk1.8.0_66

          export Path=%JAVA_HOME%/bin:$Path

  •   Save .bashrc file
  •  Now run java -version  to check configuration is successful.

Configure Eclipse IDE

Download Eclipse: Download Eclipse Latest Version

  • Click on the installable of Eclipse IDE.
  • Continue the installation by next click.
  • Select the path of JDK as installed.
  • Select the workspace location for your projects.

Now you are ready to create new projects in Eclipse IDE.

See Also :

Java: How to generate Java doc by command line and Eclipse IDE?


In the previous post, you learn about the type of comments supported by Java. Now in this post will explain the ways to generate Java documentation of project by both ways:

  1. Java Doc by Eclipse
  2. Java Doc from Commandline

Now we will continue with the same previous comments file example to generate java documents by both ways:

Java Comments Type

Java Doc generation from Eclipse

Follow the below steps to generate Java API documentation:

  • Go to Project tab
  • Select the option “Generate Javadoc”
  • Follow steps in the screen as below:
  • Click on Next button
  • Click on Next button again
  • Finally, click on Finish button

java Doc generation in eclipse 1.jpg

In your console logs will see a link like as below to java doc of file.

D:\Saurabh Gupta\Workspace-learning\JavaExamples\doc\com\common\statements\CalculatorTest.html

Open this file you will see java doc comments on class and method level of this file as highlighted:

Java doc generation eclipse 2

Java Doc generation from Command-line

To generate Java doc from command-line you can use the below command.  It will generate Java doc file in your user directory (default) on below location:

C:/Users/username/CalculatorTest.html


javadoc you_java_file_path

You can use javadoc command as below.

Java doc generation from commnad line

Here are some of the scenarios to generate java doc:

Java doc on a specific location from the package

You can use below command to generate Javadoc for all files with the package from the projects folder:

Syntax:


C:\myprojects> javadoc -d [path to javadoc destination directory] [package name]

Example:


C:\myprojects> javadoc -d C:\javadoc\test com.fiot.test

Java doc generation execution from some other location

You can use the below command when you need to generate java docs and want to run the script from a different location.

Syntax:


C:\> javadoc -d [path to javadoc destination directory] -sourcepath [path to package directory] [package name]

Example:


C:\> javadoc -d C:\javadoc\test -sourcepath C:\myprojects com.fiot.test

Java doc generation for selected files

You can use the below command when you need to generate Javadoc for specific files then you can mentioned files path separated by spaces (or use an asterisk(*) for a wild card).

Syntax:


C:\> javadoc -d [path to javadoc destination directory] 

Example:


C:\> javadoc -d C:\javadoc\test C:\projects\com\test\file1.java

If you need to generate Javadoc from the same folder use wildcard(*) and mentioned in the given example.

Example:


E:\MyJavaFileFolder> javadoc *.java

References

https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html

Java Script : Debugging


In JavaScript debugging can be performed in two ways:

  1. Generating Alerts
  2. Printing in Console

Generating Alerts

By generating alerts in javascript you can check what values are getting the pass, which method is getting executed etc . on the page popup.


var a= 5;

alert(a);

alert("Hello world !!");

When you load you page you will get alert like this:
Java script debug alert

Note : After you testing complete you have to remove these alert statment otherwise duw to lots of alerts, end user will frustrate and that would be bad experience to user.

Printing in Console

For printing console logs help to analyse the execution of statement and values so that how flow got executed.

Syntax :


console.log(statement or text or variable);

Example


  

console.log("Hello World !"); 


For checking debug logs of your page: Press Cntr + F12 function key to you open browser screen then go to console as in below screen.

Java script debug

Java : Types of Comments


Java comments are used to provide information or description about the class, statements, variable and method for future reference so that easy to understand code for future enhancement. Java comments statements don’t compile. It also helps to hide unused code.

Types of Java Comments

Java supports 3 types of comments statments:

  1. Single Line Comment
  2. Multi line Comment
  3. Documentation Comment
Java Comments Type
Java : Types of Comments

Single Line Comment

Single line comment statement is use to comment single line.


//Single line commnet statement

Multi Line Comment

Multi line comment statement is use to comment multiple line.


/*Multi line 
 *commnet statement
 */

Documentation Comment

The documentation comment statement is used to create documentation of APIs. To generate documentation of API, you need to use the Javadoc tool.


/**
 *Multi line 
 *Java doc
 *commnet statement
 */
 

See Also: How to generate Java doc by command line and Eclipse IDE

Comments Type Example

In this Calculator example all types of comments.

 /**
 * This is a calculator class to perform
 * mathematical operations
 * @author saurabh.gupta1
 *
 */
public class CalculatorTest {

public static void main(String[] args) {

CalculatorTest calculator=new CalculatorTest();
//Calling add method to get sum of
int sum=calculator.add(10, 20);

/*
* This is System method to
* debug logs statement in console
*/
System.out.println("Sum of A =10 and B=20 is "+sum);
}
/**
* This method add passing values
* and return sum
* @param a
* @param b
* @return
*/
public int add(int a, int b)
{
return a+b;
}
}
 

Output


 Sum of A =10 and B=20 is 30
 

Java : Object Creation Way


In java objects can be created by five ways as follows:

  1. Object Creation by new
  2. Object Creation by reflection Class.newInstance() method.
  3. Object Creation by clone() method
  4. Object creation by the Annonymous Object.
  5. Object Creation by  Deserialization

Object Creation Way Example

Here is a complete example after considering all ways for object creations:

ackage objects;

import java.io.Serializable;

//Cloneable and Serializable is marker interface
public class Calculation implements Cloneable, Serializable{
	public int x=5;
	void fact(int n) {
		int fact = 1;
		for (int i = 1; i <= n; i++) {
			fact = fact * i;
		}
		System.out.println("factorial is " + fact);
	}
	public Object clone()throws CloneNotSupportedException{
		return super.clone();
		} 

}

package objects;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectCreationWay {

	public static void main(String[] args) {
		System.out.println("Object Creation by New");
		// Object Creation by using New
		Calculation cal = new Calculation();
		cal.fact(3);

		System.out.println("\nObject Creation by Reflection");
		// Object creation by newInstance method by reflection
		try {
			Class calculationClass = Class
					.forName("objects.Calculation");
			Calculation calc = (Calculation) calculationClass.newInstance();
			calc.fact(5);
		} catch (ClassNotFoundException |IllegalAccessException |InstantiationException ex) {
			ex.printStackTrace();
			//Multiple exception in single catch example in java  7
		} 

		System.out.println("\nObject Creation by Clone");
		/**
		 * Object creation by clone
		 */
		try {
			System.out.println(cal.x);
			Calculation cal2 = (Calculation) cal.clone();
			System.out.println(cal2.x);
			cal.x=10;
			//No change on clone object
			System.out.println(cal2.x);
		} catch (CloneNotSupportedException ex) {
			ex.printStackTrace();
		}

		System.out.println("\nObject Creation by Annonymous");
		/**
		 * Annonymous simply means nameless.An object that have no reference is
		 * known as annonymous object. If you have to use an object only once,
		 * annonymous object is a good approach.
		 */
		// calling method with annonymous object
		new Calculation().fact(5);

		System.out.println("\nObject Creation by  Deserialization");
		//By using deserialization of serialize object

		searializeObject(); //method to serialization of calculation object

		//By deserialization create object of Calculation Object

		Calculation c=deserializationOfObject();
		c.fact(5);

	}
	//serialize from java object to Object Stream
	public static void searializeObject()
	{
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(
					"calculator.ser");

			ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

			Calculation c= new Calculation();
			c.x=12;
			//serialization of object
			objectOutputStream.writeObject(c);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	//deserialization of objectStream to Java object
	public static Calculation deserializationOfObject()
	{

			Calculation c = null;

			try {
				FileInputStream fileInputStream = new FileInputStream("calculator.ser");

				ObjectInputStream objectInputStream = new ObjectInputStream(
						fileInputStream);

				c = (Calculation) objectInputStream.readObject();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {

				e.printStackTrace();
			}

			return c;
	}

}

Output


Object Creation by New
factorial is 6

Object Creation by Reflection
factorial is 120

Object Creation by Clone
5
5
5

Object Creation by Annonymous
factorial is 120

Object Creation by  Deserialization
factorial is 120