- Compilation Error -This is because you can pass an Object or a String or char[]. Since null can fit in both, the compiler doesn't know which method to use, leading to compile error.
- Method Overloading:
1.public void prinltln(String str) { }
2.public void prinltln(char[] ch){ }
3.public void prinltln(Object ch){ - It seems the call System.out.print(null) is ambiguous to compiler because print(null) here will find the two best specific matches i.e. print(String) and print(char[]) . So compiler is unable to determine which method to call here .
- Compilation Error:
System.out.println(null)
Program #1: what will happen when we print System.out.println(null)
- Compile Fine:
System.out.println((String)null);//null
System.out.println((char[])null);
System.out.println((Object)null);//null - It's the compiler type-checking the parameters of the method call.
- But here we need to know one more thing System.out.println((char[])null); will compile fine but at run time will throw runtime exception.
Program #2: what will happen when we print System.out.println(null) by type casting
- package com.systemoutprintn;
- public class Test {
- /**
- * @Website: www.instanceofjava.com
- * @category: System.out.println(null)
- */
- public static void main(String[] args) {
- System.out.println((String)null);//null
- System.out.println((Object)null);//null
- System.out.println((char[])null);
- }
- }
Output:
- null
- null
- Exception in thread "main" java.lang.NullPointerException
- at java.io.Writer.write(Unknown Source)
- at java.io.PrintStream.write(Unknown Source)
- at java.io.PrintStream.print(Unknown Source)
- at java.io.PrintStream.println(Unknown Source)
- at com.systemoutprintn.Test.main(Test.java:13)
System.out.println((char[])null);
ReplyDeleteThis statement will not work. Because according to the javadocs, the char type will not handle null pointer which leads to a null pointer exception. String and Object works fine as you said.
-Regards,
Karthik Byggari
You are telling the compiler which implementation of System.out.println(*) to use, but when trying to use it execution fails... Interesting... Testing should lead you to validate that output...
ReplyDeleteclass J
ReplyDelete{
public static void main(String [] args)
{
System.out.println((char[])null);
}
}
this code is compile fine but runtime error like
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Writer.java:127)
at java.io.PrintStream.write(PrintStream.java:503)
at java.io.PrintStream.print(PrintStream.java:653)
at java.io.PrintStream.println(PrintStream.java:792)
at logicalquestion.J.main(J.java:9)
This is correct and exactly what is mentioned in the last line of the post:
Delete"But here we need to know one more thing System.out.println((char[])null); will compile fine but at run time will throw runtime exception."