This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hi guys, I'm trying to form a new string by selecting different characters from a string.
String s = "Whot";
String h = s.charAt(1) + s.charAt(2) + s.char(3); // expecting "hot".
But all I get is an error please help. Thanks in advance.
Your code doesn't compile as-is, but I assume the char(3) is supposed to be charAt(3).
Even so, it won't compile, because of the semantics of the + operator. In this context it's an additive operator, instead of a being used for concatination as you seem to expect.
The concat behavior only works in the context of String manipulation. For instance, this will compile and yield the result you were expecting:
This will also compile, but yield an entirely different result:
If you print the result of the last example it becomes clear that outside of the context of String manipulation + behaves as an additive operator, which adds the nummeric values of each char.
This results in an int value, which can't be directly assigned to a String.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Randall Twede wrote:Jelle, you did answer his question, but you did it "secretly" the difference is the part you added ""
that tells the compiler we are talking strings not numbers
It isn't that simple; it won't work just by adding an empty String just anywhere.
+ is left associative. That means that pairs are combined from the left. The result of each combination is then used in the next. For instance, "" + s.charAt(1) + s.charAt(2) + s.charAt(3)is equal to ((("" + s.charAt(1)) + s.charAt(2)) + s.charAt(3)) => (("h" + 'o') + 't') => ("ho" + 't') => "hot". This uses the fact that + returns a String if at least one of the two operands is a String. Otherwise it will use mathematical addition, where chars are nothing more as numbers.
If you move the "" to the end, the result is completely different: (((s.charAt(1) + s.charAt(2)) + s.charAt(3)) + "") => ((('h' + 'o') + 't') + "") => ((215 + 't') + "") => (331 + "") => "331". This uses the fact that the numerical values of 'h', 'o' and 't' are 104, 111 and 116 respectively.