Wednesday 31 May 2017

What is null in Java?

‘null’ is a reserved constant in Java, used to represent absence of some state. A null value can be assigned to an object reference of any type.

null is the default value for reference type
If you do not assign a value to reference variable, by default it is set to null.

Let us see it by an example.

Employee.java
package com.sample.model;

public class Employee {
 private int id;
 private String name;
 private String permanentAddress;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getPermanentAddress() {
  return permanentAddress;
 }

 public void setPermanentAddress(String permanentAddress) {
  this.permanentAddress = permanentAddress;
 }

}

EmployeeTest.java
package com.sample.model;

public class EmployeeTest {
 public static void main(String args[]) {
  Employee emp = new Employee();

  emp.setId(1);
  emp.setName("Hari Krishna");

  System.out.println("Id : " + emp.getId());
  System.out.println("Name : " + emp.getName());
  System.out.println("Permanent Address : " + emp.getPermanentAddress());

 }

}


Output
Id : 1
Name : Hari Krishna
Permanent Address : null

As you see the output, ‘emp.getPermanentAddress()’ return null, since the property permanentAddress is not initialized, it is set to null.

If you try to access a property (or) call a method on null reference, you will end up in NullPointerException

Test.java
public class Test {

 public static void main(String args[]) {
  String s = null;

  int length = s.length();
  
  System.out.println("length : " + length);
 }
}

When you ran above application, you will end up in NullPointerException.
Exception in thread "main" java.lang.NullPointerException
 at Test.main(Test.java:6)


null is not an instance of any type

Test.java
import java.io.File;

public class Test {

 public static void main(String args[]) {

  if (null instanceof String) {
   System.out.println("null is not instance of String");
  } else if (null instanceof Integer) {
   System.out.println("null is not instance of Integer");
  } else if (null instanceof File) {
   System.out.println("null is not instance of Folder");
  } else {
   System.out.println("null is instance of nothing");
  }
 }
}


Output
null is instance of nothing

null can be assigned to any reference types
Example
String str = null;
Integer i = null;
File file = null;


Test.java
import java.io.File;

public class Test {

 public static void main(String args[]) {

  String str = null;
  Integer i = null;
  File file = null;

  System.out.println("str " + str);
  System.out.println("i " + i);
  System.out.println("file " + file);

 }
}

Output
str null
i null
file null

null==null always return true

Test.java
public class Test {

 public static void main(String args[]) {

  if(null == null){
   System.out.println("null is equal to null");
  }
  
  if(null != null){
   System.out.println("null is not equal to null");
  }

 }
}

Output
null is equal to null

Be cautious while doing Unboxing
Java has 8 primitive data types. Every primitive type has corresponding wrapper type.

Primitive Type
Wrapper Type
Byte
Byte
Short
Short
Int
Integer
Long
Long
Float
Float
Double
Double
Boolean
Boolean
Char
Character

Autoboxing is the conversion of primitive types to corresponding wrapper classes.

Example
short s = 1;
byte b = 10;
int i = 20;
long l = 30;
float f = 1.1f;
double d = 2.2;
char c = 'c';
boolean bool = true;
                
Short s1 = s;
Byte b1 = b;
Integer i1 = i;
Long l1 = l;
Float f1 = f;
Double d1 = d;
Character c1 = c;
Boolean bool1 = bool;
                
Unboxing is the conversion of wrapper type to their primitive type.

Example
String val = "10";
                
Short s1 = Short.parseShort(val);
Byte b1 = Byte.parseByte(val);
Integer i1 = Integer.parseInt(val);
Long l1 = Long.parseLong(val);
Float f1 = Float.parseFloat(val);
Double d1 = Double.parseDouble(val);
Character c1 = new Character('a');
Boolean bool1 = Boolean.TRUE;

//Unboxing        
short s = 1;
byte b = 10;
int i = 20;
long l = 30;
float f = 1.1f;
double d = 2.2;
char c = 'c';
boolean bool = true;

You will end up in null pointer exception, while converting null reference to corresponding primitive type.


Test.java
public class Test {

 public static void main(String args[]) {

  Short s1 = null;
  
  short data = s1;
 }
}


Run above program, you will get NullPointerException like below.
Exception in thread "main" java.lang.NullPointerException
 at com.sample.util.Test.main(Test.java:9)

Be cautious while traversing through collection
For-each loop throws NullPointerException while iterating over null references.


Test.java
import java.util.List;

public class Test {

 public static void main(String args[]) {
  List<Integer> list = null;

  for (Integer i : list) {
   System.out.println(i);
  }

 }
}



No comments:

Post a Comment