Get String From Another Method?

25,007

Solution 1

Create an instance variable:

public class MyClass {

    private String str;

    public void method1() {
        // change str by assigning a new value to it
    }

    public void method2() {
        // the changed value of str is available here
    }

}

Solution 2

You need to return the modified string from the first method and pass it into the second. Suppose the first method replaces all instances or 'r' with 't' in the string (for example):

public class Program
{
    public static String FirstMethod(String input)
    {
        String newString = input.replace('r', 't');
        return newString;
    }

    public static String SecondMethod(String input)
    {
        // Do something
    }

    public static void main(String args[])
    {
        String test = "Replace some characters!";
        test = FirstMethod(test);
        test = SecondMethod(test);
    }
}

Here, we pass the string into the first method, which gives us back (returns) the modified string. We update the value of the initial string with this new value and then pass that into the second method.

If the string is strongly tied to the object in question and needs to be passed around and updated a lot within the context of a given object, it makes more sense to make it an instance variable as Bohemian describes.

Share:
25,007
sparklyllama
Author by

sparklyllama

Updated on June 09, 2020

Comments

  • sparklyllama
    sparklyllama almost 4 years

    I have two methods, the first one creates a string, then I want to use that string in the second method.

    When I researched this, I came across the option of creating the string outside of the methods, however, this will not work in my case as the first method changes the string in a couple of ways and I need the final product in the second method.

    Code:

    import java.util.Random;
    import java.util.Scanner;
    
    
    public class yaya {
        public static void main(String[] args) {
            System.out.println("Enter a word:");
            Scanner sc = new Scanner(System.in);
            String input = sc.nextLine();
            Random ran = new Random();
            int ranNum = ran.nextInt(10);
            input = input + ranNum;
        }
    
        public void change(String[] args) {
            //more string things here
        }
    }