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

Example Analysis of exception of Hollow pointer in java

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

Share

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

Editor to share with you an example of java hollow pointer exception analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!

Overview

Null pointer exceptions are often thrown because the object we call is empty.

The first out.println for problem description (request.getParameter ("username"))

If there is no username value in request, an exception will be thrown if the empty object cannot be manipulated at this time.

The second String userName = request.getParameter ("username"); If (userName.equals ("root")) {....}

If you don't have a username value, or if username is null, you cannot compare an object that is null to another.

If ("root" .equals (user Name)) {....}

If the return value is compared to a constant, you can avoid calling the equals method of the null object. No exception is thrown.

The third kind

Suppose you have a student class with the attribute name.

Student a * * string b = a.name

An error will be reported at this time, because an is empty, and the solution is to have a point to an object, Student a = new Student ()

Problem positioning

For the error messages in the log, exceptions are thrown from the inside to the outside in java, so you only need to focus on the first line of error messages. The following errors are all caused by layer-by-layer transfer of this method.

Some Solutions of null pointer exception in Java

Any object in Java can be empty, and there are several ways to avoid such exceptions. For example, our traditional null detection, programming specifications, and the use of various utility classes in java.

(1) one of the most commonly used is to judge the object directly.

For example, if (Object = = null) is used to judge all the objects used, which are our commonly used function parameters, return values, and member variables of class instances, and so on. When we detect a null value, we can throw a more targeted exception type for the exception type, plus our own added message content. We can also use some library functions directly to simplify the code:

Object checkData = Object.requireNoNull (resultMessage, "The resultMessage must not be null")

If we have used the Lombok tool, there is a @ NotNull annotation, which means that the annotated element cannot be empty, it will be custom checked.

(2) the second method is to follow the programming specification, which can reduce the occurrence of null pointer exception.

Strings.isNullOrEmpty (str); CollectionUtils.isEmpty (collection); StringUtils.isEmpty (str); if (object! = null) {object.toString ();)} / / using the toString () method, if object is empty, an exception String.valueOf (object) / / converts Object to a string, regardless of whether it is null or not.

If the return is a collection type. And is empty, do not return a null value, but to return an empty collection, if the return type is an object, we can throw an exception.

Public class Example {private static List numbers = null; public static List getList () {if (numbers = = null) return Collections.emptyList (); else return numbers;}}

Check the parameters of a method, make sure that the parameters are checked for null before executing the method, and when the parameters are checked properly, the method continues to execute. Otherwise, an exception called llegalArgumentException is thrown and notifies the calling method that the parameters passed in are incorrect.

Using the ternary operator, you can avoid NullPointerException as follows:

Boolean expression? Value1:value2

Security methods for the existence of NullPointerException

The first uses the instanceof operator

Even if the reference to the object is available to the null,instanceOf operator. When the reference is null, the instanceof operator returns false and does not throw a NullPointerException, such as:

String str = null;if (str instanceof null) {log.error (.)} how to avoid

Make sure that all objects are initialized before use.

Java null pointer exception: java.lang.NullPointException one. What is a java null pointer exception

We all know that java does not have pointers, and the "java pointer" here refers to a reference to java. We will not discuss whether it is appropriate to call a pointer here, but just analyze the exception itself.

A null pointer is a null reference, and a java null pointer exception means that the reference itself is null but the method is called, and a null pointer exception occurs at this time.

It is understandable that member variables and methods belong to the object (except static), and the corresponding member variables and methods exist in the object, and then these member variables and methods are called through the object.

For a null pointer, it does not point to any object, so there are no so-called member variables and methods. If you use it to call some properties and methods, of course, a null pointer exception will occur.

Public class Test {private int astat1; private int bread2; public static void main (String [] args) {/ / TODO Auto-generated method stub Test T1 = new Test (); Test T2 = null; System.out.println (t 1.a); System.out.println (t 2.a); System.out.println (t 2.c ());} public String c () {return "123" }}

Let's analyze the sample code above. In the Test class, there are two member variables an and b, and a method c ().

Then in the main () method, we create two objects T1 and T2, where T1 points to the Test object instantiated by the constructor, and T2 simply declares and points to null, not to the actual object.

When debugging, the first output statement can be compiled, but when the second output statement is executed, because the null pointer calls a that does not belong to it, the program terminates and reports a null pointer exception.

Similarly, when commenting on the second output statement, the same error occurs when the program executes the third output statement because it calls the c () method that does not belong to it.

two。 How to solve

For every java programmer, it is almost inevitable to encounter null pointer exceptions, especially for inexperienced beginners. And because it is difficult to debug and find other exceptions, it often takes a lot of effort to solve it.

First of all, let's meet the null in java.

Null is a very important concept in Java. Null is designed to represent something missing, such as a missing user, resource, or something else. However, a year later, the troublesome null pointer exception caused a lot of harassment to Java programmers.

Null is a keyword in java, so it cannot be written as NULL,Null, it can only be null.

Null is the default value for all reference types, and if you don't have a reference pointing to an actual object, its default value is null. Null is essentially a value, just as the default value of int is 0 and the default value of Boolean is false. Now, we usually use integrated development environments such as eclipse for development, and we usually initialize variables when defining them (which is also a good habit of writing code). If not, the system will prompt you.

The reasons for null pointer exceptions are as follows:

1 string variable not initialized

2 objects of interface type are not initialized with specific classes, such as:

List it; will report an error.

List it = new ArrayList (); it won't be wrong.

3 when the value of an object is empty, you do not judge it to be empty. You can try to add a line of code to the following code:

If (rbaked null & & rbaked = "")

Change it to:

If (rb==null)

If (rbads) or if (") .equals (rb))

The solution to a null pointer:

Focus on the line where the error occurred, and diagnose the specific error through the two main causes of null pointer exception. At the same time, in order to avoid the occurrence of null pointers, it is best to put the "null" or null value before the set value when making a judgment process.

A brief analysis of common null pointer exceptions:

(1) null pointer error

Of the eight basic data types in Java, the value of a variable can have its default value. Without its normal assignment, the java virtual machine cannot be compiled correctly, so using the basic Java data type generally will not cause a null pointer exception. In actual development, most null pointer exceptions are mainly related to the operation of objects.

The following lists several situations in which null pointer exceptions may occur and the corresponding solutions:

Code snippet 1:

Out.println (request.getParameter ("username"))

Analysis: the function of code snippet 1 is very simple, which is to output the value of "username" entered by the user.

Explanation: it seems that there are no grammatical errors in the above sentence, and there are no problems in most cases. However, if a user does not provide a value for the form field "username" when entering data, or if he or she bypasses the form and enters it directly, the value of this request.getParameter ("username") is empty (note that it is not an empty string, it is an empty object null. The println method of the out object cannot operate directly on the empty object, so the JSP page where snippet 1 is located will throw a "Java.lang.NullPointerException" exception. And even when the object may be empty, some methods of the Java.lang.Object or Object object itself, such as toString (), equal (Object obj), and so on, are called.

Code snippet 2:

String userName = request.getParameter ("username"); If (userName.equals ("root")) {....}

Analysis: the function of snippet 2 is to detect the user name provided by the user, and to perform some special actions if the user name is "root".

Description: in code snippet 2, if a user does not provide the value of the form field "username", the string object userName is null, and one null object cannot be compared directly with another object. Similarly, the JSP page where code snippet 2 is located will empty the pointer error.

A tip: if you want to compare the return value of a method with a constant, and put the constant first, you can avoid calling the equals method of the null object. For example:

If ("root" .equals (userName)) {....}

Even if the userName object returns the null object, there is no null pointer exception here, and you can run as usual.

Code snippet 3:

String userName = session.getAttribute ("session.username") .toString

Analysis: the function of snippet 3 is to take out the value of session.username in session and assign that value to the string object userName.

Note: in general, there will be no problem if the user has already had a session; however, if the application server is restarted and the user has not logged in again, (it is also possible that the user closes the browser, but still opens the original page. At this point, the value of the session is invalidated, causing the value of the session.username in the session to be empty. A direct toString () operation on an object that is null causes the system to throw a null pointer exception.

Code snippet 4:

Public static void main (String args []) {Person pendant null; p.setName ("Zhang San"); System.out.println (p.getName ());}

Parse: declare a Person object and print out the Name name in that object.

Note: at this time, your p will have a null pointer exception, because you only declared that the object of this Person type did not create an object, so there is no address reference in its heap, so be sure to create an object when you want to use the object to disable the method.

The above is all the contents of the article "example Analysis of java Hollow pointer exception". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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