Your code makes use of two different additive operators. The first three lines use string concatenation, whereas the last one uses numeric addition.

String concatenation is well-defined to turn null into "null":

  • If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

Hence there is no NPE.

Adding two Integer objects together requires them to be unboxed. This results in the null reference being dereferenced, which leads to the NPE:

  • If r is null, unboxing conversion throws a NullPointerException
Answer from NPE on Stack Overflow
🌐
Java67
java67.com › 2015 › 10 › java-how-to-convert-from-integer-to-String-in-Java.html
3 ways to Convert Integer to String in Java [Example] | Java67
This is the best and straightforward way to convert an Integer to a String object in Java. It doesn't require any auto-unboxing etc, but it will throw NullPointerException if Integer is null as shown below:
Discussions

NullPointerException possibility in Integer.toString(arg) method in java - Stack Overflow
Integer#toString does not take any args, and only passes in the field value. value can never be null because you cannot pass a null int primitive and a null String will simply throw a NumberFormatException here More on stackoverflow.com
🌐 stackoverflow.com
java - Why Integer doesn't solve null String - Stack Overflow
If you have ever spent time hunting ... due to a string value longer than the memory you supplied for it (which then overwrote some program code or other data) you will have a very good appreciation of how bad it is to not fail when something has gone wrong. Since the time of Java 1.0, interaction with databases in java has become extremely common so you might be right to suggest that there should be a method to handle this. Integer is a final ... More on stackoverflow.com
🌐 stackoverflow.com
February 27, 2013
java - Converting a String to int. Set the int to 0 if String is null - Stack Overflow
I have a function which saves Android data in sqlite but I have to convert the String data to an Integer. Whenever the String is null i would like to save as 0 The following is my code which fails More on stackoverflow.com
🌐 stackoverflow.com
java - Convert null object to String - Stack Overflow
I have written an android program to load values to table-row from web service. But value comes null so I need to convert it into a string. Can someone tell me the method to do it? try{ ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
javathinking
javathinking.com › blog › convert-int-to-string-java-null
Converting `int` to `String` in Java: Handling `null` — javathinking.com
When serializing data, such as converting objects to JSON or XML, integer values need to be converted to String to be included in the serialized output. If the integer values are stored as Integer objects, null values need to be handled to ensure the serialized data is valid.
Top answer
1 of 4
11

null is not a valid representation of integer number. Integer.parseInt() requires that the string be parsed is a vaild representation of integer number.

Integer.parseInt()

  public static int parseInt(String s, int radix)
440                 throws NumberFormatException
441     {
442         if (s == null) {
443             throw new NumberFormatException("null");
444         }

Integer.valueOf(str)] // which inviokes Integer.parseInt(Str) to return an Integer instance.

  public static Integer valueOf(String s) throws NumberFormatException
569     {
570         return new Integer(parseInt(s, 10));
571     }
2 of 4
9

The folks at Sun who implemented Integer (a long time ago :) ) probably were not thinking of databases when they wrote that method. Except when dealing with database data, or rare cases where you are trying to explicitly represent "unknown" with null, null is usually a sign of something gone terribly wrong. In general, it's a good idea to raise an exception as soon as there is a problem. (a Fail fast design)

If you have ever spent time hunting down a segmentation fault in C that is due to a string value longer than the memory you supplied for it (which then overwrote some program code or other data) you will have a very good appreciation of how bad it is to not fail when something has gone wrong.

Since the time of Java 1.0, interaction with databases in java has become extremely common so you might be right to suggest that there should be a method to handle this. Integer is a final class so if you build your own Integer like class you will loose autoboxing, so this probably does require a change to the language by oracle.

Basically, what you observed is the way it is for now, and someone will have to pay you to code around it :)

🌐
iO Flood
ioflood.com › blog › int-to-string-java
Int to String Java Conversion: Methods and Examples
February 26, 2024 - String str = "123abc"; int num ... ‘NumberFormatException’. When converting an integer to a string, a null value can result in a NullPointerException....
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › java string › integer.tostring() vs string.valueof() in java
Integer.toString() vs String.valueOf() in Java | Baeldung
April 7, 2025 - Please note, primitive int passed to String.valueOf(int i) can never be null but since there is another method String.valueOf(Object obj), we can get confused between the two overloaded methods. Let’s understand the last point with the following example: @Test(expected = NullPointerException.class) public void whenNullIntegerObjectIsPassed_thenShouldThrowException() { Integer i = null; System.out.println(String.valueOf(i)); System.out.println(i.toString()); }
🌐
Bytes
bytes.com › home › forum › topic › java
convert null into to null string - Post.Byes
July 17, 2005 - > > String x; > x = Integer.toStrin g(columns.getIn t("Integercolum nname")); > > if x is null it will be converted to '0'. I want it converted to > null.[/color] ... Re: convert null into to null string It looks like all your can do is test for null by using the getObject("colu mnName") method.
Top answer
1 of 12
24

Simply use the built-in method JSONObject#getInt(String), it will automatically convert the value to an int by calling behind the scene Integer.parseInt(String) if it is a String or by calling Number#intValue() if it is a Number. To avoid an exception when your key is not available, simply check first if your JSONObject instance has your key using JSONObject#has(String), this is enough to be safe because a key cannot have a null value, either it exists with a non null value or it doesn't exist.

JSONObject jObj = jsonarray.getJSONObject(i);
int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
2 of 12
16

Instead of writing your own function use the inbuild construction of try-catch. Your problem is, that jsonarray or jsonarray.getJSONObject(i) or the value itself is a null and you call a method on null reference. Try the following:

int block_id = 0;        //this set's the block_id to 0 as a default.
try {
    block_id =  Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id"));    //this will set block_id to the String value, but if it's not convertable, will leave it 0.
} catch (Exception e) {};

In Java Exceptions are used for marking unexpected situations. For example parsing non-numeric String to a number (NumberFormatException) or calling a method on a null reference (NullPointerException). You can catch them in many ways.

try{
    //some code
} catch (NumberFormatException e1) {
    e.printStackTrace()     //very important - handles the Exception but prints the information!
} catch (NullPointerException e2) {
    e.printStackTrace();
}

or using the fact, that they all extend Exception:

try {
    //somecode
} catch (Exception e) {
    e.printStackTrace;
};

or since Java 7:

try {
    //somecode
} catch (NullPointerException | NumberFormatException e) {
    e.printStackTrace;
};

Note

As I believe, that you'll read the answer carefully, please have in mind, that on StackOverflow we require the Minimal, Complete, and Verifiable example which include the StackTrace of your exception. In your case it probably starts with the following:

Exception in thread "main" java.lang.NullPointerException

Then, debugging is much easier. Without it, it's just guessing.

Edit: According to the accepted answer

The accepted answer is good and will work as long, as the value stored with key: block_id will be numeric. In case it's not numeric, your application will crash.

Instead of:

JSONObject jObj = jsonarray.getJSONObject(i);
int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;

One should use:

int block_id;
try{
    JSONObject jObj = jsonarray.getJSONObject(i);
    block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
} catch (JSONException | NullPointerException e) {
    e.printStackTrace();
}
🌐
Initial Commit
initialcommit.com › blog › int-to-string-java
Convert Int to String Java - Initial Commit
April 22, 2021 - Using the String.valueOf() method, developers can get the string value of various numeric primitive types and objects. Primitive types include int, float, double, and long. Object types such as Integer, Float, Double, and Long are also supported.
🌐
FavTutor
favtutor.com › blogs › int-to-string-java
Convert Int to String in Java (5 Ways) | FavTutor
July 19, 2026 - Integer.toString() - the direct method for converting an int, with an optional radix for other bases. String.valueOf() - works for every primitive type and handles null wrapper references without an exception.
🌐
Blogger
javarevisited.blogspot.com › 2011 › 08 › convert-string-to-integer-to-string.html
How to Convert String to Integer to String in Java with Example
The default value for int is zero while for Integer it is null. So, if you are looking to convert a String to an int in Java, you need to use the parseInt() method as described in this article.
🌐
CodeGym
codegym.cc › java blog › strings in java › how to convert int to string in java
Convert int to String in Java
December 18, 2024 - Just add to int or Integer an empty string "" and you’ll get your int as a String. It happens because adding int and String gives you a new String. That means if you have int x = 5, just define x + "" and you’ll get your new String.
🌐
Coderanch
coderanch.com › t › 569228 › java › Null-toString
Null and toString() (Java in General forum at Coderanch)
March 3, 2012 - toString() is only called implicitly if the object passed isn't null.