I have the following class:
public class Go {
public static void main(String args[]) {
System.out.println(\"G\" + \"o\");
System.out.prin
System.out.println("G" + "o");
System.out.println('G' + 'o');
First one + is acted as a concat operater and concat the two strings. But in 2nd case it acts as an addition operator and adds the ASCII (or you cane say UNICODE) values of those two characters.
The plus in Java adds two numbers, unless one of the summands is a String, in which case it does string concatenation.
In your second case, you don't have Strings (you have char
, and their Unicode code points will be added).
The "+" operator is defined for both int
and String
:
int + int = int
String + String = String
When adding char + char, the best match will be :
(char->int) + (char->int) = int
But ""+'a'+'b'
will give you ab
:
( (String) + (char->String) ) + (char->String) = String
+ is always use for sum
(purpose of adding two numbers) if it's number except String
and if it is String
then use for concatenation purpose of two String
.
and we know that char in java is always represent a numeric.
that's why in your case it actually computes the sum of two numbers as (71+111)=182
and not concatenation of characters as g
+o
=go
If you change one of them as String
then it'll concatenate the two
such as System.out.println('G' + "o")
it will print Go
as you expect.
In the second case it adds the unicode codes of the two characters (G - 71 and o - 111) and prints the sum. This is because char
is considered as a numeric type, so the +
operator is the usual summation in this case.
+
operator with character constant 'G' + 'o'
prints addition of charCode and string concatenation operator with "G" + "o"
will prints Go
.