Thursday, September 29, 2022

Java Map compute() With Examples

The compute() method in java.util.Map is added in Java 8 and used to compute a new value for the specified key.

Syntax of the compute method is as given below.

V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)

Parameters are as-

  • key- First parameter is the key with which the value is associated.
  • remappingFunction- This parameter is of type BiFunction functional interface and provides a function to compute new value

Method returns the new value associated with the specified key, or null if none.

The compute() method is very convenient if you want to modify value for a specified key, performs the following logic with in a one line method call.

if (oldValue != null ) {
    if (newValue != null)
       map.put(key, newValue);
    else
       map.remove(key);
 } else {
    if (newValue != null)
       map.put(key, newValue);
    else
       return null;
 }

Logic for the compute() method is as given below.

  1. If old value for the specified key is not null and the computed new value is also not null then the old value is replaced by new value for the key.
  2. If old value for the specified key is not null but the computed new value is null then the key is removed.
  3. If old value for the specified key is null and the computed new value is not null then the old value is replaced by new value for the key.
  4. If old value for the specified key is null and the computed new value is also null then return null (remove that key).

Let's try to understand all these scenarios with the help of examples.

compute() Java Examples

1. Here we have a map of items where item is the key and price is the associated value. We'll try to compute a new value for an existing key, value pair.

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

public class ComputeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", 750);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    // Increase price by 10%
    itemMap.compute("Trousers", (k,v) -> v + (v*10/100));
    System.out.println("*** Map After compute ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}
*** Map After compute ***
{Shirt=800, Belt=750, Shoes=2000, Trousers=1320}

2. In this example the remappingFunction returns null as the new value. In that case key, value pair should be removed.

public class ComputeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", 750);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    // New value as null
    itemMap.compute("Trousers", (k,v) -> null);
    System.out.println("*** Map After compute ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}
*** Map After compute ***
{Shirt=800, Belt=750, Shoes=2000}

As you can see "Trousers" is removed as key from our map.

3. In this example we'll have one of the items with price as null and then a new value will be computed which is not null. In that case null should be replace with the new value for the specified key.

public class ComputeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", null);
    itemMap.put("Belt", 750);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);

    itemMap.compute("Shoes", (k,v) -> 2500);
    System.out.println("*** Map After compute ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Belt=750, Shoes=null, Trousers=1200}
*** Map After compute ***
{Shirt=800, Belt=750, Shoes=2500, Trousers=1200}

Here you can see that the initial value for the key "Shoes" is null and the new value is computed as 2500.

4. In this example we'll have one of the items with price as null and then a new value will be computed which is also null. In that case the specified key should be removed.

public class ComputeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", null);
    itemMap.put("Belt", 750);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);

    itemMap.compute("Shoes", (k,v) -> null);
    System.out.println("*** Map After compute ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Belt=750, Shoes=null, Trousers=1200}
*** Map After compute ***
{Shirt=800, Belt=750, Trousers=1200}

That's all for this topic Java Map compute() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map computeIfPresent() With Examples
  2. LinkedHashMap in Java With Examples
  3. Map.Entry Interface in Java
  4. How to Sort Elements in Different Order in TreeSet
  5. Fail-Fast Vs Fail-Safe Iterator in Java

You may also like-

  1. Array in Java With Examples
  2. intern() Method in Java String
  3. Try-With-Resources in Java With Examples
  4. Quick Sort Program in Java
  5. Custom Validator in Angular Reactive Form
  6. Accessing Characters in Python String
  7. Sending Email Using Spring Framework Example
  8. Spring Integration With Quartz Scheduler

Monday, September 26, 2022

Java - Could not find or load main class error Fix

In this post we'll see when you can get "Could not find or load main class error" in Java and how to resolve it. From the error itself it is evident when you are trying to run the program JVM is not able to find a class with main method and start the execution.

Could not find or load main class error and resolution

Two scenarios where you may encounter this error are-

  1. Not using the correct class name while executing the program.
  2. Not using the fully qualified class name and from the correct path.

Let's try to see both scenarios with an example.

Here is a simple Java program written in a class named "MyJavaClass" and saved in a file name "MyJavaClass.java"

public class MyJavaClass{
	public static void main(String[] args){
		System.out.println("This is my Java program");
	}
}

You can compile this Java program using the javac command and passing the full file name.

javac MyJavaClass.java

Once the file is compiled a .class file with the exact same name as the class name in your Java program is generated in the same directory where the java file resides.

In order to run the program, you will have to use the java command and passing the name of the .class file. That's when you can make a mistake where you can get "Could not find or load main class error"

1. Not using the correct class name

Since the generated class file has the exact same name as the class name which means class file in our example is generated as MyJavaClass.class. If you need to run your program, you will have to use the following command.

C:\>java MyJavaClass
This is my Java program

If you deviate in any way from this name you will get the error.

C:\>java Myjavaclass
Error: Could not find or load main class Myjavaclass
Caused by: java.lang.NoClassDefFoundError: MyJavaClass (wrong name: Myjavaclass)

Here name is given as Myjavaclass instead of MyJavaClass thus the error.

2. Even the extension .class is not required.

As you can see while executing the program you have to give the name of the class with out the extension .class. Giving the full name while trying to execute also results in an error.

C:\>java MyJavaClass.class
Error: Could not find or load main class MyJavaClass.class
Caused by: java.lang.ClassNotFoundException: MyJavaClass.class

Class in a package

In the above example we have not used any package but having a class within a package may also cause the "Could not find or load main class error" if fully qualified class name is not used and from the correct path.

Let's try to include a package in our example program.

package com.netjstech;

public class MyJavaClass{
	public static void main(String[] args){
		System.out.println("This is my Java program");
	}

}

You can use the following command to compile it so that the correct folder structure as per the package name given is created.

C:\>javac -d . MyJavaClass.java

With this command you will see that the .class file is created with in the folder com\netjstech. You may think that by going to that location you should be able to run the program.

C:\com\netjstech>java MyJavaClass
Error: Could not find or load main class MyJavaClass
Caused by: java.lang.NoClassDefFoundError: com/netjstech/MyJavaClass (wrong name: MyJavaClass)

As you can see now even after providing the correct class name (java MyJavaClass) still there is an error.

Class is in the package now, so you need to use the fully qualified class name (package + class name) to locate the class. Fully qualified class name in our case is- com.netjstech.MyJavaClass

C:\com\netjstech >java com.netjstech.MyJavaClass
Error: Could not find or load main class com.netjstech.MyJavaClass
Caused by: java.lang.ClassNotFoundException: com.netjstech.MyJavaClass

As you can see even that results in an error because you are already at the location (com\netjstech) and then you are using the fully qualified class name too. When you use the fully qualified class name Java itself tries to use that full name to find the correct location.

In our case when we give the fully qualified name (java com.netjstech.MyJavaClass), Java tries to look for the class MyJavaClass with in com\netjstech from the current path which itself is C:\com\netjstech.

So, you need to go two levels up and then use the fully qualified name to run this program successfully.

C:\> java com.netjstech.MyJavaClass
This is my Java program

That's all for this topic Java - Could not find or load main class error Fix. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. static Reference to The Non-static Method or Field Error
  2. Why Class Name And File Name Should be Same in Java
  3. Why main Method static in Java
  4. java.lang.ClassCastException - Resolving ClassCastException in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Difference Between StackOverflowError and OutOfMemoryError in Java
  2. final Keyword in Java With Examples
  3. Deadlock in Java Multi-Threading
  4. HashMap Vs LinkedHashMap Vs TreeMap in Java
  5. Interface Static Methods in Java
  6. Compare Dates in Java
  7. Angular @Input and @Output Example
  8. Spring JdbcTemplate Insert, Update And Delete Example

Friday, September 23, 2022

Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example

In the post Spring MVC Exception Handling Tutorial we have already got an overview of how exception handling can be configured in Spring MVC application. In this post we’ll see a Spring MVC exception handling example using @ExceptionHandler, @ControllerAdvice, @ResponseStatus annotations and by rendering a default error page when exception is not resolved by any HandlerExceptionResolver.

Technologies used

Following is the list of tools used for the Spring MVC exception handling example.

  1. Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  2. Java 10
  3. Tomcat server V 9.0.10
  4. Eclipse IDE

Thursday, September 22, 2022

Compare Dates in Java

In this tutorial we'll see how to compare dates in Java using java.util.Date, java.util.Calendar and using the new Date and Time API in Java which has classes in java.time package.


Comparing java.util.Date

For comparing two dates method provided by java.util.Date class are-

  • int compareTo(Date anotherDate)- Compares two Dates for ordering.
  • equals(Object obj)- Compares two dates for equality.
  • after(Date when)- Tests if this date is after the specified date.
  • before(Date when)- Tests if this date is before the specified date.

Date.compareTo() Java example

compareTo() method returns one of the following three values.

  • Returns 0 if the argument Date is equal to this Date.
  • Returns a value less than 0 if this Date is before the Date argument
  • Returns a value greater than 0 if this Date is after the Date argument
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateCompareTo {

  public static void main(String[] args) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMMM-yyyy");
    Date date1 = sdf.parse("16-08-2022");
    Date date2 = sdf.parse("12-08-2022");
    
    System.out.println("date1 is- " + sdf1.format(date1));
    System.out.println("date2 is- " + sdf1.format(date2));
    
    Date date3 = sdf.parse("10-08-2022");
    Date date4 = sdf.parse("15-08-2022");
    System.out.println("date3 is- " + sdf1.format(date3));
    System.out.println("date4 is- " + sdf1.format(date4));
        
    // Comparison for date1 and date2
    int comp = date1.compareTo(date2);
    System.out.println("Comparison value is: " + comp);
    
    if(comp == 0) {
      System.out.println("Date1 is equal to Date2");
    } else if(comp > 0) {
      System.out.println("Date1 comes after Date2");
    }else if(comp < 0) {
      System.out.println("Date1 comes before Date2");
    }
     // Comparison for date3 and date4
    comp = date3.compareTo(date4);
    System.out.println("Comparison value is: " + comp);
    
    if(comp == 0) {
      System.out.println("Date3 is equal to Date4");
    } else if(comp > 0) {
      System.out.println("Date3 comes after Date4");
    }else if(comp < 0) {
      System.out.println("Date3 comes before Date4");
    }
  }
}

Output

date1 is- 16-August-2022
date2 is- 12-August-2022
date3 is- 10-August-2022
date4 is- 15-August-2022
Comparison value is: 1
Date1 comes after Date2
Comparison value is: -1
Date3 comes before Date4

Date.equals() Java example

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateEquals {

  public static void main(String[] args) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMMM-yyyy");
    Date date1 = sdf.parse("16-08-2022");
    Date date2 = sdf.parse("12-08-2022");

    System.out.println("date1 is- " + sdf1.format(date1));
    System.out.println("date2 is- " + sdf1.format(date2));

    if(date1.equals(date2)) {
      System.out.println("Date1 is equal to Date2");
    }else {
      System.out.println("Date1 is not equal to Date2");
    }

    Date date3 = sdf.parse("15-08-2022");
    Date date4 = sdf.parse("15-08-2022");
    System.out.println("date3 is- " + sdf1.format(date3));
    System.out.println("date4 is- " + sdf1.format(date4));

    if(date3.equals(date4)) {
      System.out.println("Date3 is equal to Date4");
    }else {
      System.out.println("Date3 is not equal to Date4");
    }
  }
}

Output

date1 is- 16-August-2022
date2 is- 12-August-2022
Date1 is not equal to Date2
date3 is- 15-August-2022
date4 is- 15-August-2022
Date3 is equal to Date4

Date.after() and Date.before() Java example

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateAfterBefore {

  public static void main(String[] args) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMMM-yyyy");
    Date date1 = sdf.parse("16-08-2022");
    Date date2 = sdf.parse("12-08-2022");

    System.out.println("date1 is- " + sdf1.format(date1));
    System.out.println("date2 is- " + sdf1.format(date2));

    if(date1.after(date2)) {
      System.out.println("Date1 is after Date2");
    }

    if(date1.before(date2)) {
      System.out.println("Date1 is before Date2");
    }
  }
}

Output

date1 is- 16-August-2022
date2 is- 12-August-2022
Date1 is after Date2

Comparing java.util.Calendar

A step ahead of java.util.date but still part of the old date and time API Calendar class also has a same set of methods as Date for comparison.

  • after(Object when)- Returns whether this Calendar represents a time after the time represented by the specified Object
  • before(Object when)- Returns whether this Calendar represents a time before the time represented by the specified Object.
  • compareTo(Calendar anotherCalendar)- Compares the time values (millisecond offsets from the Epoch) represented by two Calendar objects.
  • equals(Object obj)- Compares this Calendar to the specified Object.

Calendar.compareTo Java Example

compareTo() method returns one of the following three values.

  • Returns 0 if the if the time represented by the argument is equal to the time represented by this Calendar
  • Returns a value less than 0 if the time of this Calendar is before the time represented by the argument
  • Returns a value greater than 0 if the time of this Calendar is after the time represented by the argument
import java.util.GregorianCalendar;

public class CalendarCompare {

