devxlogo

Java

Image

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]”));

Image

Joining Strings with a Delimiter

Starting with Java 8, we can join several strings with a delimiter (e.g., comma) via the String.join() method: String result = String.join(“, “, “One”, “Two”, “Three”);// One, Two, ThreeSystem.out.println(result);

Image

Escape Sequences in Literals

String and character literals provide an escape mechanism that allows express character codes that would otherwise not be allowed in the literal. An escape sequence consists of a backslash character

Image

Get Packages of a Module

Java 9 has added the concept of module via Java Platform Module System. In order to obtain the names of packages from a module we can do it as follows:

Image

Understanding the Feature-rich Methods of Math Package

The Math package is feature-rich and some of the methods are illustrated below. public class MathPkg{public static void main(String args[]){MathPkg mathPkg = new MathPkg();mathPkg.proceed();}private void proceed(){int positiveNum = 5;int negativeNum

Image

What is the Advantage of Immutability?

It is difficult to maintain correctness in mutable objects, as multiple threads could be trying to change the state of the same object. This can lead to some threads seeing

Image

Swapping Two Numbers

Swapping two numbers without using a new variable is always a good approach. This helps your application to be memory and performance oriented. public class Swap2Numbers{ int firstNum = 10;

Image

Get All the Available Time Zones

Before Java 8, this was obtained as a String[] via TimeZone class: String[] zoneIds = TimeZone.getAvailableIDs(); Java 8 comes with a new approach via java.time.ZoneId class: Set zoneIds = ZoneId.getAvailableZoneIds();