Please ignore formatting and sentence related issues.
class ABC
{
public void change(Boolean x, Boolean y, StringBuffer s)
{
x=true;
y=true;
s.append("vinay");
}
public static void main(String a[])
{
Boolean x = false;
Boolean y = false;
x=false;
y=false;
StringBuffer s = new StringBuffer();
s.append("jasi");
ABC p= new ABC();
p.change(x,y,s);
System.out.println(x);
System.out.println(y);
System.out.println(s);
}
}
i want to get all changes which i made in change() method in main() method for Boolean x,y as we are getting s modified in main function. Is there any way by which we can get modified value in main method.
Java passes arguments by value, so all changes done in your change() method are not visible for caller.
In order to do what you want you can either:
1. define this variable as class members.
2. return them as a return value of the method. Yes, you are limited by only one return value but if your want to can create array of booleans or create specal class that contains both.
3. You can pass to method mutable container that contains boolean. One of the ways is to use AtomicBoolean for this:
public void change(AtomicBoolean x, AtomicBoolean y, StringBuffer s) {
x.set(true);
y.set(true);
s.append("vinay");
}
public static void main(String a[]) {
AtomicBoolean x = new AtomicBoolean(false);
Boolean y = = new AtomicBoolean(false);
change(x, y);
System.out.println(x.get() + ", " + y.get()); // will print true true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With