All posts by Saurabh Gupta

My Name is Saurabh Gupta, Done MCA from MMMEC Gorakhpur and having approx. 12 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.

Mask Zipcode/Pincode/Postal Code on Web Page


A lot of information that you share freely, such as your date of birth, phone number, ZIP code and email address, are very valuable to criminals. Think of how many accounts require you to verify your identity by entering in your birthday or your ZIP code before making a transaction.

Alone, your ZIP code might not be of much value all by itself, but criminals will take that information and post it on underground sites where they buy, sell and trade bunches of personal information. From those sites, criminals can purchase enough of your personal information to use it for fraud

See Also :

CVV Masking Example

Here considering, Pincode of length 5 digits. By masking will hide all 5 digits. For example, my pincode is 75038 than after mask will display as XXXXX. Pincode for some card can also be as six digit take this as assignment and make code changes accordingly so that support for both five and six digits.

original zipcode masked zipcode

Note :

This masking example is created considering standard length of text size and formatting of text field, that can vary according to organizations. If your organization having different format and text size modify source code according to your need. If you are facing any issue drop a comments will try to connect as soon as possible.

Download Source code

To download the source code of this example, click on below given download link.

Mask Pincode

Drop me your questions in comments section.

References

Advertisements

Mask Passport On Web Page


The passport serves as proof of your identity and your nationality which itself can be advantageous depending on your destination. As such, you should prioritize its security above all else when you travel overseas.

See Also :

Consequences of Passport Number Identity Theft

Under no circumstances should you disclose any sensitive information regarding yourself, passport number included. It may just be a jumble of digits but it’s a very valuable commodity for criminals if they even get their hands on it.
There are lots of consequences of passport identity theft as below:

  • A criminal could easily manufacture a passport with passport number, full legal name , date of birth and another person’s picture on it. This may not get them into the US (easily) but it could conceivable get them to a country nearby and then from there they could travel to the US or travel on others countries.
  • Criminal all over the world can use others stolen passport to commit a crime or do anything on others name.
  • The passport is use as an identity official documents if you don’t have driving license. Think about if someone using fraud passport and make some accident on road.
  • The fraud passport with your personal information full legal name, date of birth (available in facebook) , another person picture and address used to impersonate you. This fraud passport can be used as identity proof to open and access your credit / debit cards, social security, email, medical records, your character, your tax records.
  • A lot of passports have a chip too, which stores all your personal data.

Passport Masking Example

Here considering, Passport of length 8 digits. By masking will hide initial 4 digits. For example, my passport number is A1234765 than after mask will display as XXXX4765. Passport for some card can also be vary as per county take this as assignment and make code changes accordingly so that support for both 8 and more digits.

Original passport mask passport

Note :
This masking example is created considering standard length of text size and formatting of text field, that can vary according to organizations. If your organization having different format and text size modify source code according to your need. If you are facing any issue drop a comments will try to connect as soon as possible.

Download Source code


To download the source code of this example, click on below given download link.

Mask Passport

Drop me your questions in comments section.

References

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: HashCode and Equals Contract


In Java java.lang.Object is the superclass of all the classes provides two very important methods :

public boolean equals(Object obj)
public int hashCode()

See Also:

Internally these methods are used when need to check equality of objects but developer implementation prospects mainly used when need to implement HashMap because on that time developers have to implement these methods inside your User Defined class. Lot’s of the time when the developer is not aware of the contract of hashcode() and equals() method they make mistake and not received expected results from HashMap. Before going to detail of hashcode() and equals() contract, Let’s discuss first the problems.

Most Common Problem

In this example,  green and red car object is stored successfully in a HashMap, but when the map is asked to retrieve this green car object, the car object is not found in map and returning as null.

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

public class Car {
	private String color;

	public Car(String color) {
		this.color = color;
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof Car))
			return false;
		if (obj == this)
			return true;
		return this.color.equals(((Car) obj).color);
	}
	public static void main(String[] args) {
		Car a1 = new Car("green");//hashcode
		Car a2 = new Car("red");

		// HashMap stores car type and its quantity
		Map m = new HashMap();
		m.put(a1, 10);
		m.put(a2, 20);
		//hashcode diffrent from previos green object consider different object
		System.out.println(m.get(new Car("green")));
	}
}
         

Output

null

The above program prints as null. However, we can check that this car object is stored in the map by inspecting in the debugger:

Java hashCode and Equals Contract

In the above program problem is hashcode() method was not implemented.

Before going to the solution to this problem in detail. We need to understand the equals() and hashcode() method contract.

hashcode() and equals() Method Contract

The contract between equals() and hasCode() is that:

  1.  If two objects are equal, then they must have the same hash code value.
  2.  If two objects have the same hashcode value, they may or may not be equal.

The main idea is Map worked on hashing techniques to find an object faster in comparison to linear search. In this case, because the hashcode() method is no implemented. It will call by default method of object class i.e return different hashcode value for different objects. In this above case both the objects store in HashMap and retrieving will have different hashcode values.

See Also: Java: Hashmap Working

In HashMap, store values in form array of buckets of the object where these array having hashcode value while objects having objects that match with the same hashcode. For example, the Hash Code is like a sequence of boxes for storage where different kinds of stuff can be stored in different boxes. It is more efficient if you organize stuff to a different place instead of the same garage. So it’s a good practice to keep kinds of stuff on related boxes i.e equally distribute the hashCode value.

The solution is to add hashCode() method to the Car class. Here we are getting hash value based on the size of color length as implemented below.

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

public class Car {
	private String color;

	public Car(String color) {
		this.color = color;
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof Car))
			return false;
		if (obj == this)
			return true;
		return this.color.equals(((Car) obj).color);
	}

	public int hashCode(){
		return this.color.length();
}
	public static void main(String[] args) {
		Car a1 = new Car("green");//hashcode
		Car a2 = new Car("red");

		// HashMap stores car type and its quantity
		Map m = new HashMap();
		m.put(a1, 10);
		m.put(a2, 20);
		//hashcode different from previous green object consider different object
		System.out.println(m.get(new Car("green")));
	}

}

Output

10

Java: Aggregation and Composition (HAS-A)


Pre-requisite: Java: OOPS Concepts, Java: Class, Java: Object

If objects are having an association as “HAS-A” then there could be two types of relationship between objects:

  1. Aggregation
  2. Composition

Aggregation

Aggregation is a special type of association where objects have their independent life cycle but there is ownership. These owners and associate objects have the “HAS-A” relationship.

For Example, A person may associate with an Organization but he/she has an independent existence in the world.

Benefits of Aggregation

  • Aggregation provides reusability.

Note: For code reusability, if classes having IS-A relationship use Inheritance and for Has-A relationship use Aggregation.

Example of Aggregation

Here Employee class is associated with address class with Aggregation (HAS-A) relationship. Employee class contained an object of Address, this address object contains its own information like city, state, country, etc. Both of these objects are not strongly associate because if employee looses their jobs but still have the same address.

public class Address {
	String city, state, country;

	public Address(String city, String state, String country) {
		this.city = city;
		this.state = state;
		this.country = country;
	}

}

 

 

public class Employee {
	int id;
	String name;
	Address address;

	public Employee(int id, String name, Address address) {
		this.id = id;
		this.name = name;
		this.address = address;
	}

	void display() {
		System.out.println(id + " " + name);
		System.out.println(address.city + " " + address.state + " " + address.country);
	}

	public static void main(String[] args) {
		Address address1 = new Address("Noida", "UP", "India");
		Address address2 = new Address("Greater Noida", "UP", "India");

		Employee e = new Employee(101, "Saurabh", address1);
		Employee e2 = new Employee(102, "Gaurav", address2);

		e.display();
		e2.display();

	}
}

Composition

The composition is special type of aggregation where one object is strongly associated with another object and more restrictive. When the contained object in “HAS-A” and one object can not exist without the existence of others it’s the case of composition.

For Example:

  • Wheels in a car.
  • House has a room. Here the room can’t exist without the house.
  • An employee has a job. A job can’t exist without an employee.

Benefits of Composition

  • The composition provides reusability.
  • The composition can control the visibility of another object and reuse only when needed.

Examples of Compositions
Here Person and Job class having a composition relationship. In this case, Job class creates at runtime whenever a new person comes and we can change the salary from backend without change on client-side.

public class Person {
	//composition has-a relationship
    private Job job;

    public Person(){
        this.job=new Job();
        job.setSalary(1000L);
    }
    public long getSalary() {
        return job.getSalary();
    }
}
public class Job {
	private String role;
    private long salary;
    private int id;

    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public long getSalary() {
        return salary;
    }
    public void setSalary(long salary) {
        this.salary = salary;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

}
public class TestComposition {

	public static void main(String[] args) {
		Person person = new Person();
		long salary = person.getSalary();

	}

}

Examples of Compositions & Aggregation
Let’s have an example of a University, it’s department and professors associated with departments.

University & Department Association: It’s a composition association because without University will exist in any department.
Department and Professors Association: It’s aggregate association because both are associated but not having any dependency like if department close professor lose. Both are are an independent entities.

import java.util.List;

public class University {
	 private List departments;

     public void destroy(){
         //it's composition, when i destroy a university I also
		 //destroy the departments. they cant live without university instance
         if(departments!=null)
             for(Department d : departments) d.destroy();
         departments.clear();
         departments = null;
     }

}
public class Department {
	private List professors;
    private University university;

    Department(University univ){
        this.university = univ;
        //check here univ not null throw whatever depending on your needs
    }

    public void destroy(){
        //It's aggregation here, if we fire any professor then they
		//will come out of department but they can still keep living
        for(Professor p:professors)
            p.fire(this);
        professors.clear();
        professors = null;
    }

}
public class Professor {
	 private String name;
     private List attachedDepartments;

     public void destroy(){

     }

     public void fire(Department d){
         attachedDepartments.remove(d);
     }
}

Java: Inheritance (IS-A)


Pre-requisite: Java: OOPS Concepts, Java: Class, Java: Object

Inheritance is a process where child class acquired all the properties and behaviors of the parent class. Inheritance is used when one object is based on another object. Here parent class also called a superclass and child class called a subclass.

For Example,  Person is Parent class and Employee is a subclass of Person. which acquired all the properties and behavior of Person class.

Advantage of inheritance

What is code Reusability in Inheritance?

Inheritance facilitates to reuse the fields and methods of the parent class in child class syntax of Java Inheritance.

Syntax of Inheritance Declaration

class Subclass-name extends Superclass-name  
{  
   //fields 
   //methods   
}

In java, extends keyword is used to inherit a class where a new class derived properties and methods of an existing class. The class that inherited is called a Parent/Superclass, and a new derived class is called a child/subclass.

What You Can Do in a Subclass?

A subclass inherits all of the public and protected members(fields, methods and nested classes) of its parent class, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the private members of the parent class.

Constructors are not members of the class, so they are not inherited by child class, but the constructor of the parent class can be invoked from the child class by using super.

These inherited members can use as-is, replace them, hide them, or supplement them with new members:

  • Parent class inherited fields  can be used directly, just like any other class field.
  • You can declare a field in the child class with the same name as the one in the parent class, thus hiding it (not recommended).
  • You can declare new fields in the child class that are not in the parent class.
  • The inherited parent class methods can be used directly as they are.
  • You can write a methods in child class that has the same signature as the one in the parent class. i.e Method Overriding.
  • You can write a new static method in the child class with the same signature as on the parent class, thus hiding it.
  • You can declare new methods in the child class that are not in the parent class.
  • You can write a child class constructor that invokes the constructor of the parent class, either implicitly or by using the keyword super.

Example of Inheritance

In this example, Animal is a parent class which is extended by the Dog Child class. The animal class having properties name, breed, age and color. There is one method print() to print all these values. Dog subclass will inherit all these properties those having access modifiers as public and protected. Child class Dog print() method is calling parent class print() method by super keyword.

Java inheritance Example
Java Inheritance Example
//POJO Class
public class Animal {
	// private variables
	private String name;
	private String breed;
	private int age;
	private String color;

	// Getter and setter methods
	public Animal(String name, String breed, int age, String color) {
		this.name = name;
		this.breed = breed;
		this.age = age;
		this.color = color;
	}
    //Method of class
	public String print() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}
public class Dog extends Animal {
	private String type;

	public Dog(String name, String breed, int age, String color, String type) {
		// call super class constructor to initialize
		super(name, breed, age, color);
		this.type = type;
	}

	// Overriding method of parent class
	@Override
	public String print() {
		return "Dog [type=" + type + ", print()=" + super.print() + "]";
	}
}
public class TestInheritance {

	public static void main(String[] args) {

		 //Instance with Parameterize Constructor
	     Animal dog=new Animal("Tommy","Small Dog",5,"Black");
	     //calling super class method because reference to super class
	     System.out.println(dog.print());

	     Animal dog_tiny=new Dog("Tiny","Small Dog",4,"Black","Bichon Friese");
	     //calling super class method because reference to super class
	     System.out.println(dog_tiny.print());

	     Dog dog_big=new Dog("Tufan","Big Dog",4,"White","Spotted");
	     //calling sub class method because reference to sub class
	     System.out.println(dog_big.print());
	}
}

Output


Animal [name=Tommy, breed=Small Dog, age=5, color=Black]
Dog [type=Bichon Friese, print()=Animal [name=Tiny, breed=Small Dog, age=4, color=Black]]
Dog [type=Spotted, print()=Animal [name=Tufan, breed=Big Dog, age=4, color=White]]

Here from this output, you will see the print method called based on object not by references of the object.

Points about Inheritance

  • extends the keyword used to implement inheritance.
  • Java doesn’t support multiple inheritances. It’s possible by implementing multiple interfaces.
  • Inheritance has an “IS-A” relationship.
  • Excepting Object Class, which has no parent class, every class has one and only one direct parent class (single inheritance). In the absence of any other explicit parent class, every class is implicitly a child class of Object.

Type of Inheritance in Java

Java supports three types of inheritance only for classes:

  1. Single
  2. Multi-Level
  3. HierarchicalJava Types Of Inheritance

Note:

  • Multiple Inheritance is not supported in java through the class.
  • Multiple and Hybrid inheritance is supported in java through interface only.

Single Level Inheritance

As you have seen in the above example is a single level of inheritance.

Multi-Level Inheritance

class Animal{
void eat(){System.out.println("Animal eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("Dog barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("Baby Dog weeping...");}
}
class MultiLevelInheritanceTest{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output


Baby Dog Weepig...
Dog barking...
Animal eating...

Hierarchical Inheritance

class Animal{
void eat(){System.out.println("Animal eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("Dog barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("Cat meowing...");}
}
class TestHierchicalInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//Compile Time Error
}}

Output


Cat meowing...
Animal eating...

Why multiple inheritance is not supported in java?

Java doen’t support multiple inheritance for class because of fixing ambiguity of common members like fields or method.

Suppose, we have three claases ClassA, ClassB and ClassC where ClassC extends ClassA and ClassB which are having common method display(). If you call display() method from child class then not sure which method got called because of ambiguity.
Since java not support multiple inheritance that’s why throgh compile time exception.

class ClassA{
void display(){System.out.println("Inside Class A");}
}
class ClassB{
void display(){System.out.println("Inside Class B");}
}
//Compile time issue issue here
class ClassC extends ClassA,ClassB{
 //suppose if it were
 public static void main(String args[]){
   ClassC obj=new ClassC();
   //Here it will through compile time issue
   obj.display();
}

 

Java: Constructors


In Java, Constructors are used to creating and initializing the object’s state. The constructor also contains collections of statements to execute at time object creation.

Type of Constructors:

  • Default Constructor: A Constructor without any argument.
  • Parameterize Constructor: A Constructor with a number of arguments.

Points to Remember for Constructor

  • Constructor always has the same name as the class name in which it exists.
  • Constructor can not be used with keywords final, abstract, synchronized and static.
  • Constructors declaration with access modifiers can be used to control its access i.e so that restricts other classes to call the constructor.
  • All java classes must have at least one constructor. If you do not explicitly declare any constructor, then on time of compile Java compiler will automatically provide a no-argument constructor i.e also called the default constructor.
  • If you declare any parameterize constructor then that is must write a default constructor.
  • This default constructor calls the parent’s class no-argument constructor i.e super(); or if no parent class extended the called constructor of Object Class i.e directly or indirectly parent class of all the class.

Example of Constructors

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    }
	//Parameterize constructor
	//Constructor Overriding
	public Animal(String name, String breed)
    {
        this.name = name;
        this.breed = breed;
    } 

}

Object Creation By Constructor

Here you will see both ways to create objects of Animal Class by using the default and parameterize constructors.

public TestClass
{
	public static void main(String[] args)
	{
	 //Instance Default Constructor
	 Animal dog_tommy=new Animal();

	 //Instance with Parameterize Constructor
     Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");
	}
}

Does the Constructor return any value?

A constructor doesn’t have return type while implementation, but the constructor returns the current instance of the class. We can write return statements inside the class.

Constructor Overloading

Similar to methods, we can overload constructors also by creating an object in many ways. Java compiler differentiates between these constructors based on signature (i.e numbers, type, and order of parameters).

What is Constructor Chaining?

Constructor chaining is the process of calling a constructor from another constructor for the current object.

Constructor chaining can be performed in two ways:

  • Within the same class: Use this() keyword for same class constructors.
  • From base class: Use super() keyword to call a base class constructor.

Rules of constructor chaining

  • The this() expression should always be the first line of statment in the constructor.
  • There should always be at least one constructor without this() keyword.
  • Constructor chaining can be performed in any order.

Constructor Chaining Example: Within Same Class

Use this() keyword for constructors in the same class. Here you will see the last constructor with two arguments calling the constructor with the keyword this() for four arguments.

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    }
	//Parameterize constructor
	//Constructor Overriding
	public Animal(String name, String breed)
    {
	   //constructor chaining
	    this(name,breed,1,"black");
    }
}

Constructor Chaining Example: From Base Class

Use super() keyword to call a constructor from the base class. Here Constructor chaining occurs through inheritance. A sub-class constructor’s call the super class’s constructor first so that sub class’s object starts with the initialization of the data members of the superclass. There could be multilevel of classes in the inheritance chain. Every subclass constructor calls up the chain till class at the top is reached.


public class Person{
    private String name;
    protected String citizenship;

    public Person()
    {
    }

    public Person(String name, String citizenship) {
        super();
        this.name = name;
        this.citizenship = citizenship;
    }

    public void print() {
		System.out.println("Citizen:"+ citizenship + ",Name:" + name);
	}

}

 

public class Employee extends Person {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen) {
			}

	public Employee(int employeeId, String name, String department, String citizen, int salary) {
		// super keyword use to call parent constructor
		//constructor chaining to parent class
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

}

What is the use of constructor chaining?

Constructor chaining is the mechanism to perform multiple tasks in a single constructor rather than creating a separate constructor for each task and make their chain. Constructor Chaining makes the program more readable.

Constructors Vs Methods

Constructor Method
Constructor(s) must have the same name as the class within which it defined. The method does not have the same name as the class in which defined.
Constructor(s) does not return any type. method(s) have the return type or void if does not return any value.
A constructor is called only once at the time of Object creation. Method(s) can be called any number of times.
In case constructor not present in class, the default constructor provided by the compiler. In the case of Method, the compiler doesn’t provide the default method.
Constructs invoked implicitly Methods invoked explicitly.

Java: Object


Pre-Requisite: Java:Class
In the previous post, you learn about the Java Class declaration, implementation, and types of classes. Here we will discuss Object which is the basic unit of Object-Oriented paradigm to represent real-life entities.

When an instance of a class is created is known as Object. These instances share attributes and behaviors i.e methods of the class. These values of attributes will be unique for each object i.e called state.

A java program may have lots of objects and these objects interact with each other by invoking methods. An object consists of :

  • Identity: It gives a unique name to the identification of an object and enables one object to interact with other objects.
  • State: It is represented by attributes/properties values of an object.
  • Behavior: It is represented by methods of an object to behave in a particular state.

Object Class

Let’s consider a class of Animal, which can have an object like Dog, Cow, Lion, Elephant, etc. Each of these animals has different properties like name, breed, age, and color.

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    } 

    //Instance methods
    public String getName()
    {
        return name;
    } 

    public String getBreed()
    {
        return breed;
    } 

    public int getAge()
    {
        return age;
    } 

    public String getColor()
    {
        return color;
    }
    //methods override from Object class
	@Override
	public String toString() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}

Example of an object: Dog

Declaration of Object

We declare a variable or object like (type variable_name;). This indicates to the compiler that this variable refers to data whose type is type. In the case of the primitive type, declaration allocates space for the variable as per type but in case of a reference variable, the type must be a concrete class name. Generally, In java, we don’t create an object of Abstract class and interface.

Syntax

access_modifier class_name object_name;

Example

Animal dog_tommy;

As declared above for variable dog_tommy, show this variable is of type Animal but this will not create any object instance i.e point to undetermined value (null) as long as an object not created.

Creation & Initializing an object

When we create an instance of an object by using the new operator. It will allocate memory for a new object and return a reference to that memory. This new operator also called the class constructor to initialize the attributes of the class.

Syntax

//default constructor
access_modifier class_name object_name=new class_name();
//parameterize constructor
access_modifier class_name object_name=new class_name(arg1,arg2..);

Example

//Default Constructor
Animal dog_tommy=new Animal();

//Parameterize Constructor
Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");

Note :

  • All classes have at least one constructor. If you do not explicitly declare any constructor, then on time of compile Java compiler will automatically provide a no-argument constructor i.e also called the default constructor.
  • If you declare any parameterize constructor then that is must write a default constructor.
  • This default constructor calls the parent’s class no-argument constructor i.e super(); or if no parent class extended the called constructor of Object Class i.e directly or indirectly parent class of all the class.

Complete Example

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    } 

    //Instance methods
    public String getName()
    {
        return name;
    } 

    public String getBreed()
    {
        return breed;
    } 

    public int getAge()
    {
        return age;
    } 

    public String getColor()
    {
        return color;
    }
    //methods override from Object class
	@Override
	public String toString() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}

public TestClass
{
	public static void main(String[] args)
	{
	 //Instance Default Constructor
	 Animal dog_tommy=new Animal();

	 //Instance with Parameterize Constructor
     Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");
	}
}

Output


Animal [name=Default, breed=null, age=0, color=null]
Animal [name=Tommy, breed=Small Dog, age=5, color=Black]

Ways to create an object of a class

This is the most common way to create an instance of an object by using new operators. Java also provides other ways to create instances of an object but internally uses a new keyword only.

  1. Object by new Operator
  2. Object by Class.forName().newInstance()
  3. Object by clone() method
  4. Object by Deserialization
  5. Object for Anonymous Class

Follow this link to know about each object creation ways in detail: Java: Object Creation Ways

 

Java: Type of Classes


Pre-Requisite: Java: Class
In a previous post, you have got an understanding of java class declaration and creation.

Types of classes

Java supports lots of types of classes:

  • Concrete Class
  • Abstract Class
  • POJO Class
  • Static Class
  • Nested Class/Inner Class
  • Final Class
  • Anonymous Class
  • Lambda Expression

Here we will discuss these classes in detail.

Concrete Class

A concrete class is a normal class that is not declared with Non-access modifiers as abstract, final, etc. This class can have an implementation of a parent, interfaces or own class methods.

Example: Concrete Class

//Example Concrete Class
public class CalculatorTest {
    static int add(int a , int b)
    {
    	return a+b;
    }
    static int substract(int a , int b)
    {
    	return a-b;
    }
    static int multiply(int a , int b)
    {
    	return a*b;
    }
    static int division(int a , int b)
    {
    	return a/b;
    }
	public static void main(String[] args) {
      System.out.println("4+5 ="+add(4,5));
      System.out.println("4-5 ="+substract(4,5));
      System.out.println("4*5 ="+multiply(4,5));
      System.out.println("4/5 ="+division(4,5));
	}
}

See Also: Java: Concrete Class Examples

Abstract Class

A class that is declared with the keyword abstract is known as an abstract class in Java. It can have abstract and concrete methods (method with the body). An abstract class can not be instantiated but need to extend to implement abstract methods.

Example: Abstract Class

args)
{
Vehicle v=new Car();
v.engine();
v=new Bike();
v.engine();
v=new Truck();
v.engine();
v=new Bus();
v.engine();
}
}

See Also: Java: Abstract Class Examples

POJO Class

A class with only private variables and public getter and setter methods is called as POJO(Plain Old Java Object) class. These getter and setter methods use private variables. This class is completely encapsulated.

Example: Pojo Class

//POJO Class
public class Animal {
	//private  variables
    private String name;
    private String breed;
    private int age;
    private String color;
    //Getter and setter methods
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getBreed() {
		return breed;
	}
	public void setBreed(String breed) {
		this.breed = breed;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
}

See Also: Java: Pojo Class Examples

Static Class

A static class is a nested class declared as a static member of the class.

Example: Static Class

import java.util.Scanner;

public class StaticClasses {
	static int s;// static variable

	// static method
	static void printSum(int a, int b) {
		s = a + b;
		System.out.println(a + "+" + b + "=" + s);
	}

	static class NestedStaticClass//static class
	{
		static//static block
		{
			System.out.println("Inside Nested Class Static Block");
		}

		public void display()
		{
			Scanner scanner=new Scanner(System.in);
			System.out.println("Enter value of a:");
			int a= scanner.nextInt();
			System.out.println("Enter value of b:");
			int b= scanner.nextInt();

			printSum(a,b);
			System.out.println("Sum of numbers a+b:" +s);

		}
	}
}

public class StaticClassTest {

	public static void main(String[] args) {
		StaticClasses.NestedStaticClass nss=new StaticClasses.NestedStaticClass();
		//call method of nested class method
		nss.display();
	}
}

See Also: Java: Static Keyword & Examples

Nested Class/Inner Class

A Class declared inside of another class is called Nested Class/Inner Class.

Example: Nested Class/Inner Class

public class OuterClass {

	//nested/Inner Class: Class inside the class
	class NestedClass
	{
		public void innerMethod()
		{
			System.out.println("Inner Class Print");
		}
	}

	public static void main(String[] args) {
		System.out.println("Outer Class Print");

	}

}

See Also: Java: Nested/Inner Class Examples

Final Class

A Class declared with the final keyword is known as Final Class. This class can not be extended by another class. For Example java.lang.System, java.lang.String

Example: Final Class

public final class FinalClass {
 public void display()
 {
	 System.out.println("Display final class method.");
 }
}

//show compiler error :
//"The type BaseClass can not subclass the final class FinalClass"
class BaseClass extends FinalClass{
	public void display()
	 {
		 System.out.println("Display base class method.");
	 }
}

See Also: Java: Final Keyword & Examples

Anonymous Inner Class

Anonymous Class is an inner class without a name and for which only a single object is created. Such class is useful when you need to create an instance of an object such as overloading methods of a class or interface, without having to actually subclass a class.

Anonymous inner classes are mostly used in writing implementation classes for listener interfaces in graphics programming.

Example: Anonymous Class

//Using Anonymous Inner class Thread that extends a Class
class MyThread
{
    public static void main(String[] args)
    {
        //Here we are using Anonymous Inner class
        //that extends a class i.e. Here a Thread class
        Thread t = new Thread()
        {
            public void run()
            {
                System.out.println("Child Thread");
            }
        };
        t.start();
        System.out.println("Main Thread");
    }
}

See Also: Java: Anonymous Class Examples

Lambda Expression

Lambda expressions added in Java 8. It useful to create instances of functional interfaces (An interface with single abstract method). For Example: java.lang.Runnable is having one abstract method as run().

Example: Lambda Expression

public class LamdaTest {
	public static void main(String[] args) {
		new Thread(() -> System.out.println("This is Lamda test")).start();
	}
}

See Also: Java: Lamda Expression Examples

 

Java: Class


A Class is a blueprint or prototype from which objects are created. A class has properties and behaviors i.e methods that are common to all objects of the same type.

Object Class

Syntax of Class Declaration


Access_Modfier Non_access_modiers class class_name 
    extends super_class 
    implements interface1, interface 2..
{
fields
......
default constructor
......
parametrize constructor
......
methods
......
}
  • Access Modifiers: A modifier defined access scope of class, fields, and methods. If specifically not mentioned consider as default. See Also: Java: Access Modifiers/Specifiers
  • Class name: The class name should begin with an initial capital letter follow camel notation. See Also: Java: Identifier Naming Conventions
  • Non-Access Modifiers (if any): non-access modifiers can also be used on the class level to make a class special. See Also: Java: Non-Access Modifiers
  • Superclass(if any): A class can extend only one class i.e called parent class or superclass.
  • Interfaces(if any): A class can implement one or more interfaces. Their interfaces proceed by keyword implements and separated by a comma.
  • Body: A class body is surrounded by curly braces, { }.
    Fields: A class fields are variables that provide the state of class and it’s objects.
  • Methods: class methods are defined to implement the behavior of class and objects. See Also: Java Methods
  • Constructors: Java class constructors are used to initialize new objects. See Also: Java: Constructors

Note:

  • If a class is declared with access modifier public then java file name would also be the same. One Java file can have only one public class.
  • All the class extends Object Class i.e Object class is the superclass of all the classes.See Also: Java: java.lang.Object Class & Methods

Java Class Example

This is a very simple example of a class name as Animal. It’s having variables, constructors, methods and overriding method of superclass Object.

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    } 

    //Instance methods
    public String getName()
    {
        return name;
    } 

    public String getBreed()
    {
        return breed;
    } 

    public int getAge()
    {
        return age;
    } 

    public String getColor()
    {
        return color;
    }
    //methods override from Object class
	@Override
	public String toString() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}

Now we have got a basic understanding of class declaration and implementation. In the further post, you will learn about the types of classes and uses.

Types of classes

Java supports lots of types of classes:

  • Concrete Class
  • Abstract Class
  • POJO Class
  • Static Class
  • Nested Class/Inner Class
  • Final Class
  • Anonymous Class
  • Lambda Expression

Follow this link to know about all these classes and uses.

See Also: Java: Type of classes

Java: StringBuilder Class & Examples


Java StringBuilder is used to create a mutable String object. It’s introduced in JDK 1.5. It’s similar to StringBuffer class the only difference is non-synchronized and no thread-safe.

See Also: String Vs StringBuffer Vs StringBuilder

Constructors of StringBuilder class

Constructor Description
StringBuilder() creates an empty string Builder with the default initial capacity of 16.
StringBuilder(String str) creates a string Builder with the given string.
StringBuilder(int length) creates an empty string Builder with the given capacity as length.

Methods of StringBuilder class

Method Description 
public StringBuilder append(String s) Append the specified string with current string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public StringBuilder insert(int offset, String s) Insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
public StringBuilder replace(int startIndex, int endIndex, String str) Replace the string from the specified startIndex and endIndex.
public StringBuilder delete(int startIndex, int endIndex) Delete the string from the specified startIndex and endIndex.
public StringBuilder reverse() Reverse the string.
public int capacity() Return the current capacity of String builder.
public void ensureCapacity(int minimumCapacity) Ensure the capacity at least equal to the given minimum then only increase capacity.
public char charAt(int index) Return the character at the specified index position.
public int length() return the total count of the characters in string.
public String substring(int startIndex) is used to return the substring from the specified startIndex.
public String substring(int startIndex, int endIndex) is used to return the substring from the specified startIndex and endIndex.

Example: StringBuilder append() method

Java StringBuilder append() method used to concatenates the given argument with this string.

StringBuilder sb=new StringBuilder("Facing Issues On ");
sb.append("IT");//Original String will change
System.out.println(sb);//new string "Facing Issues On IT"

Example: StringBuilder insert() method

Java StringBuilder insert() method used to insert the given string at the given position.

StringBuilder sb=new StringBuilder("Facing On IT");
sb.insert(6," Issues ");//insert string on 6th position
System.out.println(sb);//new string "Facing Issues On IT"

Example: StringBuilder replace() method

Java StringBuilder replace() method used to replaces the given string from the specified startIndex and endIndex.

StringBuilder sb=new StringBuilder("Facing Saurabh On IT");
sb.replace(7,14,"Issues");//replace saurabh with  issues
System.out.println(sb);//new string "Facing Issues On IT"

Example: StringBuilder delete() method

Java StringBuilder delete() method use to deletes the string from the specified startIndex to endIndex..

StringBuilder sb=new StringBuilder("Facing Saurabh On IT");
sb.delete(7,14);//delete saurabh
System.out.println(sb);//new string "Facing  On IT"

Example: StringBuilder reverse() method

Java StringBuilder reverse() method used to reverses the current string.

StringBuilder sb=new StringBuilder("Facing Saurabh On IT");
sb.reverse();
System.out.println(sb);//new string "TI no seussI gnicaF"

See Also: Java: Ways to reverse String

Example: StringBuilder capacity() method

Java StringBuilder capacity() method use to returns the current capacity of the Builder. The default capacity of the Builder is 16. If the number of the character increases from its current capacity, it increases the capacity by (oldcapacity2)+2. For example, Suppose your current capacity is 16, then the next capacity will be (162)+2=34.

StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Facing Issues On IT");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (old_capacity*2)+2
sb.append("Learn from Others Experinces");
System.out.println(sb.capacity()); //now (34*2)+2=70 i.e (old_capacity*2)+2

Example: StringBuilder ensureCapacity() method

Java StringBuilder ensureCapacity() method use to ensures that the given capacity is the minimum to the current capacity. If it is greater than the ensure capacity, it increases the capacity by (oldcapacity2)+2. For example, Suppose your current capacity is 16, then the next capacity will be (162)+2=34.

StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.ensureCapacity(40);//Now Capacity will increase when reach to 40
sb.append("Facing Issues On IT");
System.out.println(sb.capacity());//because of ensure capacity capacity will 40 only
sb.append("Learn from Others Experinces");
System.out.println(sb.capacity()); //now (40*2)+2=82 i.e (oldcapacity*2)+2

 

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:[]

How to reverse String in Java?


In java, we can reverse String in java by so many ways as given below:

  1. StringBuffer
  2. StringBuilder
  3. Character Iteration

Reverse String in Java: By StringBuffer

public class ReverseStringExample1 {
public static String reverseString(String str){
    StringBuffer sb=new StringBuffer(str);
//String buffer in-built method
			sb.reverse();
    return sb.toString();
}
}

Reverse String in Java: By StringBuilder

public class ReverseStringExample2 {
public static String reverseString(String str){
    StringBuilder sb=new StringBuilder(str);
	//String builder in-built method
			sb.reverse();
    return sb.toString();
}
}

Reverse String in Java: By Character Iteration

public class ReverseStringExample3 {
public static String reverseString(String str){
    char ch[]=str.toCharArray();
    String rev="";
    //run loop in reverse order for each character
    for(int i=ch.length-1;i>=0;i--){
        rev+=ch[i]; //append characters
    }
    return rev;
}
}

Complete Example: Reverse String In Java

Here consolidated all the ways to reverse String in Java.

public class TestStringInJava {
public static void main(String[] args) {
     System.out.println(ReverseStringExample1.reverseString("My Name is Saurabh."));
     System.out.println(ReverseStringExample2.reverseString("Facing Issues on IT"));
     System.out.println(ReverseStringExample3.reverseString("Learn From Others Experinces"));
    }
}
}

Output

.hbaruaS si emaN yM
TI no seussI gnicaF
secnirepxE srehtO morF nraeL

 

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: String Vs StringBuffer Vs StringBuilder


String in Java

A String class represents an array of characters.

String Instance Creation
String instance can be created in two ways:

  • By assigning as Literals
    String title = "Facing Issues On IT";
  • By using the new keyword
    String title = new ("Facing Issues On IT");

Points to Remember for Java String

  • The string class is immutable in Java, so it’s easy to share it across different threads or functions.
  • When you create a String using double quotes, it first looks for the String with the same value in the JVM string pool, if match found it returns the reference else it creates the String object and then places it in the JVM String pool. This way JVM saves a lot of space by using the same String in different threads. But if a new operator is used, it will always explicitly creates a new String in the heap memory.
  • + operator overloading is used to concatenating two strings. Although internally it uses StringBuffer to perform this action.
  • String overrides equals() and hashCode() methods, two Strings are equal only if they have the same characters in the same order. Note that equals() method is case sensitive, so if you are not looking for case sensitive checks, you should use equalsIgnoreCase() method.
  • String value represents a string in the UTF-16 format.
  • String is a final/immutable class with all the fields as final except “private int hash”. This field contains the hashCode() function value and created only when the hashCode() method is called and then cached in this field. Furthermore, the hash is generated using the final fields of String class with some calculations, so every time hashCode() method is called, it will result in the same output. For the caller, it’s like calculations are happening every time but internally it’s cached in the hash field.

Why StringBuffer & StringBuilder?

The string class is immutable in java i.e whenever we do any manipulation in String like concatenation, substring, reverse, etc. always generate a new string and discard older String for garbage collection.

That’s the reason only Java introduced StringBuffer in JDK 1.4 and StringBuilder in JDK 1.5.

StringBuffer and StringBuilder are mutable objects and provide append(), insert(), delete() and substring() methods for String manipulation.

StringBuffer vs StringBuilder

Apart from similarities, Java StringBuffer and StringBuilder having differences:

  • StringBuffer is thread-safe because all of its methods are synchronized but the main disadvantage is performance.

Note: If you are working on a single-threaded environment go with StringBuilder and in a multithreaded environment use StringBuffer. In general scenarios for string manipulation, StringBuilder is better suited than StringBuffer because String buffer is synchronized.

String vs StringBuffer vs StringBuilder

String StringBuffer StringBuilder
Immutable Mutable Mutable
Legacy JDK 1.4 JDK 1.5
Thread Safe Thread Safe No Thread Safe
Synchronized Synchronized Not Synchronized
Performance slow in manipulation Performance slow in manipulation Performance faster in manipulation
String Concat (+) uses StringBuffer and StringBuilder internally NA NA
See Also: String Class Examples See Also: StringBuffer Examples See Also: StringBuilder Examples

Java: Abstract Class Vs Interface


Abstract class and interface in java used to provide abstraction but there are lots of differences:

Abstract Class Interface
Abstraction(0 to 100%) Abstraction(100%)
Abstract class implemented by keyword ‘extends Interface implemented by using keyword ‘implements
Abstract class also can not be instantiated but can be invoked if the main() method exists. Interface is completely abstract i.e can not create an instance of it.
Abstract class can have abstract and non-abstract methods. Interface methods are implicitly abstract and can not have an implementation(nobody)
Abstract class allowed final,non-final and static variables also. Interface allowed only final and static variables
Abstract class members are private, protected, etc. Interface members are public by default.
Abstract class can extend only one class but implements multiple java interfaces. Interface can extend other interfaces only.
Abstract class is fast compare to interface Interface is slow because it required extra indirection.
See Also: Java Abstract Class Examples See Also: Java Interface Examples

See Also:

Java: Interface


An interface is the blueprint of a class to achieve total abstraction.

  • Abstract Class: Abstraction (0 to 100%)
  • Interface: Abstraction (100%)

Points to remember for Interface in Java

  • Interface in java use interface keyword to declare.
  • Interface in java allows only abstract methods i.e methods don’t have a body.
  • Interface in java allows static constants.
  • Interface in java supports multiple inheritance.
  • Interface in java not required to declare the method as public and abstract, internally all methods are public and abstract.
  • Interface in java having all fields as public, static and final.
  • Interface in java represents the IS-A relationship.
  • Interface in java can not be instantiated just like an abstract class.

Note:
There are some enhancements in the interface as per Java versions:

  • Java 8 introduced default and static methods in an interface.
  • Java 9, allowed to support private methods in an interface.

Why use Java interface?

There is the main reason to use interface in java:

  • Interface in java used to achieve abstraction.
  • Interface in java is used to support the multiple inheritance functionality.
  • Interface in java is used to achieve loose coupling.

How to declare an interface?

Interface in java is declared by using the interface keyword. All interface methods declared with the empty body are by default public and abstract. All declared fields inside the interface are public, static and final by default.

If a java class that implements an interface must implement all the methods declared in the interface.

Syntax:

interface interface_name{  
     // declare constant fields by default public , static and final  
    // declare methods that public and abstract by default   
} 

Note: If you are not adding any modifier in methods and variables in Java interface. The compiler adds as below while compilation:

  • Java compiler will add the public and abstract before the interface methods.
  • Java compiler will add public, static and final before fields inside java interface.

Java Classes and Interface Relationship

In java a class extends another class, an interface extends another interface, but a class implements an interface.

Interface Example

In the given example, the Shape interface has only one method as draw(). This method is implemented by Rectangle and Circle classes.

In a real scenario, an interface provides an abstraction to users i.e interface is defined by someone else, but its method implementation is provided by different providers. Moreover, it is used by someone else to interact with the method but the implementation part is hidden by the user.


interface Shape{
	void draw();
}
class Rectangle implements Shape{
public void draw(){System.out.println("Drawing Rectangle Shape");}
}
class Circle implements Shape{
public void draw(){System.out.println("Drawing Circle Shape");}
}  

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

Shape d=new Circle();
      d.draw();
	  d=new Rectabgle();
      d.draw();
}}

Output


Drawing Circle Shape
Drawing Rectangle Shape

Multiple inheritances in Java by the interface

Multiple inheritance in java class can be achieve by implements multiple interfaces, or an interface by extends multiple interfaces.

interface Printable{
void print();
}
interface Shape{
void draw();
}
class Rectangle implements Shape,Printable{
public void draw(){System.out.println("Drawing Rectangle Shape");}
public void print(){System.out.println("Print Rectangle Area");}
}
class Circle implements Shape,Printable{
public void draw(){System.out.println("Drawing Circle Shape");}
public void print(){System.out.println("Print Circle Area");}
}
class TestMultipleInterface{
public static void main(String args[]){
Shape d=new Circle();
d.draw();
d.print();
d=new Rectabgle();
d.draw();
d.print();
}
}

Output


Drawing Circle Shape
Print Circle Area
Drawing Rectangle Shape
Print Rectangle Area

Multiple inheritances are not supported through the class in java, but it is possible by an interface, why?

Multiple inheritances are not supported in the case of class because of ambiguity but supported by the interface because there is no ambiguity. It is because this method implementation is provided by the implementation class.

As shown in the below example,  Showable and Printable interface have the same display() methods but its implementation is provided by class MultipleInterfaceExmple, so there is no ambiguity.

interface Printable{
void display();
}
interface Showable{
void display();
}

class MultipleInterfaceExmple implements Printable, Showable{
public void dispaly(){
System.out.println("Print Test Multiple Inheritance in java");
}
public static void main(String args[]){
MultipleInterfaceExmple obj = new MultipleInterfaceExmple();
obj.print();
}
}

Output

Print Test Multiple Inheritance in java 

Interface inheritance

A class implements an interface, but one interface can extend another interface.

interface Printable{
void display();
}
interface Showable extends Printable{
void show();
}
class InterfaceInheritanceExmple implements Showable{
public void print(){System.out.println("Print Interface Inheritance in java");}
public void display(){System.out.println("Display Interface Inheritance in java");}

public static void main(String args[]){
InterfaceInheritanceExmple obj = new InterfaceInheritanceExmple();
obj.print();
obj.display();
}
}

Output

Print Interface Inheritance in java
Display Interface Inheritance in java

What is a marker or tagged interface?

An interface that has no methods is known as a marker or tagged interface, for example, Cloneable, Serializable, Remote, etc. Marker Interface in Java is used to provide information to the JVM so that JVM treats these objects specially.

Follow below link to get Detail knowledge of Marker interface with examples:

Marker Interface in Java and Uses

What is nested Interface?

An interface declared within another interface or class is called a nested interface.

Follow below link to get detail knowledge of nested interface with examples:

Java: Nested Interface

 

Java: Nested Interface


An interface declared within another interface or class is called a nested interface.

The nested interfaces in java are used to group related interfaces so that easily maintain. The nested interface can’t be accessed directly. For accessing must be referred to by the outer interface or class.

For example, the Nested interface is just like almirah inside the room, for accessing almirah, first need to enter the room.

In the java collection framework,  Entry is the subinterface of Map i.e. accessed by Map. Entry.

Points to remember for nested interfaces

  • Nested interfaces are declared static implicitly.
  • Nested interface can have any access modifier while inside the class but if use inside interface then it must be public.

Syntax of Nested Interface inside Class

class class_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}

Syntax of Nested Interface inside Interface

interface interface_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}  

Example of Nested Interface: Interface within Interface

interface Readable{
  void show();
  interface Message{
   void messageDetail();
  }
}

Access of Nested Interface within Interface

we are accessing the Message interface by its outer interface Readable because it cannot be accessed directly.

class NestedInterfaceExample1 implements Readable.Message{

 public void messageDetail(){
 System.out.println("Hello !!! you are calling messageDetail method.");
 }  

 public static void main(String args[]){
  //upcasting here
  Readable.Message message=new NestedInterfaceExample1();
  message.messageDetail();
 }
}

Output

Hello !!! you are calling messageDetail method.

Note: For the above example when you compile Readable class, compiler internally creates the public and static interface as given below:

public static interface Showable$Message
{
  public abstract void messageDetail();
}

As you can see in the above example, The java compiler internally creates the public and static interface.

Example of Nested Interface: Interface within Class

In the below example you will see, interface implementation inside the class and how can we access it.

class ClassA{
  interface Message{
   void messageDetail();
  }
}

Access of Nested Interface within Class

class NestedInterfaceExample2 implements ClassA.Message{
 public void messageDetail(){
 System.out.println("Hello !!! you are calling messageDetail method.");
 }  

 public static void main(String args[]){
 //upcasting here
  ClassA.Message message=new NestedInterfaceExample2();
  message.messageDetail();
 }
}

Output

Hello !!! you are calling messageDetail method.

Can we define a class inside the interface?

Yes, If we implement a class inside the interface, the java compiler automatically creates a static nested class. In this example you will see how can we define a class within the interface:

interface M{
class A{}
}

 

Java: Abstract Class


Abstraction in Java

Abstraction is a concept to show only essential detail i.e hide internal detail and show functionality in simple terms. To achieve abstraction in Java, use abstract class or interface.

Example: In ATM we don’t know how internally work. In a Car don’t know about the internal mechanism.

Ways to achieve Abstraction

We can achieve abstraction in two ways:

  1. Abstract class: abstraction (0 to 100%)\
  2. Interface: abstraction (100%)

Abstract class in Java

A class that is declared with the keyword abstract is known as an abstract class in Java. It can have abstract and concrete methods (method with the body). An abstract class can not be instantiated but need to extend to implement abstract methods.

abstract class ClassA{}  

Points to Remember

  • Abstract class must be declared with the keyword abstract.
  • Abstract class can have abstract and non-abstract methods.
  • Abstract class cannot be instantiated.
  • Abstract class can have constructors and static methods also.
  • Abstract class can have final methods that will force the subclass not to change the body of the method.
  • Abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and even main() method.

Abstract Method in Java

A class method that is declared with keyword abstract and not having any implementation is known as an abstract method.

For Example

abstract class ClassA{
//no method body and abstract
abstract void printStatus(); 
}  

Note:

  • Rule 1: If a class having one or more abstract method then make to class as an abstract class by declaring with keyword abstract.
  • Rule 2: If a class is extending with an abstract class that has an abstract method, then the subclass must either need to make an abstract class or provide the implementation of the method.
  • Rule 3: The abstract class can also be used to provide some implementation of the interface. In this case, the programmer may not be forced to override all the methods of the interface.

Example of an abstract method

Let’s have a real scenario, Consider a group of vehicles like Bike, Bus, Car and Truck, and each vehicle has similarities like fuel amount, capacity, brakes, etc.

For this example, define Vehicle class as abstract with this method declaration as engine() because are similarities with all vehicles. Every vehicle has different ways to implement it so write an implementation of these methods in respective classes.

abstract class Vehicle{
  abstract void engine();
}

class Car extends Vehicle{
void engine(){
System.out.println("Car Engine is running safely");
} 

class Bike extends Vehicle{
void engine(){
System.out.println("Bike Engine is running safely");
} 

class Truck extends Vehicle{
void engine(){
System.out.println("Truck Engine is running safely");
} 

class Bus extends Vehicle{
void engine(){
System.out.println("Bus Engine is running safely");
}
} 

public TestAbstractClass
{
  public static void main(String[]args)
  {
    Vehicle v=new Car();
	v.engine();
	v=new Bike();
	v.engine();
	v=new Truck();
	v.engine();
	v=new Bus();
	v.engine();
  }
}

Output

Car Engine is running safely
Bike Engine is running safely
Truck Engine is running safely
Bus Engine is running safely

Mostly, we don’t know about the implementation class (which is hidden to the end-user), and an object of the implementation class is provided by the factory method.

abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 9;}
}    

class TestBankDetail{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("ICICI Rate of Interest is: "+b.getRateOfInterest()+" %");
}}

Output

SBI Rate of Interest is: 8 %
ICICI Rate of Interest is: 9 %

Java: OOPS Concepts


The object is Real-world entities i.e Pen, Paper, computer, watch, fan, etc.

Object-Oriented Programming is a paradigm or methodology to implement real-world entities by design a program using classes and objects.

OOPS(Object-Oriented programming System) provides a paradigm to simplifies the development and maintenance of a Software. Here are the main concepts of OOPS:

  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

Apart from these basic concepts, there are some other terminologies used to show association and dependency between the objects: and classes:

  • Coupling
  • Cohesion
  • Association
  • Aggregation
  • Composition
  • Generalization(Super Class)
  • Specialization (Sub Class)
  • Realization(Interface)

See Also:

  • Java: Class & Instance Relationship
  • Java: OOPS Design Principles
  • Java: SOLID Design principles

simula and Smalltalk are considered as first truly object-oriented programming language But the main popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

OOPS Concept

Object

A physical or logical entity that has state and behavior are known as an object. For Example Pen, Paper, computer, watch fan, etc.

An Object is an instance of a class. It contains an address and takes some space in heap memory. Communication between objects happens without knowing the detail of each other only condition is the type of message accepted and the type of response returned should be compatible.

For Example, A car is an object because it has states like color, make, model, engine, etc. as well as behaviors like speed, accelerator, music, etc.

Class

The collection of objects is called a class. Class is the blueprint of an object from which object created. Class doesn’t consume space.

For Example, Person is class and “Saurabh Gupta” is the object of that class.

Inheritance

Inheritance is a process where child class acquired all the properties and behaviors of the parent class. Inheritance is used when one object is based on another object. Here parent class also called a superclass and child class called as a subclass.

For Example,  Person is Parent class and Employee is a subclass of Person. which acquired all the properties and behavior of Person class.

Advantage of inheritance

  • Code Reusability
  • Runtime Polymorphism

Points about Inheritance

  • extends the keyword used to implement inheritance.
  • Java doesn’t support multiple inheritances. It’s possible by implementing multiple interfaces.
  • Inheritance has an “IS-A” relationship.

Polymorphism

Polymorphism (more-form) means the ability to take more than one form. It’s used when one task needs to perform in different ways.

For Example, areas of shape are having different formulae for each same like rectangle, square, circle, etc.

Polymorphism can be achieved in two ways:

  1. Runtime Polymorphism (Method Overriding)
  2. Compile-time Polymorphism (Method Overloading)

Abstraction

Abstraction is a concept to show only essential detail i.e hide internal detail and show functionality in simple terms. To achieve abstraction in Java, use abstract class or interface.

Example: In ATM we don’t know how internally work. In Car don’t know about the internal mechanism.

Abstraction can be achieved by two ways:

  • Abstract Class (0% to 100%)
  • Interface (100%)

Encapsulation

Binding (or wrapping) of data and function in a single unit is called encapsulation. The encapsulation technique is used to achieve abstraction in oops.

In Java, A class is an example of encapsulation where abstraction level depends on access modifiers(private, protected and public) uses for fields and methods. A class is considered as fully encapsulated if all data members are private.

 

Java: package and import Keyword


Java package is a mechanism to a group of similar types of classes, interfaces, and sub-packages. java Package categorizes in two forms:

  1. Built-in Package
  2. User Define Package

Built-in Package

Java provides lots of built-in packages as per specific requirements. Here is a list of most frequently used built-in packages:

Package Name Description
java.applet It provides the classes related to applet creation and communicates with its applet context.
java.awt It contains the classes for creating user interfaces designing graphics and images.
java.beans It provides classes related to developing components based on the JavaBeans architecture.
java.io Provides classes and interfaces for input and output through data streams, serialization, and the file system.
java.lang It provides fundamental classes to the design of the Java programming language.
java.math It provides classes for performing mathematical operations for integer arithmetic (BigInteger) and decimal arithmetic (BigDecimal).
java.net Provides the classes related to implementing networking applications.
java.nio Defines buffers classes which are containers for data.
java.rmi Provides the classes related to RMI.
java.security Provides the interfaces and classes for the security framework.
java.sql Provides the API for processing and accessing data stored in a data source.
java.time The Classes and Methods to deal with dates, times, instants, and durations.
java.util Provide Collections framework classes and interfaces, date and time facilities, internationalization, and miscellaneous utility classes like (string tokenizer, random-number generator, and bit array).

You can get refer the complete list of Java packages from this link : Java: Complete Package List

java Most Common Built in packages

Here we will mainly focus on User Defined Packages creation and access.

Advantage of Java Package

  1. Java package is used to group the classes and interfaces so that they can be easily maintained.
  2. Java package removes naming conflicts.
  3. Java package provides access protection.

Rule of Java Package

There are certain rules that need to follow while creating the java class files.

  • Rule 1: Declare package as the first line of the statement in class or interface or a .java file. Which shows the directory location of java file after compilation.
  • Rule 2: A single java source file can have only one public class and this file will save with public class name only.
  • Rule 3: Two same name source files can not be in the same package.
  • Rule 4: If a source file is not having a package name i.e consider in the default package.
  • Rule 5: A class accessing another class, if both are in the same package then don’t require a package name.

Java Package Example

package mypackage;
public class SimplePackageExample{
public static void main(String args[]){
System.out.println("Welcome to My Package");
}
}

How Java Package Compilation?

If you are not using any IDE, you need to follow the syntax in command-line as given below:

javac -d directory java_file_name  

For example:

javac -d . SimplePackageExample.java  

The -d argument represents destination i.e use switch specifies the destination where to put the generated class file.

Note: Use dot(.) to keep package within the same directory/current folder. You can put directory path in place of the dot(.) to move compiled class file on that location. For Example Use /home (in case of Linux), d:/myclasses (in case of windows), etc.

Java Package Program Execution

You need to use a fully qualified name e.g. mypackage.SimplePackageExample etc to run the class.

To Compile: javac -d . SimplePackageExample.java
To Run: java mypackage.SimplePackageExample
Output:Welcome to My Package

How to access package classes from another package?

Java provides three ways to access the package from outside the package:

  1. import package.*;
  2. import package.classname;
  3. fully qualified name.

import keyword

The import keyword is used to access classes and the interface of another package.

Suppose we have ClassA inside package mypackageA. Now you will see the access to this class in another package in a different way in a further post.

package mypackageA;
public class ClassA{
  public void getMessage(){
  System.out.println("Hello In Package A");
  }
}

Using import packagename.*

If you use an import package.* then all the classes and interfaces of this package will be accessible but not sub-packages.

Here in this example using ClassA from another package that’s what use import mypackageA.* to import all classes and interfaces on this package.

package mypackageB;
import mypackageA.*
public class ClassB{
public static void main(String[]args)
{
   ClassA obj = new ClassA();
   obj.getMessage();
   }
}

Note: This way of import definitely reduces the line of import statement but tries to avoid using it because if the declared package in having lots of classes and interfaces then it will load all. Definitely, it will impact your performance.

Using import packagename.className

If you import package.classname then only declared a class of mentioned package will be accessible.

In this below case for statement package mypackageA.ClassA only classA in package mypackageA will load.

package mypackageB;
import mypackageA.ClassA
public class ClassB{
public static void main(String[]args)
{
   ClassA obj = new ClassA();
   obj.getMessage();
   }
}

Using the fully qualified name

If you are using the fully qualified name of class or interface on time of declaration of reference object then only declared class of this package will be accessible. Now no need to import statements.
But the problem is you need to use a fully qualified name every time when you are accessing the class or interface.

Note: This way generally preferred when two packages have the same class name for example Date Class is in java.sql and java.util package.

package mypackageB;
public class ClassB{
public static void main(String[]args)
{
   mypackageA.ClassA obj = new mypackageA.ClassA();
   obj.getMessage();
   //another instance need to give full qualified name again.
   mypackageA.ClassA obj1 = new mypackageA.ClassA();
   obj1.getMessage();
   }
}

Now you have learned about package creation, access to another class, compilation and execution of classes. Here you will learn about subpackage and way of creation it.

Java SubPackage

The package within the package is called the subpackage. It should be created to further categorize the package.

Note: If you import a package all the classes and interface of that package excluding subpackage. Hence need to import sub package separately if required.

The standard way of defining a package is domain.company.package for example:

//admin related packages
com.fiot.admin.controller
com.fiot.admin.model
com.fiot.admin.repository
com.fiot.admin.service

//user related packages
com.fiot.user.controller
com.fiot.user.model
com.fiot.user.repository
com.fiot.user.service

In the above packages you can easily understand the code layer and modules and when you need to understand the code you can easily understand it.

As mentioned above builtin packages having related classes with the packages and sub-packages. For Example, Input/Output related classes in java.io package, Server and ServerSocket classes in java.net packages and SQL related classes in java.sql packages.

Example of java Subpackage

package com.fiot.subpackage.example;
public class SimpleSubPackageExample{
 public static void main(String args[]){
    System.out.println("Welcome to My Sub Package");
   }
}
To Compile: javac -d . SimpleSubPackageExample.java
To Run: java com.fiot.subpackage.example.SimpleSubPackageExample
Output:Welcome to My Sub Package

When you compile above program it will create SimpleSubPackageExample.class file inside the folder (current_path/com/fiot/subpackage.example). When running this file you have to mention complete package with the file name as given in the above example.

Move the class file to another drive or directory

Let consider for the above example and want to send this file classes folder in e: drive when compile. We have run as below:

To Compile: current_file_directory> javac -d e:\classes SimpleSubPackageExample.java

To run:
To run the program from the current directory, you need to set the classpath of the directory where the class files reside.


current_directory> set classpath=e:\classes;.;
current_directory> java -classpath com.fiot.subpackage.example.SimpleSubPackageExample

Note: The -classpath switch can be used with javac and java tools.

Ways to load the jar or class files

Java supports two ways to load the class files:

  1. Temporary
    By setting the classpath in the command prompt as mentioned in the above example.
By -classpath switch

Permanent
By setting the classpath in the environment variables

Create the jar file, that contains all the class files and then copying 
the jar file in the jre/lib/ext folder.

How to use static import?

The static import feature introduced in Java 5 to access any static member of a class directly. There is no need to qualify a class name.

Static Import Advantage

Less coding is required: if need to use some static members frequently.

Static import Disadvantage

If you overuse the static import statement, then it creates a problem to understand and maintain code.

Example of Static Import

import static java.lang.System.*;

public class StaticImportExample {
	public static void main(String args[]) {
		// Now no need of write System.out
		out.println("Facing Issues on IT");
		out.println("Learn from Other Experinces");

	}
}

Output

Facing Issues on IT
Learn from Other Experinces

What is the difference between import and static import?

import static import
The import statement allows the java programmer to access classes of a package without package qualification. The static import statement allows accessing the static members of a class without the class qualification.
The import statement provides accessibility to classes and interface. The static import statement provides accessibility to static members of the class.

 

Java: Runtime Class


Every Java application has a single instance of class java.lang.Runtime to interact with java runtime environment(JRE) in which the application is running. This class provides a method to invoke GC, get total and free memory and execute a process, etc.

We can get application current runtime by getRuntime() method but we can’t create our own instance of Runtime.

Runtime runtime=Runtime.getRuntime()

This method return singleton instance of runtime.

Methods of Runtime Class

Modifier and Type Method  Description
void addShutdownHook(Thread hook) Registers a new shutdown hook for the virtual machines.
int availableProcessors() Returns the number of available processors for JVM.
Process exec(String command) Executes the given string command as a separate process.
void exit(int status) Terminates the currently running JVM by initiating its shutdown sequence.
long freeMemory() Returns the amount of free memory in the Java Virtual Machine.
void gc() Runs the garbage collector.
static Runtime getRuntime() Returns the runtime instance associated with the current application.
void halt(int status) Forcibly terminates the currently running JVM.
void load(String fileName) Loads the native library given by the fileName argument.
void loadLibrary(String libName) Loads the native library given as the libName argument.
long maxMemory() Returns the maximum amount of memory that the JVM will attempt to use.
boolean removeShutdownHook(Thread hook) De-registers a previously registered  shutdown hook for JVM(Java Virtual Machine).
void runFinalization() Runs the finalization methods of any objects pending finalization.
long totalMemory() Returns the total amount of memory in the JVM.
void traceInstructions(boolean on) Enables/Disables tracing of instructions.
void traceMethodCalls(boolean on) Enables/Disables tracing of method calls.

Java Runtime Class Example

In this example, you will see no of the available processors in JVM and differences in available memory after the execution of Garbage collection.

public class RuntimeClassExample {

	public static void main(String[] args) {
		  Runtime runtime =  Runtime.getRuntime();

		  //Total Memory
		  System.out.println("Total Memory in JVM: "+runtime.totalMemory());
		  //Return amount of memory available in JVM
	      System.out.println("Free memory in JVM before Garbage Collection = "+runtime.freeMemory());
	      //Call Garbage Collection
	      runtime.gc();
	      //Return amount of memory available in JVM
	      System.out.println("Free memory in JVM after Garbage Collection = "+runtime.freeMemory());

	      System.out.println("Available Processors:"+Runtime.getRuntime().availableProcessors());
	}
}

Output

Total Memory in JVM: 128974848
Free memory in JVM before Garbage Collection = 127611672
Free memory in JVM after Garbage Collection = 128005400
Available Processors:8

Java Runtime exec() method Example

Runtime.exec() method is used to execute commands that we generally run by command prompt.

How to open notepad by Java?

public class RuntimeExecExample{
 public static void main(String args[])throws Exception{
  //note pad command will open notepad
  Runtime.getRuntime().exec("notepad");
 }
}

How to shutdown system/window OS by Java?

You can use shutdown -s command to shutdown system. In the case of windows OS, you need to provide the full path of shutdown command i.e c:\\Windows\\System32\\shutdown.
Here are a couple of system arguments we can use:

  • -s switch to the shutdown system.
  • -r switch to restart the system.
  • -t switch to specify time delay.

Restart System

public class RuntimeExecExample{
 public static void main(String args[])throws Exception{
  //switch to shutdown system
  Runtime.getRuntime().exec("shutdown -s -t 0");
 }
}

Switch Window OS

public class RuntimeExecExample{
 public static void main(String args[])throws Exception{
  //switch to shutdown window OS
  Runtime.getRuntime().exec("c:\\Windows\\System32\\shutdown -s -t 0");
 }
}

How to restart system/window OS by Java?

Restart System

public class RuntimeExecExample{
 public static void main(String args[])throws Exception{
  //restart system
  Runtime.getRuntime().exec("shutdown -r -t 0");
 }
}

Restart Window OS

public class RuntimeExecExample{
 public static void main(String args[])throws Exception{
  //restart window OS
  Runtime.getRuntime().exec("c:\\Windows\\System32\\shutdown -r -t 0");
 }
}

References

https://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html

Java: Method Overriding


Method Overriding is a concept that allows a child class to provide a specific implementation of a method that is already provided by one of its parent classes. When a method in a child class has the same name, same parameters or signature and same return type(or sub-type) as a method in its parent class, then the method in the child class is said to override the method in the parent class.

See Also:

Example of Method Overriding

Here print() method having the same signature in parent and child class i.e child class print() method overriding on parent class print() method.

public class Person
{
public void print(String name)
	{
	//some code here
	}
}
public class Employee extends Person
{
	@Override
	public void print(String name)
	{
	//some code here
	}

}

How to execute the overridden method?

Type of the object of a class being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.

  • Parent class object is used to invoke the method of the parent class.
  • A child class object is required to execute the method of the child class.

When should we use the overriding method?

It can be used when combining inheritance with overridden methods, a parent class can define the general form of the methods that will be used by all of its child class.

Ways to implement method overriding or runtime polymorphism?

  1. The access modifier of the overridden method in child class can allow more, but not less. For example, A parent class method with access modifier protected can be made public in child class but not private. if you use private will generate a compile-time error.
  2. a final method can not be overridden.
  3. private methods can not be overridden.
  4. The overriding method must have the same return type (or a subtype of it).
  5. We can call the parent class method in the overriding method using super keyword.
  6. We can not override constructors as parents and child class can never have a constructor with the same name.
  7. Abstract methods in an abstract class or interface are meant to be overridden in derived concrete classes otherwise a compile-time error will be thrown.
  8. The presence of a synchronized/strictfp modifier with the method has no effect on the rules of overriding, i.e. it’s possible that a strictfp/synchronized method can override a strictfp/non-synchronized one and vice-versa.
  9. Overriding and Exception-Handling

Rule 1: If the super-class overridden method does not throw an exception, the subclass overriding method can only throw the unchecked exception, throwing checked exception will lead to a compile-time error.

Rule 2: If the super-class overridden method does throw an exception, the subclass overriding method can only throw the same, subclass exception. Throwing parent exception in the Exception hierarchy will lead to a compile-time error. Also, there is no issue if the subclass overridden method is not throwing any exception.
See Also: Method Overloading Exception Handling with Example

  • Static methods can not be overridden(Method Overriding vs Method Hiding)
Super Class Instance Method Super Class Static Method
Sub Class Instance Method   Overrides Generates a compile-time error
Sub Class Static Method Generates a compile-time error Hides

Java: Method Overloading Vs Method Overriding


 

Method Overloading Method Overriding
Method Overloading is about the same function have different signatures. Method Overriding is about the same function, same signature but different classes connected through inheritance.
Method Overloading is a concept of compile-time polymorphism Method Overriding is a concept of run time polymorphism.
Method Overloading Example:

public class Employee
{
	public void print()
	{
	//some code here
	}
	public void print(String name)
	{
	//some code here
	}
	public void print(Employee employee)
	{
	//some code here
	}

}
Method Overriding Example:

public class Person
{
public void print(String name)
	{
	//some code here
	}
}
public class Employee extends Person
{
	@Override
	public void print(String name)
	{
	//some code here
	}

}
See Also: Java Method Overloading in Detail See Also: Java Method Overriding in Detail

See Also:

Java: Method Overloading


Java method overloading allows different methods with the same name, but different signatures. Where the signature can be different by the number of input parameters or type of passing parameters or both.

See Also:

Advantage of method Overloading

  • Don’t need to remember so many method names.

Points to remember about Method Overloading

  1. Method Overloading is related to the concept of compile-time (or static) polymorphism.
  2. Method Overloading possible on the same class.
  3. Method Overloading doesn’t consider the return type of method. If two method signature is the same and only differ in return type then the compiler will show as a duplicate method.
  4. Method Overloading can overload static methods but not based on keyword static only.
  5. Method Overloading can also be done for the main() method.
  6. Java language doesn’t support user-defined operator loading but internally supports operator overloading for example : (+) for concatenation.

Note: (Java 8+)If both methods have the same parameter types, but different return type, then it is not possible.

Ways to do Method Overloading

Method overloading is possible by:

  • Change the number of parameters in methods.
  • Change data types of the parameters in methods.
  • Change Order of the parameters of methods.

How to determine parameter matching in Overloading with different Types?

Parameter matching determines when parameter type is different but to higher type(in terms of range) in the same family.

For Example: suppose passing argument type is int, then check for an overloaded method of type int if not found then check for the data type of higher in the same family( long type if still not found then check for the float data type).

public class Demo {
	//overloaded methods
	public void show(int x) {
		System.out.println("In int " + x);
	}

	public void show(String s) {
		System.out.println("In String " + s);
	}

	public void show(byte b) {
		System.out.println("In byte " + b);
	}

	public static void main(String[] args) {
		byte a = 25;
		Demo obj = new Demo();
		// If will call method with by argument
		obj.show(a);
		obj.show("Facing Issues On IT "); // String
		obj.show(250); // Int
		/*
		 * Since method with char type is not available,
		 * so the data type higher
		 * than char in same family is int
		 */
		obj.show('A');
		/*
		 * Since method with float data type is
		 * not available and so it's higher
		 * data type, so at this step their will
		 * be an compile time error.
		 */
		// obj.show(7.5);
	}
}

Output


In byte 25
In String Facing Issues On IT 
In int 250
In int 65

 

Java: Method Signature


A method signature is part of the method declaration where a signature is a combination of the method name and parameter list. Method signature doesn’t consider return type as part of the signature.

The main reason to emphasis on method Signature is because of method overloading. Java compiler distinguishes between the methods based on the method signature.

See Also:

Method Overloading :
Method overloading provides the ability to write methods with the same name but accept different arguments. Method Overloading is compile-time Polymorphism.

Here is one example of method overloading where add method implements by three ways:

  1. double add(double a, double b)
  2. int add(int a, int b)
  3. double add(int a, int b)

Method signature doesn’t consider return type for method overloading, it will consider method 2 and 3 as a duplicate method and return this compile-time error.

Duplicate method add(int, int) in type MethodSignatureExample

As shown in below screen shot.

Java: Method Signature Example
Java: Method Signature Example

Method Signature Examples

public void getMapLocation(int xPos, int yPos)
{
//method code
}

The method signature in the above example is getMapLocation(int, int). In other words, it’s the method name (getMapLocation) and the parameter list of two integers.

public void getMapLocation(Point position)
{
//method code
}

The Java compiler will allow adding another method because its method signature is different, getMapLocation(Point).

 

Java: super Keyword


In java, super keyword is a reference variable used to refer immediate parent class object.

Whenever, we create an instance of child/subclass, an instance of the parent class created implicitly which referred to a super reference variable.

super keyword use mainly on the below cases:

  • super to refer immediate parent class instance variable.
  • super to invoke the immediate parent class method.
  • super() to invoke immediate parent class constructor.

See Also: Java: this Keyword

Note: In a constructor super() or this() will always be the first statement. If a constructor is not having this() or super() compiler will implicitly add it.

Example of Java super keyword

In this example, you will see highlighted lines and comments to find all uses of the super keyword.

import java.io.Serializable;

public class Person{
    private String name;
    protected String citizenship;

    public Person()
    {
    }

    public Person(String name, String citizenship) {
        super();
        this.name = name;
        this.citizenship = citizenship;
    }

    public void print() {
		System.out.println("Citizen:"+ citizenship + ",Name:" + name);
	}

}
public class Employee extends Person {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}
	public Employee(int employeeId, String name, String department
, String citizen, int salary) {
		// super keyword use to call parent constructor
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

	public void print() {
		System.out.println("Id :" +
+ ", Department :" + department + ", Salary:" + salary );

		//super keyword to access parent class variables
		System.out.println("Citizen:"+super.citizenship);
		//super keyword use to call parent class method
		super.print();
	}
}

 

Java: this Keyword


In Java, this keyword used as a reference variable that refers to the current object. Java this keyword having many uses:

  • this to refer current class instance variable.
  • this to invoke current class method (implicitly)
  • this() to invoke the current class constructor.
  • this to pass as an argument in the method call.
  • this to pass as an argument in the constructor call.
  • this to return the current class instance from the method.

this Keyword: Example

In the highlighted lines, you will see all the ways of using this keyword

public class Employee  {
	private int employeeId;
	protected String name;
    protected String citizenship;
    private  String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen) {
		// this keyword to resolve name ambiguity
		this.name=name;
		this.citizenship=citizen;
		this.employeeId = employeeId;
		this.department = department;
	}

	public Employee(int employeeId, String name, String department, String citizen, int salary) {
		// this keyword use to call another constructor
		this(employeeId, name, department, citizen);
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

	public void display() {
		// this to call method and pass as argument
		this.print(this);
	}

	public Employee getEmployee(){
		//This keyword to return current object
		return this;
	}

	public void print(Employee employee) {
		System.out.println("Id :" + employeeId + ", Department :" + department
				+ ", Salary:" + salary + ",Citizen:"
				+ citizenship + ",Name:" + name);
	}

}

Java: static Keyword


In Java, static keyword is used for memory management mainly. Static elements below to the class. It can apply with:

  • Static Variable (also known as a class variable)
  • Static Method (also known as a class method)
  • Static Block
  • Static Nested class
  • Static Import

Note: These static variables and method access by class name it doesn’t require any class instance.

Java Static Variable

A variable declares as static is known as static variable or class variable. This variable value would be common among all the instances of class because these variables take memory in the class area only once when the class first loaded.
Advantage: The static variable makes program memory efficient because of saves memory.

static variable.png

static Variable Example

public class Employee {

	int id;
	String name;
	static String organization = "Facing Issues On IT";

	public Employee(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public String display() {
		return "Id:" + id + " Name:" + name + " Organization:" + organization;
	}
}
public class StaticVariableTest {

	public static void main(String[] args) {
		Employee e1=new Employee(1,"Saurabh Gupta");
		Employee e2=new Employee(2,"Gaurav Kumar");

		System.out.println(e1.display());
        System.out.println(e2.display());
        //Change Static value
        Employee.organization="Learn from Others Experience";//Print before change
        System.out.println(e1.display());
        System.out.println(e2.display());
	}

}

Output


Id:1 Name:Saurabh Gupta Organization:Facing Issues On IT
Id:2 Name:Gaurav Kumar Organization:Facing Issues On IT
Id:1 Name:Saurabh Gupta Organization:Learn from Others Experience
Id:2 Name:Gaurav Kumar Organization:Learn from Others Experience

Counter Example with instance and static Variable

public class Counter {
	// instance variable count get memory each time when instance get created
	int count = 0;
	// class variable count will get memory once once when class loaded
	static int staticCount;

	public Counter() {
	//increase the value of each count
     count++;
     staticCount++;
     System.out.println("Count :"+count +" Static Count :"+staticCount);
	}
}
public class CounterExample {

	public static void main(String[] args) {
		new Counter();
		new Counter();
		new Counter();
	}

}

Output


Count :1 Static Count :1
Count :1 Static Count :2
Count :1 Static Count :3

Java Static Method

a static keyword with any method is known as a static method or class method.

  • A static method belongs to the class rather than the instance of a class.
  • A static method can be invoked by class names without the need for creating an instance of a class.
  • A static method can access static data variables only change the value of it.

Restrictions for the static method

There are mainly two restrictions for the static method:

  • The static method can not use non-static data member or call the non-static method directly.
  • this and super keyword cannot be used in static context.

Why Java main() method is static?

The static method doesn’t require an object to call because it’s called my Class Name. If the main() method were a non-static method, JVM creates an object first then call a main() method that would be the problem of extra memory allocation.

Java Static Method Example

public class Employee {

	int id;
	String name;
	static String organization = "Facing Issues On IT";

	public Employee(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public String display() {
		return "Id:" + id + " Name:" + name + " Organization:" + organization;
	}
	//static method static member only
	public static void change(String org)
	{
		organization=org;
		//these non static member will throw compile time issues.
		//id=5;
		//name="Rajesh";
	}
}

public class StaticMethodTest {

	public static void main(String[] args) {
		Employee e1=new Employee(1,"Saurabh Gupta");
		Employee e2=new Employee(2,"Gaurav Kumar");

		System.out.println(e1.display());
        System.out.println(e2.display());
        //Change Static value by calling static method
        Employee.change("Learn from Others Experience");
        System.out.println(e1.display());
        System.out.println(e2.display());
	}

}

Output


Id:1 Name:Saurabh Gupta Organization:Facing Issues On IT
Id:2 Name:Gaurav Kumar Organization:Facing Issues On IT
Id:1 Name:Saurabh Gupta Organization:Learn from Others Experience
Id:2 Name:Gaurav Kumar Organization:Learn from Others Experience

Java Static Block

  • A static block is executed before the main method at the time of classloading.
  • A static block is used to initialize the static data variables and members.
public class StaticBlockExample {

	static {
		System.out.println("Static block is executed");
	}

	public static void main(String args[]) {
		System.out.println("Main method executed");
	}

}

Output


Static block is executed
Main method executed

Can we execute a program without main() method?

It was possible till JDK 1.6. by executing the static block. Since JDK 1.7, it is not possible to execute a java class without the main method.

class Test{
  static{
  System.out.println("Static block is executed");
  System.exit(0);
  }
}

JDK 1.6


Static block is executed

JDK 1.7


Error: Main method not found in class Test, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Java Static Import

The static import feature introduced in Java 5 to access any static member of a class directly. There is no need to qualify class name.

Static Import Advantage

Less coding is required: if need to use some static member frequently.

Static import Disadvantage

If you overuse the static import statement, then it creates problem to understand and maintain code.

Example of Static Import

import static java.lang.System.*;

public class StaticImportExample {
	public static void main(String args[]) {
		// Now no need of write System.out
		out.println("Facing Issues on IT");
		out.println("Learn from Other Experinces");

	}
}

Output


Facing Issues on IT
Learn from Other Experinces

What is the difference between import and static import?

import static import
The import statement allows the java programmer to access classes of a package without package qualification. The static import statement allows to access the static members of a class without the class qualification.
The import statement provides accessibility to classes and interface. The static import statement provides accessibility to static members of the class.

Java: final Keyword


In Java, the final is keyword use with class, method, and variables. When it combined with one of these having below side effects on compile time:

  • A final class can not be instantiated.
  • A final method can not be overridden.
  • A final variable can not be re-assigned.

See Also: Difference between final, finally and finalize

final keyword 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

 

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: Object Externalizable Serialization with Inheritance Example


Serialization in the inheritance with the implementation of Externalizable interface can be done in two ways:

  • Implements Externalizable on the parent class
  • Implements Externalizable on Child class

In these below examples consider both the cases and implementation ways for each.

Pre-requisite:

Example: Serialization in Inheritance where Externalizable interface implements on Parent class Only

Here Externalizable interface implements on parent class and child class also. That’s what override writeExernal() and readExternal() methods on parent and child classes to serialize fields of individual classes.

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Person implements Externalizable{
	private String name;
	private String citizenship;

	public Person()
	{
	}

	public Person(String name, String citizenship) {
		super();
		this.name = name;
		this.citizenship = citizenship;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCitizenship() {
		return citizenship;
	}

	public void setCitizenship(String citizenship) {
		this.citizenship = citizenship;
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		// own class fields deserialization
		name=(String) in.readObject();
		citizenship=(String) in.readObject();
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		// own class fields serialization
		out.writeObject(name);
		out.writeObject(citizenship);
	}

}

Employee class serializing fields of the self class and calling super.writeExternal() and super.readExternal() to serialize and deserialize fields of the parent class.

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Employee extends Person implements Externalizable {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen, int salary) {
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

	public int getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	/**
	 * Since super class person implemented Externalizable interface then call super.writeExternal() for Serializing the parent class fields.
	 */
	@Override
	public void writeExternal(ObjectOutput out) throws IOException {

		//person superclass fields
		super.writeExternal(out);
		// Employee class fields serilization
		out.writeInt(employeeId);
		out.writeObject(department);
		out.writeInt(salary);
	}

	/**
	 * Since super class person implemented Externalizable interface then call super.readExternal() for Deserializing the parent class fields.
	 * here
	 */
	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		// Person superclass fields deserilization
		super.readExternal(in);
		//Employee class fields deserilization
		employeeId = in.readInt();
		department = (String) in.readObject();
		salary =  in.readInt();

	}

}

Here are steps to implements serialization and deserialization of Employee class.

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

public class SerializationAndDeserializationInheritanceExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh","IT","India", 52000);

		//serialization of object
		serializeEmployee(e1, "employee.txt");

		//deserialization of object
		e1 = deserializeEmployee("employee.txt");
		System.out.println("After Deserilization Employee Detail :");
		System.out.println("Id :" + e1.getEmployeeId() + "\nName: " + e1.getName() + "\nDepartment: " + e1.getDepartment()+ "\nSalary: " + e1.getSalary()+ "\nCitizenship: " + e1.getCitizenship());
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}
}

After executing the above program you will get below result.

Output


Employee Constructor Executed.
Employee object Serialize Successfully
After Deserilization Employee Detail :
Id :111
Name: Saurabh
Department: IT
Salary: 52000
Citizenship: India

Example: Serialization in Inheritance where Externalizable interface implements on Child class Only

Here Externalizable interface implements on parent class and child class also. That’s what override writeExernal() and readExternal() methods on parent and child classes to serialize fields of individual classes.

public class Person {
	private String name;
	private String citizenship;

	public Person()
	{
	}

	public Person(String name, String citizenship) {
		super();
		this.name = name;
		this.citizenship = citizenship;
	}
    //getter and setter of class
}
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Employee extends Person implements Externalizable {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen, int salary) {
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

	//getter and setter of class

	/**
	 * Since super class person not implemented Externalizable interface then for Serializing the parent class fields
	 * we can do it here also.
	 */
	@Override
	public void writeExternal(ObjectOutput out) throws IOException {

		//person superclass fields
		out.writeObject(getName());
		out.writeObject(getCitizenship());

		// Employee class fields serilization
		out.writeInt(employeeId);
		out.writeObject(department);
		out.writeInt(salary);
	}

	/**
	 * Since super class person not implemented Externalizable interface then for deserialize the parent class fields
	 * here
	 */
	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		// Person superclass fields deserilization
		setName((String) in.readObject());
		setCitizenship((String) in.readObject());

		//Employee class fields deserilization
		employeeId = in.readInt();
		department = (String) in.readObject();
		salary =  in.readInt();

	}

}

Here are steps to implements serialization and deserialization of Employee class.

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

public class SerializationAndDeserializationInheritanceExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh","IT","India", 52000);

		//serialization of object
		serializeEmployee(e1, "employee.txt");

		//deserialization of object
		e1 = deserializeEmployee("employee.txt");
		System.out.println("After Deserilization Employee Detail :");
		System.out.println("Id :" + e1.getEmployeeId() + "\nName: " + e1.getName() + "\nDepartment: " + e1.getDepartment()+ "\nSalary: " + e1.getSalary()+ "\nCitizenship: " + e1.getCitizenship());
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}
}

After executing the above program you will get below result.

Output


Employee Constructor Executed.
Employee object Serialize Successfully
After Deserilization Employee Detail :
Id :111
Name: Saurabh
Department: IT
Salary: 52000
Citizenship: India

See Also:

Java: Object Serialization with Inheritance Example


As we have read in the previous post if we implement java.io.Serializable interface on parent class then no need to implement on child class to make it serializable. Here we will discuss for both the cases after java.io.Serializable:

  • Implements Serializable on Parent Class
  • Implements Serializable on Child Class

Pre-requisite:

Example: Serializable interface implements on Parent class Only

Here you will see while the Serializable interface implemented on parent class but all the fields of parent and child class serialized.

import java.io.Serializable;

public class Person implements Serializable{
	private String name;
	private String citizenship;

	public Person()
	{
	}

	public Person(String name, String citizenship) {
		super();
		this.name = name;
		this.citizenship = citizenship;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCitizenship() {
		return citizenship;
	}

	public void setCitizenship(String citizenship) {
		this.citizenship = citizenship;
	}
}
public class Employee extends Person {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen,int salary) {
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary=salary;
		System.out.println("Employee Constructor Executed.");
	}

	public int getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationAndDeserializationInheritanceExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh","IT","India", 52000);

		//serialization of object
		serializeEmployee(e1, "employee.txt");

		//deserialization of object
		e1 = deserializeEmployee("employee.txt");
		System.out.println("Employee Detail :");
		System.out.println("Id :" + e1.getEmployeeId() + "\nName: " + e1.getName() + "\nDepartment: " + e1.getDepartment()+ "\nSalary: " + e1.getSalary()+ "\nCitizenship: " + e1.getCitizenship());
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}
}

Output


Employee Constructor Executed.
Employee object Serialize Successfully
Employee Detail :
Id :111
Name: Saurabh
Department: IT
Salary: 52000
Citizenship: India

Example: Serializable interface implements on Child class Only

Here you will notice parent class fields are not serialize.

public class Person {
	private String name;
	private String citizenship;

	public Person()
	{
	}

	public Person(String name, String citizenship) {
		super();
		this.name = name;
		this.citizenship = citizenship;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCitizenship() {
		return citizenship;
	}

	public void setCitizenship(String citizenship) {
		this.citizenship = citizenship;
	}
}
import java.io.Serializable;

public class Employee extends Person implements Serializable{
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen,int salary) {
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary=salary;
		System.out.println("Employee Constructor Executed.");
	}

	public int getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationAndDeserializationInheritanceExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh","IT","India", 52000);

		//serialization of object
		serializeEmployee(e1, "employee.txt");

		//deserialization of object
		e1 = deserializeEmployee("employee.txt");
		System.out.println("Employee Detail :");
		System.out.println("Id :" + e1.getEmployeeId() + "\nName: " + e1.getName() + "\nDepartment: " + e1.getDepartment()+ "\nSalary: " + e1.getSalary()+ "\nCitizenship: " + e1.getCitizenship());
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}
}

Output


Employee Constructor Executed.
Employee object Serialize Successfully
Employee Detail :
Id :111
Name: null
Department: IT
Salary: 52000
Citizenship: null

See Also:

Java: Serialization Exception Handling


All these exceptions are related to serialization which occurred while doing serialization and deserialization of objects. These exceptions are subclasses of ObjectStreamException which is a subclass of IOException.

Pre-requisite:

Java Serialization exception hierarchy

Exception Description
ObjectStreamException Superclass of all serialization exceptions.
InvalidClassException This exception occurred when  a class cannot be used to restore/deserialize objects for any of these reasons:

  • The class does not match the serialversionUID of the class in the stream.
  • The class contains properties with invalid primitive data types.
  • The Externalizable class doesn’t have a public no-arg constructor.
  • The  Serializable class can’t access the no-arg constructor of its closest non-serializable superclass.
NotSerializableException This exception has thrown by a readObject or writeObject method to terminate serialization or deserialization.
StreamCorruptedException This exception has thrown when some of the meta information modified:

  • If the stream header is invalid.
  • If control information not found.
  • If control information is invalid.
  • JDK 1.1.5 or fewer attempts to call readExternal on a PROTOCOL_VERSION_2 stream.
NotActiveException This exception has thrown if writeObject state is invalid within the following ObjectOutputStream methods:

  • defaultWriteObject
  • putFields
  • writeFields

This exception has thrown if readObject state is invalid within the following ObjectInputStream methods:

  • defaultReadObject
  • readFields
  • registerValidation
InvalidObjectException This exception occured when a restored object cannot be made valid.
OptionalDataException This exception has thrown by readObject when there is primitive data in the stream and an object is expected. The length field of the exception represents the number of bytes that are available in the current block.
WriteAbortedException This exception has thrown when reading a stream terminated by an exception that occurred while the stream was being written.

See Also:

References

Java: static Serialization and Deserialization Examples


The variable declares with static keyword are known as class variables these variables will not serialize when doing serialization for objects of the class.

Note: Fields declare as transient also not serialize.

Pre-requisite:

For Example: In Employee Class fields age is declared with the keyword static. When you serialize the object of class Employee then values of age will not serialize and time of deserialization initialize with default value as per type.

import java.io.Serializable;
public class Employee implements Serializable{
 int id;
 String name;
//This field will not be serialized
 static int age;
 public Employee(int id, String name,int age) {
  this.id = id;
  this.name = name;
  this.age=age;
 }
}

See Also:

Serialization Example: with the static keyword

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializationWithStaticExample {

	public static void main(String args[]) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh", 35);
		// writing object into employee file
		FileOutputStream f = new FileOutputStream("employee.txt");
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();

		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

}

Output


Employee object Serialize Successfully

Deserialization Example: with the static keyword

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializationWithStaticExample {

	public static void main(String[] args) throws Exception {
		 //Read object stream from file
		  ObjectInputStream in=new ObjectInputStream(new FileInputStream("employee.txt"));
		 //Deserialize object stream to employee object
		  Employee e=(Employee)in.readObject();
		  System.out.println("Employee Detail :");
		  System.out.println("Id :"+e.id+"\nName: "+e.name+"\nAge: "+e.age);
		  in.close();  

	}
}

Output


Employee Detail :
Id :111
Name: Saurabh
Age: 0

As you can see, the printing age of the employee returns 0 as default initialize value for int type because the value of age was not serialized.

Java: Externalizable/Custom Serialization and Deserialization Example


The Externalizable interface provides the facility of custom serialization by writing the state of an object into a byte stream by making some changes or compress format.

Pre-requisite:

The Externalizable interface is not a marker interface. It extends Serializable interface and provides two methods for serialization and deserialization of object:
Serialization

public void writeExternal(ObjectOutput out) throws IOException

Deserialization

public void readExternal(ObjectInput in) throws IOException

Advantage of Externalizable

  • Externalizable is fast in comparison to default serialization. Because JVM uses reflection when you use serializable which is quite slow.
  • Externalizable performance is fast because don’t store unnecessary information. While default serialization store information about class description i.e class description, its superclass, and instance variable associated with that class.

Disadvantage of Externalizable

  • Once any change happens on the class definition, we have to also change our implementation on writeExternal() and readExternal() accordingly.
  • In the case of inheritance, the Subclass object has to coordinate with its superclass to save and store its state by calling super.xxxx() method from subclass.

See Also:

Externalizable Example: Serialization and Deserialization

In this example, Employee class override writeExternal() and readExternal() method for serialization and deserialization of data.  Here we have written our own statement to what data need to serialize. Here you can also consider this example of data compression as storing data as compressed because not storing irrelevant data.

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Employee implements Externalizable {
	int id;
	String name;
	transient int age;
	public Employee()
	{

	}
	public Employee(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	@Override
	public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException {
		String []str=oi.readUTF().split("[|]");
		this.id=Integer.parseInt(str[0]);
		this.name=str[1];
		this.age=Integer.parseInt(str[2]);

	}

	@Override
	public void writeExternal(ObjectOutput oo) throws IOException {

		oo.writeUTF(this.id+"|"+this.name+"|"+this.age);
	}

}

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

public class ExternalizableCompressionExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh", 35);
		serializeEmployee(e1, "employee.txt");

		e1 = deserializeEmployee("employee.txt");
		System.out.println("Employee Detail :");
		System.out.println("Id :" + e1.id + "\nName: " + e1.name + "\nAge: " + e1.age);
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}

}

Output


Employee Detail :
Id :111
Name: Saurabh
Age: 35

Java: transient Serialization Example


Java transient keyword is used in serialization to declare a variable when don’t want to serialize.

Note: Fields declare as static will also not serialize.

Pre-requisite:

For Example: In Employee Class fields age is declared with keyword transient. When you serialize the object of class Employee then values of age will not serialize and time of deserialization initialize with default value as per type.

import java.io.Serializable;
public class Employee implements Serializable{
 int id;
 String name;
//This field will not be serialized
 transient int age;
 public Employee(int id, String name,int age) {
  this.id = id;
  this.name = name;
  this.age=age;
 }
}

See Also:

Serialization Example: with transient keyword

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializationWithTransientExample {

	public static void main(String args[]) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh", 35);
		// writing object into employee file
		FileOutputStream f = new FileOutputStream("employee.txt");
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();

		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

}

Output

Employee object Serialize Successfully

Deserialization Example: with transient keyword

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializationWithTransientExample {

	public static void main(String[] args) throws Exception {
		 //Read object stream from file
		  ObjectInputStream in=new ObjectInputStream(new FileInputStream("employee.txt"));
		 //Deserialize object stream to employee object
		  Employee e=(Employee)in.readObject();
		  System.out.println("Employee Detail :");
		  System.out.println("Id :"+e.id+"\nName: "+e.name+"\nAge: "+e.age);
		  in.close();  

	}
}

Output

Employee Detail :
Id :111
Name: Saurabh
Age: 0

As you can see, the printing age of the employee returns 0 as the default value for int type because the value of age was not serialized.

Java: Serialization and Deserialization Examples


Serialization is a mechanism to convert the state of an object as a byte stream to persist and traverse of an object. Byte stream makes platform independent i.e One object can serialize in a platform and deserialize in another platform.

Reverse operation of serialization is called deserialization i.e convert byte-stream to object.

Advantages of Serialization

  • Use to save/persist state of an object.
  • Use to travel an object across a network i.e also called and marshaling.

Technically, Serialization and deserialization used in Hibernate, RMI, JPA, EJB and JMS technologies to persist the state of the object as a stream.

Java Serialization and Deserialization

In Java, to make an object Serializable implements java.io.Serializable interface which is a marker interface (has no data member and methods).

See Also:

Object Serialization

We can call writeObject() method of ObjectOutputStream class for serialization of object.

public final void writeObject(Object obj) throws IOException

Object Deserilization

We can call readObject() method of ObjectInputStream class for deserialization of object.

public final Object readObject() throws IOException, ClassNotFoundException

Points to remember

  • The objects of those classes will able to serialize which are implementation java.io.Serializable interface.
  • If the parent class implemented a Serializable interface then the child class doesn’t need to implement it but vice-versa is not true.
  • Internal associated component objects of a class must implement the Serializable interface.
  • Object Constructor never called when an object is deserialized.
  • Static and transient data members of the class are not serialized. If you don’t want to serialize some of the data members make it transient.
  • In the case of array or collection, all the objects of array or collection must be serializable. If any object is not serializable, serialization will be failed.

For Example :

//Implemneted Serilizable interface to make objects of
//ClassA serializable eligible
class ClassA implements Serializable{
//Associate component object Class also need to
//implement Serializable
ClassB ob=new ClassB();
}

What is SerialVersionUID?

On-time of Serialization on an object of Serializable class associate a version called as SerialVersionUID. This version is used during Deserialization to verify that the sender and receiver of a serialized object loaded classes are compatible with respect to serialization.

In case receiver loaded class have different version UID than sender’s class then it will throw an exception as InvalidClassException.

We can explicitly declare SerialVersionUID as long in Serializable class as below:

private static final long serialVersionUID=26L;

Note: Use access modifier as private because this field is not useful for inherited classes.

Recommendation: Always explicitly declare SerialVersionUID for serializable classes with some long value because if not mentioned explicitly then compute at runtime i.e highly sensitive to class details that may vary depending on compiler implementations or any change in class fields etc. which can generate different SerialVersionUID. This different SerialVersionUID may affect the time of the deserialization of the object.

serialver

To manually check serialVersionUID of java classes. JDK provided a tool serialver. We can run this tool as below:

serialver [-classpath classpath] [-show] [classname…]

Example: Serialization and Deserialization

This Employee object needs to serialize and deserialize in the given example. The employee object implements java.io.Serializable marker interface that is required to mark as an object is eligible for serialization.

import java.io.Serializable;

public class Employee implements Serializable {
	int id;
	String name;
	int age;

	public Employee(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
}

Here we have written a separate method for the implementation of serialization and deserialization.

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

public class SerializationAndDeserilizationExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh", 35);

		//serialization of object
		serializeEmployee(e1, "employee.txt");

		//deserialization of object
		e1 = deserializeEmployee("employee.txt");
		System.out.println("Employee Detail :");
		System.out.println("Id :" + e1.id + "\nName: " + e1.name + "\nAge: " + e1.age);
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}

}

Output

Employee object Serialize Successfully
Employee Detail :
Id :111
Name: Saurabh
Age: 35

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.