• 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

K &B String Doubt

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Pg 420 of K&B ,, says
String s=new String("abc"); //creates two objects , and one refence variable
I am not able to get how two oebjcts are created there .
I can see only object being created
Thnaks in advance
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Kanchan Narang:
Pg 420 of K&B ,, says
String s=new String("abc"); //creates two objects , and one refence variable
I am not able to get how two oebjcts are created there .
I can see only object being created
Thnaks in advance



The String literal "abc" is an instance of a String object. And you create a new String.
 
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String works differently than other classes. When you have
new String("abc"); and if "abc" is being created first time, jvm will allocate memory for both "abc" itself and the object that points to "abc". However if you do it twice:

new String("abc");
new String("abc");

You only have 3 objects created. I believe that one extra hidden object thing will not be tested on the exam.
 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Whenever java can find a String constant it interns and places into String Literal pool.

so "abc" will be interned and put into String literal pool. This will be the first object.

Second is the one created by new.
 
Just let me do the talking. Ahem ... so ... you see ... we have this tiny ad...
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic