Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check null element if it is integer array in Java?

I'm quite new to Java and having an issue checking null element in integer array. I'm using Eclipse for editor and the line that checks null element is showing error:

Line that complains:

if(a[i] != null) {

Error msg from Eclipse:

The operator != is undefined for the argument type(s) int, null

In PHP, this works without any problem but in Java it seems like I have to change the array type from integer to Object to make the line not complain (like below)

Object[] a = new Object[3];

So my question is if I still want to declare as integer array and still want to check null, what is the syntax for it?

Code:

public void test() {
        int[] a = new int[3];
        for(int i=0; i<a.length; i++) {
            if(a[i] != null) { //this line complains...
                System.out.println('null!');
            }
        }
    }
like image 655
Meow Avatar asked Jun 13 '10 19:06

Meow


People also ask

How do you check if a value in an integer array is null?

To check if all of the values in an array are equal to null , use the every() method to iterate over the array and compare each value to null , e.g. arr. every(value => value === null) . The every method will return true if all values in the array are equal to null .

Can integer arrays have null values?

All elements of an array value must have the same data type. The cardinality of the array is equal to the number of elements in the array. An array value can be non-empty, empty (cardinality zero), or null. The individual elements in the array can be null or not null.

How do you check if an array is empty or null?

To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.

Can null be an element in an array Java?

In Java, an array is an object that holds similar types of data. It can be null only if it is not instantiated or points to a null reference.


2 Answers

In Java, an int is a primitive type and cannot be null. Objects, however, are stored as references, so if you declare an object reference but do not make a new object, the reference will be null.

Integers are object wrappers around ints, meaning they can be null.

public void test() {
        Integer[] a = new Integer[3];
        for(int i=0; i<a.length; i++) {
            if(a[i] != null) { //should now compile
                System.out.println('null!');
            }
        }
    }
like image 112
Justin Ardini Avatar answered Oct 11 '22 13:10

Justin Ardini


On primitive vs reference types

An int is a primitive type, which is distinct from a reference type. Only reference types can have the value null.

References

  • JLS 4.2 Primitive Types and Values
  • JLS 4.3 Reference Types and Values

Related questions

  • Is Java fully object-oriented?
  • Is java 100% object oriented ?

On Integer vs int

java.lang.Integer is in fact a reference type, the designated "box" type for the primitive type int. Thus, an Integer variable can have the value null.

With the introduction of autoboxing in Java, conversions from int to Integer and vice versa can be done implicitly. But do keep in mind that they are very different types, and in fact an attempt to unbox null will throw NullPointerException.

References

  • Java Language Guide/Autoboxing
  • JLS 5.1.7 Boxing Conversion

Related questions

  • What is the difference between an int and an Integer in Java/C#?
  • Why does autoboxing in Java allow me to have 3 possible values for a boolean?

On consequences of Integer being a reference type

One consequence is already mentioned: an Integer variable can have a null value. Another one is that the == operator on two Integer is a reference identity comparison, not numerical equality.

System.out.println(new Integer(0) == new Integer(0)); // prints "false"

Whenever possible, you should prefer primitive types to boxed types. Here's a quote from Effective Java 2nd Edition, Item 49: Prefer primitive types to boxed primitives (emphasis by author):

In summary, use primitives in preference to boxed primitive whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.

Related questions

  • Is it guaranteed that new Integer(i) == i in Java?
    • Goes in detail about how == behaves for Integer and int operands

When Integer must be used

There is one glaring exception where Integer must be used over int: generics. Type parameters in Java generics must be reference types. So you can NOT have a List<int> in Java; you must use a List<Integer> instead.

Related questions

  • Java noob: generics over objects only?

See also

  • Java Tutorials/Generics

On using the appropriate data structure

If you must have an int[] that permits null values, then the quick answer is to use Integer[]. Since you now have an array of reference types, some elements can be null. Be aware of all the consequences of working with reference types, or you may come across surprises.

At this point, however, I'd seriously consider using a List<Integer> instead (see Effective Java 2nd Edition: Prefer lists to arrays). Lists are much more feature-rich than arrays, and it interoperates well with the larger Java Collections Framework.

API references

  • java.util.List
  • Java Collections Framework Guide
like image 34
polygenelubricants Avatar answered Oct 11 '22 12:10

polygenelubricants