Java Puzzlers笔记--puzzle 11: The last laugh "" 与''的区别

    技术2022-05-11  64

    public class LastLaugh{

             public static void main(String[] args){

                      System.out.println("H" + "a");

                      System.out.println('H' + 'a');

             }

    Solution:

                    显示:Ha169

                     因为'H' + 'a' 不是连接2个字符,而是把H和a转ASC码,再进行加法运算;

    TID:

                    The + operator performs string concatenation if and only if at least one of its operands is of type String;

    Correctly:

                    StringBuffer sb = new StringBuffer();

                     sb.append('H');

                      sb.append('a');

                      System.out.println(sb);

    or:

                     System.out.println("" + 'H' + 'a' );

    or:

                     System.out.println("%c%c", 'H', 'a'); // in release 5.0 


    最新回复(0)