setlength java_Java中StringBuffer类的setLength()方法

这两天在自学java,发现Java中StringBuffer类的setLength()方法有点奇怪,在此请教高手了!!!下面是一些源代码及运行结果:代码1:publicclasshello{publicstaticvoidmain(Stringar...

这两天在自学java,发现Java中StringBuffer类的setLength()方法有点奇怪,在此请教高手了!!!下面是一些源代码及运行结果:

代码1:

public class hello{

public static void main(String args[]){

StringBuffer str=new StringBuffer("hello world!");

System.out.println(str+" "+str.length()+" "+str.capacity());

str.setLength(10);//10小于str.length()=12

System.out.println(str+" "+str.length()+" "+str.capacity());

}

}

运行结果:

hello world! 12 28

hello worl 10 28

(ps:这个结果显而易见)

代码2:(ps:就是把str.setLength(10)中的10改为比str的length=12大的数13)

public class hello{

public static void main(String args[]){

StringBuffer str=new StringBuffer("hello world!");

System.out.println(str+" "+str.length()+" "+str.capacity());

str.setLength(13);//13大于str.length()=12

System.out.println(str+" "+str.length()+" "+str.capacity());

}

}

运行结果:

hello world! 12 28

hello world!

(ps:就是hello world!后面的输出内容都不能显示了,而且更奇怪的是,如果在上面代码中的最好一句后面添加输出语句,那么结果都显示不了)

代码3:(ps:就是在输出时,把str放到后面输出)

public class hello{

public static void main(String args[]){

StringBuffer str=new StringBuffer("hello world!");

System.out.println(str+" "+str.length()+" "+str.capacity());

str.setLength(13);//13大于str.length()=12

System.out.println(str.length()+" "+str.capacity()+" "+str);

}

}

运行结果:

hello world! 12 28

13 28 hello world!

(这结果又很正常)

是不是很奇怪?请高手们分析解决吧!!!

展开

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值