String s = "Amar"; A new string object is created in String pool "Amar" and is assigned to s. So count is 1.
s = s + "50"; Now a new string object "50" is created in String pool. So right now there are two string objects "Amar" and "50". Now because of + a new String object is created "Amar50" and is assigned to s. So after this statement there are 3 string objects. "Amar", "50" and "Amar50"
s = s.substring(2, 5); This will again create a new string object that has "ar5" and assing it to s. So now we have 4 string objects "Amar", "50", "Amar50" and "ar5"
s = s.toUpperCase(); This will again create a new String object "AR5" and assign it to s. So now we have 5 string obects "Amar", "50", "Amar50", "ar5" and "AR5"
return s.toString(); this will simply return s. and hence no string objects are created here. So total result is 5 "Amar", "50", "Amar50", "ar5" and "AR5".
For Strings or other built-in clases, i dont think so you can do this. But for user defined clases you can do this by creating a static int counter and incrementing the counter in the constructor.
SCJP, SCWCD, SCBCD
bacon. tiny ad:
a bit of art, as a gift, that will fit in a stocking