devxlogo

Java

Comparing Two Integers

Before Java 7, this task required a comparator and the compareTo() method. But, beginning with Java 7, is advisable to rely on Integer.compare(), which is not exposed to overflow risks

Enabling Hibernate Statistics

In order to obtain statistics regarding SQL queries executed via Hibernate, we need to set hibernate.generate_statistics=true. In Spring, we need to add in application.properties the following setting: spring.jpa.properties.hibernate.generate_statistics=true

Understanding the Collections.unmodifiableCollection

Collection has an unmodifiableCollection method that returns a collection object that cannot be modified. It means that you cannot add or remove any element from the collection. import java.util.*;public class UnmodifiableCollection{

Apply String Indentation

Beginning with JDK 12, we can indent strings via String.indent(int n), in which n is the number of spaces.Example : indent text “abc” with 10 spaces: “abs”.indent(10);

Return a Boolean if the Optional Is Empty

Beginning with JDK 11, we can return a boolean if the Optional is empty via Optional#isEmpty(): public boolean bookIsEmpty(long id) { Optional book = // code that fetches the book

Define an URL to a Local File

If we want to define a valid URL instance for a file we need to add the “file” protocol as in the following example: URL url = new URL(“file:///C:/photos/me.png”);

Regex Has a Presence in Java as Well

See how to use this form of Regex below to identify whether or not a string has only alphabets present. public class RegexHasOnlyAlphabets{ public static void main(String args[]) { RegexHasOnlyAlphabets

Operations on Dates and Times

See how to add or subtract days, months or years with these operations. LocalDate tomorrow = LocalDate.now().plusDays(3);LocalDateTime anHourFromNow = LocalDateTime.now().plusHours(10);Long daysBetween = java.time.temporal.ChronoUnit.DAYS.between(LocalDate.now(), LocalDate.now().plusDays(2));Duration duration = Duration.between(Instant.now(), ZonedDateTime.parse(“2018-08-30T09:00:00+01:00[Europe/Stockholm]”));