-3

I am checking for null before doing a certain operation but I have run into some issues. Following is the code:

if (c != null && c.size() != null) {
    if (c.size() > 0) {
        return (Application) c.toArray()[0];
}

I am getting a 'The operator != is undefined for the argument type(s)int, null' at the point c.size() != null. I understand the return type for the size method is an integer, is that why I am getting this error? Hope someone can advise. Thank you.

Ashish Aggarwal
  • 3,018
  • 2
  • 23
  • 46
John Java
  • 153
  • 1
  • 3
  • 8
  • Doesn't the error tell you all? – devnull Mar 24 '14 at 03:32
  • 2
    `int` is a primitive type, and doesn't have `null` that is why is complaining so that condition is unnecesary. In fact as is not a reference to an object it can't be null. – nachokk Mar 24 '14 at 03:34
  • c.size() returns an int. You cannot compare an int(primitive type) with null. Also, the inner if(c.size()>0) is also redundant as you ahve already done the size check in the previous if statement. – TheLostMind Mar 24 '14 at 03:34
  • learn more about [primitive datatype](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) `.size` will never return `null`, the default value of `int` is `0`. so you should change `null` to `0` – Baby Mar 24 '14 at 03:41

2 Answers2

0

int is a primitive type and is not an Object so is not a reference that can be null. Read more in this previous answer

Then in your code just remove that condition. And also is preferred you use c.isEmpty() rather than c.size()>0

Your code would look like this:

if (c != null && !c.isEmpty()) {
    return (Application) c.toArray()[0];
}
Community
  • 1
  • 1
nachokk
  • 14,363
  • 4
  • 24
  • 53
  • Hi, if c happens to be null, that would mean it's also empty right? – John Java Mar 24 '14 at 07:38
  • @JohnJava Not, if `c` is null means that the reference `c` is not pointing to any object, so if you make `c.isEmpty()` will throw `NullPointerException` – nachokk Mar 24 '14 at 19:44
  • Thanks nachok, what about a scenario like this List list and I do a if if (list != null), there would not be a need for me to also do a list.isEmpty() right? since list in this case is an obj ref variable. – John Java Mar 26 '14 at 02:08
  • @JohnJava No!! `list` is just a reference(like a pointer) that refers to an Object of Type(LIST), if it's not pointing to anywhere then `list` is null, but if it's pointing to a `List` then could be empty or not. – nachokk Mar 26 '14 at 02:15
0

First of all, the result of c.size() is an integer. An int is a primitive, and it cannot be null. Only objects can be null.

Second, c.size() will never return null, so the check

c.size() != null

is unnecessary.

Note: There are wrapper classes for each primitive type. For example

Integer i = 4;
i = null; // valid

That assignment will be valid because i is an instance of the class Integer.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73