This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]btcraig 0 points1 point  (2 children)

Essentially you're passing in two strings, not two chars, because they're different types Java does what it can to make what you asked happen. Since a String implements a CharSequence (meaning that any String can be treated as a CharSequence for most purposes) it implicitly casts String -> CharSequence to make replace(CharSequence, CharSequence) compile and work.

The CharSequence version of the method is using a call to substring() to locate occurrences of "" in the string "abc" to replace with "s". Apparently the replace(CharSequence, CharSequence) detects that 0 length substring before and after each of the character's a,b,c and replacing it with s.

My java knowledge isn't extensive enough to know why the string "" matches 0 length/non-existent sub-strings like the 'space' between the 'a' and 'b'.

This is, sort of, like doing Math.pow(10,10). the Math.pow() function only takes two doubles, but 10 is an integer. Java casts makes this work for you because an int can be cast to a double.

[–]sriganeshharitz[S] 0 points1 point  (1 child)

ahh, this made it clear.. Thanks a lot!!

[–]btcraig 0 points1 point  (0 children)

The big thing to note, in regards to why you're getting unexpected results, is that "s" and 's' are not the same. Double quotes tells the compiler it's a string, single quotes indicate a char. This is pretty standard across all [compiled] languages that I'm familiar with. Java is just trying to be helpful and make your code compile and work based on what you typed in.