-1

I want to get to know what is the difference between null and isEmpty(). Are those 2 are same or different.

3 Answers3

0

Of course, null and isEmpty() is different.

This is a simple explanation of the difference:

Let's take an example of a String.

Null means that your object (String) is not instantiated yet. It's still pointing to nothing. While isEmpty() is a method to check if a String contains no character.

You can try to make 2 different String objects, where one String defines as a null, while the other one is empty, as below.

String nullString = null;
String emptyString = "";

try {
    System.out.println(nullString); // will produce NullPointerException
    nullString.isEmpty(); // will produce NullPointerException
} catch (NullPointerException e) {
    System.out.println(emptyString); // OUTPUT:  (empty)
    emptyString.isEmpty(); // OUTPUT: true
}

I hope it's clear. -CMIIW-

0

Supposing we have a string variable "s" whose value is null,

s == null and s.isEmpty()

will give you two different responses ie.,

s == null

will give the output "true"

And

s.isEmpty()

will give you the output "NullPointerException"

Alternatively, if the string s="" then,

s == null will give you the output "false" and s.isEmpty() will give you the output "true"

Any other string value for the variable "s" like s="java" would result in both s == null and s.isEmpty() resulting in the output "false"

Alen S Thomas
  • 923
  • 7
  • 10
0

You can think about it like this:

isEmpty() - returns boolean (true/false) in accordance of the length of something.

null - null is nothing, it is not an instance of anything and it won't return true/false if something is empty.

For more info, you can check this thread.

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53