# How many objects????

srinivas.b
Ranch Hand
Posts: 58
Hi can anyone explain how many string objects created in the following code

String s = �Sri�;
s = s + �sasi�;
s = s.substring(3, 5);
s = s.toUpperCase();
return s.toString();

v.v.satyanarayana jalluri
Greenhorn
Posts: 7
hi srinivasa rao,

1st solve this step by step.
1st statement:
String s = �Sri�;
here, jvm will create a "Sri" object and its reference is assigned to s. upto here 1 string object is created.

2nd statement:
s = s + �sasi�;
here, jvm will create "sasi" object and it is concated to the string which is in s. but strings are immutable. so the result of "Srisai" is created within new object and then its reference is assigned to s. so here 2 objects ("sasi" and "Srisasi") are created. upto here 3 string objects are created.

3rd statement:
s = s.substring(3, 5);
here, right side variable s refers to the string Srisasi. the substring is sa. Again a string object "sa" is created and it will be assigned to s. upto here 4 string objects are created.

4th statement:
s = s.toUpperCase();
here, string "sa" is changed to uppercase "SA". for this, again new string object is returned by toUpperCase() and it is assigned to s. upto here 5 string objects are created.

5th statement:
return s.toString();
here, the string in s itself is returned....

so finally, 5 string objects are created.

Xyz Abc
Greenhorn
Posts: 27
2nd statement:
s = s + �sasi�;
here, jvm will create "sasi" object and it is concated to the string which is in s. but strings are immutable. so the result of "Srisai" is created within new object and then its reference is assigned to s. so here 2 objects ("sasi" and "Srisasi") are created. upto here 3 string objects are created.

I didn't realise that creating "sasi" actually creates a new object!!

v.v.satyanarayana jalluri
Greenhorn
Posts: 7
Originally posted by Nicole Facompre:

I didn't realise that creating "sasi" actually creates a new object!!

see dear, in java each string is treated as an object. so "sasi" in the expression s+"sasi" is a string object.

Bert Bates
author
Sheriff
Posts: 8898
5
there used to be exam questions that asked "in this code how many string objects are created?"

there aren't anymore.