Thursday 23 May 2019

Can I cast a null to reference type in Java?


Yes, you can cast a null to reference type in Java.

App.java

package com.sample.app;

public class App {
 public static void main(String args[]) {
  String s1 = null;
  String s2 = (String) null;
  Integer i1 = (Integer) null;
  Float f1 = (Float) null;
  
  //Integer i2 = (Integer) s1; You can't do this
  
  System.out.println("s1 : " + s1);
  System.out.println("s2 : " + s2);
  System.out.println("i1 : " + i1);
  System.out.println("f1 : " + f1);
 }
}

Output
s1 : null
s2 : null
i1 : null
f1 : null


You may like

No comments:

Post a Comment