Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

It seems so simple, Help !

 
Albert Kam
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear all,

I think this simple lines of code already says the intention of it ..


And the output is -1

Why is it not located by the indexOf method ? Any workaround for this ?
Please share your thoughts ..

Regards,
Albert Kam
 
Albert Kam
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear all,

Actually i just want to add a byte to string, and later on, find and replace the byte with a unicode char, and i ended up the first question.

Anyway i found the solution .. here's the code that works :
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String's indexOf is overridden to take a char. So if you're providing a byte, the byte is converted to char. Interestingly, this is done by first widening to type int and then narrowing to type char. (See JLS 5.1.4.)

So s.indexOf((byte)218) is looking for the char represented by 65498, but I assume you want it to look for a String representation of the byte value -38. That is, s.indexOf(Byte.toString((byte)218)).
 
Albert Kam
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you bartender
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic