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

Java 8 Stream.iterate examples

In Java 8, we can use Stream.iterate to create stream values on demand, so called infinite stream. 1. Stream.iterate 1.1 Stream of 0 – 9 //Stream.iterate(initial value, next value) Stream.iterate(0, n -> n + 1) .limit(10) .forEach(x -> System.out.println(x)); Output 0 1 2 3 4 5 6 7 8 9 1.2 Stream of odd numbers …

Read more

Git – How to undo the last commit?

In Git, we can use git reset –soft HEAD~1 to undo the last commit in local. (The committed files haven’t pushed to the remote git server) 1. Case Study git commit and find out some unwanted target/* files are committed accidentally, I haven’t issue the git push, any idea how to undo the commit? Terminal …

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

Maven – How to force re-download project dependencies?

In Maven, you can use Apache Maven Dependency Plugin, goal dependency:purge-local-repository to remove the project dependencies from the local repository, and re-download it again. Terminal $ mvn dependency:purge-local-repository [INFO] Scanning for projects… [INFO] [INFO] ————–< com.mkyong.examples:maven-code-coverage >————— [INFO] Building maven-code-coverage 1.0-SNAPSHOT [INFO] ——————————–[ jar ]——————————— [INFO] [INFO] — maven-dependency-plugin:2.8:purge-local-repository (default-cli) @ maven-code-coverage — Downloading from …

Read more

Maven – PMD example

In this article, we will show you how to use Maven PMD Plugin to analyze the Java code. P.S PMD requires Java 1.7 1. Maven PMD Plugin Define the maven-pmd-plugin in the reporting tag, so that mvn site will generate the PMD report. pom.xml <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>3.11.0</version> </plugin> </plugins> </reporting> 2. Java …

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

mvn site : java.lang.ClassNotFoundException: org.apache.maven.doxia.siterenderer.DocumentContent

Generating a Maven report with mvn site, but hits the following errors java.lang.NoClassDefFoundError: org/apache/maven/doxia/siterenderer/DocumentContent Caused by: java.lang.ClassNotFoundException: org.apache.maven.doxia.siterenderer.DocumentContent [INFO] ———————————————————————— [INFO] BUILD FAILURE [INFO] ———————————————————————— [INFO] Total time: 28.280 s [INFO] Finished at: 2018-11-19T13:20:14+08:00 [INFO] ———————————————————————— [ERROR] Failed to execute goal org.apache.maven.plugins:maven-site-plugin:3.3:site (default-site) on project maven-static-code-analysis: Execution default-site of goal org.apache.maven.plugins:maven-site-plugin:3.3:site failed: A required class …

Read more

Maven – JaCoCo code coverage example

In this article, we will show you how to use a JaCoCo Maven plugin to generate a code coverage report for a Java project. Tested with Maven 3.5.3 JUnit 5.3.1 jacoco-maven-plugin 0.8.2 Note JaCoCo is an actively developed line coverage tool, that is used to measure how many lines of our code are tested. 1. …

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

Upgrade MySQL 5.5 to MySQL 5.7

On Debian 9.5, the MySQL package is still the old MySQL 5.5. This little guide show you how to upgrade it to MySQL 5.7 1. Download MySQL APT 1.1 Get the MySQL APT and select MySQL 5.7 $ wget https://dev.mysql.com/get/mysql-apt-config_0.8.10-1_all.deb $ sudo gdebi mysql-apt-config_0.8.10-1_all.deb 1.2 Below “configuration mysql-apt-config” screen will be prompted, clicks the first …

Read more

Nginx – Unit nginx.service is masked

Upgraded a Nginx Server to the latest 1.15.x, but hits the following error message : Terminal $ sudo service nginx status * nginx.service Loaded: masked (/dev/null; bad) Active: inactive (dead) $ sudo service nginx restart Failed to restart nginx.service: Unit nginx.service is masked. Solution To solve it, just unmask with this : sudo systemctl unmask …

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 – How to sum all the stream integers

The sum() method is available in the primitive int-value stream like IntStream, not Stream<Integer>. We can use mapToInt() to convert a stream integers into a IntStream. int sum = integers.stream().mapToInt(Integer::intValue).sum(); int sum = integers.stream().mapToInt(x -> x).sum(); Full example. Java8Stream.java package com.mkyong.concurrency; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class Java8Stream { public static void main(String[] …

Read more

Maven Profiles example

In this article, we will show you few Maven profile examples to pass different parameters (server or database parameters) for different environments (dev, test or prod). P.S Tested with Maven 3.5.3 1. Basic Maven Profiles 1.1 A simple profile to skip the unit test. pom.xml <!– skip unit test –> <profile> <id>xtest</id> <properties> <maven.test.skip>true</maven.test.skip> </properties> …

Read more

Maven – How to create a multi module project

In this tutorial, we will show you how to use Maven to manage a Multi-module project containing four modules : Password module – Interface only. Password md5 module – Password module implementation, MD5 password hashing. Password sha module – Password module implementation, SHA password hashing. Web module – A simple MVC web app to hash …

Read more

Maven test failed on Spring @Autowired and jUnit 5

Review the following jUnit 5 examples to test a Spring 5 MVC web application. TestWelcome.java package com.mkyong.web; import com.mkyong.web.config.SpringConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration(classes = …

Read more

No more mvn eclipse:eclipse, what’s next?

The Apache Maven Eclipse Plugin is retired, no more following commands # support eclipse ide $ mvn eclipse:eclipse # web project $ mvn eclipse:eclipse -Dwtpversion=2.0 What is the equivalent in Eclipse IDE? 1. Solution Please use Eclipse Maven Integration (m2e). Latest Eclipse IDE has bundled the m2e plugin : 2. How to use m2e? The …

Read more

Eclipse IDE – No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

Maven compile a project in Eclipse IDE, but hits the following error messages : $ mvn clean compile [ERROR] COMPILATION ERROR : [INFO] ————————————————————- [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? [INFO] 1 error [INFO] ————————————————————- [INFO] ———————————————————————— [INFO] BUILD FAILURE [INFO] ———————————————————————— …

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 – List of available MessageDigest Algorithms

In Java, you can use the Security.getAlgorithms(“MessageDigest”) to list all the available MessageDigest algorithms. ListMessageDigest.java package com.mkyong.hashing; import java.security.Security; import java.util.Set; public class ListMessageDigest { public static void main(String[] args) { Set<String> messageDigest = Security.getAlgorithms("MessageDigest"); messageDigest.forEach(x -> System.out.println(x)); } } Output SHA3-512 SHA-384 SHA SHA3-384 SHA-224 SHA-512/256 SHA-256 MD2 SHA-512/224 SHA3-256 SHA-512 MD5 SHA3-224 P.S …

Read more

Java – How to convert byte arrays to Hex

This article shows you a few ways to convert byte arrays or byte[] to a hexadecimal (base 16 or hex) string representative. String.format Integer.toHexString Apache Commons Codec – commons-codec Spring Security Crypto – spring-security-crypto Bitwise shifting and masking. (educational purposes) Note Both Apache Commons-Codec and Spring Security Crypto modules are using the similar 5. Bitwise …

Read more

Maven – List all the project’s plugins

In Maven, you can use mvn help:effective-pom to list all the current project’s plugins and its version. D:\maven-examples\java-web-project> mvn help:effective-pom [INFO] Scanning for projects… [INFO] [INFO] ——————< com.mkyong.web:java-web-project >——————- [INFO] Building java-web-project Maven Webapp 1.0-SNAPSHOT [INFO] ——————————–[ war ]——————————— [INFO] [INFO] — maven-help-plugin:3.1.0:effective-pom (default-cli) @ java-web-project — [INFO] Effective POMs, after inheritance, interpolation, and profiles …

Read more

Java – How to join List String with commas

In Java, we can use String.join(“,”, list) to join a List String with commas. 1. Java 8 1.1 String.join JavaStringExample1.java package com.mkyong; import java.util.Arrays; import java.util.List; public class JavaStringExample1 { public static void main(String[] args) { List<String> list = Arrays.asList("a","b","c"); String result = String.join(",", list); System.out.println(result); } } Output a,b,c 1.2 Stream Collectors.joining JavaStringExample2.java package …

Read more

Python – Check if a String contains another String?

In Python, we can use in operator or str.find() to check if a String contains another String. 1. in operator name = "mkyong is learning python 123" if "python" in name: print("found python!") else: print("nothing") Output found python! 2. str.find() name = "mkyong is learning python 123" if name.find("python") != -1: print("found python!") else: print("nothing") …

Read more

Python – How to check if a file exists

In Python, we can use os.path.isfile() or pathlib.Path.is_file() (Python 3.4) to check if a file exists. 1. pathlib New in Python 3.4 from pathlib import Path fname = Path("c:\\test\\abc.txt") print(fname.exists()) # true print(fname.is_file()) # true print(fname.is_dir()) # false dir = Path("c:\\test\\") print(dir.exists()) # true print(dir.is_file()) # false print(dir.is_dir()) # true If check from pathlib import …

Read more