In Java, we can use new ArrayList(Arrays.asList(array)) to convert an Array into an ArrayList ArrayExample1.java package com.mkyong; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayExample1 { public static void main(String[] args) { String[] str = {"A", "B", "C"}; List<String> list = new ArrayList<>(Arrays.asList(str)); list.add("D"); list.forEach(x -> System.out.println(x)); } } Output A B C D […]

Read more Java – Convert Array to ArrayList

Few Java examples to show you how to check if a String is numeric. 1. Character.isDigit() Convert a String into a char array and check it with Character.isDigit() NumericExample.java package com.mkyong; public class NumericExample { public static void main(String[] args) { System.out.println(isNumeric("")); // false System.out.println(isNumeric(" ")); // false System.out.println(isNumeric(null)); // false System.out.println(isNumeric("1,200")); // false System.out.println(isNumeric("1")); […]

Read more Java – How to check if a String is numeric

In Java, we can use (str != null && !str.isEmpty()) to make sure the String is not empty or null. StringNotEmpty.java package com.mkyong; public class StringNotEmpty { public static void main(String[] args) { System.out.println(notEmpty("")); // false System.out.println(notEmpty(null)); // false System.out.println(notEmpty("hello")); // true System.out.println(notEmpty(" ")); // true, a space… } private static boolean notEmpty(String str) { […]

Read more Java – Check if a String is empty or null

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 Jackson @JsonView examples

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 How to ignore null fields with Jackson

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 – Convert ArrayList<String> to String[]

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 java.lang.UnsupportedClassVersionError

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 How to get user input in Java

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 Java List java.lang.UnsupportedOperationException

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 Is Java pass-by-value or pass-by-reference?

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 ‘javac’ is not recognized as an internal or external command, operable program or batch file

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 – Could not find or load main class

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 Java – How to send Email

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 How to read a file in Java

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 create and write to a file

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 Files.readAllBytes example

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 – How to declare and initialize an Array

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 How to compare strings in Java

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 JSONAssert – How to unit test JSON data

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 log4j2 – Failed to load class “org.slf4j.impl.StaticLoggerBinder”

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 run Windows bat file

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 – How to list all files in a directory?

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 ProcessBuilder 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 Files.walk examples

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 – How to read a file into a list?

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 – Check if a String contains a substring

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 Semaphore 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 Sequence Generator 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 ExecutorService 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 ScheduledExecutorService examples