JUnit 5 + Maven examples

This article shows you how to add JUnit 5 in a Maven project, nothing special, just add the JUnit 5 junit-jupiter-engine library and make sure the maven-surefire-plugin is at least version 2.22.0 Technologies used: Maven 3.6 Java 8 JUnit 5.5.2 1. Maven + JUnit 5 1. Add the JUni 5 jupiter engine. pom.xml <dependency> <groupId>org.junit.jupiter</groupId> …

Read more

Java 12 – Switch Expressions

Java 12, JEP 325: Switch Expressions enhanced the traditional switch statement to support the following new features: Multiple case labels Switch expression returning value via break (replaced with yield in Java 13 switch expressions) Switch expression returning value via label rules (arrow) P.S Switch expressions are a preview feature and are disabled by default. A …

Read more

Python – How to trim a String?

In Python trim method is called strip, it removes the leading and trailing spaces of a String. str.strip() #trim str.lstrip() #ltrim str.rstrip() #rtrim #!/usr/bin/python str = " abc " print(str) print(str.strip()) print(str.lstrip()) print(str.rstrip()) Output {space} abc {space} abc abc {space} {space} abc References Python docs str.strip()

Java – Get the last element of a list

In Java, index starts at 0, we can get the last index of a list via this formula: list.size() – 1 JavaExample1.java package com.mkyong.test; import java.util.Arrays; import java.util.List; public class JavaExample1 { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); System.out.println(list.get(list.size() – 1)); System.out.println(list.get(list.size() – 2)); System.out.println(list.get(list.size() – 3)); …

Read more

Java – How to get keys and values from Map

In Java, we can get the keys and values via map.entrySet() Map<String, String> map = new HashMap<>(); // Get keys and values for (Map.Entry<String, String> entry : map.entrySet()) { String k = entry.getKey(); String v = entry.getValue(); System.out.println("Key: " + k + ", Value: " + v); } // Java 8 map.forEach((k, v) -> { …

Read more

Spring JdbcTemplate Handle Large ResultSet

Spring JdbcTemplate example to get a large ResultSet and process it. P.S Tested with Java 8 and Spring JDBC 5.1.4.RELEASE 1. Get large ResultSet 1.1 Below is a classic findAll to get all data from a table. BookRepository.java public List<Book> findAll() { return jdbcTemplate.query( "select * from books", (rs, rowNum) -> new Book( rs.getLong("id"), rs.getString("name"), …

Read more

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long

Below example, the jdbcTemplate.queryForList returns an object of Integer and we try to convert it into a Long directly: public List<Customer> findAll() { String sql = "SELECT * FROM CUSTOMER"; List<Customer> customers = new ArrayList<>(); List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql); for (Map row : rows) { Customer obj = new Customer(); obj.setID(((Long) row.get("ID"))); // the …

Read more

Java – How to lock a file before writing

In Java, we can combine RandomAccessFile and FileChannel to lock a file before writing. LockFileAndWrite.java package com.mkyong; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileLock; import java.util.concurrent.TimeUnit; public class LockFileAndWrite { public static void main(String[] args) { writeFileWithLock(new File("D:\\server.log"), "mkyong"); } public static void writeFileWithLock(File file, String content) { // auto close and release the …

Read more

Java – How to read last few lines of a File

In Java, we can use the Apache Commons IO ReversedLinesFileReader to read the last few lines of a File. pom.xml <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> 1. Test Data A server log file sample d:\\server.log a b c d 1 2 3 4 5 2. Read Last Line 2.1 Read the last 3 lines of a …

Read more

Spring Boot JDBC Stored Procedure Examples

In this tutorial, we will show you how to use Spring Boot JDBC SimpleJdbcCall to call a stored procedure and stored function from a Oracle database. Technologies used : Spring Boot 2.1.2.RELEASE Spring JDBC 5.1.4.RELEASE Oracle database 19c HikariCP 3.2.0 Maven 3 Java 8 Unlike JdbcTemplate, Spring Boot didn’t create any SimpleJdbcCall automatically, we have …

Read more

Spring Boot JDBC Examples

In this tutorial, we will show you how to use Spring Boot JDBC JdbcTemplate and NamedParameterJdbcTemplate. Technologies used : Spring Boot 2.1.2.RELEASE Spring JDBC 5.1.4.RELEASE HikariCP 3.2.0 H2 in-memory database 1.4.197 Maven 3 Java 8 In Spring Boot JDBC, the database related beans like DataSource, JdbcTemplate and NamedParameterJdbcTemplate will be configured and created during the …

Read more

Java Regular Expression Examples

Java 8 stream and regular expression examples. Note Learn the basic regular expression at Wikipedia 1. String.matches(regex) 1.1 This example, check if the string is a number. JavaRegEx1.java package com.mkyong.regex; import java.util.Arrays; import java.util.List; public class JavaRegEx1 { public static void main(String[] args) { List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211"); for (String number …

Read more

Java 8 Stream – Convert List<List<String>> to List<String>

As title, we can use flatMap to convert it. Java9Example1.java package com.mkyong.test; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class Java9Example1 { public static void main(String[] args) { List<String> numbers = Arrays.asList("1", "2", "A", "B", "C1D2E3"); List<List<String>> collect = numbers.stream() .map(x -> new Scanner(x).findAll("\\D+") .map(m -> m.group()) .collect(Collectors.toList()) ) .collect(Collectors.toList()); collect.forEach(x -> System.out.println(x)); …

Read more

How to loop an enum in Java

Call the .values() method of the enum class to return an array, and loop it with the for loop: for (EnumClass obj : EnumClass.values()) { System.out.println(obj); } For Java 8, convert an enum into a stream and loop it: Stream.of(EnumClass.values()).forEach(System.out::println); 1. For Loop Enum 1.1 An enum to contain a list of the popular JVM …

Read more

java.sql.SQLException: The server time zone value ‘xx time’ is unrecognized

Making a JDBC connection to the MySQL server with the latest mysql-connector-java:8.0.16 and hits the following SQLException: Tested with MySQL 5.7 Java 8 JDBC driver, mysql-connector-java 8.0.16 try (Connection conn = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/test", "root", "password")) { //… } catch (Exception e) { e.printStackTrace(); } Output java.sql.SQLException: The server time zone value ‘Malay Peninsula Standard Time’ …

Read more

Java – Convert Integer to Long

In Java, we can use Long.valueOf() to convert an Integer to a Long TestInteger.java package com.mkyong.example; public class TestInteger { public static void main(String[] args) { Integer num = 1; System.out.println(num); // 1 Long numInLong = Long.valueOf(num); System.out.println(numInLong); // 1 } } References Long.valueOf JavaDocs)

Java 8 Parallel Streams Examples

Few Java 8 examples to execute streams in parallel. 1. BaseStream.parallel() A simple parallel example to print 1 to 10. ParallelExample1.java package com.mkyong.java8; import java.util.stream.IntStream; public class ParallelExample1 { public static void main(String[] args) { System.out.println("Normal…"); IntStream range = IntStream.rangeClosed(1, 10); range.forEach(System.out::println); System.out.println("Parallel…"); IntStream range2 = IntStream.rangeClosed(1, 10); range2.parallel().forEach(System.out::println); } } Output Normal… 1 2 …

Read more

java.sql.SQLException: operation not allowed: Ordinal binding and Named binding cannot be combined!

Ordinal binding or index binding: String name = stat.getString(2); BigDecimal salary = stat.getBigDecimal(3); Timestamp createdDate = stat.getTimestamp(4); Named binding: String name = stat.getString("NAME"); BigDecimal salary = stat.getBigDecimal("SALARY"); Timestamp createdDate = stat.getTimestamp("CREATED_DATE"); If we mixed both like this: String name = stat.getString(2); BigDecimal salary = stat.getBigDecimal("SALARY"); Timestamp createdDate = stat.getTimestamp(4); Error: java.sql.SQLException: operation not allowed: Ordinal …

Read more

Java 8 – Convert ZonedDateTime to Timestamp

Java example to convert java.time.ZonedDateTime to java.sql.Timestamp and vice verse. 1. ZonedDateTime -> Timestamp TimeExample1.java package com.mkyong.jdbc; import java.sql.Timestamp; import java.time.ZonedDateTime; public class TimeExample1 { public static void main(String[] args) { ZonedDateTime now = ZonedDateTime.now(); // 1. ZonedDateTime to TimeStamp Timestamp timestamp = Timestamp.valueOf(now.toLocalDateTime()); // 2. ZonedDateTime to TimeStamp , no different Timestamp timestamp2 = …

Read more

Python – How to print dictionary

Python example to print the key value of a dictionary. stocks = { ‘IBM’: 146.48, ‘MSFT’: 44.11, ‘CSCO’: 25.54 } print(stocks) for k, v in stocks.items(): print(k, v) for k in stocks: print(k, stocks[k]) Output {‘IBM’: 146.48, ‘MSFT’: 44.11, ‘CSCO’: 25.54} IBM 146.48 MSFT 44.11 CSCO 25.54 IBM 146.48 MSFT 44.11 CSCO 25.54 References Python …

Read more

Java 8 Stream – The peek() is not working with count()?

Many examples are using the .count() as the terminal operation for .peek(), for example: Java 8 List<String> l = Arrays.asList("A", "B", "C", "D"); long count = l.stream().peek(System.out::println).count(); System.out.println(count); // 4 Output – It’s working fine. A B C D 4 However, for Java 9 and above, the peek() may print nothing: Java 9 and above …

Read more

Java 8 – Convert LocalDateTime to Timestamp

In Java, we can use Timestamp.valueOf(LocalDateTime) to convert a LocalDateTime into a Timestamp. 1. LocalDateTime Timestamp Java example to convert java.time.LocalDateTime to java.sql.Timestamp and vice verse. TimeExample.java package com.mkyong; import java.sql.Timestamp; import java.time.LocalDateTime; public class TimeExample { public static void main(String[] args) { // LocalDateTime to Timestamp LocalDateTime now = LocalDateTime.now(); Timestamp timestamp = Timestamp.valueOf(now); …

Read more

Java Events 2019

Some Java Conferences and Events 2019. 1. JAX London (October 7–10, 2019) JAX London is a four-day conference for cutting edge software engineers and enterprise-level professionals. JAX brings together the world’s leading innovators in the fields of JAVA, microservices, continuous delivery and DevOps. Date: October 7–10, 2019 Location: Business Design Centre, London Discount(15%): mky_jxl19#15 Twitter: …

Read more

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

This is caused by the requested SID doesn’t exist in {ORACLE_HOME}/network/admin/tnsnames.ora P.S Tested with Oracle database 19c with ojdbc8.jar 1. JDBC try (Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "system", "password")) { //… } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Output: SQL State: 66000 Listener refused the connection with the following …

Read more

JDBC CallableStatement – PostgreSQL Stored Function

A JDBC CallableStatement example to show you how to call a stored function from PostgreSQL database. P.S Tested with PostgreSQL 11 and Java 8 pom.xml <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.5</version> </dependency> 1. Call Function 1.1 Create a stored function and calling it via JDBC. FunctionReturnString.java package com.mkyong.jdbc.callablestatement; import java.sql.*; public class FunctionReturnString { public static void …

Read more

JDBC Class.forName() is no longer required

Since Java 1.6, JDBC 4.0 API, it provides a new feature to discover java.sql.Driver automatically, it means the Class.forName is no longer required. Just put any JDBC 4.x driver in the project classpath, and Java is able to detect it. For example, JDBC driver for PostgreSQL: pom.xml <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.5</version> </dependency> And it works: …

Read more

JDBC – How to print all table names from a database?

A JDBC example to connect to a PostgreSQL, and print out all the tables from the default database postgres pom.xml <dependencies> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.5</version> </dependency> </dependencies> P.S Tested with Java 8 and postgresql jdbc driver 42.2.5 PrintAllTables.java package com.mkyong.jdbc; import java.sql.*; public class PrintAllTables { public static void main(String[] argv) { System.out.println("PostgreSQL JDBC Connection …

Read more

Java – How to change date format in a String

If Java 8, DateTimeFormatter, else SimpleDateFormat to change the date format in a String. 1. DateTimeFormatter (Java 8) Convert the String to LocalDateTime and change the date format with DateTimeFormatter DateFormatExample1.java package com.mkyong; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateFormatExample1 { // date format 1 private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); // date …

Read more

Java – Add new line in String

Different operating system has a different new line or line separator string: UNIX, Linux or Mac OSX = \n Windows = \r\n NewLineExample.java package com.mkyong; public class NewLineExample { public static void main(String[] args) { String original = "Hello World Java"; System.out.println(original); // add new line String originalNewLine = "Hello\nWorld\nJava"; System.out.println(originalNewLine); } } Output Hello …

Read more

Java 8 – Should we close the Stream after use?

Only Streams whose source are an IO channel like Files.lines(Path, Charset) need to be closed. Read this Stream JavaDocs Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by …

Read more

Java – Convert File to String

In Java, we have many ways to convert a File to a String. A text file for testing later. c:\\projects\\app.log A B C D E 1. Java 11 – Files.readString A new method Files.readString is added in java.nio.file.Files, it makes reading a string from File much easier. FileToString1.java package com.mkyong; import java.io.IOException; import java.nio.file.Files; import …

Read more

Java – How to save a String to a File

In Java, there are many ways to write a String to a File. 1. Java 11 – Files.writeString Finally, a new method added in java.nio to save a String into a File easily. StringToFileJava11.java package com.mkyong; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class StringToFileJava11 { public static void main(String[] args) …

Read more

FastJson – Convert Java objects to / from JSON

FastJson provides easily APIs to convert Java objects to / from JSON JSON.toJSONString – Java objects to JSON JSON.parseObject – JSON to Java objects JSON.parseArray – JSON array to List of Java objects Note You may have interest to read this How to parse JSON with Jackson Overall, the FastJson is really simple and easy …

Read more

Java password generator example

Here’s the Java password generator to generate a secure password that consists of two lowercase chars, two uppercase chars, two digits, two special chars, and pad the rest with random chars until it reaches the length of 20 characters. Secure password requirements: Password must contain at least two digits [0-9]. Password must contain at least …

Read more

Java – How to generate a random String

Few Java examples to show you how to generate a random alphanumeric String, with a fixed length. 1. Random [a-ZA-Z0-9] 1.1 Generate a random alphanumeric String [a-ZA-Z0-9], with a length of 8. RandomExample.java package com.mkyong; import java.security.SecureRandom; public class RandomExample { private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz"; private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase(); …

Read more