1

One interviewer asked me this below question what is the output of the program.

But I try it in my end the line one compile but line two not compile what is the reason behind it.

Anyone can tell me please.

package swain.javainterviewhub.blogspot.in;

import java.util.Scanner;

public class JavaInterviewHub {

    public static void main(String[] args) {

        String str=null;
        System.out.println(str);//Line 1 Compile 
        System.out.println(null);/Line 2 Not compile
    }

}

What is null in real.Its string or charecter or integer.My question is what is null type. Thanks Sitansu

Sitansu
  • 3,225
  • 8
  • 34
  • 61
  • What error does the compiler give you? That will give you a hint as to the reason. – Cameron Skinner Aug 24 '15 at 04:58
  • The method println(char[]) is ambiguous for the type PrintStream – Sitansu Aug 24 '15 at 05:00
  • The compiler can't distinguish in the second case if you mean `System.out.println((Object)null)` or `System.out.println((String)null)` or indeed `System.out.println((char[])null)`. Note that there may be some other overloads of `println` that could take a `null` reference as well. – clstrfsck Aug 24 '15 at 05:06
  • [3.10.7. The Null Literal](https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.7) – Jin Kwon Aug 24 '15 at 05:48

3 Answers3

7

Line two doesn't compile because System.out is a PrintStream instance, and PrintStream has more than one println method that take a reference type argument (println(String x) and println(char x[])). When you pass a null, the compiler can't decide which of the overloaded methods to choose.

System.out.println(str) passes compilation since the type of the argument (String) matches only one of the overloaded versions of println - println(String x).

Eran
  • 387,369
  • 54
  • 702
  • 768
2

you can cast it to make it work

System.out.println((String)null);
Dima
  • 8,586
  • 4
  • 28
  • 57
-1

i Don't Why you are printing Null . you can Null As s String on Print Statement . You Can Use Like That :

String str=null;
System.out.println(str);//Line 1 Compile 
System.out.println("null");Print Null 
Anand Dwivedi
  • 1,452
  • 13
  • 23