Page 1 of 1

StringBuilder's NullPointerException

Posted: Mon May 11, 2020 1:11 am
by saregg
Oracle Docs say:
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.
https://docs.oracle.com/en/java/javase/ ... ilder.html
But the book says:
If you pass a null , the string "null" is appended to or inserted in the
existing StringBuilder. No NullPointerException is thrown.
why are these saying antonymous facts, Does they refer to the same context

Re: StringBuilder's NullPointerException

Posted: Mon May 11, 2020 2:20 am
by admin
They are not contradictory. The statement in Javadoc that you have quoted is a general statement about all methods. The book is giving you the details of the methods after going through what is written for those methods in the javadoc that are important for the exam.
You can try them out by writing some test code and see what happens.

Re: StringBuilder's NullPointerException

Posted: Sat May 16, 2020 2:57 pm
by saregg
Can you be more specific on which methods ?

Re: StringBuilder's NullPointerException

Posted: Sat May 16, 2020 7:45 pm
by admin
Yes, already mentioned in the book in the paragraph from which you have quoted. All the append and insert methods.

Re: StringBuilder's NullPointerException

Posted: Fri May 29, 2020 3:41 am
by saregg
'append' method is overloaded in StringBuilder class: append(String),
append(StringBuffer) and append(char[]) etc. In this case compiler gets
confused as to which method `append(null)` can be tagged because
String, StringBuffer and char[] are not related to each other in multilevel
inheritance. Hence `sb.append(null)` causes compilation error.

--this should be correct ?

Re: StringBuilder's NullPointerException

Posted: Fri May 29, 2020 3:42 am
by saregg

Code: Select all

public class Test 
	{ public static void main(String[] args) 
 		{ 	StringBuilder sb = new StringBuilder(); 
 			System. out .println(sb.append( null ).length()); 
 		}
 	 }

Re: StringBuilder's NullPointerException

Posted: Fri May 29, 2020 5:22 am
by admin
Not sure what you are asking. Where is this statement from? What is the result of compiling the code that you have given?

Re: StringBuilder's NullPointerException

Posted: Fri May 29, 2020 5:51 am
by saregg
The result of the compilation of code says, ambiguous function call and the reason for that is the explanation given before, but in previous posts you said null can be passed inside append function ? can you explain why ?

Re: StringBuilder's NullPointerException

Posted: Fri May 29, 2020 7:38 am
by admin
String obj = null;
sb.append(obj);