File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes using replace() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "using replace() method" Watch "using replace() method" New topic

using replace() method

Paul Keohan
Ranch Hand

Joined: Mar 15, 2000
Posts: 411
I have a String str = "12345678";
Can anyone tell me why :
str.replace('4', 'B'); will give me "123B5678"
but :
str.replace((char)4, 'B'); won't change str.

replace() requires a char parameter and I can't see anything wrong with casting an int to char.
Thanks for any help!
Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2591

because (char)4 is not '4'.
Try this code -
System.out.println((char)4); //doesn't print 4
replace() method can't find character with unicode value 4 in the sting.
- Manish
Argm Mastoi
Ranch Hand

Joined: Oct 16, 2001
Posts: 35
yes and replace('4','B'), will search for char '4' not for ((char)4) as they've diff values and then if found then replace it with 'B'. hope i helped
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: using replace() method
It's not a secret anymore!