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

来源:互联网 发布:网络信息时代如何赚钱 编辑:程序博客网 时间:2024/04/27 13:25

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 

原创粉丝点击