Home > Mobile >  In what cases can Java strings be updated?
In what cases can Java strings be updated?

Time:12-06

Consider the following Java program:

Version 1:

public class Traverse
{
    public static void main(String[] args)
    {
        String str = "Frog";
        // processString(str);
        str = str.substring(2, 3)   str.substring(1, 2)   str.substring(0, 1);
        System.out.println(str);
    }
}

Version 2:

public class Traverse
{
    public static void main(String[] args)
    {
        
        String str = "Frog";
        processString(str);
        System.out.println(str);

    }
    
    public static void processString (String str)
    {
        str = str.substring(2, 3)   str.substring(1, 2)   str.substring(0, 1);
    }
}

Version 1 prints the output "orF", while version 2 prints the output "Frog".

It seems that when we attempt to use the processString method (version 2) to change the string, it fails, while if we try to manually change the string without using the processString method (version 1), it succeeds.

Why is this the case?

CodePudding user response:

Strings are Reference/Complex Object Type. And every reference type in java is a subclass of type java.lang.object
this means a String variable holds a reference to the actual data. However, a copy of the reference is passed. (In Java nothing is passed by reference) Object references are also passed by value. Next to that String class is immutable, meaning when you create a String object an array of characters is made; when this is "edited" its not actually getting edited, but a new object is being made from the contents of the old string the edits you have done.
these two together result in the string "not being edited" outside the method, because the passed refrence value is changed (the refrence to the array inside the String) and when a refrence is change in a method, the original refrence doesnt change outside the method. resulting in all changes only done on the string inside the method and not outside. if you could change the array values inside the string, it technically would have changed. (but as far as i know that is not possible on the String class).

Now you have a few options to do it in a method:
by returning the changed value:

public class Traverse
{
    public static void main(String[] args)
    {
        
        String str = "Frog";
        str=processString(str);
        System.out.println(str);

    }
    
    public static String processString (String str)
    {
        return str.substring(2, 3)   str.substring(1, 2)   str.substring(0, 1);
    }
}

or by a holder class:

public class Holder{
    public String str;
}
void fillString(Holder string){
    string.str.substring(2, 3)   string.str.substring(1, 2)   string.str.substring(0, 1);
}

there are also other ways for example with an array of length 1 (depending on your usecase outside of this question).

  • Related