Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

using replace() method

 
Paul Keohan
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
Paul
 
Manish Hatwalne
Ranch Hand
Posts: 2595
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
HTH,
- Manish
 
Argm Mastoi
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic