In this example, you will find the basic structure and concepts of Java.lang.String with code example and description.
/
Java Library provide three class to handle Strings
* String, StringBuffer and StringBuilder
* In this section, the details and working of String class is included, however we will discuss the further parts in upcoming sections.
*
* String is an immutable Object.
* By Immutable, we mean, the Object that can never be changed after once created.
*
* In this program, declaration of String and Immutable Property is covered.
*
*/
public class FirstProgram { public FirstProgram() { // Methods to declare a String. String s1 = "abcdef"; String s2 = new String(); s2 = "xyz"; String s3 = new String("abcd"); // The String Objects are Immutable, but what about their reference ?? s1 = s1.concat(s2); System.out.println(s1); // Output : abcdefxyz // In above code, new String Object containing the value "abcdefxyz" will be created and s1 will reference the new object, // note that the old object containing value "abcdef" will not changed, it will be unreferenced, in other terms that is lost !!! s2.concat(s3); System.out.println(s2); // Output : xyz // In above line of code, a new Object will be created containing the value "xyzabcd" but it is not referenced, so it is lost !!! // But here note that, the original value of original s2 reference is unchanged. s3.substring(1, 2); s3.toUpperCase(); s3.replace("c", "q"); System.out.println(s3); // Output : abcd // In all above three cases, same logic is there. s3 = s3.replace("c", "q").toUpperCase(); System.out.println(s3); // Output : ABQD // Now, s3 will reference to the new object "abqd" and "abcd" Object is lost now !!! } public void checkYourSelf() { // Try to find what will be printed, and for extra concept how many Objects and Reference will be created. String one = "One"; String two = "Two"; String three = one.concat(" half ") + two; one += two; three.concat(two); System.out.println(one + " " + two + " " + three); } public static void main(String a[]) { new FirstProgram(); } }