183

Can an int be null in Java?

For example:

int data = check(Node root);

if ( data == null ) {
 // do something
} else {
 // do something
}

My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.

I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.

Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
user220755
  • 4,358
  • 16
  • 51
  • 68

15 Answers15

233

int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!

e.g. this:

int a = object.getA(); // getA returns a null Integer

will give you a NullPointerException, despite object not being null!

To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer> or java.util.OptionalInt

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • 2
    There are good reasons for existence of Integer class, so use it when the needs are compelling. – Blessed Geek Feb 12 '10 at 19:27
  • 6
    @h2g2java: I hope you're not thinking that being able to use them with the default collection is compelling because for stuff like HashMap the level of waste is huge and non-compelling. Which is why Trove's TIntIntHashMap, using only primitives, runs around circle the non-compelling HashMap. – SyntaxT3rr0r Feb 12 '10 at 20:02
  • 1
    int can't be checked for null, however, you can safely assign null to int in Java by casting it to Integer, for example if the check(root) method can return null then you can safely cast it to int by doing something like this: `int data = (Integer)check(node);` – sactiw Oct 11 '12 at 14:06
  • @sactiw - Can you elaborate ? I'm not sure I understand what you're getting at – Brian Agnew Jun 24 '14 at 15:37
  • 7
    @BrianAgnew Let me rectify what I said here, I was plain wrong, I basically didn't realize that `int i = (Integer)null;` will throw NPE at run-time while unboxing it. – sactiw Jan 23 '16 at 12:22
  • I suggest using `IntOptional` instead of `Optional` – Lino Mar 18 '19 at 10:19
  • If you mean https://docs.oracle.com/javase/8/docs/api/java/util/OptionalInt.html, that would make sense too – Brian Agnew Mar 18 '19 at 11:00
46

No. Only object references can be null, not primitives.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 3
    It's worth mentioning the Integer class which would be a better fit if the OP wants a null value. Or he could use a negative value to indicate "not found" – Glen Feb 12 '10 at 19:13
32

A great way to find out:

public static void main(String args[]) {
    int i = null;
}

Try to compile.

Matt Luongo
  • 14,371
  • 6
  • 53
  • 64
  • 49
    Actually .. The OP already found that out himself as per the last phrase in his question: *it was easy to figure out that it doesn't work.* – BalusC Feb 12 '10 at 19:35
  • 13
    For posterity nearly 4 years later- that bit was in a later edit. – Matt Luongo Dec 19 '13 at 21:36
  • 5
    but.. `Integer ii = null; int i = ii;` will compile but throw NullPointerException on runtime – premek.v Feb 25 '16 at 16:50
19

In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.

The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.

This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.

Jonathon Faust
  • 12,396
  • 4
  • 50
  • 63
9

Along with all above answer i would like to add this point too.

For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.

So by default we have,

   int a=0;

and not

   int a=null;

Same with other primitive types and hence null is only used for objects and not for primitive types.

Shoaib Chikate
  • 8,665
  • 12
  • 47
  • 70
7

instead of declaring as int i declare it as Integer i then we can do i=null;

Integer i;
i=null;
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Minati
  • 71
  • 1
  • 4
5

The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:

Integer data = check(Node root);

if ( data == null ) {
 // do something
} else {
 // do something
}

On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.

int data = check(Node root);

// do something

Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.

To learn more about autoboxing, check this Sun guide.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    Unfortunately if "check" returns an int rather than an Integer, this won't help, because the int (which won't be null) will be automatically boxed into the Integer. – Paul Tomblin Feb 12 '10 at 19:16
  • 2
    D'oh, that was just a basic example to show **when** you can test for null. On the other hand, if check is declared to return `int`, it can never be null and the whole if block is then superfluous. – BalusC Feb 12 '10 at 19:17
2

Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so

public int getHeight(String name){
    if(map.containsKey(name)){
        return map.get(name);
    }else{
        return -1;
    }
}
Nino van Hooff
  • 3,677
  • 1
  • 36
  • 52
2

No, but int[] can be.

int[] hayhay = null; //: allowed (int[] is reference type)
int   hayno  = null; //: error   (int   is primitive type)
                     //: Message: incompatible types: 
                     //: <null> cannot be converted to int
KANJICODER
  • 3,611
  • 30
  • 17
1

As @Glen mentioned in a comment, you basically have two ways around this:

  • use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
  • Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
0

Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.

0

Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.

Eg: Integer i=null;

0

An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.

Data Type / Default Value (for fields)

int ------------------ 0

long ---------------- 0L

float ---------------- 0.0f

double ------------- 0.0d

char --------------- '\u0000'

String --------------- null

boolean ------------ false

-3

Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:

new Integer(null);
George
  • 330
  • 1
  • 8
  • 19
Sandy
  • 9
-17

I'm no expert, but I do believe that the null equivalent for an int is 0.

For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.

In some situations, this may be of use.

Marcel Gwerder
  • 8,353
  • 5
  • 35
  • 60
Lahn
  • 3