devxlogo

Java

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

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

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:

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

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

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;

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();

Avoid NPE via JDK 8, Optional

Starting with JDK 8, you can avoid NullPointerException by returning an Optional. For example, instead of returning null, this method returns an empty Optional: public Optional fetchShoppingCart(long id) { ShoppingCart