Win a copy of Zero to AI - A non-technical, hype-free guide to prospering in the AI era this week in the Artificial Intelligence and Machine Learning forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

Que regarding strings

Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Can anybody please explain why this code does not use Java's string pool.

This question is from dan's exam and the answer provided is false, true.
I think i am struggling with strings. My main problem is that i cannot see whether this checks with the pool or not. As in this case it does not.

The below code gives true, true

Can anybody let me know the whole funda behind strings so that in future it will be easy to tackle them.

Thanks a lot,
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey Kitty,
Remember that whenever a string literal is encountered,
it is put in the pool, if it is already in the pool then that
object(the one in the pool) is reused as it is.

eg String s1="abc";// means check if a String "abc" is in the pool
// if it is reuse it, if not create a new
// String object with the value "abc"
// and put it in the pool

String s2 = new String("abc");// whenever u use the new operator
// a new object is created regardless
// if it exists in the pool

as Strings are immutable, all the string functions
(in the case of the ques) always return a new String.they use a new
operator internally.

String s3 = s1.substring(4,7);// the pool is never used here.

Moral of the story is, pool is used only in case of String literals.
I hope this makes things more clear.

Kitty Dayal
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Stoned Brains. You cleared my brain on strings.

We should throw him a surprise party. It will cheer him up. We can use this tiny ad:
the value of filler advertising in 2020
    Bookmark Topic Watch Topic
  • New Topic