devxlogo

Java

Image

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

Image

Understanding the FindAny Method

Learn how to use the findAny method in java.util.Stream. This returns an Optional describing an element, or an empty Optional if Stream is empty. Also, remember that the same stream

Image

Escape Characters in Regular Expressions

In Java, characters as  cannot appear in a regular expression without being escaped. For this, rely on the Pattern.quote() method as in the following example: public static boolean contains(String t1, String

Image

Finding the Java Version Programatically

import java.util.*;public class FindJavaVersion{ public static void main(String args[]) { FindJavaVersion findJavaVersion = new FindJavaVersion(); findJavaVersion.printDetails(); } private void printDetails() { Properties systemProperties = System.getProperties(); System.out.println(“Java version: ” + systemProperties.get(“java.version”));

Image

Counting Digits in a Given Number

A typical mechanism of converting to a string, traversing and counting has a lot of processing to complete. Instead, the code below shows a combination of methods in Math package

Image

Finding the Available Drive Types in the System

Getting to know the available drive types in the system is essential for certain activities in Java. The following code snippet lists the available drive types in the system: */import

Image

Boost the Switch Statement in JDK 12

Starting with JDK 12, the “switch” statement is extended so that it can be used as either a statement or an expression. A sample: switch (day) { case MONDAY, FRIDAY,

Image

Creating a Specific Date in Java

To create a new date, you will need a Calendar instance and then you can set the Calendar instance to the date you need. Calendar calendar = Calendar.getInstance(); The line