char* 转为 String的问题

s_wclin1
char* 转为 String的问题

本来我是用char[] buf从文件里读出字符串,然后再转为String,然后输出就老是出错。
所以写了下面这个测试程序。

下面的输出是12,后面还有3个不知道是什么字符。然后也没有输出right哦。

public class TestString {
    public static void main(String []args)
    {

        char []t = new char[5];
        t[0]='1'; t[1]='2';
        String test = new String(t);
        System.out.println(test);
        if(test.equals("12"))
            System.out.println("right");
    }

}

sgmoonlover
char 的默认值是 '/u0000', 所以你的test里面有5个character,不可能等于"12"

附:
For type byte, the default value is zero, that is, the value of (byte)0.
For type short, the default value is zero, that is, the value of (short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '/u0000'.
For type boolean, the default value is false.
For all reference types, the default value is null.
上一篇:如何学好JAVA,对于职业教育的一点看法 下一篇:下面没有链接了