javareturnreturn-type

Return different type of data from a method in java?


public static void main(String args[]) {
    myMethod(); // i am calling static method from main()
 }

.

public static ? myMethod(){ // ? = what should be the return type
    return value;// is String
    return index;// is int
}

myMethod() will return String and int value. So take these returning values from main() i came up with following solution.

create a class call ReturningValues

public class ReturningValues {
private String value;
private int index;

// getters and setters here
}

and change myMethod() as follows.

 public static ReturningValues myMethod() {
    ReturningValues rv = new ReturningValues();
    rv.setValue("value");
    rv.setIndex(12);
    return rv;
}

Now my question,is there any easier way to achieve this??


Solution

  • Finally i thought my way is better since when number of return types go higher this kind of a implementation do that in best way.

    public static ReturningValues myMethod() {
    ReturningValues rv = new ReturningValues();
    rv.setValue("value");
    rv.setIndex(12);
    return rv;
    }