简体   繁体   中英

How to pass a string from one method to another method in Java

I declared string:

private String name;

1st method:

private void showJSON(String response){
    name = collegeData.getString(Config.KEY_NAME);
}

I want to use the value of name in this method:

private void setRealmData() {}

Your question is a bit unclear, but there are two distinct cases of how to implement this:

A. The name variable is an instance variable:

public class myClass{
    private String name;
    private void showJSON(String response){
        // name = collegeData.getString(Config.KEY_NAME); - this was your code
        this.name = collegeData.getString(Config.KEY_NAME); // Set the 'name' variable to the value you want for this instance
        setRealmData();                                     // No argument passed, provided that 'name' is an instance variable
    }
    private void setRealmData(){
        System.out.println(this.name);  // Sample code
    }
}

B. The name variable is a local variable:

public class myClass{       
    private void showJSON(String response){
        String name;
        // name = collegeData.getString(Config.KEY_NAME); - this was your code
        name = collegeData.getString(Config.KEY_NAME);  // Set the 'name' variable to the value you want for the method
        setRealmData(name);                             // Single argument passed, provided that 'name' is a local variable
    }
    private void setRealmData(string name){
        System.out.println(name);   // Sample code
    }
}

Note that the myClass class is a dummy class I used to show the scope of the variables and methods, adjust accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM