Mc Gyver Basaya Mc Gyver Basaya - 4 months ago 8
Java Question

get the value from another class

Main.java

public static void main(String[] args) {
String username ="";
String password = "";
Class_b b = new Class_b();
b.login("username","password");
}


Class_b.java

public String login(String user, String pass) {
String username = "admin";
String password = "password";
return username+" "+password;
}


I want to get the username and password values from Class_b and store it into the string variable username and password in Main.java.

Answer

You could return a custom java type, or just an array of String1. Something like

Class_b.java

public String[] login(String user, String pass) {
      String username = "admin";
      String password = "password";
      return new String[] { username, password };
}

and then you might invoke it like

public static void main(String[] args) {
    String username ="";
    String password = "";
    Class_b b = new Class_b();
    String[] arr = b.login(username,password);
    if (arr.length > 1) {
        username = arr[0];
        password = arr[1];
    }
    System.out.println("username=" + username + ", password=" + password);
}

1It's also not clear why you're passing the String(s) to your method, you ignore them and return new values.

Comments