• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

My String won't trim

 
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a GUI with a JPassword field named pswrd.
When I read the entered password I save it in a String
named password and trim to get out leading and trailing
empty spaces (user pressed the space bar).

but when I print the password (using a JOptionPane)

to check that the empty spaces are gone, they never are.
Why, and what can I do about it?
Thanks!
 
Ranch Hand
Posts: 1376
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a standard mistake when working with Strings. Strings are immutable, meaning they do not change. The syntax "password.trim();" does nothing to the original String, it simply returns a NEW String with the spaces trimmed off. The following modification will work:
password = password.trim();
Hope this helps.
Joe
 
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,
Hope this too clarify the answer, according to the API specification of the String class,
trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
Important thing to note here is that, it returns a String.
Better check the API if you get similar problems.
Cheers...........
 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String in Java is immutable. So you can't change it instead get the new trimmed String.
 
Elouise Kivineva
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh geez! I really should have seen that...
Thanks ya'll, Elouise
 
I love a woman who dresses in stainless steel ... and carries tiny ads:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic