论坛首页 入门技术论坛

关于+连接字符串和字符的区别

浏览 1304 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-11-26  

Java语言中,+可以用来拼接字符串,这是个很实用的功能,而且很简洁,不过用+拼接字符串和用+拼接字符可不一样。通过这个程序就能明白了。


public class ChineseCharTest {
    public static void main(String[] args){
        char a1 = '中';
        char b1 = '文';
        char c1 = '测';
        char d1 = '试';
        char e1 = '成';
        char f1 = '功';
       
        char a2 = '中';
        char b2 = '文';
        char c2 = '测';
        char d2 = '试';
        char e2 = '成';
        char f2 = '功';
       
        System.out.print(a1);
        System.out.print(b1);
        System.out.print(c1);
        System.out.print(d1);
        System.out.print(e1);
        System.out.print(f1);
       
        System.out.println();
       
        System.out.println(a2+b2+c2+d2+e2+f2);
    }
}


程序运行结果如下:中文测试成功
                           156035


由此可见,当+用于字符串之间的拼接,呵呵,一切正常,但当用于字符之间时,就变成了一堆数字。实际上,当+用于字符之间时,其效果等同于数字与数字之间,是一种算术运算。By the way, 从程序中我们可以看到,在Java中,一个char型变量可以保存一个中文字符哦。因为Java中,char型变量是2个字节,16位。

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics