# How does the String object work in Java?

**URL:** <https://boards.straightdope.com/t/how-does-the-string-object-work-in-java/490789>\
**Category:** Factual Questions\
**Created:** [March 25, 2009, 9:10pm UTC](https://boards.straightdope.com/t/how-does-the-string-object-work-in-java/490789 "2009-03-25T21:10:27Z")\
**Posts on this page:** 1\
**Page:** 2

<div class="post-metadata">

**Author:** ![chrisk](https://avatars.discourse-cdn.com/v4/letter/c/6de8d8/32.png) [@chrisk](https://boards.straightdope.com/u/chrisk)\
**Post date:** [March 27, 2009, 12:13am UTC](https://boards.straightdope.com/t/how-does-the-string-object-work-in-java/490789/21 "2009-03-27T00:13:45Z")

</div>

> [@Winsling](#):
>
> It’s not the case. Strings are immutable, so if Java has the chance it will reuse existing String objects when you declare a new String. However, you can force it to allocate a new String if you want. In that case, the Strings will point to different locations, but contain the same values - .equals() will return true while == will return false.
> 
> If that’s not complicated enough, there’s a method on String, intern(), that will return the canonical representation of the String. If you call that on all your Strings you can use == to compare them. Nobody ever does this.

Alright

I think that the example I most clearly remember was a quiz applet, where you need to test an answer the user types in a textbox to see if it’s identical to the ‘correct’ answer. I don’t imagine that Java would be smart enough to reuse existing String objects in that situation. Hence our need for the .equals()  
Actually, I went at least one step more clever and started scanning the input strings, case-insensitive, for various keywords so that the users wouldn’t get marked wrong for some small issue with the way they phrased the answer if they had the core idea right. 🙂

[Previous page](https://boards.straightdope.com/t/how-does-the-string-object-work-in-java/490789.md?page=1)
