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.
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.
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");
}