Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does concatenated characters print a number?

Tags:

java

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?

like image 615
Sai Ye Yan Naing Aye Avatar asked Aug 23 '12 05:08

Sai Ye Yan Naing Aye


People also ask

How do you concatenate characters?

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.

How do you concatenate letters in Java?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.

Can we concatenate string and char in Java?

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.


4 Answers

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.

like image 175
Tudor Avatar answered Nov 04 '22 21:11

Tudor


+ operator with character constant 'G' + 'o' prints addition of charCode and string concatenation operator with "G" + "o" will prints Go.

like image 30
KV Prajapati Avatar answered Nov 04 '22 22:11

KV Prajapati


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).

like image 37
Thilo Avatar answered Nov 04 '22 22:11

Thilo


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.

like image 27
Chandra Sekhar Avatar answered Nov 04 '22 20:11

Chandra Sekhar