Anshul Jindal
Anshul Jindal

Reputation: 39

Output when we check any Set!=null

Consider the following piece of code

Set<String> a = new HashSet<String>();
System.out.println(a!= null);

The output is true.

Please tell me what does any Set!= null actually checks as the desired output should have been false P.S. - I know we can use isEmpty(), but i would like to know what effect does null check has

Upvotes: 1

Views: 876

Answers (4)

Meet
Meet

Reputation: 242

A null check for reference is check if any object is assigned to it or not. Here in your case reference a is already refer to HashSet Object in heap memory so it will return false.

Upvotes: 0

Keerthivasan
Keerthivasan

Reputation: 12890

You have actually done the instantiation and reference to a new HashSet Object for variable a

Set<String> a = new HashSet<String>();

so, checking it if it refers to something will return true only since it is not null

System.out.println(a!= null);

You shouldn't have instatiated your variable a if you want to make the test fail (false) by just doing the declaration without initialization

Set<String> a; // implicitly this will not refer any object. so, null
or
Set<String> a = null;

If you do the test,

 System.out.println(a!= null);

the result would be false. Adding to that, isEmpty() method returns true if this set contains no elements. You can make use of it when you want to check if the set is empty or not.

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

Set<String> a = new HashSet<String>(); // here a has initialized 

And now a is an empty HashSet.

Set<String> a; // now a is null since a is not initialize

Consider the following case

static Set<String> set;
public static void main(String[] args) {
    System.out.println(set!=null);
}

Now set is null and will get out put false

So it means set!= null is used to check whether set initialized or not for avoid occur NullPointerException. That is your answer.

Upvotes: 0

Aniket Thakur
Aniket Thakur

Reputation: 68975

Please tell me what does any Set!= null actually checks?

a!= null checks only if the reference a points to Set Object(Or Polymorphic reference) or not.

This expression is usually used for NPE checks and not to check of Collection has elements or not.

Upvotes: 0

Related Questions