  public static void main(String[] args) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy");
    GregorianCalendar date1 = new GregorianCalendar(2022, Calendar.MAY, 20, 18, 9, 22);
    GregorianCalendar date2 = new GregorianCalendar(2022, Calendar.MAY, 22, 18, 9, 22);
    
    System.out.println("date1 is- " + sdf.format(date1.getTime()));
    System.out.println("date2 is- " + sdf.format(date2.getTime()));

    int comp = date1.compareTo(date2);
    System.out.println("Comparison value is: " + comp);
      
    if(comp == 0) {
      System.out.println("Date1 is equal to Date2");
    } else if(comp > 0) {
      System.out.println("Date1 comes after Date2");
    }else if(comp < 0) {
      System.out.println("Date1 comes before Date2");
    }
  }
}

Output

date1 is- 20-May-2022
date2 is- 22-May-2022
Comparison value is: -1
Date1 comes before Date2

Calendar.equals() Java example

public class CalendarCompare {

  public static void main(String[] args) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy");
    GregorianCalendar date1 = new GregorianCalendar(2022, Calendar.MAY, 20, 18, 9, 22);
    GregorianCalendar date2 = new GregorianCalendar(2022, Calendar.MAY, 22, 18, 9, 22);
    
    System.out.println("date1 is- " + sdf.format(date1.getTime()));
    System.out.println("date2 is- " + sdf.format(date2.getTime()));
    
    if(date1.equals(date2)) {
      System.out.println("Date1 is equal to Date2");
    }else {
      System.out.println("Date1 is not equal to Date2");
    }
  }
}

Output

date1 is- 20-May-2022
date2 is- 22-May-2022
Date1 is not equal to Date2

Calendar.after() and Calendar.before() Java example

public class CalendarCompare {

  public static void main(String[] args) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy");
    GregorianCalendar date1 = new GregorianCalendar(2022, Calendar.MAY, 20, 18, 9, 22);
    GregorianCalendar date2 = new GregorianCalendar(2022, Calendar.MAY, 22, 18, 9, 22);
    
    System.out.println("date1 is- " + sdf.format(date1.getTime()));
    System.out.println("date2 is- " + sdf.format(date2.getTime()));
    
    if(date1.after(date2)) {
      System.out.println("Date1 is after Date2");
    }
    
    if(date1.before(date2)) {
      System.out.println("Date1 is before Date2");
    }       
  }
}

Output

date1 is- 20-May-2022
date2 is- 22-May-2022
Date1 is before Date2

Comparing LocalDate in Java

Java 8 added a new Date and Time API which has classes like LocalDate, LocalTime and LocalDateTime to represent date, time and date-time.

For comparing two LocalDate instances methods are-

  • isEqual(ChronoLocalDate other)- Checks if this date is equal to the specified date. Returns true if this date is equal to the specified date.
  • isAfter(ChronoLocalDate other)- Checks if this date is after the specified date. Returns true if this date is after the specified date.
  • isBefore(ChronoLocalDate other)- Checks if this date is before the specified date. Returns true if this date is before the specified date.
  • equals(Object obj)- Checks if this date is equal to another date. Returns true if this date is equal to the other date.
  • compareTo(ChronoLocalDate other)- Compares this date to another date. Returns a negative value if this Date is before the Date argument, a positive value if this Date is after the Date argument, value 0 if dates are equal.
import java.time.LocalDate;
import java.time.Month;

public class LocalDateCompare {

  public static void main(String[] args) {
    LocalDate date1 = LocalDate.of(2022, Month.APRIL, 28);
    LocalDate date2 = LocalDate.of(2022, Month.APRIL, 26);
    
    System.out.println("Date1- " + date1);
    System.out.println("Date2- " + date2);
    
    // Using compareTo()
    if(date1.compareTo(date2) == 0) {
      System.out.println("Date1 is equal to Date2");
    }else if(date1.compareTo(date2) > 0) {
      System.out.println("Date1 comes after Date2");
    }else if(date1.compareTo(date2) < 0) {
      System.out.println("Date1 comes before Date2");
    }
    
    // Using equals
    if(date1.equals(date2)) {
      System.out.println("Date1 is equal to Date2");
    }else {
      System.out.println("Date1 is not equal to Date2");
    }
    
    // Using isAfter()
    if(date1.isAfter(date2)) {
      System.out.println("Date1 comes after Date2");
    }
    // Using isBefore()
    if(date1.isBefore(date2)) {
      System.out.println("Date1 comes before Date2");
    }
    // Using isEqual()
    if(date1.isEqual(date2)) {
      System.out.println("Date1 is equal to Date2");
    }
  }

}

Output

Date1- 2022-04-28
Date2- 2022-04-28
Date1 is equal to Date2
Date1 is equal to Date2
Date1 is equal to Date2

That's all for this topic Compare Dates in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Difference Between Two Dates in Java
  2. How to Display Time in AM-PM Format in Java
  3. Format Date in Java Using SimpleDateFormat
  4. Java Program to Get Current Date and Time
  5. How to Find Last Modified Date of a File in Java

You may also like-

  1. Linked List Implementation Java Program
  2. Reading File in Java Using Files.lines And Files.newBufferedReader
  3. Producer-Consumer Java Program Using wait notify
  4. StringJoiner Class in Java 8
  5. Java is a Strongly Typed Language
  6. Spring Object XML Mapping (OXM) JAXB Example
  7. Spring WebFlux Example Using Functional Programming - Spring Web Reactive
  8. What is Client Side Routing in Angular

Wednesday, September 21, 2022

Spring Boot Spring Initializr

In the post Spring Boot Hello World Web Application Example we have already seen how to create a Spring Boot application by adding Maven dependencies yourself but you don’t even need to add dependencies or create build file yourself instead you can use Spring Initializr to create a Spring Boot application.


Using Spring Initializr

Spring Initializr provides a web UI (https://start.spring.io), you can enter details about your application, pick your favorite build system, version of Spring Boot you want to use and then choose the required dependencies from a menu. Click the Generate Project button, and you have a ready-to-execute application.

Options you can choose using Spring Initializr are-

  1. Build System- Maven Project or Gradle Project
  2. Language- Java, Kotlin or Groovy
  3. Spring Boot version
  4. Project metadata- Group, Artifact and other Options like Name, Java version, packaging (Jar or War)
  5. Dependencies- To select the required dependencies in the form of starters.
Spring Initializr

Spring Boot application using Spring Initializr

In this example we’ll create a Hello world web application using Spring Initializr. For the project build system selected is Maven.

Since we are building a web application, in the Dependencies section type web, from the suggested options select ‘Spring Web Starter’ for the web application. This starter adds the dependencies required for creating a Spring web application and also includes Tomcat as the default embedded container.

Following image shows the selected options for the example-

Spring Initializr application

Click “Generate the project” and save the generated zip file when prompted. This zip file contains the generated Maven project based on the options you chose in Spring Initializr.

You can unzip the downloaded zip file, you should see the genrated project structure with a build file (pom.xml).

Import generated project

You can import generated Maven project to Eclipse IDE.

Select File – Import – Maven – Existing Maven Project

In the “Import Maven Projects” window, Select Root directory as the location where you have unzipped the downloaded zipped project structure.

Select the pom.xml file for the project and click Finish to start the import.

Spring Boot Spring Initializr

On opening the pom.xml you should see the Spring boot version, Java version as per your selection in Spring Initializr. Also the spring-boot-starter-web for the selected dependency.

Spring Initializr also adds-

spring-boot-starter-test which pulls all the required dependencies for unit testing like Spring Boot Test, JSONPath, JUnit, AssertJ, Mockito, Spring Test.

spring-boot-maven-plugin which provides many convenient features-

  • It creates an executable jar (fat jar) by collecting all the jars on the classpath.
  • It searches for the public static void main() method to flag as a runnable class.
  • It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>org.netjs</groupId>
  <artifactId>SpringBootApp</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringBootApp</name>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>11</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

In the generated project you’ll also find an application class with the main method-

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootAppApplication {
 public static void main(String[] args) {
  SpringApplication.run(SpringBootAppApplication.class, args);
 }
}

@SpringBootApplication is a convenience annotation that adds all of the following:

  • @Configuration: Marks this class as a source of bean definitions for the application context.
  • @EnableAutoConfiguration: Tells Spring Boot to automatically start creating beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.
  • @ComponentScan: Tells Spring to look for other components, configurations, and services in the base package, letting it find the controllers.

Main method in the class is the application entry point. The main method delegates to Spring Boot’s SpringApplication class by calling run method. It is the task of SpringApplication to bootstrap our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server.

Rest Controller class

As you can see by selecting options in the Spring Initializr you have the build file with the appropriate starters and an application class in place.

We’ll add a rest controller class annotated with @RestController annotation to get the hello world functionality.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
  @GetMapping(value="/{name}")
  public String displayMessage(@PathVariable("name") String name) {
    return "Hello " + name;
  }
}

The @GetMapping annotation provides “routing” information here. It tells Spring that any HTTP request with the /name path should be mapped to the displayMessage method.

Running the Spring Boot Hello world Rest application

1. You can run this application as a Java application by executing the class with main method.

Right click SpringBootAppApplication – Run As – Java Application

That will start the SpringBootApp, initialize WebApplicationContext and Tomcat server.

You can access the application by entering http://localhost:8080/netjs

Here /netjs is the value for the name parameter.

2. spring-boot-starter-parent POM also provides a run goal that you can use to start the application. Type mvn spring-boot:run from the root project directory to start the application.

F:\NETJS\NetJS_2017\Spring Boot\SpringBootApp\SpringBootApp>mvn spring-boot:run

3. You can also create a completely self-contained executable jar file. We have already added spring-boot-maven-plugin in pom.xml for this.

To create an executable Jar run mvn package from the root project directory.

F:\NETJS\NetJS_2017\Spring Boot\SpringBootApp\SpringBootApp>mvn package

[INFO] Building jar: F:\NETJS\NetJS_2017\Spring Boot\SpringBootApp\SpringBootApp\target\SpringBootApp-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.1.9.RELEASE:repackage (repackage) @ SpringBootApp ---
[INFO] Replacing main artifact with repackaged archive
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 31.979 s
[INFO] Finished at: 2019-10-08T12:18:08+05:30
[INFO] Final Memory: 23M/77M
[INFO] ------------------------------------------------------------------------

If you look in the target directory, you should see SpringBootApp-0.0.1-SNAPSHOT.jar. To run that application, use the java -jar command, as follows:

F:\NETJS\NetJS_2017\Spring Boot\SpringBootApp\SpringBootApp>java -jar target\SpringBootApp-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.9.RELEASE)

2019-10-08 12:20:07.395  INFO 11676 --- [           main] o.n.S.SpringBootAppApplication           : Starting SpringBootAppApplication v0.0.1-SNAPSHOT on user 
with PID 11676 (F:\NETJS\NetJS_2017\Spring Boot\SpringBootApp\SpringBootApp\target\SpringBootApp-0.0.1-SNAPSHOT.jar 
2019-10-08 12:20:07.410  INFO 11676 --- [           main] o.n.S.SpringBootAppApplication           : No active profile set, falling back to default profiles: default
2019-10-08 12:20:11.326  INFO 11676 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-10-08 12:20:11.607  INFO 11676 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-10-08 12:20:11.607  INFO 11676 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.26]
2019-10-08 12:20:12.190  INFO 11676 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-10-08 12:20:12.191  INFO 11676 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4625 ms
2019-10-08 12:20:13.531  INFO 11676 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-10-08 12:20:14.328  INFO 11676 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-10-08 12:20:14.360  INFO 11676 --- [           main] o.n.S.SpringBootAppApplication           : Started SpringBootAppApplication in 9.324 seconds (JVM running for 12.267)

That's all for this topic Spring Boot Spring Initializr. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Boot StandAlone (Console Based) Application Example
  2. Spring Boot spring-boot-starter-parent
  3. Spring MVC JSON as Response Example
  4. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  5. Spring MVC Checkbox And Checkboxes Form Tag Example

You may also like-

  1. Spring XML Configuration Example
  2. Spring Object XML Mapping (OXM) Castor Example
  3. Passing Arguments to getBean() Method in Spring
  4. Spring Integration With Quartz Scheduler
  5. ListIterator in Java
  6. Parallel Stream in Java Stream API
  7. Producer-Consumer Java Program Using ArrayBlockingQueue
  8. Python Program to Display Fibonacci Series

Tuesday, September 20, 2022

Linked List Implementation Java Program

In this post we’ll see an implementation of Linked List in Java. Operations covered in this singly Linked List Java implementation are as per the given table of contents-


Linked List data structure

Linked list data structure though linear in nature doesn’t store its node in contiguous memory location like array. In Linked list nodes are linked by each node holding reference to the next node.

Following image shows the nodes in the Linked List and how nodes are linked.

Linked list implementation in Java

Java program for Linked List

For representing nodes of the linked list a separate class is used which, apart from the data, also holds a reference to itself.

class Node{
 //data
 int i;
 // Reference to next node
 Node next;
}

