Java – Convert String to double

In Java, we can use Double.parseDouble() to convert a String to double 1. Double.parseDouble() Example to convert a String 3.142 to an primitive double. String str = "3.142"; double pi = Double.parseDouble(str); System.out.println(pi); Output 3.142 2. Double.valueOf() Example to convert a String 3.142 to an Double object. String str = "3.142"; Double pi = Double.valueOf(str); …

Read more

Java – Convert Array to ArrayList

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

JSON.simple – How to parse JSON

In this tutorial, we will show you how to parse JSON with JSON.simple Note You may have interest to read – How to parse JSON with Jackson or Gson JSON.simple short history This project was formerly JSON.simple 1.x from a Google code project by Yidong, now maintaining by Clifton Labs, read this JSON.simple history P.S …

Read more

Java – How to check if a String is numeric

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 – Check if a String is empty or null

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

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

Spring – Read file from resources folder

In Spring, we can use ClassPathResource or ResourceLoader to get files from classpath easily. P.S Tested with Spring 5.1.4.RELEASE 1. src/main/resources/ For example, an image file in the src/main/resources/ folder 2. ClassPathResource import org.springframework.core.io.Resource; import org.springframework.core.io.ClassPathResource; import java.io.File; import java.io.InputStream; Resource resource = new ClassPathResource("android.png"); InputStream input = resource.getInputStream(); File file = resource.getFile(); 3. ResourceLoader …

Read more

Spring Boot – How to send email via SMTP

In this tutorial, we will show you how to send email via SMTP in Spring Boot. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Java Mail 1.6.2 Maven 3 Java 8 1. Project Directory 2. Maven To send email, declares spring-boot-starter-mail, it will pull the JavaMail dependencies. pom.xml <?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 …

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

Maven – source value 1.5 is obsolete and will be removed in a future release

In IntelliJ IDEA, Maven builds a project, and hits the following warning message? Warning:java: source value 1.5 is obsolete and will be removed in a future release Warning:java: target value 1.5 is obsolete and will be removed in a future release To fix it, add maven-compiler-plugin plugin. pom.xml <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> …

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

Spring Boot Log4j 2 example

In this tutorial, we will show you how to use Apache Log4j 2 in Spring Boot framework. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Log4j 2.11.1 Maven 3 Java 8 1. Project Directory 2. Maven The key is exclude the default logback, and include log4j with spring-boot-starter-log4j2 pom.xml <?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" …

Read more

JavaScript – Get selected value from dropdown list

A JavaScript example to show you how to get the selected value or text from a dropdown list. A drop box list. <select id="country"> <option value="None">– Select –</option> <option value="ID001">China</option> <option value="ID002" selected>United State</option> <option value="ID003">Malaysia</option> </select> Get option value : var e = document.getElementById("country"); var result = e.options[e.selectedIndex].value; alert(result); //ID002 Get option text : …

Read more

log4j2.yml example

A simple log4j2.yml example, just for self-reference P.S Tested with Log4j 2.11.2 1. Jackson for YML Log4j 2 need the following libraries to parse yml file pom.xml <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.11.2</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.11.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency> 2. log4j2.yml src/resources/log4j2.yml Configuration: status: warn appenders: Console: …

Read more

log4j2.properties example

A simple log4j2.properties example, just for self-reference P.S Tested with Log4j 2.11.2 src/resources/log4j2.properties status = warn appender.console.type = Console appender.console.name = LogToConsole appender.console.layout.type = PatternLayout appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} – %msg%n #appender.file.type = File #appender.file.name = LogToFile #appender.file.fileName=logs/app.log #appender.file.layout.type=PatternLayout #appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} – %msg%n # Rotate log file appender.rolling.type = …

Read more

log4j2.xml example

Some log4j2.xml examples, just for self-reference P.S Tested with Log4j 2.11.2 1. ConsoleAppender Logs to console. log4j2.xml <?xml version="1.0" encoding="UTF-8"?> <Configuration status="DEBUG"> <Appenders> <Console name="LogToConsole" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} – %msg%n"/> </Console> </Appenders> <Loggers> <!– avoid duplicated logs with additivity=false –> <Logger name="com.mkyong" level="debug" additivity="false"> <AppenderRef ref="LogToConsole"/> </Logger> <Root level="error"> <AppenderRef ref="LogToConsole"/> </Root> …

Read more

Log4j 2 – java.lang.NoClassDefFoundError: com/lmax/disruptor/EventTranslatorVararg

Enable the log4j 2 loggers to asynchronous, but hits the following order : $ mvn -Dlog4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector -jar app.jar java.lang.NoClassDefFoundError: com/lmax/disruptor/EventTranslatorVararg at java.lang.ClassLoader.defineClass1 (Native Method) at java.lang.ClassLoader.defineClass (ClassLoader.java:1009) at java.security.SecureClassLoader.defineClass (SecureClassLoader.java:174) at java.net.URLClassLoader.defineClass (URLClassLoader.java:545) at java.net.URLClassLoader.access$100 (URLClassLoader.java:83) at java.net.URLClassLoader$1.run (URLClassLoader.java:453) Solution To fix it, add disruptor pom.xml <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>3.4.2</version> </dependency> Note Read this Making …

Read more

JavaScript – How to redirect a page

In JavaScript, we can use either location.replace() or location.href to redirect a page. Normally, we use location.replace() to simulate an HTTP redirect. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <h1>JavaScript – How to redirect a page</h1> <h3>1. location.replace</h3> <button onclick="httpRedirect()">location.replace</button> <h3>2. location.href</h3> <button onclick="mouseClick()">location.href</button> <script> // Simulate an HTTP redirect function httpRedirect() { location.replace("https://www.mkyong.com") …

Read more

Apache Log4j 2 Tutorials

A simple log4j 2 hello world example. Tested with Log4j 2.11.2 Maven 3 Java 8 Note Apache Log4j 2, the fastest Java logging framework, provides significant improvements over its predecessor, Log4j 1.x. 1. Project Directory 2. Maven <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.11.2</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.11.2</version> </dependency> pom.xml <?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 …

Read more

Spring Boot + Spring Data JPA + PostgreSQL example

This article shows how to use Spring Web MVC to create REST endpoints for CRUD database operations using the Spring Data JPA and PostgreSQL. At the end of the tutorial, we will use Docker to start a PostgreSQL container to test the Spring Boot REST endpoints using curl commands. We will use Spring Test and …

Read more