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
Explicitly Dereferencing You can use null to dereference an object and release its memory, then it will be eligible for garbage collection.
Did you know that, you can explicitly add null values in ArrayLists.
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 returned9 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.
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.
It is possible to check for an object being null
using the ==
operator:
Attempting to access any field or call a method of a variable that's set to null
causes a NullPointerException
to be thrown
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
.
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 :
2. Define a Java class model that represents the JSON :
3. Parse the JSON using ObjectMapper API from Jackson :
4. Run it :
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:
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:
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:
This can also be simplified:
We can also iterate over all entries present in a JsonObject
:
and the output will be:
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
:
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:
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:
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:
After running the code, this should be the output:
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
):
- Maven (pom.xml
):
- 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
We will then reuse the same records that are also used for demonstrating json-java:
To use jackson, we need to construct an
ObjectMapper
which can be used to convert JSON String
s to Java objects:
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:
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:
We can then create a
JSONObject
from a JSON String and extract information using the corresponding methods:
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