Java implementation of linked list given here is a double ended list where we have two references head and tail; head always points to the first node and the tail is a reference to the last node.

Insertion in linked list

For insertion there are three scenarios insert at the beginning, insert at the end and insert at the given index.

1- Inserting node in linked list at the beginning has two scenarios.

If it is the first node then both head and tail should point to it.

If nodes already exist then the inserted node should reference the current first node and head should start pointing to the inserted node.

public void insertFirst(int i){
 //Create a new node
 Node newNode = new Node(i);
 if(isEmpty()){
  tail = newNode;
 }
 newNode.next = head;
 head = newNode;
 size++;
}

Note here that size variable is used to store the current size of the List.

2- Inserting node in linked list at the end has two scenarios.

If it is the first node then both head and tail should point to it.

If nodes already exist then the current last node should reference the inserted node and tail should start pointing to the inserted node.

public void insertLast(int i){
 Node newNode = new Node(i);
 if(isEmpty()){
  head = newNode;
 }else{
  tail.next = newNode;
 }
 tail = newNode;
 size++;
}
3- Inserting node in linked list at the given index has three scenarios.

If inserting at index 0 that is equivalent to insertFirst.

If inserting at index when (index == size) that is equivalent to insertLast.

Otherwise traverse to the node currently at the given index and change the references so that the new node starts referencing the current node and the node which was previously referencing the current node should start referencing the new node.

linked list insertion java
public void insertAtIndex(int i, int index){
  if(!isValidIndex(index)){
    throw new IndexOutOfBoundsException("Index " + index +" not valid for linked list of size " + size);
  }
  Node newNode = new Node(i);
  Node current = head;
  Node temp = head;
  //insert at the start
  if(index == 0){
    insertFirst(i);
  }
  // insert at last
  else if(index == size){
    insertLast(i);
  }else{
    for(int j = 0; j < index && current.next != null; j++){
      temp = current;
      current = current.next;
    }
    newNode.next = current;
    temp.next = newNode;
    size++;    
  }        
}

Linked List traversal

For Linked list traversal from start to end you need to start from head and then move sequentially unless the next node reference is not null.

// Method to traverse and display all nodes
public void displayList(){
 Node current = head;
 while(current != null){
  current.displayData();
  current = current.next;
 }
 System.out.println("");
}

To get element at a given index traverse to the node currently at that index and return that node.

public Node get(int index){
  if(!isValidIndex(index)){
    throw new IndexOutOfBoundsException("Index " + index +" not valid for linked list of size " + size);
  }
  Node current = head;
  for(int j = 0; j < index; j++){
    current = current.next;
  }
  return current;        
}

Deleting node in Linked List

For deletion there are three scenarios-

  • Delete first node
  • Delete last node
  • Delete node at given index

1- If you are deleting the first node then in your Linked list Java program what you need to do is to change the head reference so that it starts referencing the next node.

public void removeFirst(){
 if(head == null){
  throw new RuntimeException("List is empty..");
 }
 // if there is only one node
 if(head.next == null){
  tail = null;
 }
 head = head.next;
 size--;
}

2- If you are deleting the last node in a linked list then change the reference for tail so that it starts referencing the previous node. Since it is a singly linked list implementation so you need to start from the first node and traverse the list till the end.

public void removeLast(){
 if(tail == null){
  throw new RuntimeException("List is empty..");
 }
 Node current = head;
 Node temp = head;
 // if there is only one node
 if(head.next == null){
  head = null;
 }  
 while(current != tail){
  temp = current;
  current = current.next;
 }
 tail = temp;
 tail.next = null;
 size--;
}
3- Deleting node at the given index has three scenarios.

If deleting node at index 0 that is equivalent to removeFirst.

If deleting node at index when (index == size) that is equivalent to removeLast.

Otherwise traverse to the node at the given index and change the references so that the node on the left of the node to be deleted starts referencing the node on the right of the node to be deleted.

public void removeAtIndex(int index){   
  if(!isValidIndex(index +1)){
    throw new IndexOutOfBoundsException("Index " + index +" not valid for linked list of size " + size);
  }
  Node current = head;
  Node temp = head;
  //remove at the start
  if(index == 0){
    removeFirst();
  }
  // remove at last
  else if(index == size - 1){
    removeLast();
  }else{
    for(int j = 0; j < index && current.next != null; j++){
      temp = current;
      current = current.next;
    }
    temp.next = current.next;
    current.next = null;
    size--;
  }
}

Linked List implementation in Java – Full Program

class Node{
  //data
  int i;
  // Reference to next node
  Node next;

  public Node(int i){
    this.i = i;
    this.next = null;
  }
  public void displayData(){
    System.out.print(" " + i);
  }
}

public class LinkedList {
  private Node head;
  private Node tail;
  private int size = 0;
  public LinkedList(){
    head = null;
    tail = null;
  }
  public boolean isEmpty(){
    return head == null;
  }
    
  public void insertFirst(int i){
    //Create a new node
    Node newNode = new Node(i);
    if(isEmpty()){
      tail = newNode;
    }
    newNode.next = head;
    head = newNode;
    size++;
  }
    
  public void insertLast(int i){
    Node newNode = new Node(i);
    if(isEmpty()){
      head = newNode;
    }else{
      tail.next = newNode;
    }
    tail = newNode;
    size++;
  }
    
  public void insertAtIndex(int i, int index){
    if(!isValidIndex(index)){
      throw new IndexOutOfBoundsException("Index " + index +" not valid for linked list of size " + size);
    }
    Node newNode = new Node(i);
    Node current = head;
    Node temp = head;
    //insert at the start
    if(index == 0){
      insertFirst(i);
    }
    // insert at last
    else if(index == size){
      insertLast(i);
    }else{
      for(int j = 0; j < index && current.next != null; j++){
        temp = current;
        current = current.next;
      }
      newNode.next = current;
      temp.next = newNode;
      size++;    
    }        
  }
    
  public Node get(int index){
    if(!isValidIndex(index)){
      throw new IndexOutOfBoundsException("Index " + index +" not valid for linked list of size " + size);
    }
    Node current = head;
    for(int j = 0; j < index; j++){
      current = current.next;
    }
    return current;        
  }
    
  // Method to traverse and display all nodes
  public void displayList(){
    Node current = head;
    while(current != null){
      current.displayData();
      current = current.next;
    }
    System.out.println("");
  }
    
  public void removeFirst(){
    if(head == null){
      throw new RuntimeException("List is empty..");
    }
    // if there is only one node
    if(head.next == null){
      tail = null;
    }
    head = head.next;
    size--;
  }
    
