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;
}
}
By-Value: The value of a variable is sent to function. The actual parameter cannot be changed by function.
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.
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.
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.
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
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