• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

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.
 
This. Exactly this. This is what my therapist has been talking about. And now with a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic