Mercy
Mercy
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/26/2025 in #❓︱qotw-answers
Week 110 — What is the null literal and how can it be used in Java applications?
The null literal in Java represents the absence of a value or a reference that doesn't point to any object. According to my research, the null keyword in java is a literal. It is neither a data type nor an object. Null represents the absence of a value. If you assign a null to an object of string Class, it does not refer to any value in the memory. The null cannot be assigned to primitive data types. The reserved word null is case sensitive and cannot be written as Null or NULL as the compiler will not recognize them and will certainly give an error. null is used as a special value to signify: 1. It can also be used to initialise variables String str = null; Uninitialized state Termination condition Non-existing object An unknown value The null is used to express a particular value within a program. They are constant values that directly appear in a program and can be assigned now to a variable. 2. Checking for Null Values NullPointer exception is thrown when you try to use a variable with a null value, so to avoid it, you need to check the NullPointerException as I did below
if (str != null) {
System.out.println(str.length());
} else {
System.out.println("String is null");
}
if (str != null) {
System.out.println(str.length());
} else {
System.out.println("String is null");
}
Explicitly Dereferencing You can use null to dereference an object and release its memory, then it will be eligible for garbage collection.
MyClass obj = new MyClass();
obj = null;
MyClass obj = new MyClass();
obj = null;
Did you know that, you can explicitly add null values in ArrayLists.
List<String> list = new ArrayList<>();
list.add(null);
List<String> list = new ArrayList<>();
list.add(null);
9 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/26/2025 in #❓︱qotw-answers
Week 110 — What is the null literal and how can it be used in Java applications?
Care should be taken with how nulls are used and handled. If the code is not expecting and guarding against them, NullPointerExceptions will result. Furthermore, because potential null values complicate the code or open it up to potential bugs, other mechanisms (like Optional<T>) should be used whenever possible.
9 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/26/2025 in #❓︱qotw-answers
Week 110 — What is the null literal and how can it be used in Java applications?
Some ways that null can be used: * As the initial value of a variable or field to indicate that it hasn't been assigned a real value yet * As a method call argument to indicate "no value" for that parameter * Returned from a method to indicate that no sensible value could be returned
9 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/26/2025 in #❓︱qotw-answers
Week 110 — What is the null literal and how can it be used in Java applications?
In Java, null indicates the absence of an object. If null is assigned to a non-primitive variable or field, then that variable or field points to nothing. Furthermore, any non-primitive field that is not explicitly assigned a value will be null.
9 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/26/2025 in #❓︱qotw-answers
Week 110 — What is the null literal and how can it be used in Java applications?
0x01 ACONST_NULL pushes a null reference onto the stack. Its used to represent the absence of an object.
// Pushes a null ref onto the stack
// [0x01]
ACONST_NULL

// Sets the value of MyClass.someField to NULL
// [0xB3, 0xFieldRef, 0xFieldDescriptor]
PUTSTATIC com/example/MyClass/someField Ljava/lang/Object;
// Pushes a null ref onto the stack
// [0x01]
ACONST_NULL

// Sets the value of MyClass.someField to NULL
// [0xB3, 0xFieldRef, 0xFieldDescriptor]
PUTSTATIC com/example/MyClass/someField Ljava/lang/Object;
Myclass.someField = null;
Myclass.someField = null;
9 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/26/2025 in #❓︱qotw-answers
Week 110 — What is the null literal and how can it be used in Java applications?
A null literal is a constant value that can be assigned to ReferenceType variables to point to a null reference.
9 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/26/2025 in #❓︱qotw-answers
Week 110 — What is the null literal and how can it be used in Java applications?
null is a key word that means a non-reference. It is used to state that a Reference-Type variable/field is not pointing to any valid reference. Also, it is known as the 1 bilion dollar error. List<Integer> myList = List.of(1, 2, 3); // Now, myList is pointing to a list returned by List.Of() method myList = null; // From this point, myList is not pointing to that List anymore.
9 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/26/2025 in #❓︱qotw-answers
Week 110 — What is the null literal and how can it be used in Java applications?
The literal null refers to a special value that can be used for any reference type in a Java program. It refers to the absence of a value i.e. if a variable is null, it means there is no value of the type set.
Object someVariable = null;
LocalDateTime someLocalDateTimeVariable = null;
// etc
Object someVariable = null;
LocalDateTime someLocalDateTimeVariable = null;
// etc
It is possible to check for an object being null using the == operator:
if (someVariable == null) {
System.out.println("the variable is null");
} else {
System.out.println("the variable has a value");
}
if (someVariable == null) {
System.out.println("the variable is null");
} else {
System.out.println("the variable has a value");
}
Attempting to access any field or call a method of a variable that's set to null causes a NullPointerException to be thrown
Object someNullObject = null;
someNullObject.toString();//throws java.lang.NullPointerException: Cannot invoke "Object.toString()" because "someNullObject" is null
Object someNullObject = null;
someNullObject.toString();//throws java.lang.NullPointerException: Cannot invoke "Object.toString()" because "someNullObject" is null
class ClassWithVariable{
int i;
}
ClassWithVariable nullInstance = null;
int j = nullInstance.i;//throws java.lang.NullPointerException: Cannot read field "i" because "nullInstance" is null
class ClassWithVariable{
int i;
}
ClassWithVariable nullInstance = null;
int j = nullInstance.i;//throws java.lang.NullPointerException: Cannot read field "i" because "nullInstance" is null
The Objects class provides some utility methods for dealing with null. For example, the method Objects.requireNonNullElse returns the variable passed as the first argument if it is non-null and the second argument otherwise. The Objects.requireNonNull method can be used as a simple null assertion and throws a NullPointerException if the argument is null.
LocalDateTime someLocalDateTimeVariableOrNow = Objects.requireNonNullElse(someLocalDateTimeVariable, LocalDateTime.now());

Objects.requireNonNull(someVariable, "exception message in case someVariable is null");
LocalDateTime someLocalDateTimeVariableOrNow = Objects.requireNonNullElse(someLocalDateTimeVariable, LocalDateTime.now());

Objects.requireNonNull(someVariable, "exception message in case someVariable is null");
9 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/19/2025 in #❓︱qotw-answers
Week 109 — How can one parse JSON text in a Java application?
ObjectMapper mapper = new ObjectMapper(); String jsonString = "{"name":"John", "age":30}"; JsonNode root = mapper.readTree(jsonString); Add either the jackson-databind or gson dependency to your project to make use of these librarie
12 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/19/2025 in #❓︱qotw-answers
Week 109 — How can one parse JSON text in a Java application?
Important ⚠️ : The following answer is based on my knowledge and expertise using Java starting from v7 to v17 LTS for years. I have not yet fully explored the capabilities of Java 21 LTS or any subsequent versions. AFAIK, Java core do not include a built-in feature specifically designed for JSON. Alternatively there are some popular 3rd-party libraries, one of them is called Jackson, one of the most popular and powerful java libraries, it provides a set of tools to handle JSON easily and effectively. What is JSON parsing ? IMO, Parsing is a process of analyzing a string data according to a particular syntax and converting it into a structured representation like objects in Java. For JSON, parsing means interpreting a JSON text/string and converting it into a Java object. This is closely tied to serialization and deserialization. Parsing JSON Example 1. Consider the following JSON object :
{"id": 123, "name": "Jhon"}
{"id": 123, "name": "Jhon"}
2. Define a Java class model that represents the JSON :
record MyJson(long id, String name) {}
record MyJson(long id, String name) {}
3. Parse the JSON using ObjectMapper API from Jackson :
package com.myorg.myjson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import static java.lang.System.out;

public class MyJsonParser {
private static final ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] arguments) {
String jsonAsString = "{ \"id\": 123, \"name\": \"Jhon\"}";
try {
MyJson json = objectMapper.readValue(jsonAsString, MyJson.class);
out.print("id : " + json.id());
out.print("name : " + json.name());
} catch (JsonProcessingException ex) {
out.print("unable to parse JSON: " + ex.getMessage());
}
}
}
package com.myorg.myjson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import static java.lang.System.out;

public class MyJsonParser {
private static final ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] arguments) {
String jsonAsString = "{ \"id\": 123, \"name\": \"Jhon\"}";
try {
MyJson json = objectMapper.readValue(jsonAsString, MyJson.class);
out.print("id : " + json.id());
out.print("name : " + json.name());
} catch (JsonProcessingException ex) {
out.print("unable to parse JSON: " + ex.getMessage());
}
}
}
4. Run it :
id: 123
id: 123
Done ! 🎉
12 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/19/2025 in #❓︱qotw-answers
Week 109 — How can one parse JSON text in a Java application?
Using core directly is very manual and verbose, so most applications will use the annotations and databind libraries to assist:
String json = "{\"name\":\"Mac\",\"occupation\":\"software developer\"}";
ObjectMapper mapper = new ObjectMapper();
Employee emp = mapper.readValue(json, Employee.class);
System.out.println(emp);
String json = "{\"name\":\"Mac\",\"occupation\":\"software developer\"}";
ObjectMapper mapper = new ObjectMapper();
Employee emp = mapper.readValue(json, Employee.class);
System.out.println(emp);
12 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/19/2025 in #❓︱qotw-answers
Week 109 — How can one parse JSON text in a Java application?
A quick Jackson example... Jackson exposes a couple of different "levels" of functionality. The core library provides low level parsing and generating utilities, and is the foundation that the other levels are built on:
String json = "{\"name\":\"Mac\",\"occupation\":\"software developer\"}";
JsonFactory jackson = new JsonFactory();
try (final JsonParser parser = jackson.createParser(json)) {
Employee emp = new Employee();
while (parser.nextToken() != JsonToken.END_OBJECT) {
String keyName = parser.currentName();
if ("name".equals(keyName)) {
parser.nextToken();
emp.name = parser.getText();
} else if ("occupation".equals(keyName)) {
parser.nextToken();
emp.occupation = parser.getText();
}
}
System.out.println(emp);
}
String json = "{\"name\":\"Mac\",\"occupation\":\"software developer\"}";
JsonFactory jackson = new JsonFactory();
try (final JsonParser parser = jackson.createParser(json)) {
Employee emp = new Employee();
while (parser.nextToken() != JsonToken.END_OBJECT) {
String keyName = parser.currentName();
if ("name".equals(keyName)) {
parser.nextToken();
emp.name = parser.getText();
} else if ("occupation".equals(keyName)) {
parser.nextToken();
emp.occupation = parser.getText();
}
}
System.out.println(emp);
}
12 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/19/2025 in #❓︱qotw-answers
Week 109 — How can one parse JSON text in a Java application?
Applications should use an existing library for working with JSON. The most commonly used one is Jackson, but other popular libraries include Google's GSON and Jakarta EE's JSON-P.
12 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/19/2025 in #❓︱qotw-answers
Week 109 — How can one parse JSON text in a Java application?
Now, we can get json elements from the object using the get method:
JsonElement nameElement = object.get("name");
// true - our "name" is a JsonPrimitive representing a String
if(nameElement.isJsonPrimitive()) {
JsonPrimitive namePrimitive = nameElement.getAsJsonPrimitive();
String name = namePrimitive.getAsString();
System.out.println(name);
}
JsonElement nameElement = object.get("name");
// true - our "name" is a JsonPrimitive representing a String
if(nameElement.isJsonPrimitive()) {
JsonPrimitive namePrimitive = nameElement.getAsJsonPrimitive();
String name = namePrimitive.getAsString();
System.out.println(name);
}
This can also be simplified:
JsonElement nameElement = object.get("name");
// true - our "name" is a JsonPrimitive representing a String
if(nameElement.isJsonPrimitive()) {
String name = nameElement.getAsString();
System.out.println(name);
}
JsonElement nameElement = object.get("name");
// true - our "name" is a JsonPrimitive representing a String
if(nameElement.isJsonPrimitive()) {
String name = nameElement.getAsString();
System.out.println(name);
}
We can also iterate over all entries present in a JsonObject:
for(Map.Entry<String, JsonElement> entry : object.entrySet()) {
String key = entry.getKey();
JsonElement value = entry.getValue();
if(value.isJsonPrimitive()) {
System.out.println(key + ": " + value.getAsString());
}
}
for(Map.Entry<String, JsonElement> entry : object.entrySet()) {
String key = entry.getKey();
JsonElement value = entry.getValue();
if(value.isJsonPrimitive()) {
System.out.println(key + ": " + value.getAsString());
}
}
and the output will be:
name: John
surname: Paul
age: 21
height: 171.3
alive: true
name: John
surname: Paul
age: 21
height: 171.3
alive: true
12 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/19/2025 in #❓︱qotw-answers
Week 109 — How can one parse JSON text in a Java application?
But... What if we don't know what fields are present? Then we can't really use the method shown before. We can, however, parse our JSON into a JsonObject. You can think of JsonObject as a Map, with String keys and JsonElement values. JsonElement is a base class for all JSON elements. It can either be an instance of JsonObject, JsonArray, JsonPrimitive, or even JsonNull. Let's begin by parsing our user.json into a JsonObject. For that we'll use JsonParser:
JsonObject object;
try(Reader reader = new FileReader("user.json")) {
object = JsonParser.parseReader(reader).getAsJsonObject();
}
JsonObject object;
try(Reader reader = new FileReader("user.json")) {
object = JsonParser.parseReader(reader).getAsJsonObject();
}
12 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/19/2025 in #❓︱qotw-answers
Week 109 — How can one parse JSON text in a Java application?
Now, let's assume, we have the following json:
{
"name": "John",
"surname": "Paul",
"age": 21,
"height": 173.7,
"alive": true
}
{
"name": "John",
"surname": "Paul",
"age": 21,
"height": 173.7,
"alive": true
}
stored in a file named user.json. GSON allows you to parse JSON in two main ways. You can either parse the JSON into a JsonObject/JsonElement, or, if you know the JSON's structure, you can convert it into your own object. We will go with the latter method. First, let's create a class to hold the data parsed from JSON. Our JSON has 5 fields: - name - String - surname - also a String - age - an int - height - a float - alive - a boolean With this, we can construct our class:
class User {
public String name;
public String surname;
public int age;
public float height;
public boolean alive;
}
class User {
public String name;
public String surname;
public int age;
public float height;
public boolean alive;
}
Normally you may want to make the fields private and use getters, but for this example I want to keep things as simple as possible. Now we need to actually parse the JSON. GSON allows parsing both from String and from a Reader. Since we don't have a String representation of our JSON, we need to use a FileReader. Parsing the file into a User instance is as simple as doing:
import com.google.gson.*;

public class Main {
public static void main(String[] args) {

// Open the user.json file
try (Reader reader = new FileReader("user.json")) {

// Actually parse the JSON
User user = new Gson().fromJson(reader, User.class);

// Print all of user's fields
System.out.println("Name: " + user.name);
System.out.println("Surname: " + user.surname);
System.out.println("Age: " + user.age);
System.out.println("Height (cm): " + user.height);
System.out.println("Alive: " + user.alive);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import com.google.gson.*;

public class Main {
public static void main(String[] args) {

// Open the user.json file
try (Reader reader = new FileReader("user.json")) {

// Actually parse the JSON
User user = new Gson().fromJson(reader, User.class);

// Print all of user's fields
System.out.println("Name: " + user.name);
System.out.println("Surname: " + user.surname);
System.out.println("Age: " + user.age);
System.out.println("Height (cm): " + user.height);
System.out.println("Alive: " + user.alive);
} catch (Exception e) {
e.printStackTrace();
}
}
}
After running the code, this should be the output:
Name: John
Surname: Paul
Age: 21
Height (cm): 173.7
Alive: true
Name: John
Surname: Paul
Age: 21
Height (cm): 173.7
Alive: true
12 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/19/2025 in #❓︱qotw-answers
Week 109 — How can one parse JSON text in a Java application?
Java itself does not include a way to parse JSON, although a person with enough knowledge can write their own parser. Still, parsing JSON in Java is easy, as there are many parser libraries available! This leads us to the first question: "which library should I use?" Currently, these are the two most popular JSON parsers: - Jackson - GSON Which one you use is only up to you. After choosing a library, the next step is to include it in our project. In this example I will use the GSON libray, as in my personal opinion it's the easiest to use. Depending on your project, including the library can be done in a few ways: - If your project is using a build system, the recommended way of including the library is to add it to the dependencies section of your build system's config file. Here are some examples: - Gradle (build.gradle):
dependencies {
implementation group: 'com.google.code.gson', name: 'gson', version: '2.11.0'
}

dependencies {
implementation group: 'com.google.code.gson', name: 'gson', version: '2.11.0'
}

- Maven (pom.xml):
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
<dependencies>

<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
<dependencies>

- If you are not using a build system, but are still using an IDE, you can download the .jar file manually from the Maven repository and include it in your project's dependencies using your IDE's tools. For example in Eclipse all you need to do is right-click on your project (assuming it has a Java nature), navigate to Build Path > Configure Build Path... and in the Libraries tab click on Classpath and then the Add External JARs... button. - If you are using javac to compile your code, you need to include the .jar file in the classpath, by using javac -classpath path/to/gson.jar ...
12 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/19/2025 in #❓︱qotw-answers
Week 109 — How can one parse JSON text in a Java application?
Another library for JSON processing is Jackson which can not only parse JSON data but also automatically deserialize it to objects matching the names. To add jackson to a Maven project, the following dependency can be used
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.2</version>
</dependency>
We will then reuse the same records that are also used for demonstrating json-java:
record Data(int id, String name, Nested someNestedObject){}
record Nested(String hello){}
record Data(int id, String name, Nested someNestedObject){}
record Nested(String hello){}
To use jackson, we need to construct an ObjectMapper which can be used to convert JSON Strings to Java objects:
ObjectMapper objectMapper = new ObjectMapper();
ObjectMapper objectMapper = new ObjectMapper();
We can then convert a JSON String to a Java object using the readValue method in the ObjectMapper which accepts the JSON String and a Class object for the type we want to deserialize to:
String json = """
{
"id": 1337,
"name": "some name",
"someNestedObject": {
"hello": "world"
}
}
""";

Data data = objectMapper.readValue(json, Data.class);
String json = """
{
"id": 1337,
"name": "some name",
"someNestedObject": {
"hello": "world"
}
}
""";

Data data = objectMapper.readValue(json, Data.class);
12 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/19/2025 in #❓︱qotw-answers
Week 109 — How can one parse JSON text in a Java application?
While the JDK doesn't include a public API for parsing JSON, there are multiple available libraries for that purpose. One example of a library performing JSON parsing is json-java. This library can be added by adding the following dependency to the pom.xml:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20250107</version> <!-- use the latest available version here -->
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20250107</version> <!-- use the latest available version here -->
</dependency>
We can then create a JSONObject from a JSON String and extract information using the corresponding methods:
record Data(int id, String name, Nested someNestedObject){}
record Nested(String hello){}
record Data(int id, String name, Nested someNestedObject){}
record Nested(String hello){}
String json = """
{
"id": 1337,
"name": "some name",
"someNestedObject": {
"hello": "world"
}
}
""";

JSONObject jsonObject = new JSONObject(json);

//we can get field of the JSONObject by calling its methods:
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
//JSONObjects can contain nested JSONObjects
JSONObject nestedJsonObject = jsonObject.getJSONObject("someNestedObject");
String nestedHello = nestedJsonObject.getString("hello");
Nested nested = new Nested(nestedHello);
Data data = new Data(id, name, nested);
String json = """
{
"id": 1337,
"name": "some name",
"someNestedObject": {
"hello": "world"
}
}
""";

JSONObject jsonObject = new JSONObject(json);

//we can get field of the JSONObject by calling its methods:
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
//JSONObjects can contain nested JSONObjects
JSONObject nestedJsonObject = jsonObject.getJSONObject("someNestedObject");
String nestedHello = nestedJsonObject.getString("hello");
Nested nested = new Nested(nestedHello);
Data data = new Data(id, name, nested);
12 replies
JCHJava Community | Help. Code. Learn.
Created by JavaBot on 1/12/2025 in #❓︱qotw-answers
Week 108 — What is a `try`-with-resources statement and what is it useful for?
Some other items of note about try-with-resources: - Any class that implements java.lang.AutoCloseable can be used inside the try() block - Multiple resources can be instantiated inside try(), separated with a semicolon, e.g. try (InputStream is = ...; OutputStream os = ...) - It is valid to have a try-with-resources statement without any catch or finally blocks, as long as the method propagates any potential exceptions via the throws clause, and no additional cleanup is needed beyond the managed resources - The resources will have been closed before any exception handler or finally block is run - If the try block generates an exception, then any exceptions generated when auto-closing the resource will be suppressed, and the exception from the try block will be thrown. The suppressed exceptions can be retrieved with the Throwable::getSuppressed method.
8 replies