Forums Register Login

Guess the answer

+Pie Number of slices to send: Send
Hi,

just guess the answer don't compile it

String aa="hello";
StringBuffer bb= new StringBuffer("hello");

System.out.println(aa.equals(null)); // line 1
System.out.println(bb.append(null)); // line 2

which line will throw exception and why?


Regards,

Abdul Mohsin
+Pie Number of slices to send: Send
Hi Abdul,

Good!

String aa="hello";
StringBuffer bb= new StringBuffer("hello");

System.out.println(aa.equals(null)); // line 1
System.out.println(bb.append(null)); // line 2

First line will compile and run fine, return false, any equals comparison with
null returns false.

Line 2 is ambiguous call;
[ May 01, 2007: Message edited by: Chandra Bhatt ]
+Pie Number of slices to send: Send
Well, if it does not compile the second line, then it will not throw any exceptions.
+Pie Number of slices to send: Send
why is it ambiguous if we pass null to append method??
+Pie Number of slices to send: Send
Hi Sampath,

Welcome to the JavaRanch!

Originally posted by sampath kumar yanagandla:
why is it ambiguous if we pass null to append method??





StringBuffer has following methods where null can be ok to pass:
1- append(char[] char)
2- append(CharSequence s)
3- append(Object obj)
4- append(String args)
5- append(StringBuffer args)



See the following code, where I have overloaded append methods with same argument what StringBuffer's append() requires


Take care of order in which methods are defined in the class regarding error
message. No method is more specific than the other.

Suppose you have only two overloaded methods, one takes Object and another takes StringBuffer, that is fine StringBuffer will be called because it is more specific than the Object one. What that can be passed to StringBuffer
can be passed to Object but vice versa in not true.

OK now add one more method which takes String, now the call to append is
ambiguous, all three can be passed null and no one is specific than the other. If compiler chooses String, it can be more specific than the Object but not than the StringBuffer, because String can't be assigned to StringBuffer.

The same ambiguity is caused when you have a method that takes char[],
it is also not specific than the other one.

You can try using own example:




Comment the ambiguous methods one by one and see the method call.
[ May 03, 2007: Message edited by: Chandra Bhatt ]
+Pie Number of slices to send: Send
I got it..
Thanks for the explanation.
if you think brussel sprouts are yummy, you should try any other food. And this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1040 times.
Similar Threads
Are Objects passed by value or reference?
generic question
StringBuffer
reading content of files line by line
Doubt regarding Strings
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 01:36:13.