boolean d1 = false, d2 = false;
void func(boolean b)
{
b = !b;
}
void caller()
{
func(d1);
System.out.println(d1);//I expect the value of d1 to be true
}
How to change the value of d1
by passing d1
's pointer?
boolean d1 = false, d2 = false;
void func(boolean b)
{
b = !b;
}
void caller()
{
func(d1);
System.out.println(d1);//I expect the value of d1 to be true
}
How to change the value of d1
by passing d1
's pointer?
There are no pointers in Java. Instead, return the value:
boolean func(boolean b)
{
return !b;
}
And in caller
:
d1 = func(d1);
System.out.println(d1);
This will print true
.
If you have multiple things to pass into the method, put it in an object. For example, let's say you have a Person class:
class Person {
public String name;
public String lastName;
}
Now let's say you want a method that will change the name of Person:
void changeName(Person p) {
p.name = "Jon";
p.lastName = "Skeet";
}
Since objects are passed by reference, this will work.