  public void removeLast(){
    if(tail == null){
      throw new RuntimeException("List is empty..");
    }
    Node current = head;
    Node temp = head;
    // if there is only one node
    if(head.next == null){
      head = null;
    }        
    while(current != tail){
      temp = current;
      current = current.next;
    }
    tail = temp;
    tail.next = null;
    size--;
  }
    
  public void removeAtIndex(int index){
    if(!isValidIndex(index +1)){
      throw new IndexOutOfBoundsException("Index " + index +" not valid for linked list of size " + size);
    }
    Node current = head;
    Node temp = head;
    //remove at the start
    if(index == 0){
      removeFirst();
    }
    // remove at last
    else if(index == size - 1){
      removeLast();
    }else{
      for(int j = 0; j < index && current.next != null; j++){
        temp = current;
        current = current.next;
      }
      temp.next = current.next;
      current.next = null;
      size--;
    }
  }
    
  private boolean isValidIndex(int index){
    return index >= 0 && index <= size;
  }
    
  public static void main(String[] args) {
    LinkedList list = new LinkedList();
    
    list.insertFirst(1);
    list.insertLast(2);
    list.insertLast(3);
    list.insertLast(4);
    list.insertLast(5);
    System.out.println("After insertions--");
    list.displayList();
    list.removeLast();
    System.out.println("After removal--");
    list.displayList();
    list.removeAtIndex(1);
    System.out.println("After removal--");
    list.displayList();
    System.out.println("Get Node--");
    Node node = list.get(1);
    node.displayData();
  }
}

Output

After insertions--
 1 2 3 4 5
After removal--
 1 2 3 4
After removal--
 1 3 4
Get Node--
 3

That's all for this topic Linked List Implementation Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Reverse a Linked List in Java
  2. Java Program to Detect And Remove Loop in a Linked List
  3. Binary Tree Traversal Using Depth First Search Java Program
  4. Exponential Search Program in Java
  5. Radix Sort Program in Java

You may also like-

  1. How to Display Time in AM-PM Format in Java
  2. How to Find Last Modified Date of a File in Java
  3. Setting And Getting Thread Name And Thread ID in Java
  4. How to Find Common Elements Between Two Arrays Java Program
  5. How LinkedList Class Works Internally in Java
  6. Lambda Expressions in Java 8
  7. Switch-Case Statement in Java
  8. Spring Asynchronous Method Execution Support Using @Async Annotation

Monday, September 19, 2022

Java is a Strongly Typed Language

One thing about Java which you should know before you dig any deeper is that Java is a strongly typed language. What it means is that every variable must be declared with a proper type before those variables can be used.

<type> <variable>;

Here type may be a primitive data type or a non-primitive data type (user defined type i.e. a class).

Here are some examples of variable declaration using primitive types

int x;
float f;

Here are some examples of variable declaration using non-primitive types (some class)

Employee e;
ArrayList numList;
Scanner sc;

But that is not all that makes Java strongly typed, each assignment and parameter passing to the method is checked for type compatibility.

For example, a variable once declared as int can only be assigned an Integer value.

int x = 5; // correct assignment is compatible to variable type
x = 10;  // correct new assignment is compatible to variable type
x = 10.92; // error trying to assign decimal value to an int type variable
x = "test"; // error trying to assign String value to an int type variable

Same way for classes where assignment is a bit different because you actually create an object of the class but still it has to be of compatible type.

Employee emp = new Employee();

Refer Class in Java for more clarity on how class is created and how object of a class is defined.

Same way as an example let's say you have a method sum in a class as defined below

public class Test {

	public static void main(String[] args) {
		Test t = new Test();
		t.sum(5.6, 6.7);
		t.sum("a", "b"); // Error trying to pass parameters of incompatible type
		t.sum(4, 5);
	}
	
	public void sum(double a, double b){
		double r = a + b;
		System.out.println("Sum is- " + r);
	}
}

As you can see method sum takes two arguments of type double so first call to the method is correct but second call where two parameters of type String are passed results in an error.

You may wonder why third call where two parameters of type int are passed works? That is because both int and double are ultimately numbers and there is something called widening type conversion which takes care of this parameter passing.

Refer Type Casting in Java With Conversion Examples to know more about type conversion in Java.

Advantages of strongly typed language

One of the main advantages of strongly typed language is having strict type checking at the compile time itself. So that at run time you don't have exceptions thrown for incompatible types.

Java 10 introduced a new feature called local variable type inference where the type of the variable is inferred from the variable initializer. A new reserved type name "var" is added in Java to define and initialize local variables, read more about var type here- Var type in Java - Local Variable Type Inference

That's all for this topic Java is a Strongly Typed Language. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Java Pass by Value or Pass by Reference
  2. Java Automatic Numeric Type Promotion
  3. Why Class Name And File Name Should be Same in Java
  4. Why main Method static in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Object Creation Using new Operator in Java
  2. super Keyword in Java With Examples
  3. Difference Between Abstract Class And Interface in Java
  4. Check Given Strings Anagram or Not Java Program
  5. ArrayList in Java With Examples
  6. Spring Java Configuration Example Using @Configuration
  7. Angular First App - Hello world Example
  8. Python continue Statement With Examples

Sunday, September 18, 2022

Method Reference in Java

We generally use lambda expressions to create anonymous methods but sometimes lambda expressions are also used to call an existing method. There is another feature provided in Java 8 related to lambda expression called method reference in Java that provides a clearer alternative to refer to the existing method by name.

Important thing to note about Java method references is that they provide a way to refer to a method, they don't execute the method.

Method reference in Java relates to lambda expression as they also require a target type context and at the time of execution they also create an instance of functional interface.

How lambda expressions and method references differ is where lambda expressions let us define anonymous methods which can be used as an instance of functional interfaces. Method references do the same thing, but with existing methods.


Kinds of Method References in Java

There are four kinds of method references in Java.

Kind Example Syntax
Reference to a static method ContainingClass::staticMethodName ClassName::methodName
Reference to an instance method of a particular object containingObject::instanceMethodName objRef::methodName
Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName ClassName::instanceMethodName
Reference to a constructor ClassName::new classname::new

Notice that the class name is separated from the method name by a double colon. The :: is a new separator (known as double colon operator) that has been added in Java 8.

Method References to static methods

The following example code shows a static method reference in Java. In the example there is a functional interface IMyStringFunc with a method stringFunc.

import java.util.Arrays;

@FunctionalInterface
interface IMyStringFunc<T, R>{
  R stringFunc(T t);
}
public class MethodRefDemo {
  public static void main(String[] args) {
    //String array of names
    String[] strNames = new String[]{"Ram", "shyam", "Ramesh", "John", "brad", 
           "Suresh"};
    // method reference to the static method sortName
    IMyStringFunc<String[],String[]> stringFunc = SortClass::sortName;
    // Here calling strngFunc will refer to the implementing method
    // sortName()
    String[] sortedNames = stringFunc.stringFunc(strNames);
    for(String name : sortedNames){
      System.out.println(name);
    }
  }
}

class SortClass{
  // A static method that sorts an array
  static String[] sortName(String[] names) {
    //Sorting array using sort method (case sensitive)
    Arrays.sort(names);
    return names;
  }
}

Output

John
Ram
Ramesh
Suresh
brad
shyam

In the code in this line SortClass::sortName; existing method sortName() is referred using method reference. This works because sortName is compatible with the IMyStringFunc functional interface. Thus, the expression SortClass::sortName evaluates to a reference to an object in which method sortName provides the implementation of abstract method stringFunc in functional interface IMyStringFunc.

Method References to Instance Methods

To pass a reference to an instance method of a particular object is similar to static method reference, instead of class we need to use object

objRef::methodName

Let's see the same example again with object

import java.util.Arrays;
@FunctionalInterface
interface IMyStringFunc<T, R>{
  R stringFunc(T t);
}

public class MethodRefDemo {
  public static void main(String[] args) {
    // creating an object
    SortClass sc = new SortClass();
    //String array of names
    String[] strNames = new String[]{"Ram", "shyam", "Ramesh", "John", "brad", 
            "Suresh"};  
    // method reference to the instance method sortName
    IMyStringFunc<String[],String[]> refObj = sc::sortName;
    String[] sortedNames = refObj.stringFunc(strNames);
    for(String name : sortedNames){
      System.out.println(name);
    }
  }
}

class SortClass{
  // A non-static method that sorts an array
  String[] sortName(String[] names) {
    //Sorting array using sort method (case sensitive)
    Arrays.sort(names);
    return names;
  }
}

Reference to an instance method of an arbitrary object of a particular type

There may be a situation when you want to specify an instance method that can be used with any object of a given class without any particular object. In that case name of the class is used even when a non-static method is specified.

ClassName::instanceMethodName

Let's take one example where we have a Person class and we have a list of Person object. We want to call getFirstName() method on all those person objects.

Person Class

public class Person {
  private String firstName;
  private String lastName;
  private int age;
  private char gender;
  public Person(String firstName, String lastName, int age, char gender){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.gender = gender;
  }
    
  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public int getAge() {
    return age;
  }
  public char getGender() {
    return gender;
  }
    
  public String toString(){
    StringBuffer sb = new StringBuffer();
    sb.append(getFirstName()).append(" ");
    sb.append(getLastName()).append(" ");
    sb.append(getAge()).append(" ");
    sb.append(getGender());
    return sb.toString();      
  }
}
@FunctionalInterface
interface IMyStringFunc<T, R>{
  R stringFunc(T t);
}

public class MethodRefDemo {
  public static void main(String[] args) {
    List<Person> personList = createList();
    List allNames = MethodRefDemo.listAllNames (personList, Person::getFirstName);
    System.out.println("" + allNames);
  }
    
  //Utitlity method to create list
  private static List<Person> createList(){
    List<Person> tempList = new ArrayList<Person>();
    IMyFunc createObj = Person::new;
    Person person = createObj.getRef("Ram","Tiwari", 50, 'M');
    tempList.add(person);
    person = createObj.getRef("Prem", "Chopra", 13, 'M');
    tempList.add(person);
    person = createObj.getRef("Tanuja", "Trivedi", 30, 'F');
    tempList.add(person);
    person = createObj.getRef("Manoj", "Sharma", 40, 'M');
    tempList.add(person);
    person = createObj.getRef("John", "Trevor", 70, 'M');
    tempList.add(person);
    person = createObj.getRef("Alicia", "Sliver", 17, 'F');
    tempList.add(person);
    System.out.println("List elements are - ");
    System.out.println(tempList);
    return tempList;
  }

  private static List<String> listAllNames(List<Person> person, 
         IMyStringFunc<Person, String> func){
    List<String> result = new ArrayList<String>();
    person.forEach(x -> result.add(func.stringFunc(x)));
    return result;
  }
}

Notice this line Person::getFirstName here we are calling getFirstName method on all the objects of the list not any one particular object.

Reference to a Constructor

A constructor can be referenced in the same way as a static method by using new.

public class Person {
  private String firstName;
  private String lastName;
  private int age;
  private char gender;
  public Person(String firstName, String lastName, int age, char gender){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.gender = gender;
  }
    
  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public int getAge() {
    return age;
  }
  public char getGender() {
    return gender;
  }
    
  public String toString(){
    StringBuffer sb = new StringBuffer();
    sb.append(getFirstName()).append(" ");
    sb.append(getLastName()).append(" ");
    sb.append(getAge()).append(" ");
    sb.append(getGender());
    return sb.toString();
  }
}
@FunctionalInterface
interface IMyFunc {
  Person getRef(String firstName, String lastName, int age, char gender);
}

public class LambdaDemo {
  public static void main(String[] args) {
    List<Person> personList = createList();
    System.out.println("Name - " + personList.get(0).getFirstName());
  }
  // Utitlity method to create list
  private static List<Person> createList(){
    List<Person> tempList = new ArrayList<Person>();
    IMyFunc createObj = Person::new;
    Person person = createObj.getRef("Ram","Tiwari", 50, 'M');
    tempList.add(person);
    person = createObj.getRef("Prem", "Chopra", 13, 'M');
    tempList.add(person);
    person = createObj.getRef("Tanuja", "Trivedi", 30, 'F');
    tempList.add(person);
    person = createObj.getRef("Manoj", "Sharma", 40, 'M');
    tempList.add(person);
    person = createObj.getRef("John", "Trevor", 70, 'M');
    tempList.add(person);
    person = createObj.getRef("Alicia", "Sliver", 17, 'F');
    tempList.add(person);
    System.out.println("List elements are - ");
    System.out.println(tempList);
    return tempList;
  }
}

Output

List elements are - 
[Ram Tiwari 50 M, Prem Chopra 13 M, Tanuja Trivedi 30 F, Manoj Sharma 40 M, John Trevor 70 M, Alicia Sliver 17 F]
Name - Ram

In the program notice that the getRef method of the IMyFunc returns a reference of type Person and has String, String, int and char as parameters. Also notice that in the Person class there is a constructor which specifies String, String, int and char as parameters.

Using this line Person::new a constructor reference to a Person constructor is created. Functional interface method also takes the same params thus the constructor of the Person class is referred through it.

That's all for this topic Method Reference in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Functional Interface Annotation in Java
  2. How to Resolve Local Variable Defined in an Enclosing Scope Must be Final or Effectively Final Error
  3. Java Lambda Expression as Method Parameter
  4. Java Lambda Expression And Variable Scope
  5. Java Lambda Expressions Interview Questions And Answers

You may also like-

  1. How HashSet Works Internally in Java
  2. equals() And hashCode() Methods in Java
  3. final Vs finally Vs finalize in Java
  4. Difference Between throw And throws in Java
  5. static Method Overloading or Overriding in Java
  6. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  7. PermGen Space Removal in Java 8
  8. How to Create PDF From XML Using Apache FOP

Saturday, September 17, 2022

How to Find Last Modified Date of a File in Java

There are two ways to get the last modified date of a file in Java.

  • Using File.lastModified() method- Using this method you can get the file's last modified timestamp.
  • Using Files.readAttributes() method- Java 7 onward you can use Files.readAttributes() method which returns an object of java.nio BasicFileAttributes that encapsulates all the attributes associated with the file. That way apart from last modified date you can also get the file creation date and several other attributes.

Java program to find the last modified date of a file

Following program uses both of the above mentioned methods to get the last modified date of a file in Java. Note here that when java.io.File's lastModified method is used it returns the time in milliseconds (long) so SimpleDateFormat is used to format it into dd/MM/yyyy format.

Files.readAttributes() method returns an instance of BasicFileAttributes. BasicFileAttributes class has methods creationTime() and lastModifiedTime() to get the file creation date and last modified date. Both of these methods return an instance of FileTime which is converted to milliseconds and then formatted to the desired format using SimpleDateFormat.

public class FileDate {
  public static void main(String[] args) {
    /*For below Java 7*/ 
    // get the file
    File f = new File("F:\\NetJS\\programs.txt");
    // Create a date format
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    // get the last modified date and format it to the defined format
    System.out.println("File last modified date " + sdf.format(f.lastModified()));
        
    /*Java 7 or above using NIO*/
    // Get the file
    Path path = Paths.get("F:\\NetJS\\programs.txt");
    BasicFileAttributes attr;
    try {
      // read file's attribute as a bulk operation
      attr = Files.readAttributes(path, BasicFileAttributes.class);
      // File creation time
      System.out.println("File creation time - " 
        + sdf.format(attr.creationTime().toMillis()));
      // File last modified date
      System.out.println("File modified time - " 
        + sdf.format(attr.lastModifiedTime().toMillis()));        
    } catch (IOException e ) {
        System.out.println("Error while reading file attributes " + e.getMessage());
    }       
  }
}

That's all for this topic How to Find Last Modified Date of a File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Format Date in Java Using SimpleDateFormat
  2. How to Count Lines in a File in Java
  3. How to Read File From The Last Line in Java
  4. How to Read Properties File in Java
  5. How to Untar a File in Java

You may also like-

  1. How to Run Threads in Sequence in Java
  2. Converting String to Enum Type in Java
  3. How to Run javap Programmatically From Java Program
  4. Count Number of Words in a String Java Program
  5. Java Pass by Value or Pass by Reference
  6. final Vs finally Vs finalize in Java
  7. How to Loop Through a Map in Java
  8. Dependency Injection in Spring Framework

Friday, September 16, 2022

java.lang.ClassNotFoundException - Resolving ClassNotFoundException in Java

In this article we’ll see what is java.lang.ClassNotFoundException and how to resolve ClassNotFoundException in Java.

ClassNotFoundException in Java

ClassNotFoundException is a child class of Exception class. Being a descendant of Exception class also makes it a checked exception that means it needs to be either caught in a method (with in a try-catch block), or the method needs to specify that exception in a throws clause declaration.

When is ClassNotFoundException thrown

ClassNotFoundException is thrown when a Java application tries to load in a class through its string name but definition for the class with the specified name could not be found.

Methods that can be used for loading a class through its String name are as following-

  • The Class.forName method in class Class.
  • The findSystemClass method in class ClassLoader.
  • The loadClass method in class ClassLoader.

ClassNotFoundException is thrown at runtime since classloader tries to load the class at runtime using the String name.

Java ClassNotFoundException example

As the name of the exception itself suggests this exception is thrown when the class that has to be loaded is not found. One scenario where you may find this exception is if you try to load JDBC drivers using Class.forName() but the required jar is not in the classpath.

I have also encountered ClassNotFoundException when upgrading to new version of jar in my system and using some new classes available in that jar but not upgrading the jar in the Test server or production. With that you get the scenario which is often quoted by the developers “In my system it is working fine”!!!

For example following program tries to load Oracle driver but the required ojdbcxx.jar is not present in the classpath.

public class JDBCCon {
  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("oracle.jdbc.driver.OracleDriver");

      // Creating connection
      connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
                   "root", "admin");

      // creating Statement
      Statement stmt = connection.createStatement();  

      // Executing Query
      ResultSet rs = stmt.executeQuery("Select * from Employee");

      // Processing Resultset
      while(rs.next()){
        System.out.println("id : " + rs.getInt("id") + " Name : " 
          + rs.getString("name") + " Age : " + rs.getInt("age")); 
      }
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(connection != null){
        //closing connection 
        try {
          connection.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}

Output

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
 at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
 at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
 at java.base/java.lang.Class.forName0(Native Method)
 at java.base/java.lang.Class.forName(Class.java:332)
 at org.netjs.prgrm.JDBCCon.main(JDBCCon.java:16)

As evident from the exception stack trace OracleDriver is not found so the ClassNotFoundException is thrown.

Resolving ClassNotFoundException in Java

As seen in the above example it is easy to see from the error log or exception stacktrace which class is causing the exception. Then you need to check whether the required jar (where the class resides) is present in the classpath or not.

If jar is there then ensure that you have the correct version and the class you are trying to load is part of that jar version.

If you are packaging your application and putting that jar or war in a server or another system to run make sure that all the classes are packaged properly and there are no omissions.

If class is there in the classpath then do ensure that there is no classpath change as part of some startup script.

That's all for this topic java.lang.ClassNotFoundException - Resolving ClassNotFoundException in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  2. Difference Between throw And throws in Java
  3. Multi-Catch Statement in Java Exception Handling
  4. Try-With-Resources in Java With Examples
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. intern() Method in Java String
  2. Private Methods in Java Interface
  3. Java Program to Convert a File to Byte Array
  4. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  5. ConcurrentSkipListMap in Java
  6. Spring MVC Example With @PathVariable - Creating Dynamic URL
  7. Spring Web Reactive - Spring WebFlux Example Using Annotation-Based Programming
  8. Python Installation on Windows