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!
System.out.println(a.trim())
. This will print the trimed string but do not change actual stringa
. – Colmartrim()
as far as I can see. Have a look yourself: the Java 6 doc and the Java 7 doc. – Extremaduraa.trim()
? Maybe there's been a misunderstanding such as AJ had suggested. – Marrowfattrim()
was as it is from day 1, I believe your teacher made a mistake, or she has done something likeAJ
mentioned. – Shoshonean