java – a = a.trim()和a.trim()之间有什么区别?

我遇到了一点混乱.

我知道String对象是不可变的.这意味着如果我从String类调用一个方法,比如replace(),那么String的原始内容不会改变.相反,将根据原始字符串返回新的String.但是,可以为同一变量分配新值.

基于这个理论,我总是写一个a = a.trim(),其中a是一个String.一切都很好,直到我的老师告诉我,也可以使用a.trim().这搞砸了我的理论.

我和老师一起测试了我的理论.我使用了以下代码

String a = "    example   ";
System.out.println(a);
a.trim();      //my teacher's code.
System.out.println(a);
a = "    example   ";
a = a.trim();  //my code.
System.out.println(a);

我得到以下输出

example   
    example   
example

当我向老师指出时,她说,

it’s because I’m using a newer version of Java (jdk1.7) and a.trim()
works in the prevIoUs versions of Java.

请告诉我谁有正确的理论,因为我完全不知道!

解决方法

字符串在java中是不可变的.而trim()返回一个新字符串,所以你必须通过赋值来获取它.
String a = "    example   ";
    System.out.println(a);
    a.trim();      // String trimmed.
    System.out.println(a);// still old string as it is declared.
    a = "    example   ";
    a = a.trim();  //got the returned string,Now a is new String returned ny trim()
    System.out.println(a);// new string

编辑:

she said that it’s because I’m using a newer version of java (jdk1.7) and a.trim() works in the prevIoUs versions of java.

请找一位新的java老师.这完全是一个没有证据的虚假陈述.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...