-3
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?

Luka
  • 1,761
  • 2
  • 19
  • 30
  • This question appears to lack any research. – Mena Jun 12 '14 at 15:00
  • Java is always [pass by value](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) that might be helpful understanding that – chancea Jun 12 '14 at 15:02
  • In java the methods (thanks to @Luiggi Mendoza)parameters are passed by value. When the function "func(param)" is called, an copy of "param" is made, and any changes on "func()" takes effect on copy. – Cold Jun 12 '14 at 15:03
  • @ColdHack Java has no functions, it has methods. – Luiggi Mendoza Jun 12 '14 at 15:03

1 Answers1

4

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.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75