Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Objects - Count

 
Ravi Bhatt
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All,

Can you please tell me how many string objects are created by below code?

1. String s= "Faltu";
2. s=s+"47";
3. s=s.substring(2,5);
4. s=s.toUpperCase();


As far as i know, it is 5. one point holding "Faltu", one holding "47" and rest 3 are created as a result of line 2,3,4.

But the answer is different in one of the mock tests that i took.

i tried this.

String s= "Faltu";
System.out.println(s.hashCode());
s=s+"47";
System.out.println(s.hashCode());
s=s.substring(2,5);
System.out.println(s.hashCode());
s=s.toUpperCase();
System.out.println(s.hashCode());

this code prints a different hashcode each time. confirming creation of new object.

Am i missing something? Please help. Thanks in advance.
 
camilo lopes
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, to each creation of a new object jvm to give one hashcode different, when the implementation is on the part of it, has not to be that you programmer defines as must function hashcode for object X.
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps this thread may help you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic