Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How we can get Boolean value updated through other method in main method

Tags:

java

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.

like image 538
Vinay Sharma Avatar asked Dec 20 '25 01:12

Vinay Sharma


1 Answers

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
}
like image 94
AlexR Avatar answered Dec 22 '25 14:12

AlexR