0
class Trial {
static void main() {
    int i = 0;
    change(i);
    System.out.println(i);
}
static void change(int n) {
    n = n + 2;
    }
}

Output I'm getting - 0 Output I want - 2

Please help me change my code.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115

1 Answers1

3

Everything in Java is pass by value: http://www.javaranch.com/campfire/StoryPassBy.jsp

Try this instead:

class Trial {
    static void main() {
        int i = 0;
        i = change(i);
        System.out.println(i);
    }
    static int change(int n) {
        return n + 2;
    }
}

Edit

A parameter to a method is given a copy of the value. This value will either be a raw value (primitive) or an object reference (object).

For objects, a copy of the reference means you can change the state of an object within a method. What you cannot do is change the state having changed what the parameter is referring to.

Example 1:

class Person {
    private String name;
    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }
    public String getName() {
        return this.name;
    }
    public void setName(final String name) {
        this.name = name;
    }
}

Person p = new Person("James");
changeName(p);
System.out.println(p.getName()); // This will output Changed
...
public void changeName(Person person) {
    person.setName("Changed");
}

Example 2:

Person p = new Person("James");
changeName(p);
System.out.println(p.getName()); // This will output James
...
public void changeName(Person person) {
    person = new Person(); // person is now referring to new object, not the one passed
    person.setName("Changed");
}
JamesB
  • 7,774
  • 2
  • 22
  • 21
  • 2
    that's not strictly true - Objects are passed by _copy of a reference_, so you can modify an object that has been passed as a parameter. What you can't do is modify the reference the caller already had to make it point at a different object. – Alnitak Aug 05 '14 at 07:54
  • @Alnitak Whilst your comment is valid, nothing I have stated in my answer is not true. Pass by value in Java means you get a copy of the value in a method call - that value will be either a primitive value or an object reference. – JamesB Aug 05 '14 at 08:01
  • and without qualification, a reader might understand "pass by value" to mean that objects' _values_ are copied when they're passed as parameters. – Alnitak Aug 05 '14 at 08:03