简体   繁体   中英

What is the difference between a = a.trim() and a.trim()?

I've ran into a bit of a confusion.

I know that String objects are immutable . This means that if I call a method from the String class, like replace() then the original contents of the String are not altered. Instead, a new String is returned based on the original. However the same variable can be assigned new values.

Based on this theory, I always write a = a.trim() where a is a String . Everything was fine until my teacher told me that simply a.trim() can also be used. This messed up my theory.

I tested my theory along with my teacher's. I used the following code:

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);

I got the following output:

    example   
    example   
example

When I pointed it out to my teacher, she said,

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

Please tell me who has the correct theory, because I've absolutely no idea !

String is immutable in java. And trim() returns a new string so you have to get it back by assigning it.

    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

Edit:

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.

Please find a new java teacher. That's completely a false statement with no evidence.

String are immutable and any change to it will create a new string. You need to use the assignment in case you want to update the reference with the string returned from trim method. So this should be used:

a = a.trim()

简单地使用“a.trim()”可能会在内存中修剪它(或者智能编译器会完全抛出表达式),但结果不会存储,除非您先将其分配给变量,如“a = a.trim” ();”

You have to store string value in same or different variable if you want some operation (eg trim)on string.

String a = "    example   ";
System.out.println(a);
a.trim();      //output new String is not stored in any variable
System.out.println(a); //This is not trimmed
a = "    example   ";
a = a.trim();  //output new String is  stored in a variable
System.out.println(a); //As trimmed value stored in same a variable it will print "example"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM