Checking null in Java

Author: Eugene Taylor
Date Of Creation: 9 August 2021
Update Date: 22 June 2024
Anonim
How To Check If An Object Reference Is Null Or Not? | Java Tips And Tricks
Video: How To Check If An Object Reference Is Null Or Not? | Java Tips And Tricks

Content

Null indicates that a variable does not refer to an object and has no value. You can use a standard "if" statement to check a null value in a piece of code. Null is usually used to indicate or confirm the non-existence of something. In that context, it can be used as a condition for starting or stopping other processes within the code.

To step

Part 1 of 2: Checking null in Java

  1. Use "=" to define a variable. A single "=" is used to declare a variable and assign a value to it. You can use this to set a variable to null.
    • A value of "0" and null are not the same and will behave in different ways.
    • variableName = null;
  2. Use "==" to check the value of a variable. A "==" is used to check if two values ​​on both sides of the counter are equal. If you have set a variable to null with "=", then checking that the variable is null will return "true".
    • variableName == null;
    • You can also use "! =" To check if a value is NOT equal.
  3. Use an "if" statement to create a condition for the null. The expression returns a boolean (true or false). You can use the Boolean value as a condition for what the statement will do next.
    • For example, if the value is null, then print the text "object is null". If "==" does not return the variable to be null, then it will skip the condition or follow a different route.
    • Object object = null; if (object == null) {System.out.print ("object is null"); }

Part 2 of 2: Using a null check

  1. Use null as an unknown value. It is common to use null as the default value instead of an assigned value.
    • string () means the value is null until actually used.
  2. Use null as a condition for stopping a process. Returning a null value can be used as a trigger to stop a loop or abort a process. This is more commonly used to throw an error or exception when something went wrong or an unwanted condition is met.
  3. Use null to indicate an uninitiated state. Likewise, null can be used as a flag to indicate that a process has not started, or as a condition to indicate the start of a process.
    • For example, do something while an object is null, or do nothing until an object is NOT null.

      synchronized method () {while (method () == null); method (). nowCanDoStuff (); }

Tips

  • Some find the frequent use of null bad programming within object oriented programming, where values ​​should always point to an object.