Jackson @JsonView examples

In Jackson, we can use the annotation @JsonView to control which fields of the same resource are displayed for different users. Table of contents: 1. Download Jackson 2. Define View Classes 3. Annotate model class with @JsonView 4. Testing the Jackson @JasonView 5. Download Source Code 6. References P.S Tested with Jackson 2.17.0 1. Download …

Read more

How to parse JSON string with Jackson

This article uses the Jackson framework to parse JSON strings in Java. Table of contents: 1. Download Jackson 2. Parse JSON String with Jackson 3. Parse JSON Array with Jackson 4. Convert Java Object to JSON String 5. Convert JSON String to Java Object 6. Download Source Code 7. References P.S Tested with Jackson 2.17.0 …

Read more

How to ignore null fields with Jackson

In Jackson, we can use @JsonInclude(JsonInclude.Include.NON_NULL) to ignore the null fields during serialization. Table of contents: 1. Jackson default include null fields 2. Ignore all null fields globally 3. Ignore null fields (Class Level) 4. Ignore null fields (Field Level) 5. Download Source Code 6. References P.S Tested with Jackson 2.17.0 1. Jackson default include …

Read more

Java – Convert ArrayList<String> to String[]

In the old days, we can use list.toArray(new String[0]) to convert a ArrayList<String> into a String[] StringArrayExample.java package com.mkyong; import java.util.ArrayList; import java.util.List; public class StringArrayExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); // default, returns Object[], not what we want, // Object[] objects = list.toArray(); // …

Read more

java.lang.UnsupportedClassVersionError

Start a Java class and hits this java.lang.UnsupportedClassVersionError, what is class file version 52 56? Error: A JNI error has occurred, please check your installation and try again Exception in thread "main" java.lang.UnsupportedClassVersionError: TestHello has been compiled by a more recent version of the Java Runtime (class file version 56.0), this version of the Java …

Read more

How to get user input in Java

