Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the null pointer exception of Java automatic unpacking

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to solve the Java automatic unpacking null pointer exception", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to solve the Java automatic unpacking null pointer exception" bar!

Problem recurrence

Let's take a simple example to reproduce the scenario in which the exception occurs.

Public class BoxTest {public static void main (String [] args) {Map result = httpRequest (); long userId = (Long) result.get ("userId");} / / simulate a HTTP request private static Map httpRequest () {Map map = new HashMap (); map.put ("userId", null); return map;}}

The basic scenario is to request an interface to fetch a value from the interface, which is of type Long. After getting the value from Map, a strong turn of type Long is performed. When the userId returned by the API is null, turning this block strongly throws a null pointer exception:

Exception in thread "main" java.lang.NullPointerException at com.choupangxia.box.BoxTest.main (BoxTest.java:15)

The above scenario has the same exception effect as the following code:

Public class BoxTest {public static long getValue (long value) {return value;} public static void main (String [] args) {Long value = null; getValue (value);}}

The above code is also an exception caused by unboxing the Long type, but one is in the code and the other is in the parameter. In order to simplify the analysis, let's take the second example to explain.

Cause analysis

At first, you may wonder, the code that throws an exception does not have a method call to an object, so how can there be a null pointer?

What is mainly involved in this is an automatic unpacking operation. Is it caused by unpacking? Let's take a look at the bytecode.

Check the corresponding bytecode through javap-c:

Public class com.choupangxia.box.BoxTest {public com.choupangxia.box.BoxTest (); Code: 0: aload_0 1: invokespecial # 1 / / Method java/lang/Object. "": () V 4: return public static long getValue (long); Code: 0: lload_0 1: lreturn public static void main (java.lang.String []) Code: 0: aconst_null 1: astore_1 2: aload_1 3: invokevirtual # 2 / / Method java/lang/Long.longValue: () J 6: invokestatic # 3 / / Method getValue: (J) J 9: pop2 10: return}

Where the getValue method call corresponds to the operations numbered 3 and 6 in the main method. Number 3 is the command invokevirtual is the method instruction. The corresponding value.longValue,value corresponds to the declared Long type.

In other words, the compiler splits the getValue (value) into two steps. The first step is to unbox it through the longValue method of value, and then pass the result to the method. Equivalent to:

Long primitive = value.longValue (); test (promitive)

Compared to the original code, if value is null, NullPointerException is thrown when the longValue method is called.

So, in essence, the so-called automatic unpacking and packing are just grammatical sweets provided by Java.

Confirm again

Here is an example of int type to verify how the syntax of automatic unpacking and automatic boxing works at the same time:

Public class IntBoxTest {public static void main (String [] args) {Integer index = 11; int primitive = index;}}

Also look at the bytecode of the code above:

Public class com.choupangxia.box.IntBoxTest {public com.choupangxia.box.IntBoxTest (); Code: 0: aload_0 1: invokespecial # 1 / / Method java/lang/Object. "": () V 4: return public static void main (java.lang.String []) Code: 0: bipush 11 2: invokestatic # 2 / / Method java/lang/Integer.valueOf: (I) Ljava/lang/Integer; 5: astore_1 6: aload_1 7: invokevirtual # 3 / / Method java/lang/Integer.intValue: () I 10: istore_2 11: return}

You can see that the main method section, numbered 2, boxed the original type int into Integer, called the method Integer.valueOf; and unboxed the numbered 7 to convert the Integer type to the int type, and called the method Integer.intValue.

The essence of automatic unpacking

From the above analysis, we can see that the so-called unboxing and boxing operations are just a syntactic sugar function. When compiling an operation, the compiler essentially calls different methods of the corresponding wrapper class to handle it.

The valueOf method of the wrapper class is usually called when boxing, and the xxxValue () method of the wrapper class is usually called when unpacking, where xxx is similar to boolean/long/int, and so on.

The operations of automatic unpacking and packing mainly occur in assignment, comparison, arithmetic operation, method invocation and so on. At this point, we need the main null pointer problem.

Interview questions

Look at an interview question: how to perform the following when foo1 and foo2 are called? And make a brief analysis.

Public void foo1 () {if ((Integer) null = = 1) {}} public void foo2 () {if ((Integer) null > 1) {System.out.println ("abc");}}

It is obvious that null pointer exceptions are thrown when both methods are called. With regard to the cause and analysis process of the abnormal short pointer, as mentioned above, you can try to analyze the bytecode.

Look at another interview question: can the following sentences be executed normally?

Integer value1 = (Integer) null; Double value2 = (Double) null; Boolean value3 = (Boolean) null

Answer: it can be executed normally. Null is a special value in Java that can be assigned to or converted to any reference type.

Thank you for your reading, the above is the content of "how to solve Java automatic unpacking null pointer exception". After the study of this article, I believe you have a deeper understanding of how to solve the problem of Java automatic unpacking null pointer exception, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report