一道有关StringBuffer的面试题

xiaoxiao2026-06-15  5

public class Test { public static StringBuffer doSomething(StringBuffer buff) { buff = new StringBuffer(); buff.append("Hello World"); System.out.println(buff); //Hello World return buff; } public static void main(String[] args) { StringBuffer buff = new StringBuffer(); buff.append("Hello"); System.out.println(doSomething(buff)); //Hello World System.out.println(buff); //Hello } }

 

 

 

2:现在doSomething()方法中 除去:buff = new StringBuffer();

public class Test { public static StringBuffer doSomething(StringBuffer buff) { buff.append("Hello World"); System.out.println(buff); return buff; } public static void main(String[] args) { StringBuffer buff = new StringBuffer(); buff.append("Hello"); System.out.println(doSomething(buff)); System.out.println(buff); } }

 

结果:

HelloHello WorldHelloHello WorldHelloHello World

 

技术要点:1中虽然传入了StringBuffer对象,虽然把main中buff引用赋给了doSomething()中的形参,但是在方法内部有重新指向另外一个对象(内存)。所以原来的就不起作用了!

       2中始终是一个buff对象

 

 

转载请注明原文地址: https://www.6miu.com/read-5050201.html

最新回复(0)