Joke Collection Website - Public benefit messages - How to solve java.lang.nullpointerexception?

How to solve java.lang.nullpointerexception?

Java.lang.NullPointerException is a common exception in Java, which is often translated into null pointer exception in Chinese.

Trigger condition: When an object is empty,? When you try to call an object's method or access or modify an object's properties, you will throw a null pointer exception.

The solution to this exception:?

Try to avoid using empty objects,

Or judge whether it is empty before using it,

Or use try catch to catch the exception and handle it.

Reference code

Error demonstration

Public? Class? Demonstration? {

Public? Static electricity Invalid? main(String[]? args)? {

String? str? =? null

if(str.equals("ABC "))? {? //str is empty. Call the equals method of str. You will report an error.

System.out.println ("The content of the string is ABC");

} something else? {

System.out.println ("The content of the string is not ABC");

}

}

} Solution demonstration 1

Public? Class? Demonstration? {

Public? Static electricity Invalid? main(String[]? args)? {

String? str? =? null

if("ABC "。 equals(str))? {? //Use the non-empty object "ABC" to set its equals method to null.

System.out.println ("The content of the string is ABC");

} something else? {

System.out.println ("The content of the string is not ABC");

}

}

Demonstration 2: Determine whether it is empty before calling methods and accessing properties.

Public? Class? Demonstration? {

Static electricity String? str 1;

Public? Static electricity Invalid? main(String[]? args)? {

if(str 1! =null)? {//Talking? Its length method

system . out . println(str 1 . length());

} something else? {

System. out.println ("str1object is empty");

}

}

} demo 3

Import? Java . util . scanner;

Public? Class? Demonstration? {

Static electricity String? str 1;

Public? Static electricity Invalid? main(String[]? args)? {

Try it? {

system . out . println(str 1 . length());

}catch(NullPointerException? e)? {

System. out.println ("str1is empty ... please specify a value ...");

Scanner? sc? =? New? Scanner (system. in);

str 1? =? sc . nextline();

System. out.println (the length of "str1is"+str1.length ());

}

}

}

//str 1 is empty ... Please specify a value. ..

//ABC

The length of //str 1 is: 3