Page 1 of 1

[HD Pg 0, Sec. 5.2.2 - stringbuilder-api]

Posted: Sat Jan 11, 2020 2:18 am
by nk2164
About this point :

If you pass a null, the string "null" is appended to or inserted in the existing StringBuilder. No NullPointerException is thrown.
=============

Code: Select all

		StringBuilder str = new StringBuilder("Hello");
		str.append(null);
Failed with "The method append(Object) is ambiguous for the type StringBuilder."

============
Then i tried this one .

Code: Select all

		String str1 = null;
		
		StringBuilder str = new StringBuilder("Hello ");
		str.append(str1);
		
		System.out.println(str);
=======================
And it printed: Hello null
======================

Is it because if i directly pass a null , it has no way of knowing what the type of object being passed is ?

Re: [HD Pg 0, Sec. 5.2.2 - stringbuilder-api]

Posted: Sat Jan 11, 2020 2:36 am
by admin
Yes, it should say, "if you pass a variable that is null" and not just a null literal for the reason that you mentioned. Passing null literal would be ambiguous.
Added to errata. Thank you for your feedback!

Re: [HD Pg 0, Sec. 5.2.2 - stringbuilder-api]

Posted: Sat Jan 11, 2020 2:38 am
by nk2164
Thank you