UTIL PACKAGE / CATATAN</>↗Util Package07 Apr 2025
Unwrapping a value from an Optional in Java safely is a common concern. Java’s Optional is designed to handle null values more gracefully by avoiding NullPointerException. Below are some best practices to unwrap and access the value of an Optional safely: 1. Using Optional.ifPresent (Best for side effects) If you don’t need to handle the […]
UTIL PACKAGE / CATATAN</>↗Util Package07 Apr 2025
Using the Optional class in Java is a great way to handle the potential absence of a value and avoid explicit null checks in your code. Here’s a detailed explanation of how you can use Optional effectively to avoid null checks: 1. Use Optional Instead of null Instead of returning null from a method, return […]
UTIL PACKAGE / CATATAN</>↗Util Package07 Apr 2025
In Java, the Optional class provides a way to handle possible null values in a more functional style. If you’re using an Optional and want to provide a default value, you can do so using the orElse() or orElseGet() methods. Here’s an explanation and code examples for both: 1. Using Optional.orElse() The orElse() method provides […]
UTIL PACKAGE / CATATAN</>↗Util Package07 Apr 2025
To check if a Java Optional has a value, you can use the isPresent() or isEmpty() methods: Using isPresent() This method returns true if the Optional contains a value, and false if it is empty. Optional<String> optional = Optional.of("Hello"); if (optional.isPresent()) { System.out.println("Value is present: " + optional.get()); } else { System.out.println("Value is not present."); […]
UTIL PACKAGE / CATATAN</>↗Util Package07 Apr 2025
To create an Optional in Java, you can use the Optional class, which was introduced in Java 8 as part of the java.util package. It is used to represent a value that can either exist (non-null) or be absent (null), making your code more robust and reducing the risk of NullPointerExceptions. Here are some common […]
CORE API / CATATAN</>↗Core API07 Apr 2025
To set and read custom HTTP headers using HttpURLConnection in Java, you can make use of its methods setRequestProperty to set headers and getHeaderField to read them. Here’s how you can do it: Setting Custom HTTP Headers You can set custom HTTP headers on a request using the setRequestProperty method. For example: package org.kodejava.net; import […]