空指针异常 是一个运行时异常。在里面 JAVA ,可以为对象引用指定一个特殊的空值。当程序试图使用具有空值的对象引用时,会引发NullPointerException。 这些可以是:
- 从空对象调用方法。
- 访问或修改空对象的字段。
- 获取null的长度,就像它是一个数组一样。
- 访问或修改空对象的插槽,就像它是一个数组一样。
- 抛出null,就好像它是一个可丢弃的值。
- 当您尝试通过空对象进行同步时。
为什么我们需要空值? Null是Java中使用的一个特殊值。它主要用来表示没有给参考变量赋值。null的一个应用是实现链表和树等数据结构。其他应用程序包括空对象模式(参见 这 详细信息)和 单例模式 .Singleton模式确保只创建一个类的实例,并且旨在提供对对象的全局访问点。 最多创建一个类实例的一种示例方法是将其所有构造函数声明为private,然后创建一个公共方法,返回该类的唯一实例:
JAVA
// To use randomUUID function. import java.util.UUID; import java.io.*; class Singleton { // Initializing values of single and ID to null. private static Singleton single = null ; private String ID = null ; private Singleton() { /* Make it private, in order to prevent the creation of new instances of the Singleton class. */ // Create a random ID ID = UUID.randomUUID().toString(); } public static Singleton getInstance() { if (single == null ) single = new Singleton(); return single; } public String getID() { return this .ID; } } // Driver Code public class TestSingleton { public static void main(String[] args) { Singleton s = Singleton.getInstance(); System.out.println(s.getID()); } } |
输出:
10099197-8c2d-4638-9371-e88c820a9af2
在上面的示例中,是singleton类的静态实例。在Singleton getInstance方法中,该实例最多初始化一次。 如何避免NullPointerException? 为了避免NullPointerException,我们必须确保所有对象在使用之前都已正确初始化。当我们声明一个引用变量时,我们必须在从对象中请求一个方法或一个字段之前验证对象是否为null。 以下是克服该问题的解决方案的常见问题。
案例1:字符串与文本的比较
一个非常常见的案例问题涉及字符串变量和文本之间的比较。文本可以是字符串或枚举的元素。而不是从空对象调用方法,而是考虑从文本中调用它。
JAVA
// 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"); } } } |
输出:
NullPointerException Caught
我们可以通过对文本而不是对象调用equals来避免NullPointerException。
JAVA
// A Java program to demonstrate that we can avoid // NullPointerException import java.io.*; class GFG { public static void main (String[] args) { // Initializing 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"); } } } |
输出:
Not Same
案例2:检查方法的参数
在执行新方法的主体之前,我们应该首先检查它的参数是否为空值,并且只有在正确检查参数后,才能继续执行该方法。否则,它将抛出一个 非法数据异常 并通知调用方法传递的参数有问题。
JAVA
// 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(); } } |
输出:
013IllegalArgumentException caught
案例3:三元运算符的使用
三元运算符可用于避免NullPointerException。首先,对布尔表达式求值。如果表达式是 符合事实的 然后返回值1,否则返回值2。我们可以使用三元运算符来处理空指针:
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 String variable with null value String str = null ; String message = (str == null ) ? "" : str.substring( 0 , 5 ); System.out.println(message); // Initializing String variable with null value str = "Geeksforgeeks"; message = (str == null ) ? "" : str.substring( 0 , 5 ); System.out.println(message); } } |
输出:
Geeks
如果str的引用为空,则消息变量将为空 无效的 就像案例1一样。否则,如果str指向 实际数据 ,消息将检索其前6个字符,如案例2所示。 相关文章- 关于Java中Null的有趣事实 本文由 尼希尔·梅赫瓦尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。