What is null pointer exception in java

Reasons and Solutions of Null Pointer Exception in Java

In this article, we will learn about null pointer exceptions in Java and look into some of the common errors that result in them. We will also see how we can prevent them from happening.

What is a Null Pointer Exception in Java?

The Null Pointer Exception is a runtime exception in Java. It is also called the unchecked exception as it escapes during compile-time but is thrown during runtime. A program throws this exception when it attempts to dereference an object that has a null reference.

Simply put, the null pointer exception is raised when we try to call a method or variable that has a null reference.

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "example.word" is null at example.main(example.java:4)

From the above code, we see that when we call the String variable word to change to the upper case, we get a null pointer exception as word has a null reference.

Читайте также:  Java regex and unicode

Reasons for Null Pointer Exceptions

Some of the common mistakes that we may commit are:

// Invoking methods of a null object class example1 < void add()< int x = 4, y = 6; System.out.println(x+y); >public static void main(String args[]) < example1 obj = null; obj.add(); >>
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "example1.add()" because "" is null at example1.main(example1.java:9)
// Using or altering fields of a null object class example2 < int x = 10; public static void main(String args[])< example2 obj = null; int i = obj.x; // Accessing the field of a null object obj.x = 20; // Modifying the field of a null object >>
Exception in thread "main" java.lang.NullPointerException: Cannot read field "x" because "" is null at example2.main(example2.java:6)
// Calling length of a null array import java.util.*; class example3 < public static void main(String args[])< Scanner sc = new Scanner(System.in); int arr[] = null; System.out.println(arr.length); >>
Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "" is null at example3.main(example3.java:7)
// Using or altering the items of a null array class example4 < public static void main(String args[])< int arr[] = null; arr[2]=arr[3]+2; >>
Exception in thread "main" java.lang.NullPointerException: Cannot load from int array because "" is null at example4.main(example4.java:7)
// Throwing null value instead of a valid object class example5 < public static void main(String args[])< throw null; >>
Exception in thread "main" java.lang.NullPointerException: Cannot throw exception because "null" is null at example5.main(example5.java:4)

Avoiding Null Pointer Exceptions

Let’s discuss some situations where we can carry out some steps to prevent null pointer exceptions. Of course, we must take care of all the above-mentioned reasons.

    Inspect the arguments passed to a method
    Sometimes, we may pass variables with null values to a method that results in a null pointer exception during runtime. It is always a better practice to check the arguments before proceeding to use them in the method.
    Let’s look at an example,

class example_1< static int add(String s)< try< System.out.println(s.concat("HI")); >catch(NullPointerException e) < System.out.println("null value found"); >return 6; > public static void main(String args[]) < String word = null; System.out.println(add(word)); >>
Using valueOf(): null Using toString(): Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toString()" because "" is null at example_4.main(example_4.java:6)

I hope this article has helped you understand the null pointer exceptions in Java.

Читайте также:  Html link to content on page

Источник

Null Pointer Exception In Java – Explained | How To Avoid and Fix

null pointer exception in java

Exceptions are helpful in the smooth running of code and allow the programmers the errors that need to be solved. Today, we will focus on the Null pointer exception in Java.

NullPointerException in java occurs when a java program attempts to use an object reference that has the null value. In the Java world, you can assign a null value to an object reference.

What is Null Pointer Exception in Java?

The Null pointer exception in Java i.e java.lang.NullPointerException is a kind of Runtime exception that occurs when you try to access a variable that doesn’t point to any object and refers to nothing or null. The Null Pointer Exception in Java doesn’t necessarily be caught and handled in the application code.

null pointer exception

Source: ATechDaily

What Causes NullPointer Exception?

The null pointer exception in a java program occurs when you try to access or modify an uninitialized object. This is a special situation in the application code.

Following are the most common situations for the java null pointer exception occurrence.

  1. When null parameters are passed on to a method.
  2. Trying to access the properties or an index element of a null object.
  3. Calling methods on a null object.
  4. Following incorrect configuration for dependency injection frameworks such as Spring.

NullPointer Exception Example

Here is an example of NullPointerException in java that is thrown when you call a length() method of a null String object.

null pointer exception example

In the above example, the length() method of string is called by the printLength() method without performing a null check before calling the method. As the value of the string passed from the main() method is null, the above code results in a NullPointerException:

How to Fix NullPointer Exception?

To fix Null pointer exception in java programming, you should check the string for empty or null values before it is used any further.

import org.apache.commons.lang3.StringUtils; public class NullPointerExceptionExample < private static void printLength(String str) < if(StringUtils.isNotEmpty(str)) < System.out.println(str.length()); >else < System.out.println("Empty String"); >> public static void main(String [] args) < String myString = null; printLength(myString); >>

In order to fix the java.lang.NullPointException, the printLength() method in the above code is updated with a check that ensures that the string parameter is not empty using the StringUtils.isNotEmpty() method. If the string parameter is empty it prints the message “Empty String” to the console and if the string is not empty the length() method of the string is called.

How to avoid the NullPointer Exception in Java Programming?

To avoid NullPointerException in java programming, always make sure that all the objects are properly initialized before you use them. Before invoking a method on an object, verify that the object is not null while declaring a reference variable.

Given below are some null pointer exception problems with solutions.

1. String Comparison With Literals

The most common null pointer exception problems involve a comparison between a history variable and a literal that may be a string or an element of Enum. Consider invoking the method from the literal rather than invoking it from the null object.

// A Java program to demonstrate that invoking a method on null // causes NullPointerException import java.io.*; class GFG < public static void main (String[] args) < // Initializing String variable with null value String ptr = null; // Checking if ptr.equals null or works fine. try < // This line of code throws NullPointerException, because ptr is null if (ptr.equals("gfg")) System.out.print("Same"); else System.out.print("Not Same"); >catch(NullPointerException e) < System.out.print("NullPointerException Caught"); >> >

Output:
NullPointerException Caught

In this case, NullPointerException can be avoided by calling equals on literal instead of calling object.

// A Java program to demonstrate that we can avoid // NullPointerException import java.io.*; class GFG < public static void main (String[] args) < // Initialing String variable with null value String ptr = null; // Checking if ptr is null using try catch. try < if ("gfg".equals(ptr)) System.out.print("Same"); else System.out.print("Not Same"); >catch(NullPointerException e) < System.out.print("Caught NullPointerException"); >> >

2. Use of Ternary Operator

You can use a ternary operator to avoid a NullPointerException. First of all the Boolean expression is evaluated for the true or false results. If the expression is true then the value true is returned and if it is wrong the value false is returned. Ternary operator can be used to handle null pointer exceptions in java.

// A Java program to demonstrate that we can use // ternary operator to avoid NullPointerException. import java.io.*; class GFG < public static void main (String[] args) < // Initializing message variable with non-null value String str = null; String message = (str == null) ? "" : str; System.out.println(message); // Initializing message variable with non-null value str = "Seagence"; message = (str == null) ? "" : str; System.out.println(message); >>

3. Keeping a Check of the Arguments of a Method

Always ensure the arguments of the new method for non-null before executing the body of the new method and continue with the method execution, only when the arguments are properly checked. Or else, it will return an IllegalArgumentException and notifies the calling method that something isn’t right with arguments passed.

// A Java program to demonstrate that we should // check if parameters are null or not before // using them. import java.io.*; class GFG < public static void main (String[] args) < // String s set an empty string and calling getLength() String s = ""; try < System.out.println(getLength(s)); >catch(IllegalArgumentException e) < System.out.println("IllegalArgumentException caught"); >// String s set to a value and calling getLength() s = "GeeksforGeeks"; try < System.out.println(getLength(s)); >catch(IllegalArgumentException e) < System.out.println("IllegalArgumentException caught"); >// Setting s as null and calling getLength() s = null; try < System.out.println(getLength(s)); >catch(IllegalArgumentException e) < System.out.println("IllegalArgumentException caught"); >> // Function to return length of string s. It throws // IllegalArgumentException if s is null. public static int getLength(String s) < if (s == null) throw new IllegalArgumentException("The argument cannot be null"); return s.length(); >>

Output:
0
13
IllegalArgumentException caught

To avoid Null point Exceptions, you need to take care that all objects are initialized with a legitimate value (that is not null), before using them. As any operation performed on a null reference variable will lead to the NullPointerException, at the time of defining, it must be verified that the reference variable is not null.

Conclusion

Avoiding and fixing null point exceptions is an important task for the developers in Java. Unlike many other programming languages, Java doesn’t provide any methods to check null pointer exceptions.

That’s why developers need additional tools that can help them prevent NullPointerException in java. Seagence is one such tool that automates Java error management, prioritizing the errors, making the process of error fixing easier than ever. Try Seagence free today! Click here to know more.

Источник

Кофе-брейк #98. Новое исключение Nullpointer в Java 17. Что означает в Java?

Java-университет

Кофе-брейк #98. Новое исключение Nullpointer в Java 17. Что означает <T> в Java? - 1

Источник: Dev.to Каждому Java-разработчику стоит знать о существовании в Java 17 нового исключения Nullpointer Exception или NPE. Это одна из таких ситуаций, которую всегда нужно стараться предотвратить. Иногда Nullpointer означает, что необходима отладка кода, чтобы найти небольшую ошибку. NPE — это исключение времени выполнения, которое возникает, когда ваш код хочет использовать объект или ссылку на объект, имеющий нулевое значение. Оно может возникать, если не присвоено значение или объект не имеет ссылки. До последней версии OpenJDK (версия 17) обычное исключение Nullpointer в трассировке стека выглядело примерно так:

 java.lang.NullPointerException: null 

Конечно, это далеко не все, что вам нужно знать о трассировке стека. Как видите, тут не указано, где и почему возникло это исключение. Посмотрите, как с этой проблемой справляется Java 17:

 Exception in thread "main" java.lang.NullPointerException: Cannot assign field "i" because "a" is null at Prog.main(Prog.java:5) 

Что означает в Java?

Кофе-брейк #98. Новое исключение Nullpointer в Java 17. Что означает <T> в Java? - 2

Источник: Dev.to — это обычная буква, обозначающая “Type”, и она относится к концепции Generic в Java. Вы можете использовать для этого и другую букву, но, как можно заметить, буква T более предпочтительна.

Что такое Generic?

Generic — это способ параметризации класса, метода или интерфейса. Давайте посмотрим на пример дженерика:

 package Generics; class House < T doorNumber; public House(T doorNumber) < this.doorNumber = doorNumber; >public void print() < System.out.println("Your house number is: " + this.doorNumber); >> 
  • У нас есть класс под названием House , который может принимать произвольный тип объекта.
  • Далее у нас есть поле с именем doorNumber , которое также может принимать любой тип объекта.
  • В конце мы объявляем параметризованный конструктор и выводим номер двери.
 public class GenericsExample < public static void main(String[] args) < HousemainHouse = new House<>("14a"); mainHouse.print(); > > 

Мы заменим букву “Т” на “String” и введем номер дома в конструктор. Мы можем использовать несколько типов, если, например, нам нужно, чтобы класс принимал более одного объекта. Можно добавить еще одну букву и тем самым сказать: мы хотим, чтобы класс принял другой Generic.

 package Generics; class House < T doorNumber; V streetName; public House(T doorNumber, V streetName) < this.doorNumber = doorNumber; this.streetName = streetName; >public void print() < System.out.println("You live at: " + this.doorNumber + " " + this.streetName); >> public class GenericsExample < public static void main(String[] args) < HousemainHouse = new House<>(14, "Tellson Avenue"); mainHouse.print(); > > 

До сих пор мы видели примеры использования Generic на уровне класса. Но у нас также могут быть общие методы и интерфейсы.

Метод Generic

 package Generics; class House < public void print(T doorNumber) < System.out.println("You live at house number: " + doorNumber); >> public class GenericsExample < public static void main(String[] args) < House mainHouse = new House(); mainHouse.print(14); > > 

Метод принимает любой тип объекта и выводит номер двери, который будет любым типом Object . В этом случае мы хотим, чтобы метод принимал целое число. Результат будет:

Интерфейс Generic

package Generics; interface Property

 package Generics; public class House implements Property  < @Override public void hasBalcony(String balcony) < System.out.println("Is there a balcony in the room? " + balcony); >public static void main(String[] args) < House mainHouse = new House(); mainHouse.hasBalcony("YES"); >> 
  1. Лучшая проверка во время компиляции : если вы используете тип объекта, отличный от того, который вы указали, компилятор сообщит вам об этом.
  2. Возможность повторного использования : вы можете использовать класс, метод или интерфейс несколько раз, потому что вы решаете, какой тип объекта применять в зависимости от того, чего вы пытаетесь достичь.
  3. Он отлично подходит для структур данных и алгоритмов : ArrayList и HashMap — это лишь несколько примеров, где используется Generic.

Источник

Оцените статью