Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

How many Objects...

 
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello all...
This is from RHE Mock Test.
How many Objects r created in below Prog ?
StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = sb1;
StringBuffer sb3 = new StringBuffer("Hello");
According to the mock test, the answer was 3 Objects.
The reason:- 2 Stringbuffer Objects & 1 String Literal.
But i think it is 2 Objects.
Can someone explain me if i m wrong?
Also in the same mock there was a question on valid int literal
the Example given was:-
int i = 3, int j = &simi;
What does &simi means?
Thanks.
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are 3 objects.
StringBuffer sb1 = new StringBuffer("Hello");
This line all by itself creates 2 objects, one String that holds "Hello" and one StringBuffer that refers to the first String.
The second line creates nothing.
The third line uses the "new" keyword again and therefore creates ANOTHER StringBuffer object. However it reuses the String "Hello". Any modifications to the StringBuffer value causes an additional String object to be created if it does not already exist in the String pool.
 
reply
    Bookmark Topic Watch Topic
  • New Topic