Java Tutorials

Java is a general-purpose programming language that is a concurrent, class-based, and object-oriented language. Java follows the concept of “write once and run anywhere (WORA).” This means that compiled Java code can be run on all different platforms that support Java. There’s no need for recompilation.

Eclipse IDE

Chapter 1 How to Download and Install Eclipse IDE
Chapter 2 How to Clone a project from GitLab using Eclipse
Chapter 3 How to Export Eclipse projects to GitLab

IntelliJ IDE

Chapter 1 How to install IntelliJ on Windows
Chapter 2 How to create a Java project in IntelliJ
Chapter 3 How to Clone a project from GitLab using IntelliJ
Chapter 4 How to Export IntelliJ project to GitLab

Basics of Java

Chapter 1 How to Download & Install Java JDK 11 in Windows
Chapter 2 Data Types and Operators in Java
Chapter 3 Decision Making in Java – If, If Else, Switch, Break, Continue
Chapter 4 Loop Control Statements in Java – For, While, Do While, Enhanched For Loop
Chapter 5 String Manipulation
Chapter 6 Difference between == and equals() method in Java
Chapter 7 Arrays in Java
Chapter 8 Java Access Modifiers: Explained with Examples
Chapter 9 ArrayList in Java
Chapter 10 How to compare ArrayLists – contains?
Chapter 11 How to compare ArrayLists – containsAll method?
Chapter 12 Methods in Java
Chapter 13 Method Overloading in Java
Chapter 14 Constructors in Java   
Chapter 15 This Keyword in Java   
Chapter 16 Static Keyword – Static Variable and Static Method in Java
Chapter 17 Difference between Static Method and Non-Static Method
Chapter 18 How to use Java Lambda expression to create thread via Runnable function
Chapter 19 runAsync and supplyAsync in ComputableFuture in Java8
Chapter 20 HashMap in Java
Chapter 21 LinkedHashMap in Java
Chapter 22 Iterators in Java

OOPs Concepts

Chapter 1 Class and Object in Java
Chapter 2 Inheritance in Java
Chapter 3 Encapsulation in Java
Chapter 4 Polymorphism in Java
Chapter 5 Abstraction in Java
Chapter 6 Interface in Java
Chapter 7 Difference between Abstract Class and Interface

Exceptions in Java

Chapter 1 Exception Handling in Java
Chapter 2 Java Exceptions Tutorial: Built-in and User-defined Exceptions
Chapter 3 Flow control in try catch finally in Java
Chapter 4 Multiple Catch Exceptions
Chapter 5 Throw in Java
Chapter 6 Throws in Java

Data Handling (Excel Manipulation)

Chapter 1 How to download and install Apache POI
Chapter 2 Reading Excel Data with Apache POI in Java
Chapter 3 How to Write Data to Excel File in Java using Apache POI
Chapter 4 How to update existing excel in Java
Chapter 5 Java Excel Tutorial: Creating Excel with Formulas Using Apache POI
Chapter 6 Change Font Style in Excel with Apache POI – NEW

Multiple Choice Questions

Chapter 1 Multiple questions on Exception Handling in Java

Java Library

Chapter 1 AssertJ – Fluent Assertions in Java

How to test POST JSON Object request using Java Map in Rest Assured

HOME

In the last tutorial, I explained How to test POST request from JSON Object in Rest Assured where the request body is built in JSONObject. In this tutorial, I will create a request body using JSON Object in Rest Assured. 

We can create a JSON Object using a Map in Java. A JSON Object is a key-value pair and can be easily created using a Java Map. A Map in Java also represents a collection of key-value pairs.

<dependencies>

    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20231013</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>5.3.2</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.15.2</version>
    </dependency>

  </dependencies>

I have created a simple Java map and filled it with the values that represent JSON properties.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;

public class Json_Demo {

    @Test
    public void passBodyAsMap() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("employee_name", "MapTest");
        map.put("employee_salary", "99999");
        map.put("employee_age", "30");
        map.put("profile_image", "test.png");
        RestAssured.given()
                .contentType(ContentType.JSON)
                .body(map)
                .log().all()

                .when()
                .post("https://dummy.restapiexample.com/api/v1/create")

                .then()
                .assertThat().statusCode(200)
                .body("data.employee_name", equalTo("MapTest"))
                .body("data.employee_age", equalTo("30"))
                .body("data.employee_salary", equalTo("99999"))
                .body("message", equalTo("Successfully! Record has been added.")).log().all();
    }
}

The request body as well as the response body will look as shown below:-

Above one is a simple JSON Request Body. Let us take an example of a Complex Request Body or nested Request Body as shown below.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;

public class Json_Demo {

    @Test
    public void passBodyAsMultipleMap() {

        // First JSON Object using Hash Map
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("employee_name", "MapTest");
        data.put("profile_image", "test.png");

        // Second JSON Object using Hash Map
        Map<String, String> msg = new HashMap<String, String>();
        msg.put("updated_message", "Details of New Resource");
        msg.put("employee_age", "30");
        data.put("details", msg);
        data.put("employee_salary", "99999");
        RestAssured.given().contentType(ContentType.JSON).body(data).log().all()
                // WHEN
                .when().post("https://dummy.restapiexample.com/api/v1/create")
                // THEN
                .then().assertThat().statusCode(200).body("data.employee_name", equalTo("MapTest"))
                .body("data.details.updated_message", equalTo("Details of New Resource"))
                .body("data.details.employee_age", equalTo("30")).body("data.employee_salary", equalTo("99999"))
                .body("message", equalTo("Successfully! Record has been added.")).log().all();
    }
}

The request body as well as the response body will look as shown below image. The first part is the body of the request and the second part is the response provided by the API.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Deserialization – How to convert JSON to Map using Jackson API

HOME

This tutorial shows how to convert JSON to JAVA map using Jackson’s data binding. In the previous tutorials, I have explained converting Java Objects/Arrays to JSON String using Jackson API. You can refer below tutorials.

Serialization – How to create JSON Payload from Java Object – Jackson API

Deserialization – How to convert JSON to Java Object using Jackson API

How to create JSON Array Payload using POJO – Jackson API

How to create Nested JSON Object using POJO – Jackson API

To start with, we need to add Jackson Maven Dependency to the POM. Always add the latest version of Jackson dependency to your project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency

Deserialization converts a stream of bytes into a Java object that we can use in code.

We use Jackson’s ObjectMapper, as we did for serialization, using readValue() to process the input. Also, note our use of Jackson’s TypeReference, which we’ll use in all of our deserialization examples to describe the type of our destination Map.

   @Test
	public void DeserializationMapTest() throws JsonProcessingException {

		String employeeString = 
                     "{\r\n" 
                    + "  \"firstName\" : \"Deserialization\",\r\n"
				    + "  \"lastName\" : \"Test\",\r\n" 
                    + "  \"age\" : 25,\r\n" 
                    + "  \"salary\" : 50000.0,\r\n"
				    + "  \"designation\" : \"Manager\",\r\n" 
                    + "  \"contactNumber\" : \"+918882211111\",\r\n"
				    + "  \"emailId\" : \"abc@test.com\",\r\n" 
                    + "  \"gender\" : \"female\",\r\n"
				    + "  \"maritalStatus\" : \"single\"\r\n" 
                    + " }";

		Map<String, String> resultMap = new HashMap<String, String>();
		ObjectMapper mapper = new ObjectMapper();

		// Converting a JSON to Java Map
		try {
			resultMap = mapper.readValue(employeeString, new TypeReference<HashMap<String, String>>() {
			});
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		System.out.println("Output Map :" + resultMap);
	}

Output

We can get the JSON from a file and convert it to a Hash Map too. Below is an example of the same.

   @Test
	public void PayloadFromFile() {

		String userDir = System.getProperty("user.dir");
		ObjectMapper mapper = new ObjectMapper();

		// Converting Employee JSON string to Employee class object
		Map<String, Object> empMap;
		try {
			empMap = mapper.readValue(new File(userDir + "\\src\\test\\resources\\JSONFromMap.json"),
					new TypeReference<Map<String, Object>>() {
					});

			System.out.println("Gender : " + empMap.get("gender"));
			System.out.println("DOB : " + empMap.get("DOB"));
			System.out.println("Name : " + empMap.get("name"));
			System.out.println("ContactNumber : " + empMap.get("contactNumber"));
			System.out.println("SkillSet : " + empMap.get("skillset"));
		} catch (StreamReadException e) {
			e.printStackTrace();
		} catch (DatabindException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

Output

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Serialization – How to convert Map to JSON string using Jackson API

HOME

This tutorial shows how to convert a Java map to JSON string using Jackson’s data binding. In the previous tutorials, I explained converting Java Objects/Arrays to JSON String using Jackson API. You can refer to the below tutorials.

Serialization – How to create JSON Payload from Java Object – Jackson API

How to create JSON Array Payload using POJO – Jackson API

How to create Nested JSON Object using POJO – Jackson API

To start off, add the latest Jackson dataformat Maven dependency to the project.

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.13.0</version>
</dependency>

Sample JSON

{
  "skillset" : [ 
                 "Java",
                 "Teradata",
                 "Python", 
                 "Power BI" 
               ],
  "gender" : "female",
  "DOB" : "12-02-1985",
  "name" : "Vibha Singh",
  "contactNumber" : "+919999988822",
  "employeeId" : "10342256",
  "location" : "Dublin",
  "emailId" : "abc@test.com",
  "salary" : "75000.0"
}

First, we will populate a Map, then convert them into JSON and later write that JSON to a file.

	@Test
	public void SerializationMapTest() {

		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> inputMap = new HashMap<String, Object>();

		inputMap.put("employeeId", "10342256");
		inputMap.put("name", "Vibha Singh");
		inputMap.put("DOB", "12-02-1985");
		inputMap.put("salary", "75000.0");
		inputMap.put("location", "Dublin");
		inputMap.put("contactNumber", "+919999988822");
		inputMap.put("emailId", "abc@test.com");
		inputMap.put("gender", "female");

		List<String> skillset = new ArrayList<String>();

		skillset.add("Java");
		skillset.add("Teradata");
		skillset.add("Python");
		skillset.add("Power BI");

		inputMap.put("skillset", skillset);

		// Converting map to a JSON payload as string
		try {
			String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(inputMap);
			System.out.println(employeePrettyJson);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		String userDir = System.getProperty("user.dir");

        //Writing JSON on a file
		try {
			mapper.writerWithDefaultPrettyPrinter()
					.writeValue(new File(userDir + "\\src\\test\\resources\\JSONFromMap.json"), inputMap);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

Output

As mentioned above, the new JSON is saved in a file and placed under src/test/resources.

Below is the file with JSON.

Congratulations, we are done. We have successfully created a JSON using HashMap.

HashMap in Java

HOME

A HashMap stores items in “key/value” pairs, and you can access them by an index of another type (e.g. a String).

One object is used as a key (index) to another object (value). It can store different types: String keys and Integer values, or the same type, like String keys and String values. We need to import java.util.HashMap or its superclass in order to use the HashMap class and methods.

It is not an ordered collection, which means it does not return the keys and values in the same order in which they have been inserted into the HashMap.

Create a HashMap object as shown below from:-

import java.util.HashMap;

Syntax of HashMap

HashMap<String, String> employeeDetail = new HashMap<String, String>();

HashMap<String, String> employeeDetail = new HashMap<>();

HashMap<String, Integer> employeeDetail = new HashMap<String, Integer>();

Add Items

Below is an example where we are adding items to HashMap by using put() method.

import java.util.HashMap;

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

        /* This is how to declare HashMap of key and Value as String  */
        HashMap<String, String> employeeDetail = new HashMap<String, String>();

        // Add keys and values (Name, Designation)
        employeeDetail.put("Tim", "DBA");
        employeeDetail.put("Dong", "SDET");
        employeeDetail.put("Nisha", "BA");
        employeeDetail.put("Ulana", "Dev");

        System.out.println("Detail of Employees :" + employeeDetail);
    }

}

Below is an example where we are adding items to HashMap by using put() method.

Here, the key is String, and the Value is Integer.

import java.util.HashMap;

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

        // Combination of String(key) and Integer(value)
        HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

        // Add keys and values (Name, Age)
        employeeAge.put("Tim", 25);
        employeeAge.put("Dong", 26);
        employeeAge.put("Nisha", 29);
        employeeAge.put("Ulana", 34);

        System.out.println("Age of Employees :" + employeeAge);
    }

}

Access an Item

To access a value in the HashMap, use the get() method and refer to its key:-

import java.util.HashMap;

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

        // Combination of String(key) and Integer(value)
        HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

        // Add keys and values (Name, Age)
        employeeAge.put("Tim", 25);
        employeeAge.put("Dong", 26);
        employeeAge.put("Nisha", 29);
        employeeAge.put("Ulana", 34);

        System.out.println("Age of Employees :"+ employeeAge);

        // Access a value
        System.out.println("Access Value of Key Nisha :" + employeeAge.get("Nisha"));
    }
}

Remove an Item

To remove an item, use the remove() method and refer to the key:

import java.util.HashMap;

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

        // Combination of String(key) and Integer(value)
        HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

        // Add keys and values (Name, Age)
        employeeAge.put("Tim", 25);
        employeeAge.put("Dong", 26);
        employeeAge.put("Nisha", 29);
        employeeAge.put("Ulana", 34);

        System.out.println("Age of Employees :" + employeeAge);

        // To remove an item, use the remove() method and refer to the key
        employeeAge.remove("Ulana");
        System.out.println("List of Employee after removing Ulana :" + employeeAge);
    }
}

To remove all items, use the clear() method:-

import java.util.HashMap;

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

        // Combination of String(key) and Integer(value)
        HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

        // Add keys and values (Name, Age)
        employeeAge.put("Tim", 25);
        employeeAge.put("Dong", 26);
        employeeAge.put("Nisha", 29);
        employeeAge.put("Ulana", 34);

        System.out.println("Age of Employees :" + employeeAge);

        // To remove all items, use the clear() method:
        employeeAge.clear();
        System.out.println("List of Employes after clear:" + employeeAge);
    }
}

Checking whether HashMap is empty or not

We are using isEmpty() method of the HashMap class to perform this check.

import java.util.HashMap;

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

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

        // Add keys and values (Name, Designation)
        employeeDetail.put("Tim", "DBA");
        employeeDetail.put("Dong", "SDET");
        employeeDetail.put("Nisha", "BA");
        employeeDetail.put("Ulana", "Dev");

        System.out.println("Detail of Employees :" + employeeDetail);

        // Checking whether HashMap is empty or not
        System.out.println("Is HashMap Empty? " + employeeDetail.isEmpty());

        // Delete all items from HasMap
        employeeDetail.clear();
        System.out.println("Is HashMap Empty now? " + employeeDetail.isEmpty());
    }
}

Check if a particular key exists in HashMap

We will be using containsKey() method of the HashMap class to perform this check.  This method returns a boolean value.

import java.util.HashMap;

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

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

        // Add keys and values (Name, Designation)
        employeeDetail.put("Tim", "DBA");
        employeeDetail.put("Dong", "SDET");
        employeeDetail.put("Nisha", "BA");
        employeeDetail.put("Ulana", "Dev");

        System.out.println("Detail of Employees :" + employeeDetail);

        // Check if a particular key exists in HashMap
        boolean flag = employeeDetail.containsKey("Nisha");
        System.out.println("Key Nisha exists in HashMap? : " + flag);

        boolean flag1 = employeeDetail.containsKey("Shawn");
        System.out.println("Key Shawn exists in HashMap? : " + flag1);
    }
}

Check if a particular value exists in HashMap

We will be using containsValue() method of the HashMap class to perform this check.

import java.util.HashMap;

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

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

        // Add keys and values (Name, Designation)
        employeeDetail.put("Tim", "DBA");
        employeeDetail.put("Dong", "SDET");
        employeeDetail.put("Nisha", "BA");
        employeeDetail.put("Ulana", "Dev");

        System.out.println("Detail of Employees :" + employeeDetail);

        // Check if a particular value exists in HashMap
        boolean valueExists = employeeDetail.containsValue("Dev");
        System.out.println("String Dev exists in HashMap? : " + valueExists);

        boolean valueNotExists = employeeDetail.containsValue("Test");
        System.out.println("String Test exists in HashMap? : " + valueNotExists);
    }
}

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!