Sai Ye Yan Naing Aye
Sai Ye Yan Naing Aye

Reputation: 6738

Why does concatenated characters print a number?

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?

Upvotes: 7

Views: 8537

Answers (7)

npinti
npinti

Reputation: 52185

This previous SO question should shed some light on the subject, in your case you basically end up adding their ASCII values (71 for G) + (111 for o) = 182, you can check the values here).

You will have to use the String.valueOf(char c) to convert that character back to a string.

Upvotes: 1

subodh
subodh

Reputation: 6158

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

Upvotes: 0

Andy
Andy

Reputation: 3743

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

Upvotes: 0

Tudor
Tudor

Reputation: 62459

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.

Upvotes: 9

Thilo
Thilo

Reputation: 262684

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

Upvotes: 2

Chandra Sekhar
Chandra Sekhar

Reputation: 19500

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.

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94645

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

Upvotes: 2

Related Questions