Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update variables, passed to a method? [duplicate]

Tags:

java

when i pass variables to my method they are not updated in the main code, but only passed to the method. how to do that once passed variable would update in main code? Thanks!

//////////// here is main code:
public static  class MyCoding extends MainScreen{ static int mee=1;
        public static void myCode(){

       Status.show("mee="+mee, 2000);   // shows me=1

       Moo.moo(mee);

       Status.show("mee="+mee, 2000);// should be mee=76547545 but still shows mee=1 !

    }
}


//////////// here is my method:

public static  class Moo extends MainScreen{
    public static void moo(int bee){
        mee=76547545;

        return;
    }
}

What to do? Thanks!

like image 410
ShoulO Avatar asked Dec 02 '22 00:12

ShoulO


1 Answers

Passing Primitive Data Type Arguments

Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost.

Passing Reference Data Type Arguments

Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.

To get the behavior you are expecting, you will need to return a value and assign it to the original variable.

mee = Moo.moo(mee);

And in your method:

public static int moo(int mee)
{
   // some processing
   mee += 76547545;

   return mee;
}

Passing Information to a Method or a Constructor

like image 91
Beau Grantham Avatar answered Dec 30 '22 12:12

Beau Grantham