In Java, we can use java.util.Scanner to get user input from console. 1. Scanner 1.1 Read a line. UserInputExample1.java package com.mkyong; import java.util.Scanner; public class UserInputExample1 { public static void main(String[] args) { // auto close scanner try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter something : "); String input = scanner.nextLine(); // Read user …

Read more

Java two-dimensional array example

A Java 2d array example. ArrayExample.java package com.mkyong; public class ArrayExample { public static void main(String[] args) { int[][] num2d = new int[2][3]; num2d[0][0] = 1; num2d[0][1] = 2; num2d[0][2] = 3; num2d[1][0] = 10; num2d[1][1] = 20; num2d[1][2] = 30; //or init 2d array like this : int[][] num2dInit = { {1, 2, 3}, …

Read more

Java List java.lang.UnsupportedOperationException

A simple List.add() and hits the following java.lang.UnsupportedOperationException ListExample.java package com.mkyong; import java.util.Arrays; import java.util.List; public class ListExample { public static void main(String[] args) { List<String> str = Arrays.asList("A", "B", "C"); str.add("D"); System.out.println(str); } } Output Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.AbstractList.add(AbstractList.java:153) at java.base/java.util.AbstractList.add(AbstractList.java:111) at com.mkyong.ListExample.main(ListExample.java:14) Solution The Arrays.asList returns a fixed-size list, modify …

Read more

Is Java pass-by-value or pass-by-reference?

In Java, for primitive types, parameters are pass-by-value; For object types, object reference is pass-by-value, however, Java is allowed to modify object’s fields via object reference. 1. Primitive Type No doubt, for primitive type, the parameters are pass by value. PrimitiveExample.java package com.mkyong; public class PrimitiveExample { public static void main(String[] args) { int value …

Read more

‘javac’ is not recognized as an internal or external command, operable program or batch file

A popular common error for new Java users. Terminal C:\Users\mkyong>javac ‘javac’ is not recognized as an internal or external command, operable program or batch file. C:\Users\mkyong>java -version ‘java’ is not recognized as an internal or external command, operable program or batch file. 1. Solution To fix it, update the system variable PATH to JDK_folder\bin 1. …

Read more

Java – Could not find or load main class

A popular error message for new Java users. Error: Could not find or load main class ClassName.class Caused by: java.lang.ClassNotFoundException: ClassName.class 1. No Package 1.1 Reviews a simple Java Hello World, no package. C:\projects\HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } } Terminal # Compile Java source code C:\projects> …

Read more

Java – How to send Email

To send email in Java, we need JavaMail pom.xml <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> 1. Send Email Send a normal email in text format. SendEmailSMTP.java package com.mkyong; import com.sun.mail.smtp.SMTPTransport; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; public class SendEmailSMTP { // for example, smtp.mailgun.org private static final String …

Read more

How to read a file in Java

This article focus on a few of the commonly used methods to read a file in Java. Files.lines, return a Stream (Java 8) Files.readString, returns a String (Java 11), max file size 2G. Files.readAllBytes, returns a byte[] (Java 7), max file size 2G. Files.readAllLines, returns a List<String> (Java 8) BufferedReader, a classic old friend (Java …

Read more

Java create and write to a file

In Java, we can use Files.write to create and write to a file. String content = "…"; Path path = Paths.get("/home/mkyong/test.txt"); // string -> bytes Files.write(path, content.getBytes(StandardCharsets.UTF_8)); The Files.write also accepts an Iterable interface; it means this API can write a List to a file. List<String> list = Arrays.asList("a", "b", "c"); Files.write(path, list); Short History …

Read more

Java Files.readAllBytes example

In Java, we can use Files.readAllBytes to read a file. byte[] content = Files.readAllBytes(Paths.get("app.log")); System.out.println(new String(content)); 1. Text File A Java example to write and read a normal text file. FileExample1.java package com.mkyong.calculator; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; public class FileExample1 { public static void main(String[] …

Read more

Java – How to Iterate a HashMap

In Java, there are 3 ways to loop or iterate a HashMap 1. If possible, always uses the Java 8 forEach. Map<String, String> map = new HashMap<>(); map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value)); 2. Normal for loop in entrySet() Map<String, String> map = new HashMap<>(); for …

Read more

Java – How to declare and initialize an Array

Few Java examples to declare, initialize and manipulate Array in Java 1. Declares Array 1.1 For primitive types. ArrayExample1.java package com.mkyong; import java.util.Arrays; public class ArrayExample1 { public static void main(String[] args) { //declares an array of integers int[] num1 = new int[5]; int[] num2 = {1, 2, 3, 4, 5}; int[] num3 = new …

Read more

Java – Convert Integer to String

In Java, you can use String.valueOf() to convert an Integer to String. 1. String.valueOf 1.1 Example to convert an Integer or int 10 to a String. Integer num = 10; //int num = 10; String numInString = String.valueOf(num); System.out.println(numInString); Output 10 2. toString() It works on Integer object only. Integer num = 10; String numInString …

Read more

How to compare strings in Java

In Java, we use equals() to compare string value. String str1 = "apple"; // compare strings case-sensitive if (str1.equals("apple")) { System.out.println("I have an apple."); } String str2 = "apple"; // compare strings case-insensitive if (str2.equalsIgnoreCase("APPLE")) { System.out.println("I have an APPLE."); } Output Terminal I have an apple. I have an APPLE. In this article, we …

Read more

JSONAssert – How to unit test JSON data

In Java, we can use JSONAssert to unit test JSON data easily. 1. Maven pom.xml <dependency> <groupId>org.skyscreamer</groupId> <artifactId>jsonassert</artifactId> <version>1.5.0</version> </dependency> 2. JSON Object To test the JSON Object, Strict or not, fields order does not matter. If the extended fields are matter, enable the strict mode. 2.1 When the strictMode is off. JSONObject actual = …

Read more

log4j2 – Failed to load class “org.slf4j.impl.StaticLoggerBinder”

The Java project is using log4j2, but look like some components are used SLF4J logging and caused the following error message: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Solution To fix it, we need a SLF4J Bridge. Puts log4j-slf4j-impl in the classpath. pom.xml …

Read more

Java ArrayIndexOutOfBoundsException example

This java.lang.ArrayIndexOutOfBoundsException is thrown when we are accessing an array with an index which is greater than the size of an array. P.S Array index starts with 0 ArrayExample.java package com.mkyong; public class ArrayExample { public static void main(String[] args) { // array of 3 int[] num = new int[3]; num[0] = 1; num[1] = …

Read more

Java – How to run Windows bat file

In Java, we can use ProcessBuilder to run a Windows batch file like this : ProcessBuilder processBuilder = new ProcessBuilder("C:\\Users\\mkyong\\hello.bat"); //or ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command("cmd", "/c", "hello.bat"); File dir = new File("C:\\Users\\mkyong\\"); processBuilder.directory(dir); Alternatively, Runtime.getRuntime().exec like this : Process process = Runtime.getRuntime().exec( "cmd /c hello.bat", null, new File("C:\\Users\\mkyong\\")); 1. Java Example 1.1 A …

Read more

Java – How to list all files in a directory?

Two Java examples to show you how to list files in a directory : For Java 8, Files.walk Before Java 8, create a recursive loop to list all files. 1. Files.walk 1.1 List all files. try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.filter(Files::isRegularFile) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); …

Read more

Java ProcessBuilder examples

In Java, we can use ProcessBuilder to call external commands easily : ProcessBuilder processBuilder = new ProcessBuilder(); // — Linux — // Run a shell command processBuilder.command("bash", "-c", "ls /home/mkyong/"); // Run a shell script processBuilder.command("path/to/hello.sh"); // — Windows — // Run a command processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\mkyong"); // Run a bat file processBuilder.command("C:\\Users\\mkyong\\hello.bat"); Process …

Read more

Java Files.walk examples

The Files.walk API is available since Java 8; it helps to walk a file tree at a given starting path. Topics Files.walk() method signature List all files List all folders or directories Find files by file extension Find files by filename Find files by file size Update all files last modified date 1. Files.walk() method …

Read more

Java – How to read a file into a list?

In Java, there are few ways to read a file line by line into a List 1. Java 8 stream List<String> result; try (Stream<String> lines = Files.lines(Paths.get(fileName))) { result = lines.collect(Collectors.toList()); } 2. Java 7 Files.readAllLines(new File(fileName).toPath(), Charset.defaultCharset()); 3. Classic BufferedReader example. List<String> result = new ArrayList<>(); BufferedReader br = null; try { br = …

Read more

Java BlockingQueue examples

In Java, we can use BlockingQueue to create a queue which shared by both producer and the consumer. Producer – Generate data and put it into the queue. Consumer – Remove the data from the queue. Note Read this article to understand what is producer and consumer. The BlockingQueue implementations are thread-safe, safely be used …

Read more

Java – Check if a String contains a substring

In Java, we can use String.contains() to check if a String contains a substring. 1. String.contains() – Case Sensitive JavaExample1.java package com.mkyong; public class JavaExample1 { public static void main(String[] args) { String name = "mkyong is learning Java 123"; System.out.println(name.contains("Java")); // true System.out.println(name.contains("java")); // false System.out.println(name.contains("MKYONG")); // false System.out.println(name.contains("mkyong")); // true if (name.contains("Java")) { …

Read more

Java Semaphore examples

In Java, we can use Semaphore to limit the number of threads to access a certain resource. 1. What is Semaphore? In short, a semaphore maintains a set of permits (tickets), each acquire() will take a permit (ticket) from semaphore, each release() will return back the permit (ticket) back to the semaphore. If permits (tickets) …

Read more

Java Sequence Generator examples

An example to show you how to create a thread safe sequence generator. 1. SequenceGenerator SequenceGenerator.java package com.mkyong.concurrency.examples.sequence.generator; public interface SequenceGenerator { long getNext(); } 1.1 First try, read, add, write the value directly. Below method is not thread safe, multiple threads may get the same value at the same time. UnSafeSequenceGenerator.java package com.mkyong.concurrency.examples.sequence.generator; public …

Read more

Java ExecutorService examples

In Java, we can use ExecutorService to create a thread pool, and tracks the progress of the asynchronous tasks with Future. The ExecutorService accept both Runnable and Callable tasks. Runnable – Return void, nothing. Callable – Return a Future. 1. ExecutorService 1.1 A classic ExecutorService example to create a thread pool with 5 threads, submit …

Read more

Java ScheduledExecutorService examples

In Java, we can use ScheduledExecutorService to run a task periodically or once time after a predefined delay by TimeUnit. 1. Run a Task Once The ScheduledExecutorService accepts both Runnable and Callable tasks. 1.1 Run a Runnable task after 5 seconds initial delay. ScheduledExecutorExample.java package com.mkyong.concurrency.executor.scheduler; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledExecutorRunnable …

Read more

Java Fork/Join Framework examples

What is Fork/Join? Read this Java Fork/Join paper by Doug Lea The fork/join framework is available since Java 7, to make it easier to write parallel programs. We can implement the fork/join framework by extending either RecursiveTask or RecursiveAction 1. Fork/Join – RecursiveTask A fork join example to sum all the numbers from a range. …

Read more

Java Fibonacci examples

Fibonacci number – Every number after the first two is the sum of the two preceding. Few Java examples to find the Fibonacci numbers. 1. Java 8 stream 1.1 In Java 8, we can use Stream.iterate to generate Fibonacci numbers like this : Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]}) .limit(10) .forEach(x …

Read more

JMH – Java Forward loop vs Reverse loop

A JMH benchmark test about Forward loop vs Reverse loop for a List. There is a myth about reverse loop is faster, is this true? Tested with JMH 1.21 Java 10 Maven 3.6 CPU i7-7700 Forward loop for (int i = 0; i < aList.size(); i++) { String s = aList.get(i); System.out.println(s); } Reverse loop …

Read more

Java JMH Benchmark Tutorial

Benchmark (N) Mode Cnt Score Error Units BenchmarkLoop.loopFor 10000000 avgt 10 61.673 ± 1.251 ms/op BenchmarkLoop.loopForEach 10000000 avgt 10 67.582 ± 1.034 ms/op BenchmarkLoop.loopIterator 10000000 avgt 10 66.087 ± 1.534 ms/op BenchmarkLoop.loopWhile 10000000 avgt 10 60.660 ± 0.279 ms/op In Java, we can use JMH (Java Microbenchmark Harness) framework to measure the performance of a …

Read more