Why does concatenated characters print a number?

前端 未结 7 1715
离开以前
离开以前 2020-12-16 04:44

I have the following class:

   public class Go {
     public static void main(String args[]) {
      System.out.println(\"G\" + \"o\");
      System.out.prin         


        
相关标签:
7条回答
  • 2020-12-16 05:28
    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.

    0 讨论(0)
  • 2020-12-16 05:29

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

    0 讨论(0)
  • 2020-12-16 05:29

    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
    
    0 讨论(0)
  • 2020-12-16 05:30

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

    0 讨论(0)
  • 2020-12-16 05:42

    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.

    0 讨论(0)
  • 2020-12-16 05:42

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

    0 讨论(0)
提交回复
热议问题