-4

My question is about what is the use of below code in a program.

Sample obj=null;

what does this mean?

In what way it can be used?

azro
  • 53,056
  • 7
  • 34
  • 70
Vijay
  • 1
  • 1
  • 4
    Possible duplicate of [Assign an object to null](https://stackoverflow.com/questions/13927077/assign-an-object-to-null) – Kaustubh Khare Jul 18 '18 at 05:21
  • 1
    This one line does a lot: _declares_ a _variable_ that is _named_ `a`, and _initialises_ it to _`null`_. Which of the five concepts are you asking about? If all five, you need a Java tutorial, not a StackOverflow answer. – Amadan Jul 18 '18 at 05:22
  • If you are talking about when would doing this be useful, I would say it is being more explicit than `Sample obj;`. This makes your intention clearer if you set the value of `obj` later and return it. – Jai Jul 18 '18 at 05:24
  • @Jai I disagree. If this is a field, explicitly initializing to `null` is unnecessary (and may actually have some overhead because that explicit initialization will generate additional bytecode iirc), and if it is a local variable, you disable some of the static analysis the Java compiler does for you (that is: that you didn't forget to initialize it in any code path). – Mark Rotteveel Jul 18 '18 at 20:40
  • @KaustubhKhare That duplicate seems to be about pass by reference vs pass by value, not about declaring and initializing a variable with null. That means it doesn't apply here. – Mark Rotteveel Jul 18 '18 at 20:42

2 Answers2

0

A person has attributes name and city. Lets define a class Person:

public class Person {
    private String name;
    private String city;
    public Person(String name, String city) {
        this.name = name;
        this.city = city;
    }
    public String getName() {
        return name;
    }
    public String getCity() {
        return city;
    }
}

Consider the statement: Person obj = new Person("Krish", "Bombay");

  • Person is a class.
  • obj is a variable name of type Person.
  • new Person(...) creates (or instantiates) an object (or an instance) of type Person with attributes name="Krish" and address="Bombay".
  • The newly created Person object is assigned to the variable obj; obj is a reference variable (or a reference) and refers (or points) to the object.

Consider the statement Person obj = null;. What a Person and obj is explained above. What is a null?

The null

Types in the Java programming language are of two categories:

  • Primitive types and reference types.
  • The primitive types (boolean, byte, short, int, long, char, float and double).
  • The reference types are class types, interface types, and array types.

And, there is a special type: the null.

The Null Literal (from the Java Language Specification): The null type has one value, the null reference, represented by the null literal null, which is formed from ASCII characters. A null literal is always of the null type. The null type is special, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type.

Objects and null

Consider the statements:

Person obj1 = new Person("Krish", "Bombay");
Person obj2 = null;
  • An object is a dynamically created instance of a class type; in this case a Person object. The variables obj1 and obj2 are of type Person and can hold an object of type Person (or its sub-class like an Employee, where Employee extends Person) or a null.
  • The values of a reference type are references to objects (obj1 and obj2). The reference values are pointers to these objects, and a special null reference, which refers to no object.

In addition, arrays of a type T (e.g., Person) can hold null values and also a variable of type java.lang.Object can hold a null reference.

Interface and null

Consider the statements:

Integer i = new Integer(12); 
Comparable comp = null;
comp = i;

A variable (comp) of an interface type (Comparable) can hold a null reference or a reference to any instance of any class (e.g., Integer) that implements the interface. In the above code snippet, Comparable is an interface and Integer is a class and both are defined in java.lang package. And, Integer implements Comparable.

Sample obj = null;

1: Person obj = null;
2: obj = new Person("Pete", "Aukland");
3: obj = null;

A value of the null type may be assigned to any reference type, resulting in a null reference of that type (see the statements 1 and 3 in the above code snippet). A value of the null type may be converted to a reference type by assigning a value to the reference (statement 2).

null Reference Usage

The object of null reference can also be used in a method invocation, instanceof operator, the reference equality operators == and != and String concatenation. An example using method invocation and checking reference equality with null:

private void printPerson(Person p) {
    if (p != null) {
        System.out.println(p.getName() + " : " + p.getCity());
    }
    System.out.println(p.getName());
}

The above method is invoked as follows:

Person obj = new Person("Pete", "Aukland");
printPerson(obj); // this will print "Pete : Aukland" and "Pete"
obj = null;
printPerson(obj); // this will throw a NullPointerException (see note below)

NullPointerException

There is the class java.lang.NullPointerException. This is a runtime exception. This exception is thrown when an application attempts to use null in a case where an object is required (what a null case is...).

null and Garbage Collection (GC)

A way to remove a reference to an object is to set the reference variable that refers to the object to null. In the following example code, if a Person object is created, used and then finally assigned a null and not used (or referred) further, that object is eligible for GC.

Person obj1 = new Person(...); // create an object
Person obj2 = new Person(...); // create another object
printPerson(obj1); // use it
obj1 = null; // assign a null, so that it can be GC'd
// more code here: use obj2 and etc., ...

Also see: Introduction to Java garbage collection

prasad_
  • 12,755
  • 2
  • 24
  • 36
0
String str = null;

This means that str is a reference type not pointing anywhere. This reference is created in stack.

However,

String str = new String();

This would mean that str refernce type is now pointing to the String object created in the heap.