Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change a functions argument's values?

Tags:

java

function

This may seem like a stupid question, but would this function actually affect the variable bool (there is greater context to how I'm going to use this, but this is basically what I'm unsure about)? (I am asking specifically about java)

void truifier (boolean bool) {
    if (bool == false) {
        bool = true;
    }
}
like image 866
LRFLEW Avatar asked Apr 09 '11 20:04

LRFLEW


People also ask

Can you change the value of a function parameter?

By-Value: The value of a variable is sent to function. The actual parameter cannot be changed by function.

How do you make a function accept any number of arguments?

To make a function that accepts any number of arguments, you can use the * operator and then some variable name when defining your function's arguments.

Can you edit parameters in Java?

You can change that copy inside the method, but this will have no effect on the actual parameter. Unlike many other languages, Java has no mechanism to change the value of an actual parameter.


2 Answers

Consider a slightly different example:

public class Test {

    public static void main(String[] args) {
        boolean in = false;
        truifier(in);
        System.out.println("in is " + in);
    }

    public static void truifier (boolean bool) {
        if (bool == false) {
            bool = true;
        }
        System.out.println("bool is " + bool);
    }
}

The output from running this program would be:

bool is true
in is false

The bool variable would be changed to true, but as soon as the truifier method returned, that argument variable goes away (this is what people mean when they say that it "falls out of scope"). The in variable that was passed in to the truifier method, however, remains unchanged.

like image 180
pohl Avatar answered Sep 21 '22 12:09

pohl


As another response pointed out, when passed as a parameter, a boolean will be created locally for your truifier function, but an object will be referenced by location. Hence, you can get two very different results based on what parameter type you are using!

class Foo {
    boolean is = false;
}
class Test
{
    
    static void trufier(Foo b)
    {
        b.is = true;
    }
    public static void main (String[] args)
    {
        // your code goes here
        Foo bar = new Foo();
        trufier(bar);
        System.out.println(bar.is); //Output: TRUE
    }
}

If however you are not using a boolean, but an Object, a parameter can then modify an object. //THIS CODE OUTPUTS TRUE

like image 35
Max Alexander Hanna Avatar answered Sep 18 '22 12:09

Max Alexander Hanna