String makeStrings() {
String s = "HI"; //String literal
s = s + "5"; //concatenation creates new String object (1)
s = s.substring(0,1); //creates new String object (2)
s = s.toLowerCase(); //creates new String object (3)
return s.toString(); //returns already defined String
}
संयोजन के संबंध में, जब एक नया स्ट्रिंग बनाने, JVM
StringBuilder
का उपयोग करता है, अर्थात्:
s = new StringBuilder(s).append("5").toString();
toString()
एक StringBuilder
के लिए है:
public String toString() {
return new String(value, 0, count); //so a new String is created
}
substring
एक नया स्ट्रिंग बनाता है ऑब्जेक्ट जब तक संपूर्ण String
अनुक्रमणित है:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex)
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
toString()
करता नहीं एक नया स्ट्रिंग बनाने के लिए:
public String toString()
{
return this;
}
toLowerCase()
एक बहुत लंबा तरीका है, लेकिन यह पर्याप्त कहना है कि अगर String
नहीं पहले से ही है सभी लोअरकेस, यह new String
लौटाएगा।
यह देखते हुए कि प्रदान किया गया उत्तर है, जैसा कि जॉन स्कीट ने सुझाव दिया था, हम मान सकते हैं कि दोनों स्ट्रिंग अक्षर पहले ही स्ट्रिंग पूल में हैं। पूल में स्ट्रिंग जोड़े जाने के बारे में अधिक जानकारी के लिए, Questions about Java's String pool देखें।
मुझे संदेह है कि अंतर यह है कि "HI" और "5" स्ट्रिंग पूल में पहले से ही हैं, इसलिए वे प्रत्येक विधि आमंत्रण पर नहीं बनाए गए हैं। –
@GrijeshChauhan मैंने एसओ मेटा पर एक [पोस्ट] बनाया है (http://meta.stackexchange.com/questions/190688/determining-whether-a-post-should-be-marked-as-a-duplicate#190689)। इस पोस्ट को बंद करने के बजाय, मुझे लगता है कि हमें दूसरे को बंद करने के लिए वोट देना चाहिए। शायद मैं पक्षपातपूर्ण हूं, लेकिन मुझे लगता है कि ये उत्तर बेहतर हैं ... –
@SteveP। मैंने इसे पहले से ही डुप्लिकेट विकल्प के साथ बंद करने के लिए वोट दिया ... –