How can I return more than one variable with a function with Java?
Printable View
How can I return more than one variable with a function with Java?
You can't, sort of. But in Java nearly all classes are not immutable. So you can do this trick except with primatives (int, long, byte, etc.) and the String class.
Code:public void doCrap(StringBuffer s1, StringBuffer s2)
{
s1.append(s2);
s2.doOtherCrap();
}
Or you can have a class that will expose some members/methods and then return an object from your method.
Here is an example can you just change it ... I do not understand what both you mean.
Code:
public class returnClass {
public static void main ( String Args[])
{
int iPrice1,iPrice2;
iPrice1 = 100;
iPrice2 = 13;
System.out.println("Price 1 : " + iPrice1 + "\nPrice 2 : " + iPrice2);
}
public static int SwitchNumbers(int iX, int iY)
{
int itempo=0;
iTempo = iX;
iX=iY;
iY=itempo;
return iX,iY;
}
}
thx for help :\
Eh, I just said you can't do that technique with non-immutable data types which include primitives. I don't have a clear understanding of what Serge is talking about, too.
Maybe something like this:
then just use this class in your main classCode:public class RetClass
{
private int val1;
private int val2;
public RetClass()
{
val1 = 0;
val2 = 0;
}
public RetClass(int a, int b)
{
val1 = a;
val2 = b;
}
public int getVal1()
{
return val1;
}
public int getVal2()
{
return val2;
}
}
Code:import RetClass;
class MyClass
{
public static void main(String args[])
{
RetClass ret = DoCrap(5, 6);
System.out.println("Returned values are a: " + ret.getVal1() + " b: " + ret.getVal2());
}
public static RetClass DoCrap(int a, int b)
{
//here do something with your a and b values
a = (a * b);
b = b * 2;
RetClass ret = new RetClass(a, b);
return ret;
}
}
Thx you :)
Or, I suppose that you could create an array or Vector with the info that you would like to return and then return the array or the Vector.