This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
Second Question is If StringBuilder s5 = new StringBuilder(null); and StringBuffer s = new StringBuffer(null); do not throw "Compiler Error" Why does String s66 = new String(null); throw a compiler error "The constructor String(String) is ambiguous" This example was tested with Eclipse and With Java 1.5 Thanks Deepak
s3 is null. System.out is a java.io.PrintStream. If you look at the source code for println(Object) you see that it calls String.valueOf(Object) which converts any null value into the String "null".
When you say "new StringBuffer(null)" you call the StringBuffer(String) constructor. In the source code you can see that the first thing this constructor does is call the length() method on the string that is passed in. This will obviously result in a NullPointerException if the argument is null.
The second question. String's constructor is overloaded. That means that the compiler has to infer by the number and types of arguments that you pass to the constructor, which one is intented. However new String(null) could mean new String((String)null), new String((StringBuilder)null) or new String((StringBuffer)null), i.e., the call is ambiguous.
SCJP 1.4, SCWCD 1.4
Joined: Aug 05, 2006
No its not correct
If s3 was null. then s3 = s3.toUpperCase(); should have resulted in exception which it did not. After reading Java Specs , it says if one of the operand of "+" is null then null is converted to String "null" and used. I hope you agree to this. Thanks Deepak
Originally posted by Deepak Jain: If s3 was null. then s3 = s3.toUpperCase(); should have resulted in exception which it did not. After reading Java Specs , it says if one of the operand of "+" is null then null is converted to String "null" and used. I hope you agree to this. Thanks Deepak
String s3 = s1 + s2;
String addition is actually syntatic sugar -- the compiler converts the operations to a StringBuffer/StringBuilder instantiation, followed by calls to the append() method, and finally, by a call to toString() to get the string.
The append() method will convert all null references to "null" strings during the append. So after the addition of two nulls, you should have s3 equal to "nullnull".
s3 = s3.toUpperCase();
The toUpperCase() method will return a new string, in upper case. So s3 should now be referenced to a string of value "NULLNULL".