| Author |
String objects
|
Kanika Khanna
Greenhorn
Joined: Mar 11, 2012
Posts: 6
|
|
What should be ans ???
11. public String makinStrings() {
12. String s = “Fred”;
13. s = s + “47”;
14. s = s.substring(2, 5);
15. s = s.toUpperCase();
16. return s.toString();
17. }
How many String objects will be created when this method is invoked?
A. 1
B. 2
C. 3
D. 4
E. 5
F. 6
|
 |
Astha Sharma
Ranch Hand
Joined: Oct 15, 2011
Posts: 211
|
|
|
[Edited to remove answer. - Stephan van Hulst]
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3065
|
|
Astha, please refrain from posting straight answers. We're here to help people reason for themselves.
Kanika, what do you think is the answer, and why?
|
 |
Kanika Khanna
Greenhorn
Joined: Mar 11, 2012
Posts: 6
|
|
But ans given is3??
What about toString()??? It doesn't create any new string object???
|
 |
Kanika Khanna
Greenhorn
Joined: Mar 11, 2012
Posts: 6
|
|
Answer should be either 5 or 6.
6 in case toString() creates a new string Object.But it was given 3 in some test papers.
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3065
|
|
|
You can tell from the String.toString() documentation that it won't return a new object. Furthermore, the question is how many Strings will be created by the method, right? Do you recall when String literals are created?
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16811
|
|
Please QuoteYourSources.
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Kanika Khanna
Greenhorn
Joined: Mar 11, 2012
Posts: 6
|
|
You mean to say there are two literals "Fred" and "47". Rest 3 are objects.bt how can we make sure that both string are present in pool???. If they are not in pool,then new objects would be created for both.right??? wrote:
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3065
|
|
|
They will be in the pool from the point the class is loaded, if I'm not mistaken. Anyway, they are not guaranteed to be created during the method call.
|
 |
Mezan Shareef
Ranch Hand
Joined: Apr 01, 2010
Posts: 40
|
|
Kanika Khanna wrote:What should be ans ???
11. public String makinStrings() {
12. String s = “Fred”;
13. s = s + “47”;
14. s = s.substring(2, 5);
15. s = s.toUpperCase();
16. return s.toString();
17. }
How many String objects will be created when this method is invoked?
A. 1
B. 2
C. 3
D. 4
E. 5
F. 6
My answer would be 5.
1st object - "Fred"
2nd object - "47"
3rd object - "Fred47"
4th object - "d4"
5th object - "D4"
And there is only 1 reference variable to objects, if try to print output for s. It should be 5th object. D4.
correct me, if i am wrong. Thankyou guys.
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3065
|
|
|
Reread this thread, Mezan.
|
 |
 |
|
|
subject: String objects
|
|
|