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

前端之家收集整理的这篇文章主要介绍了java – a = a.trim()和a.trim()之间有什么区别?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我遇到了一点混乱.

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

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

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

  1. String a = " example ";
  2. System.out.println(a);
  3. a.trim(); //my teacher's code.
  4. System.out.println(a);
  5. a = " example ";
  6. a = a.trim(); //my code.
  7. System.out.println(a);

我得到以下输出

  1. example
  2. example
  3. 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()返回一个新字符串,所以你必须通过赋值来获取它.
  1. String a = " example ";
  2. System.out.println(a);
  3. a.trim(); // String trimmed.
  4. System.out.println(a);// still old string as it is declared.
  5. a = " example ";
  6. a = a.trim(); //got the returned string,now a is new String returned ny trim()
  7. 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老师.这完全是一个没有证据的虚假陈述.

猜你在找的Java相关文章