Category Archives: Java

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.

 

Advertisements

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<String> 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<String> 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<E> 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 the 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<String> list = new ArrayList<String>();
	        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<Integer> list = new ArrayList<Integer>();
		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<Integer>list = new ArrayList<Integer>();
		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<Days, String> map = new EnumMap<Days, String>(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<Days,String> 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<Key, Magzine> map = new EnumMap<Key, Magzine>(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<Key, Magzine> 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<Integer,String> map=new HashMap<Integer,String>();
  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<Integer,String> map=new HashMap<Integer,String>();
      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<Integer,String> map=new HashMap<Integer,String>();
      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&amp;lt;Integer,String&amp;gt; map=new TreeMap&amp;lt;Integer,String&amp;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&amp;lt;Integer, String&amp;gt; map = new TreeMap&amp;lt;Integer, String&amp;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&amp;lt;Integer, String&amp;gt; map = new TreeMap&amp;lt;Integer, String&amp;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&amp;lt;Integer, String&amp;gt; map = new TreeMap&amp;lt;Integer, String&amp;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&amp;lt;Integer, Magzine&amp;gt; table = new TreeMap&amp;lt;Integer, Magzine&amp;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&amp;lt;Integer, Magzine&amp;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<String> list = new ArrayList<String>();
	        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<Integer> list = new ArrayList<Integer>();
		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<Integer> list = new ArrayList<Integer>();
		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<Integer, String> hm = new LinkedHashMap<Integer, String>();

		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<Integer, String> map = new LinkedHashMap<Integer, String>();
		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<Integer, String> map = new LinkedHashMap<Integer, String>();
		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<Integer, String> map = new LinkedHashMap<Integer, String>();
		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<Integer, Magzine> map = new LinkedHashMap<Integer, Magzine>();
		// 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<Integer, Magzine> 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<Integer,String> hm = new Hashtable<Integer,String>();

		//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<Integer,String> map = new Hashtable<Integer,String>();
		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<Integer,String> map = new Hashtable<Integer,String>();
		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<Integer,String> map=new Hashtable<Integer,String>();
     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<Integer,Magzine> table = new Hashtable<Integer,Magzine>();
		// 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<Integer,Magzine> 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<String, Integer> map = new HashMap<>();
map.put("Ankur", 35);
map.put("Saurabh", 36);
map.put("Gaurav", 32);
map.put("Raghav", 29);
map.put("Rajendra", 40);
map.put("Shailesh", 33);

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

HashMap Representataion.jpg

Calculating Index Formulae:


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

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

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

Hash Collision

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

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

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

HashMap get() method to retrieve values

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

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


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

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

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

Java: HashMap Class Methods and Examples


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

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

HashMap Class Declaration


public class HashMap extends implements Map, Cloneable, Serializable  

See Also:

Points to Remember:

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

HashMap Representataion

Difference between HashSet and HashMap

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

HashMap Class Constructors

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

HashMap Class Methods

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

Example: add elements

Here, you will learn different ways to insert elements.

import java.util.*;

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

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

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

Output :


Initial hash map elements: {}

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

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

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

HashMap Example : remove()

Here you will see different ways to remove elements from HashMap

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

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

Output :


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

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

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

Updated hash map  elements: {23=Gaurav}

HashMap Example : replace()

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

import java.util.*;

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

Output :


Initial hash map elements:
20 Anuj
21 Virendra
22 Raghav

Updated hash map elements:
20 Anuj
21 Virendra
22 Gaurav

Updated hash map elements:
20 Anuj
21 Ravi
22 Gaurav

Updated hash map elements:
20 Anuj
21 Anuj
22 Anuj

HashMap Example: Objects handling

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

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

public class HashMapWithObjectsExample {

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

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

Output :



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

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

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

References

Java: Difference between HashMap and Hashtable


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

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

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

For more detail:

 

Java: Unmodifiable Collection Methods and Example


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

Collections Class Unmodifiable Methods

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

Example: Synchronized Collections

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

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

public class CollectionUnmodifiedExample {

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

}

References

Java: Synchronized Collection Methods and Examples


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

Synchronized Collection

These are the classes only are synchronized:

  • Vector
  • HashTable

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

Collections Class Synchronized Methods

All these methods are static:

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

Example: Synchronized Collections

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

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

public class CollectionSunchronizationExample {

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

	}

}

References

Java: Properties Class Methods and Examples


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

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

Method of Properties Class

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

Example: Create Properties File

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

public class CreateProprtiesFile {

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

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

Output

Properties file creation

Example: Read Properties File

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

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

public class ReadPropertiesFile {

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

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

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

}

Output


Saurabh Gupta
FacingIssuesOnIT@gmail.com

Example : Print System Level Properties

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

public class PrintSystemProperties {

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

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

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

	}

}

Output


Your Machine Properties :

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

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

Java 8: Lambda Expression


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

Where to use the Lambda Expression

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

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

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

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

Points to remember

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

Java Lambda expression Syntax

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


 (parameter_list) -> {function_body}

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

Note:

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

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

No Argument Syntax


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

One Argument Syntax


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

Two Argument Syntax


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

Method vs Lambda Expression in Java

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

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

Example 1: Lambda Expression with a predefined functional interface

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

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

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

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

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

Example 2: lambda Expression with your own functional interface

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

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

public class CalculateClass {

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

Output


Result: 220

Example 3: Lambda Expression with no arguments

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

Output


Welcome to Facing Issues on IT !!

Example 4: Lambda Expression for Collection Iteration

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

Output


Saurabh
Gaurav
Bharti
Herry
Henry

Note:

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

References

Java 8: Optional for handling NULL


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

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

Create Optional Object

Create Optional Object : Empty


Optional optionalObj=Optional.empty();

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


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

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


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

Check Optional Object for value present

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


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

Optional Object for value

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


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

Set Optional Object default value and actions

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


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

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

Example 1

In this example, covered all the above case.


import java.util.Optional;
public class OptionalExamples {

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

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

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

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

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

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

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

}

Output


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

Example 2

public class OptionalExaple2

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

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

	}

}

Output


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

References

 

Java 8: Base64 Encoding and Decoding


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

  • Simple
  • URL
  • MIME

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

Simple

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

Example: Simple Encoding and Decoding

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

public class Base64s {

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

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

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

Output


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

URL

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

Example: URL Encoding and Decoding

import java.util.Base64;

public class Base64URLExample {

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

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

}

Output


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

MIME

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

Example: MIME Encoding and Decoding

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

public class Base64Mime {

	public static void main(String[] args) {

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

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

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

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

}

Output


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

References

Java 8: Arrays Parallel Processing


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

Java 8 new methods for Arrays

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

Example: Arrays Parallel Processing

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

public class ParallelArrays {

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

}

Output


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

References

Java 8 : Nashorn JavaScript Engine


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

Points to remember

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

Exmaple: Nashorn JavaScript Engine

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

public class NashornEngineTest {

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

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

	}

}

Output


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

References

Java 8:Named Parameters in Reflection


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

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

Example: Named Parameter Reflection API

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

public class NamedParameterExample {

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

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

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

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

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

Output: Without Configuration for the named parameter


Method :main Parameters are :
Parameter: arg0

Method :printValues Parameters are :

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

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

Output: With Configuration for the named parameter



Method :main Parameters are :
Parameter: args

Method :printValues Parameters are :

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

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

Eclipse Configuration for Named Parameter

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

Java 8 named parameter eclipse setting

Console Configuration for Named Parameter

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

Maven Configuration for Named Parameter

On section of the maven-compiler-plugin:


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

Java 8: Reflection API to get Repeatable Annotation Detail


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

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

Pre-requisite: Java: Annotations

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

Example: Retrieve Annotation Detail by Reflection API

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

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

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

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

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

	public static void main(String[] args) {

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

}

Output


filter1
filter2

Java 8: Repeatable Annotations


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

Pre-Requisite : Java: Annotations Tutorial

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

Create Custom Repeatable Annotation

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

Create an array of repeatable annotation


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

Use of repeatable annotation


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

    } 

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

Java 8: StringJoiner Class


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

Constructors

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

Example 1: StringJoiner with delimiter (:)

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

import java.util.StringJoiner;

public class StringJoinerExample {

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

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

}

Output


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

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

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

import java.util.StringJoiner;

public class StringJoinerPrefixSuffixExample {

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

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

}

Output


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

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

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

import java.util.StringJoiner;

public class StringJoinerMergeExample {

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

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

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

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

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

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

	}

}

Output


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

References

Java 8: Functional Interface


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

Points to Remember

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

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

Where to use Functional Interface

  • Functional Interface uses to represent Lambda Expressions.

Create your own functional interface

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

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

Use of Functional Interface

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

Example: Use your own functional interface

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

public class CalculateClass {

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

Output


Result: 220

Example: Use a predefined functional interface

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

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

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

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

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

References

Java : Data Types


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

Java allowed two types of data types:

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

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

See Also: Java : Primitive Types size and default value

Java Data Types

 

Java : Program Execution


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

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

Java program exceution

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

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

 

JDK, JRE, JIT,SDK, JVM Introduction


JDK (Java  Development Kit)

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

JDK Java development Kit
Java Development Kit

See Also: Java: Program Execution

JRE (Java Runtime Environment)

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

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

JDK and JRE Formulae

JVM (Java Virtual Machine)

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

JVM Architecture

Now discussed terminology used for JVM.

Class Loader

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

Method Area

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

Heap

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

Stack

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

PC Registers

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

JIT Compiler

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

Native Method Stack

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

Native Method interface

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

Garbage collection

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

JDK Architecture & API’s Details

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

JDK APIs Architecture

Difference between API and Methods

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

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

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

Difference between JDK and SDK

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

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

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

See Also: Java Versions History

 

Java: final Vs finally Vs finalize


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

final

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

final Example

A final variable can not be re-assigned.

final variable example
Final Variable can be reassigned

A final class can not be subclassed.

Final Class Example
Final class can not be subclassed

A final method can not be overridden.

Final method Example
final method can not be overloaded

finally

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

finally Example

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

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

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

Output


Exception occured: / by zero
Finally Executed.

finalize

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

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

finalize Example

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

public class FinalizeMethodTest {

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

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

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

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

Output


finalize method overriden
Main Method Completed !!
finalize method overriden

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

 

Java: do-while loop


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

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

See Also: Java: Types of Looping Statements

Syntax:


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

Flow chart of do-while loop

do while loop flow chart

Example: Prints Even numbers between 1 to 20.

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

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

Output:


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

Java Infinitive do-while Loop

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

Syntax:


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

Example: do-while infinite loop

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

Output:


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

ctrl+c

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