Johnathan Au
Johnathan Au

Reputation: 5362

Why does trim() not remove the trailing white spaces in this example?

I am revising Java from here: http://java-success.blogspot.com.au/2012/06/core-java-coding-questions-frequently.html and came along this question:

"Q1. What will be the output of the following code snippet?

String s = " Hello ";
s += " World ";
s.trim( );
System.out.println(s);

A1. The output will be

" Hello  World "

with the leading and trailing spaces. Some would expect a trimmed "Hello World".

So, what concepts does this question try to test?

String objects are immutable and there is a trick in s.trim( ) line. Understanding object references and unreachable objects that are eligible for garbage collection."

Can someone explain why the trailing white spaces are not removed?

Upvotes: 1

Views: 1743

Answers (1)

rgettman
rgettman

Reputation: 178303

The method trim() doesn't modify the String, which is immutable. It returns the trimmed String, which is promptly ignored, leaving s unchanged. Replace

s.trim( );

with

s = s.trim( );

Upvotes: 10

Related Questions