I have the following class:
public class Go {
public static void main(String args[]) {
System.out.println("G" + "o");
System.out.println('G' + 'o');
}
}
And this is compile result;
Go
182
Why my output contain a number?
The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function. In the above example, we have declared two char arrays mainly str1 and str2 of size 100 characters.
There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.
How do you concatenate characters in java? Concatenating strings would only require a + between the strings, but concatenating chars using + will change the value of the char into ascii and hence giving a numerical output.
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
.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With