Java – what is the difference between a = a.trim() and a.trim()?
I'm in a bit of a mess
I know that string objects are immutable This means that if I call a method from the string class, such as replace (), the original content of the string will not change Instead, a new string is returned based on the original string However, you can assign new values to the same variable
Based on this theory, I always write a = a.trim (), where a is a string Everything was fine until my teacher told me that I could also use a. trim() This messed up my theory
I tested my theory with my teacher 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 get the following output:
example example example
When I pointed it out to the teacher, she said,
Please tell me who has the right theory, because I don't know at all!
Solution
Strings are immutable in Java Trim () returns a new string, so you must get it by assignment
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:
Please find a new Java teacher This is a completely unsubstantiated misrepresentation