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

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 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

JDBC PreparedStatement SQL IN condition

Java JDBC PreparedStatement example to create a SQL IN condition. 1. PreparedStatement + Array In JDBC, we can use createArrayOf to create a PreparedStatement IN query. @Override public List<Integer> getPostIdByTagId(List<Integer> tagIds) { List<Integer> result = new ArrayList<>(); String sql = "SELECT tr.object_id as post_id FROM wp_term_relationships tr " + " JOIN wp_term_taxonomy tt JOIN wp_terms …

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

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 – 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 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

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

Java – Global variable examples

In Java, there is no global keyword, but we can use public static variable to referring a global variable. For example : MagicUtils.java package com.mkyong.example; public class MagicUtils { public static final String NAME = "mkyong"; // global public static final int LUCKY_NUMBER = 7; // global } JavaExample.java package com.mkyong.example; public class JavaExample { …

Read more

Java – How to get the first item from Set

In Java, we can use Set.iterator().next() to get the first item from a java.util.Set JavaExample.java package com.mkyong; import java.util.HashSet; import java.util.Set; public class JavaExample { public static void main(String[] args) { Set<String> examples = new HashSet<>(); examples.add("1"); examples.add("2"); examples.add("3"); examples.add("4"); examples.add("5"); System.out.println(examples.iterator().next()); // java 8 System.out.println(examples.stream().findFirst().get()); } } Output 1 1 References Oracle doc – …

Read more

Java – How to convert int to BigInteger?

In Java, we can use BigInteger.valueOf(int) to convert int to a BigInteger JavaExample.java package com.mkyong; import java.math.BigInteger; public class JavaExample { public static void main(String[] args) { int n = 100; System.out.println(n); // convert int to Integer Integer integer = Integer.valueOf(n); System.out.println(integer); // convert int to BigInteger BigInteger bigInteger = BigInteger.valueOf(n); System.out.println(bigInteger); // convert Integer …

Read more

Java – Find the length of BigInteger?

In Java, we can convert the BigInteger to a String object and get the length of the String. JavaExample.java package com.mkyong; import java.math.BigInteger; public class JavaExample { public static void main(String[] args) { BigInteger bigInteger = BigInteger.valueOf(100000000000000000L); //18 System.out.println(bigInteger.toString().length()); } } Output 18 References BigInteger JavaDoc Quora – What are the limits of String Size …

Read more

Java – How to convert System.nanoTime to Seconds

We can just divide the nanoTime by 1_000_000_000, or use the TimeUnit.SECONDS.convert to convert it. Note 1 second = 1_000_000_000 nanosecond JavaExample.java package com.mkyong; import java.util.concurrent.TimeUnit; public class JavaExample { public static void main(String[] args) throws InterruptedException { long start = System.nanoTime(); Thread.sleep(5000); long end = System.nanoTime(); long elapsedTime = end – start; System.out.println(elapsedTime); // …

Read more

Java – Count the number of items in a List

In Java, we can use List.size() to count the number of items in a List package com.mkyong.example; import java.util.Arrays; import java.util.List; public class JavaExample { public static void main(String[] args) { List<String> list = Arrays.asList("a", "b", "c"); System.out.println(list.size()); } } Output 3 References Java doc – List

Java – How to print a Pyramid

A Java example to print half and full pyramid, for fun. CreatePyramid.java package com.mkyong; import java.util.Collections; public class CreatePyramid { public static void main(String[] args) { int rows = 5; System.out.println("\n1. Half Pyramid\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j <= i; j++) { System.out.print("*"); } …

Read more

PDFBox – How to read PDF file in Java

This article shows you how to use Apache PDFBox to read a PDF file in Java. 1. Get PDFBox pom.xml <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.6</version> </dependency> 2. Print PDF file Example to extract all text from a PDF file. ReadPdf.java package com.mkyong; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.apache.pdfbox.text.PDFTextStripperByArea; import java.io.File; import java.io.IOException; public class ReadPdf { …

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

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

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