假设字符串s是用new String()创建的,那么s.length()是多少?
求解释???
不知道你要问什么,
String s = new String("abc");
这s.length()就是3,也变不出其他的
String s = new String();
System.out.println(s.length());//输出0
字符串s是用new String()创建的,那么s.length()是0。此时只有'\0'
不管什么方式,s.length()总是返回字符串的字符(不是字节)数。
也就是有几个字符就返回几。
String s = new String();
System.out.println(s);
System.out.println(s.length());
console:
String s = new String();是创建的一个String对象,而对象的值默认为“”,所以s.length()的值为0
没添加字符串,长度当然是0
因为只是创建了一个对象
默认值为空串
对象长度就是0
最好的解释是看源码,看下new String()做了什么事情:
/**
* Initializes a newly created {@code String} object so that it represents
* an empty character sequence. Note that use of this constructor is
* unnecessary since Strings are immutable.
*/
public String() {
this.offset = 0;
this.count = 0;
this.value = new char[0];
}
这是String s = new String();的构造函数,通过注释可以看到这个操作返回的是一个空的字符串,是**空**不是null,并将count设置为0了。count又是什么呢?看下下面的String.length()方法返回的是什么就知道了,还是源码:
/**
* Returns the length of this string.
* The length is equal to the number of <a href="Character.html#unicode">Unicode
* code units</a> in the string.
*
* @return the length of the sequence of characters represented by this
* object.
*/
public int length() {
return count;
}
也就是说如果你使用了String s = new String();构建了一个空的字符串,那么当调用length方法时会返回count值,根据构造函数中的赋值,count为0,所以答案为0.
因为你的new String()中并没有字符,所以长度为0,
不是0吗?楼上可以上机试一下,实践是检验真理的唯一标准