-4

Pseudocode:

In Loop for n-iterations {
    // I am doing a check below
    if (params.contains("test") {

    }
}

Will the string test be created as object n times?

Eypros
  • 5,370
  • 6
  • 42
  • 75
Srinath
  • 5
  • 4
  • 3
    No. There will be one string instance created for `"test"`. Java is actually fairly aggressive about caching and reusing `String` instances. For further discussion, see: http://stackoverflow.com/questions/3801343/what-is-string-pool-in-java – aroth Jan 21 '15 at 12:24

2 Answers2

4

No.. "test" is a String literal , so it goes into the String constants pool and will be reused for all future accesses of "test". if you do new String("test") (bad way of creating String) ,then several instances of the String "test" will be created - one for each iteration

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • Also worth noting that any other methods that output a `String` object representing "test" are almost certain to create other instances. – J Richard Snape Jan 21 '15 at 12:40
  • @JRichardSnape - That depends.. For example if you call `trim()` on `"test"`, then the same `"test"` instance will be returned. – TheLostMind Jan 21 '15 at 12:56
  • 1
    absolutely - hence the "almost" certain. To be honest, it's deviating from the exact question somewhat. It can be the source of nasty "gotchas" for some, hence my comment, but you've answered the question. – J Richard Snape Jan 21 '15 at 12:59
3

No. "test" is a unique object, that is stored in the String pool. It's thus even the same object as any other "test" literal you might have elsewhere in the application.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255