Checking Null in Java (with Pictures)

Table of contents:

Checking Null in Java (with Pictures)
Checking Null in Java (with Pictures)
Anonim

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. Within that context, it can be used as a condition for starting or stopping other processes within the code.

Steps

Part 1 of 2: Checking null in Java

Check Null in Java Step 1

Step 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;

Check Null in Java Step 2

Step 2. Use '==' to check the value of a variable

A '==' is used to check if two values ​​on either side of the counter are equal. If you set a variable to null with '=', it will check if the variable is equal to null and return 'true'.

  • variableName == null;

  • You can also use '!=' to check if a value is NOT equal.
Check Null in Java Step 3

Step 3. Use an 'if' statement to create a condition for the null

The result of the expression is a boolean (true or false). You can use the boolean 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 as null, then it will skip the condition or take another route.
  • Object object = null; if (object == null) { System.out.print('object is null'); }

Part 2 of 2: Using a null check

Check Null in Java Step 4

Step 1. Use null as unknown value

It is common to use null as the default value instead of an assigned value.

  • string()

    means the value is null until it is actually used.
Check Null in Java Step 5

Step 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 has gone wrong or an unwanted condition has been met.

Check Null in Java Step 6

Step 3. Use null to indicate an uninitiated state

Similarly, 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(); }

Popular by topic