-2

Based on program below I am confused whether null is an object because my program compiles fine with out any error. I thought it will give a null pointer exception as I am passing null at line 1

public class GC {
    private Object o;
    private void doSomethingElse(Object obj)
    {
        o = obj;
        System.out.println(o); // prints null
    }
    public static void main(String[] args) {
        GC g = new GC();
        g.doSomethingElse(null); // LINE 1
    }
}
kittu
  • 6,662
  • 21
  • 91
  • 185

3 Answers3

3

No, 'null' is a value. In java you are passing arguments to function as reference (except basic types), which value (of this reference) 'points' to object. In this case value of reference points to nothing.

Additional explanation;

Integer n = new Integer(8);

n - is a reference to an object in memory. value of this reference is something like Integer@23434342, like memory address. At this address is your object, with some field that holds 8.

n = null tells that n point to nowhere. Thats why it's a value of reference.

Kuba
  • 839
  • 7
  • 16
1

When you pass an object as an argument, its' address is passed. null passes the addresses value 0. If you're curious as to why your code compiles, that's why.

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
0

No, null is a literal expression. The value of this literal expression is a "null reference". The null reference is the only possible value of an expression of null type.

For more details take a look at Java Language Specification

Leonardo Cruz
  • 1,189
  • 9
  • 16