-2
package Sample;
public class Sample4Array {
public static void main(String[] args) {
    int a[] = new int[10];
    System.out.println(a[1]);

    for(int i=0;i<a.length;i++) {
        System.out.println(a[i]);
        //default value is 0
    }

    Integer x[] = new Integer[10];

    for(int i=0;i<x.length;i++) {
        System.out.println(x[i]);
        //default value is null & not throwing an exception.
    }       
}
}

To consider; the first for loop returns 0 as default value & second for loop even its default value is null then also it's not throwing any exception

jaibalaji
  • 3,159
  • 2
  • 15
  • 28

4 Answers4

2

Which Exception you are expecting to be thrown? NullpointerException? It won't throw this exception because you are not trying to access any method/variable on the null reference.

What you are seeing is perfectly normal.

0

There wont be any NullPointerException because

System.out.println(x[i]); internally makes use of String.valueOf() on x[i] to get its string representation.

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

String.valueOf() internally checks if the incoming object is null and if yes, it uses the String null as its value. See below :

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}
Krishnan Mahadevan
  • 14,121
  • 6
  • 34
  • 66
0

It is not going to throw an Exception. You aren't trying to dereference a null pointer. The default value set to an Integer Object is null. You are simply printing that null value. However, if you did try to dereference that null value, you would get an error.

If you do only this:

Integer[] x;

The variable x is pointing to a null value. You WILL get an error now if you try to dereference it.

The moment you do:

x = new Integer[10];

Memory is being allocated to it using the new operator. It no longer points to null. Therefore, you don't get a NullPointerException.

Debanik Dawn
  • 797
  • 5
  • 28
0

Because when you construct an array of int (primitive) like this int a[] = new int[10]; the array is created with default values of 0

And when you construct an array of Integer (Object) like this Integer x[] = new Integer[10]; the array is created with default values of null.So when you try to access any element it will give you its value which is null (null is a value)

But if you tried to do any operation on the returned value it throw null pointer exception

x[i].intValue(); //this will give you java.lang.NullPointerException
  • Default for anything that holds an object is null
  • Default for booleans is a false.
  • Default for char that is the null character '\u0000' (whose decimal
    equivalent is 0).
  • Default for int/short/byte/long that is a 0
  • Default for float/double that is a 0.0
karim mohsen
  • 2,164
  • 1
  • 15
  • 19