Adding character/s to a string has two different variations.
If you add two characters to a string you get an int as an output but when you add one character it works.
Please explain. Here is an example with output for reference.
Output-:
182eeksforGeeks
[eeksforGeeks
8 Replies
⌛
This post has been reserved for your question.
Hey @theash2473! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose Post
button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
That's an unfortunate result of the fact that operator + may mean addition or concatenation
And also of the fact that Java sees the char type as a number with weird literals
If you apply operator + with any of its two operands being a non-wrapped object, then it is concatenation. It will produce a String which is the result of converting operands to String as needed, and then producing the String that is the first operand's String immediately followed by the second's.
If you apply operator + on two number operands, then it is addition. And chars are seen as numbers. So it adds '[' and '[', which is 182. Then it concatenates 182 with "eeksforGeeks"
💤
Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping
.
Warning: abusing this will result in moderative actions taken against you.
Forgot to mention what I found. If first two operands has a string then it will become a string no matter how many oeprands. Otherwise it will be converted to an int.
Mentioned in here - https://stackoverflow.com/a/8688708/10841645
Stack Overflow
In Java, is the result of the addition of two chars an int or a char?
When adding 'a' + 'b' it produces 195. Is the output datatype char or int?
Sample code to understand all cases.
Right. It's what I said above, and operators are evaluated left to right
💤
Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping
.
Warning: abusing this will result in moderative actions taken against you.
💤
Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping
.
Warning: abusing this will result in moderative actions taken against you.