This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
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

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
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
I agree. Here's the link:
subject: using replace() method
It's not a secret anymore!