#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    1
    Rep Power
    0

    Question Can someone help me understand strings please?


    Everything I read about strings tells me that they are immutable - i.e. once created they cannot be changed.

    That being the case, can someone please explain in idiot terms what is going on here?

    To the uninitiated (me!) it looks like str1 is being changed. Obviously I am not understanding something basic here, but as I have just started programming I have no idea what.

    Any help would be appreciated!


    Code:
    public class Test {
    
    	public Test() {
    		// TODO Auto-generated constructor stub
    	}
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		String str1 = "I can't be changed once created!";
    		System.out.println(str1);
    		str1 = "Now I have been changed";
    		System.out.println(str1);
    
    	}
    
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    74
    Rep Power
    19
    Your code does not compile, yet, because you are missing a return type in the Test() method. (which isn't used in this example). When I run the program I get:

    Code:
    I can't be changed once created
    Now I have been changed
    What I have understood from the immutability (spelling?) of a Java String object, is that the String itself will not change, but the reference to its value will. In contrast to the use of the reserved word 'final' which disallows an object to mutate its reference to its value.

    Look at the text on wikipedia:
    *** begin quote from http://en.wikipedia.org/wiki/Immutable_object ***
    A classic example of an immutable object is an instance of the Java String class.
    Code:
    String s = "ABC";
    s.toLowerCase();
    The method toLowerCase() will not change the data "ABC" that s contains. Instead, a new String object is instantiated and given the data "abc" during its construction. A reference to this String object is returned by the toLowerCase() method. To make the String s contain the data "abc", a different approach is needed.
    Code:
    s = s.toLowerCase();
    *** End Quote ***

    Comments on this post

    • stdunbar agrees

IMN logo majestic logo threadwatch logo seochat tools logo