Java – How to add days to current date

This article shows you how to add days to the current date, using the classic java.util.Calendar and the new Java 8 date and time APIs. 1. Calendar.add Example to add 1 year, 1 month, 1 day, 1 hour, 1 minute and 1 second to the current date. DateExample.java package com.mkyong.time; import java.text.DateFormat; import java.text.SimpleDateFormat; import …

Read more

Java 8 – Period and Duration examples

Few examples to show you how to use Java 8 Duration, Period and ChronoUnit objects to find out the difference between dates. Duration – Measures time in seconds and nanoseconds. Period – Measures time in years, months and days. 1. Duration Example A java.time.Duration example to find out difference seconds between two LocalDateTime DurationExample.java package …

Read more

Java 8 – How to format LocalDateTime

Few examples to show you how to format java.time.LocalDateTime in Java 8. 1. LocalDateTime + DateTimeFormatter To format a LocalDateTime object, uses DateTimeFormatter TestDate1.java package com.mkyong.time; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class TestDate1 { public static void main(String[] args) { //Get current date time LocalDateTime now = LocalDateTime.now(); System.out.println("Before : " + now); DateTimeFormatter formatter …

Read more

Java – Convert Object to Map example

In Java, you can use the Jackson library to convert a Java object into a Map easily. 1. Get Jackson pom.xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.3</version> </dependency> 2. Convert Object to Map 2.1 A Jackson 2 example to convert a Student object into a java.util.Map Student.java package com.mkyong.examples; import java.util.List; public class Student { private String …

Read more

Gradle – Multiple start script examples

Few build.gradle examples to show you how to create multiple start scripts or executable Java application. 1. Single Start Script 1.1 In Gradle, you can use the application plugin to create an executable Java application : build.gradle apply plugin: ‘application’ mainClassName = "com.mkyong.analyzer.run.threads.MainRunApp" applicationName = ‘mainApp’ applicationDefaultJvmArgs = ["-Xms512m", "-Xmx1024m"] 1.2 Create the executable Java …

Read more

Java Static keyword example

The static keyword in Java is a modifier used to create memory efficient code. It helps in managing the memory occupied by objects, variables and method definitions. The static keyword makes sure that there is only one instance of the concerned method, object or variable created in memory. It is used when one needs to …

Read more

Java – How to compare two Sets

In Java, there is no ready make API to compare two java.util.Set 1. Solution Here’s my implementation, combine check size + containsAll : SetUtils.java package com.mkyong.core.utils; import java.util.Set; public class SetUtils { public static boolean equals(Set<?> set1, Set<?> set2){ if(set1 == null || set2 ==null){ return false; } if(set1.size()!=set2.size()){ return false; } return set1.containsAll(set2); } …

Read more

Spring Data MongoDB + JSR-310 or Java 8 new Date APIs

While saving an object containing the new Java 8 java.time.LocalDateTime, the following error is thrown : org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.time.LocalDateTime] to type [java.util.Date] Tested Spring 4.3.2.RELEASE Spring Data MongoDB 1.9.2.RELEASE Is Spring-data supporting the new Java 8 Date APIs (JSR-310)? 1. Spring Data + JSR-310 Yes, Spring-data supports the …

Read more

Java 8 – HijrahDate, How to calculate the Ramadan date

Ramadan is the 9th month of the Islamic calendar, the entire month. 1. HijrahDate -> Ramadan 2016 Full example to calculate the start and end of the Ramadan 2016 TestHijrahDate.java package com.mkyong.date; import java.time.LocalDate; import java.time.chrono.HijrahDate; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAdjusters; public class TestDate { public static void main(String[] args) { //first day of Ramadan, 9th …

Read more

Java 8 – MinguoDate examples

This MinguoDate calendar system is primarily used in Taiwan (Republic of China…) (ISO) 1912-01-01 = 1-01-01 (Minguo ROC) To convert the current date to the Minguo date, just subtracts the current year with number 1911, for example 2016 (ISO) – 1911 = 105 (Minguo ROC) 1. LocalDate -> MinguoDate Review a full example to convert …

Read more

Java – ResourceBundle example

The java.util.ResourceBundle is a library used for internationalization (multiple languages). It is able to return messages as per the default Locale configured for the system. Such a functionality is used when one develops systems to be used all over the world. 1. How it works? The library reads a property file based on the locale and name …

Read more

Java 8 – ZonedDateTime examples

Few Java 8 java.time.ZonedDateTime examples to show you how to convert a time zone between different countries. Table of contents 1. Convert LocalDateTime to ZonedDateTime 2. Malaysia (UTC+08:00) -> Japan (UTC+09:00) 3. France, Paris (UTC+02:00, DST) -> (UTC-05:00) 4. References 1. Convert LocalDateTime to ZonedDateTime The LocalDateTime has no time zone; to convert the LocalDateTime …

Read more

Java 8 – Convert Date to LocalDate and LocalDateTime

Here is the code to convert java.util.Date to java.time.LocalDate. Date date = new Date(); LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // different way of create instant object LocalDate localDate = Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate(); Convert java.util.Date to java.time.LocalDateTime. Date date = new Date(); LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); Convert java.util.Date to java.time.ZonedDateTime. Date date = new Date(); ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault()); …

Read more

Java 8 – Convert Instant to ZonedDateTime

Java 8 examples to show you how to convert from Instant to ZonedDateTime 1. Instant -> ZonedDateTime Example to convert a Instant UTC+0 to a Japan ZonedDateTime UTC+9 InstantZonedDateTime1.java package com.mkyong.date; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; public class InstantZonedDateTime1 { public static void main(String[] argv) { // Z = UTC+0 Instant instant = Instant.now(); …

Read more

Java 8 – Convert Instant to LocalDateTime

Java 8 examples to show you how to convert from Instant to LocalDateTime 1. Instant -> LocalDateTime The java.time.LocalDateTime has no concept of time zone, just provide a zero offset UTC+0. InstantExample1.java package com.mkyong.date; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; public class InstantExample1 { public static void main(String[] argv) { // Parse a ISO 8601 …

Read more

Java – Display all ZoneId and its UTC offset

A Java 8 example to display all the ZoneId and its OffSet hours and minutes. P.S Tested with Java 8 and 12 1. Display ZoneId and Offset DisplayZoneAndOffSet.java package com.mkyong; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; public class DisplayZoneAndOffSet { public static final boolean SORT_BY_REGION = false; …

Read more

Java 8 – How to convert String to LocalDate

Here are a few Java examples of converting a String to the new Java 8 Date API – java.time.LocalDate DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy"); String date = "16/08/2016"; //convert String to LocalDate LocalDate localDate = LocalDate.parse(date, formatter); The key is understand the DateTimeFormatter patterns Note You may interest at this classic java.util.Date example – How to …

Read more

Java 8 – How to sort a Map

Java 8 Stream examples to sort a Map, by keys or by values. 1. Quick Explanation Steps to sort a Map in Java 8. Convert a Map into a Stream Sort it Collect and return a new LinkedHashMap (keep the order) Map result = map.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); P.S By …

Read more

Java 8 – Convert a Stream to List

A Java 8 example to show you how to convert a Stream to a List via Collectors.toList Java8Example1.java package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8Example1 { public static void main(String[] args) { Stream<String> language = Stream.of("java", "python", "node"); //Convert a Stream to List List<String> result = language.collect(Collectors.toList()); result.forEach(System.out::println); } } output …

Read more

Java 8 – Filter a null value from a Stream

Review a Stream containing null values. Java8Examples.java package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8Examples { public static void main(String[] args) { Stream<String> language = Stream.of("java", "python", "node", null, "ruby", null, "php"); List<String> result = language.collect(Collectors.toList()); result.forEach(System.out::println); } } output java python node null //

Java 8 – Convert Map to List

Few Java examples to convert a Map to a List Map<String, String> map = new HashMap<>(); // Convert all Map keys to a List List<String> result = new ArrayList(map.keySet()); // Convert all Map values to a List List<String> result2 = new ArrayList(map.values()); // Java 8, Convert all Map keys to a List List<String> result3 = …

Read more

How to backup and restore (import and export) MySQL database or table

This tutorial will show you how to back up and restore (import or export) MySQL / MariaDB database or tables. Table of contents: 1. MySQL – Backup or export databases and tables 2. MySQL – Restore or import databases and tables 3. Backup and Restore MySQL 4. References 1. MySQL – Backup or export databases …

Read more

Java Final keyword example

Final keyword in Java is a modifier used to restrict the user from doing unwanted code or preventing from the code or value from being changed. It is possible to use this keyword in 3 contexts. They are: Final keyword as a variable modifier Final keyword as a method modifier Final keyword as a class …

Read more

JUnit + Spring integration example

In this tutorial, we will show you how to test the Spring DI components with JUnit frameworks. Technologies used : JUnit 4.12 Hamcrest 1.3 Spring 4.3.0.RELEASE Maven 1. Project Dependencies To integrate Spring with JUnit, you need spring-test.jar pom.xml <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> …

Read more

JUnit – Categories Test

In JUnit, you can organize the test cases into different categories, and run those categorized test cases with @Categories.ExcludeCategory or @Categories.IncludeCategory Note This @Categories annotation is available since JUnit 4.12 1. Category = Marker Interface In JUnit, you need to create marker interfaces to represent the categories: PerformanceTests.java package com.mkyong.category; //category marker interface public interface …

Read more

JUnit – Assert if a property exists in a class

Includes hamcrest-library and test the class property and its value with hasProperty() : P.S Tested with JUnit 4.12 and hamcrest-library 1.3 ClassPropertyTest.java package com.mkyong; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasProperty; import static org.junit.Assert.assertThat; public class ClassPropertyTest { //Single Object @Test public void testClassProperty() { Book obj …

Read more

Java Custom Exception Examples

In Java, there are two types of exceptions – checked and unchecked exception. Here’s the summary : Checked – Extends java.lang.Exception, for recoverable condition, try-catch the exception explicitly, compile error. Unchecked – Extends java.lang.RuntimeException, for unrecoverable condition, like programming errors, no need try-catch, runtime error. 1. Custom Checked Exception Note Some popular checked exception : …

Read more

JUnit – Run test in a particular order

In JUnit, you can use @FixMethodOrder(MethodSorters.NAME_ASCENDING) to run the test methods by method name, in lexicographic order. P.S Tested with JUnit 4.12 ExecutionOrderTest.java package com.mkyong; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; //Sorts by method name @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ExecutionOrderTest { @Test public void testB() { assertThat(1 + 1, is(2)); …

Read more

Intellij + Infinitest Continuous Testing

The Infinitest is a continuous testing plugin, it helps to run the test automatically. 1. Install on IntelliJ 1.1 In Plugins, clicks on the “Browse repositories…” 1.2 Type “Infinitest” and clicks on the “Install” button. 1.3 Restart the Intellij IDEA. 2. Add Infinitest facet In the project structure / settings, add a “Infinitest” facet. 3. …

Read more

Intellij IDEA – How to build project automatically

By default, Intellij IDEA doesn’t compile classes automatically. But, you can enable the auto compile feature by following steps : In “Project settings or preferences” Select “Build, Execution, Deployment -> Compiler” Checked Make project automatically P.S This feature is available since IDEA 12 References Brand New Compiler Mode in IntelliJ IDEA 12

JUnit – How to test a Map

Forget about JUnit assertEquals(), to test a Map, uses the more expressive IsMapContaining class from hamcrest-library.jar pom.xml <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency> <!– This will get hamcrest-core automatically –> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> <scope>test</scope> </dependency> </dependencies> 1. IsMapContaining Examples All the below assertThat checks will be passed. …

Read more

JUnit – How to test a List

First, exclude the JUnit bundled copy of hamcrest-core, and include the useful hamcrest-library, it contains many useful methods to test the List data type. pom.xml <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency> <!– This will get hamcrest-core automatically –> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> <scope>test</scope> </dependency> </dependencies> 1. Assert List …

Read more

Hamcrest – How to assertThat check null value?

Try to check null value with the Hamcrest assertThat assertion, but no idea how? @Test public void testApp() { //ambiguous method call? assertThat(null, is(null)); } 1. Solution 1.1 To check null value, try is(nullValue), remember static import org.hamcrest.CoreMatchers.* //hello static import, nullValue here import static org.hamcrest.CoreMatchers.*; import org.junit.Test; //… @Test public void testApp() { //true, …

Read more

Maven and JUnit example

In Maven, you can declare the JUnit dependency like this: pom.xml <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> But, it comes with a bundled copy of hamcrest-core library. $ mvn dependency:tree … [INFO] \- junit:junit:jar:4.12:test [INFO] \- org.hamcrest:hamcrest-core:jar:1.3:test … 1. Maven + JUnit + Hamcrest Note Not a good idea to use the default …

Read more

Java Swing – JOptionPane showInputDialog example

This is a review of the showInputDialog() method of JOptionPane Class. With this method we can prompt the user for input while customizing our dialog window. The showConfirmDialog returns either String or Object and can be called using the following combinations of parameters: Object (returns String) – Shows a question-message dialog requesting input from the …

Read more

Gradle and JUnit example

In Gradle, you can declare the JUnit dependency like this: build.gradle apply plugin: ‘java’ dependencies { testCompile ‘junit:junit:4.12’ } By default, JUnit comes with a bundled copy of hamcrest-core $ gradle dependencies –configuration testCompile testCompile – Compile classpath for source set ‘test’. \— junit:junit:4.12 \— org.hamcrest:hamcrest-core:1.3 1. Gradle + JUnit + Hamcrest Normally, we need …

Read more

Logback – Set log file name programmatically

In Logback, it is easy to set a log file name programmatically : In logback.xml, declares a variable like ${log.name} In Java, set the variable via System.setProperty(“log.name”, “abc”) 1. Full example 1.1 A logback file, we will set the ${log.name} variable later. src/main/resources/logback.xml <?xml version="1.0" encoding="UTF-8"?> <configuration> <property name="PRO_HOME" value="/home/mkyong/ant/logs" /> <property name="USER_HOME" value="${PRO_HOME}" /> …

Read more

MongoDB – group, count and sort example

Some MongoDB examples to show you how to perform group by, count and sort query. 1. Test Data A whois_range collection, containing many records. > db.whois_range.find(); { "_id" : 1, "country" : "us", "source" : "ARIN", "status" : "NEW", "createdDate" : ISODate("2016-05-03T08:52:32.434Z") }, { "_id" : 2, "country" : "us", "source" : "ARIN", "status" : …

Read more