Exception in thread main java.lang.nullpointerexception là gì năm 2024

A NullPointerException in Java is one of the most common errors. It means that you are trying to access a part of something that doesn’t exist.

For example, in the code below we call .length() on myString, which would usually return the length of the string. In this case, the string doesn’t exist (we set it to null), and so this throws a NullPointerException.

public class Main {public static void main(String[] args) { String myString = null; int stringLength = myString.length(); } }

You can fix this by ensuring that your object is not null before calling the method. For example:

public class Main {public static void main(String[] args) { String myString = null; if (myString != null) { int stringLength = myString.length(); } else { System.out.println("myString is null"); } } }

Here we first ensure that myString is not null before calling

public class Main {public static void main(String[] args) { String myString = null; int stringLength = myString.length(); } }

3.

If it is, we print “myString is null” instead.

Of course, in real-world code it’s not normally as simple to identify which variables might be null, as they might be passed in from other methods or classes, or be dependent on user input.

You can use some defensive programming techniques to avoid NullPointerExceptions such as always validating user input, and always checking if objects are null before calling their methods.

Sometimes it is also helpful to think about which variables might be null. If you are checking a user input variable against a constant, it is better to call the method from the constant instead of from the variable.

public class Main {public static void main(String[] args) { String userInput = null; System.out.println(userInput.equals("MY_VERY_SECRET_PASSWORD")); } }

This code throws a NullPointerException, and if we’re not sure ahead of time what

public class Main {public static void main(String[] args) { String myString = null; int stringLength = myString.length(); } }

6 will be, we need to handle the case where it is null. We could add a null check as in the previous example, but a simpler way is to restructure the code as follows.

public class Main {public static void main(String[] args) { String userInput = null; System.out.println("MY_VERY_SECRET_PASSWORD".equals(userInput)); } }

Output:

In this case, we know that “MY_VERY_SECRET_PASSWORD” is not going to be null, as it is hardcoded, but we are not sure about

public class Main {public static void main(String[] args) { String myString = null; int stringLength = myString.length(); } }

6. Because

public class Main {public static void main(String[] args) { String myString = null; int stringLength = myString.length(); } }

8 is the same as

public class Main {public static void main(String[] args) { String myString = null; int stringLength = myString.length(); } }

9, we can simply swap the variables and operate on the one we know exists.

Bởi vì nếu bạn không chú ý đến null, bạn có thể chắc chắn rằng Java sẽ khiến bạn đau khổ khủng khiếp private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

6và bạn sẽ rút ra được bài học nhưng bạn sẽ đi vào một con đường khó khăn hơn. Viết mã chống sự cố là một nghệ thuật và nhóm của bạn, khách hàng cũng như người dùng sẽ đánh giá cao điều đó. Theo kinh nghiệm của tôi, một trong những nguyên nhân chính private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

7là do thiếu kiến ​​thức về null trong Java. Nhiều bạn đã quen với null, những bạn còn lại sẽ có thể tìm hiểu một số điều cũ và mới về từ khóa null. Hãy xem lại hoặc tìm hiểu một số điều quan trọng về null trong Java.

Giá trị rỗng trong Java là gì

Như tôi đã nói, null là một khái niệm rất, rất quan trọng trong Java. Ban đầu nó được phát minh để biểu thị sự vắng mặt của thứ gì đó, chẳng hạn như sự vắng mặt của người dùng, tài nguyên hoặc bất cứ thứ gì, nhưng đã khiến các lập trình viên Java bối rối với rất nhiều private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

8. Trong hướng dẫn này, chúng ta sẽ tìm hiểu những thông tin cơ bản về từ khóa null trong Java và tìm hiểu một số thủ thuật để tránh rắc rối private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

9và giảm thiểu việc kiểm tra null.

  1. Đầu tiên, null là một từ khóa trong Java, giống như

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    0,

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    1hoặc

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    2. Phân biệt chữ hoa chữ thường, bạn không thể viết null dưới dạng Null hoặc NULL, trình biên dịch sẽ không nhận ra nó và sẽ xảy ra lỗi.

    Object obj = NULL; // Not Ok Object obj1 = null //Ok

    Điều này thường gặp phải đối với những lập trình viên đã chuyển từ ngôn ngữ lập trình khác sang, nhưng khi sử dụng các IDE hiện đại, vấn đề trở nên không đáng kể. Ngày nay, các IDE như Eclipse hay NetBeans có thể sửa lỗi này khi bạn gõ, nhưng trong thời đại của Notepad, Vim và Emacs, đây là một vấn đề phổ biến có thể ngốn rất nhiều thời gian quý báu.
  2. Так же, How каждый примитив имеет meaning по умолчанию, например, у

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    3 это 0, у boolean это false, null это meaning по умолчанию любых ссылочных типов, проще говоря, для всех an objectов. Так же, How при создании логической переменной ее meaning по умолчанию равно false, так и любые ссылочные переменные в Java по умолчанию будут равны null. Это истинно для всех типов переменных: переменной-члена or локальной переменной, переменной экземпляра or статической переменной, кроме того, компилятор будет ругаться, если Вы используете локальную переменную не проинициализировав ее.

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    Это истинно How для статических, так и для не статических an objectов, How Вы можете видеть здесь, я сделал

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    4 статической ссылкой, так что я могу использовать ее непосредственно в методе

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    5, который является статическим методом и не позволяет обращаться к не статическим переменным изнутри.
  3. Несмотря на распространенное заблуждение, null это не an object (

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

  4. и ни тип. Это просто специальное meaning, которое может быть назначено любому ссылочному типу, и Вы можете привести null к любому типу, How показано ниже:

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    Как Вы можете видеть, приведение null к любому ссылочному типу пройдет успешно How во время компиляции, так и во время выполнения программы. В отличии от того, что многие из Вас возможно подумали, это не приведет к выбрасыванию

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    7.
  5. null может быть назначен только ссылочному типу, Вы не можете назначить null примитивной переменной вроде

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    3,

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    9,

    int i = null; // type mismatch : cannot convert from null to int short s = null; // type mismatch : cannot convert from null to short byte b = null: // type mismatch : cannot convert from null to byte double d = null; //type mismatch : cannot convert from null to double Integer itr = null; // this is ok int j = itr; // this is also ok, but NullPointerException at runtime

    0 or

    int i = null; // type mismatch : cannot convert from null to int short s = null; // type mismatch : cannot convert from null to short byte b = null: // type mismatch : cannot convert from null to byte double d = null; //type mismatch : cannot convert from null to double Integer itr = null; // this is ok int j = itr; // this is also ok, but NullPointerException at runtime

    1. Компилятор выразит Вам свое недовольство если Вы сделаете How показано ниже:

    int i = null; // type mismatch : cannot convert from null to int short s = null; // type mismatch : cannot convert from null to short byte b = null: // type mismatch : cannot convert from null to byte double d = null; //type mismatch : cannot convert from null to double Integer itr = null; // this is ok int j = itr; // this is also ok, but NullPointerException at runtime

    Как Вы можете видеть, когда мы непосредственно присваиваем null примитиву, то получаем ошибку процесса компиляции, но, если присвоить null an objectу класса-обертки, а затем присвоить этот an object соответствующему примитивному типу, компилятор не отреагирует, но мы будем вознаграждены

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    8 во время выполнения. Это происходит из-за авто упаковки (

    int i = null; // type mismatch : cannot convert from null to int short s = null; // type mismatch : cannot convert from null to short byte b = null: // type mismatch : cannot convert from null to byte double d = null; //type mismatch : cannot convert from null to double Integer itr = null; // this is ok int j = itr; // this is also ok, but NullPointerException at runtime

  6. в Java, и мы еще встретимся с ним в следующем пункте.
  7. Любой класс-обертка со meaningм null будет выбрасывать

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    6 когда Java распакует(

    int i = null; // type mismatch : cannot convert from null to int short s = null; // type mismatch : cannot convert from null to short byte b = null: // type mismatch : cannot convert from null to byte double d = null; //type mismatch : cannot convert from null to double Integer itr = null; // this is ok int j = itr; // this is also ok, but NullPointerException at runtime

  8. его в примитивную переменную. Некоторые программисты делают ошибку допуская, что авто упаковка(

    int i = null; // type mismatch : cannot convert from null to int short s = null; // type mismatch : cannot convert from null to short byte b = null: // type mismatch : cannot convert from null to byte double d = null; //type mismatch : cannot convert from null to double Integer itr = null; // this is ok int j = itr; // this is also ok, but NullPointerException at runtime

  9. позаботится о конвертации null в meaning по умолчанию для соответствующего примитивного типа, например, 0 для

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    3, false для

    int i = null; // type mismatch : cannot convert from null to int short s = null; // type mismatch : cannot convert from null to short byte b = null: // type mismatch : cannot convert from null to byte double d = null; //type mismatch : cannot convert from null to double Integer itr = null; // this is ok int j = itr; // this is also ok, but NullPointerException at runtime

    1 и т.д., но это не верно, в чем можно убедиться ниже:

    Integer iAmNull = null; int i = iAmNull; // Remember - No Compilation Error

    Но, когда Вы запустите данный фрагмент codeа, в консоли Вы увидите

    Exception in thread "main" java.lang.NullPointerException

    Это часто происходит при работе с

    int i = null; // type mismatch : cannot convert from null to int short s = null; // type mismatch : cannot convert from null to short byte b = null: // type mismatch : cannot convert from null to byte double d = null; //type mismatch : cannot convert from null to double Integer itr = null; // this is ok int j = itr; // this is also ok, but NullPointerException at runtime

    9 и

    Integer iAmNull = null; int i = iAmNull; // Remember - No Compilation Error

    0. Выполнение codeа, показанного ниже прервется, How только Вы его запустите.

    ` import java.util.HashMap; import java.util.Map; /
  10. An example of Autoboxing and NullPointerExcpetion
  11. @author WINDOWS 8

    */ public class Test { public static void main(String args[]) throws InterruptedException { Map numberAndCount = new HashMap<>(); int[] numbers = {3, 5, 7,9, 11, 13, 17, 19, 2, 3, 5, 33, 12, 5}; for(int i : numbers){ int count = numberAndCount.get(i); numberAndCount.put(i, count++); // NullPointerException here } } }

    Output: Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:25)

    Mã này trông rất đơn giản và vô hại. Bạn chỉ cần đếm số lần một số xuất hiện trong một mảng, một kỹ thuật cổ điển để tìm các số trùng lặp. Nhà phát triển lấy số lượng đã đếm trước đó, tăng lên một đơn vị và chèn lại vào

    Integer iAmNull = null; int i = iAmNull; // Remember - No Compilation Error

    1. Anh ta có thể nghĩ rằng auto-boxing sẽ đảm nhiệm việc chuyển đổi

    Integer iAmNull = null; int i = iAmNull; // Remember - No Compilation Error

    2thành

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    3, giống như khi phương thức được gọi

    Integer iAmNull = null; int i = iAmNull; // Remember - No Compilation Error

    4, nhưng anh ta quên rằng nếu số đó chưa được đếm thì phương thức

    Integer iAmNull = null; int i = iAmNull; // Remember - No Compilation Error

    5sẽ trả về

    int i = null; // type mismatch : cannot convert from null to int short s = null; // type mismatch : cannot convert from null to short byte b = null: // type mismatch : cannot convert from null to byte double d = null; //type mismatch : cannot convert from null to double Integer itr = null; // this is ok int j = itr; // this is also ok, but NullPointerException at runtime

    9null, chứ không phải 0, vì giá trị mặc định là Số nguyên, đây là null, không phải 0 và tính năng tự động đánh quyền anh sẽ xuất hiện

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    8khi cố gắng chuyển đổi Số nguyên thành một biến

    String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error

    ` 3.
  12. Toán tử

    Integer iAmNull = null; int i = iAmNull; // Remember - No Compilation Error

    9sẽ trả về false nếu bất kỳ biến tham chiếu nào có giá trị null hoặc null được chỉ định làm tham số. Ví dụ:

    Integer iAmNull = null; if(iAmNull instanceof Integer){ System.out.println("iAmNull is instance of Integer"); }else{ System.out.println("iAmNull is NOT an instance of Integer"); }

    Output : iAmNull is NOT an instance of Integer

    Đây là một thuộc tính quan trọng của toán tử

    Integer iAmNull = null; int i = iAmNull; // Remember - No Compilation Error

    9giúp nó hữu ích cho việc thử nghiệm các kiểu ép kiểu.
  13. Bạn biết rằng bạn không thể gọi một phương thức không tĩnh trên biến tham chiếu null, nó sẽ gọi

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    7, nhưng bạn có thể không biết rằng bạn có thể gọi một phương thức tĩnh trên biến tham chiếu null. Bởi vì các phương thức tĩnh sử dụng liên kết tĩnh, chúng không loại bỏ các tệp

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    7. Đây là một ví dụ:

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    0

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    1
  14. Bạn có thể truyền null làm tham số cho một phương thức chấp nhận bất kỳ loại tham chiếu nào, ví dụ:

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    2 có thể được gọi như thế

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    3 Điều này là bình thường theo quan điểm của trình biên dịch, nhưng hành vi tiếp theo hoàn toàn phụ thuộc vào phương thức. Một phương thức an toàn null sẽ không ném

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    7mà chỉ thoát ra một cách duyên dáng. Nếu logic nghiệp vụ cho phép, bạn nên viết các phương thức null-safe.
  15. Bạn có thể so sánh null bằng cách sử dụng toán

    Exception in thread "main" java.lang.NullPointerException

    4tử (bằng) và

    Exception in thread "main" java.lang.NullPointerException

    5(không bằng), nhưng bạn không thể sử dụng nó với các toán tử số học hoặc logic khác như

    Exception in thread "main" java.lang.NullPointerException

    6(nhỏ hơn) hoặc

    Exception in thread "main" java.lang.NullPointerException

    7(lớn hơn). Không giống như SQL, Java

    Exception in thread "main" java.lang.NullPointerException

    8sẽ trả về true như dưới đây:

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    4

    private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

    5

Đây là tất cả về null trong Java. Bằng cách tích lũy một số kinh nghiệm về lập trình Java và sử dụng các thủ thuật đơn giản để tránh private static Object myObj; public static void main(String args[]){ System.out.println("What is value of myObjc : " + myObj); } What is value of myObjc : null

7, bạn có thể làm cho mã của mình an toàn. Bởi vì null có thể được coi là giá trị trống hoặc chưa được khởi tạo, điều này thường gây nhầm lẫn, đó là lý do tại sao việc ghi lại hành vi của một phương thức khi nhập giá trị null là rất quan trọng. Hãy luôn nhớ rằng null là giá trị mặc định của các biến tham chiếu và bạn không thể gọi các phương thức phiên bản hoặc truy cập các biến phiên bản bằng cách sử dụng tham chiếu null trong Java.

Chủ đề