Checking Integer Wrapper against NULL as well as primitive value 0
Asked Answered
H

6

6

I have refer to this before posting this Question.
Checking Null Wrappers against primitive values

And I have situation that I want to check Wrapper Integer with null as well 0

if( statusId != null || statusId != 0 ) //statusId is Integer it maybe 0 or null
    // Do Somethimg here

How can I overcome this situation ?

Horizontal answered 24/7, 2017 at 11:2 Comment(4)
Is there a question here?Inroad
what do you actually want? if it was about something to do when it is not null or 0 you have already done that.Ishii
@DhaRmvEErsiNgh the problem with above code is that it should throw a NPE if statusId is nullAvarice
@CarlosHeuberger yes it was.Horizontal
M
8

Replace or by and :

if( statusId != null && statusId != 0 ) 

It will work because only if statusId is not null :

statusId != null

you will try to unbox statusId to int:

statusId != 0 

And in the case of statusId is null, the short-circuiting && operator will prevent to throw a NullPointerException as statusId != 0 will not be evaluated.

Metallography answered 24/7, 2017 at 11:4 Comment(9)
More exactly, this will work because of the short-circuiting behaviour of &&, the right hand operand (expression) is only evaluated if the left hand operand (expression) yields true. I don't see why people downvote your answer, as it is the most 'natural' way to express the check?Catabolism
@Catabolism I edited to be more complete. Thank you. Downvotes are very often relevant but not always.Metallography
@davidxxx, this was so simple How can i forget about && operator, thanksHorizontal
@shantaram_ You are very welcome. We should know this page by heart ;) docs.oracle.com/javase/tutorial/java/nutsandbolts/…Metallography
@Metallography I was just forget about using && since longHorizontal
I’d be careful about statusId != 0. I’m pretty sure that is not an unboxing operation, but rather equivalent to statusId != Integer.valueOf(0), which only works because Integer values in the range -128 – 127 are always reference comparable. The code is safe, but might encourage unknowing programmers to rely on it for values outside that range, for which it would not be safe.Tacky
@Tacky An Integer and a primitive int are compared with a != operator. Why do you think that it would not result to an unboxing operation ? Anyway, I have tested and it works with value out of the -128 _ 127 range and jvm invokes intValue to evaluate statusId as it generally does when it unboxes Number instances.Metallography
After reading the JLS carefully, I’m convinced you are right: Integer != int causes unboxing followed by numeric comparison. != is interpreted as a reference equality test only if no other type of comparison is possible. Though the visual ambiguity would be reason enough for me to opt for something more explicit like statusId.intValue() != 0.Tacky
@Tacky I get your feeling. It may really be error prone. For my own mind tranquility, I would do the same thing as you in my own code. I answered this morning to a question and it is right that instinctively I didn't provide this way in first intention Integer i = ... if (a==1){... while it works.Metallography
D
2

If you want to get rid of null check then you can use equals, e.g.:

Integer i = null;
if(Integer.valueOf(0).equals(i)){
    System.out.println("zero");
}else{
    System.out.println("not zero");
}
Deandreadeane answered 24/7, 2017 at 11:5 Comment(3)
Should not use new Integer(0) as it create a new object... Use Integer.valueOf(0) instead.Hyracoid
@UsagiMiyamoto thanks for the input, updated the answer.Deandreadeane
@DarshanMehta, here I don't have separate situation for null OR 0, I have same situation for null AND 0 to be executed.Horizontal
D
1

The problem is that you're letting the null through to the second check, and getting a null pointer.

Equivalent working logic:

if (!(statusId == null || statusId == 0)) {
}
Duque answered 24/7, 2017 at 11:9 Comment(4)
the ! operator will be applied to the whole boolean expression statusId == null || statusId == 0. So, if (!(statusId == null || statusId == 0)) { will be true for statusId with a 0 value. Suppose statusId has the 0 Integer value, it means that (statusId == null || statusId == 0) will be evaluated to false and the reverse of this evaluation (!false) is true.Metallography
My try was to avoid NullPointerException and it is doing that. thank to you tooHorizontal
@Metallography thanks. you made me realise why this was hurting. I was trying to reproduce the actual boolean logic, and failing. But now realise the question is flawed. Your answer is what the OP actually meant. I've posted another pedantic answer which answers what the OP actually requested :)Duque
@Mr Spoon You are welcome. Indeed, the question is not explicit about the need. I have read it multiple times to guess with high probability the OP meaning. You should have edited your first answer. With a horizontal line separator for example. It would make readable your thinkings.Metallography
C
0

There are plenty of good 'classic' Java answers in this thread already, so for the sake of it... here's a Java 8 one: use OptionalInt.

Assuming statusId is an OptionalInt, you would write:

if(statusId.isPresent() && statusId.getAsInt() != 0)

Or slightly more cryptically, you could do this:

if(statusId.orElse(0) != 0)

In this scenario, statusId is never set to null; instead it is set to either a OptionalInt.of(<some int>), OptionalInt.ofNullable(<some Integer>) or OptionalInt.empty().

The point of this answer is that as of Java 8, the standard library offers convenient Optional and related classes for primitives to write null-safe Java code. You might want to check them out. Optional is especially handy, because of its filter and map methods.

Catabolism answered 24/7, 2017 at 11:21 Comment(1)
but I've not yet used Java 8Horizontal
D
0

Just realised why this question hurt so much. It's actually about a typo (if so, @davidxxx's answer is correct). It's not about logical equivalence.

But, for what it's worth. The question specifically asks for:

if( statusId != null || statusId != 0 )

i.e. "If it isn't null" it gets in. Or "if it isn't zero", it gets in.

So, really, the solution is:

if (true)
Duque answered 24/7, 2017 at 11:47 Comment(0)
B
0

I don't know your exact context, but you can consider null-safe methods from Apache Commons Lang, e.g.

if (ObjectUtils.defaultIfNull(statusId, 0) != 0)
  // Do Somethimg here
Binette answered 24/7, 2017 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.