Reputation: 301
I cannot add one to the integer on the function below, it still prints 5. Can anyone explain this?
public class HelloWorld {
public static void main(String[] args) {
int x = 5;
System.out.print('Hello world~~~~~');
for(int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
System.out.println(Runtime.getRuntime().maxMemory());
System.out.println(Runtime.getRuntime().totalMemory());
System.out.println(Runtime.getRuntime().freeMemory());
OnePlusNumber(x);
System.out.println(x);
Date date = new Date();
System.out.println(date);
}
private static Integer OnePlusNumber(int number) {
number += 1;
return number;
}
}
Upvotes: 0
Views: 80
Reputation: 69470
You have to change yout code:
OnePlusNumber(x);
Should be
x = OnePlusNumber(x);
So you have the return value.
And your method schould reurn an int:
private static int OnePlusNumber(int number){
Upvotes: 1
Reputation: 7079
Change
OnePlusNumber(x);
to
x=OnePlusNumber(x);
It will assign returned value from the method to x variable again, as it is a primitive data type (int).
If the passed parameter would have been an object of a class, you did not have to assign it like this. As same object's state gets changed when reference is passed to a method -
for ex-
Employee emp=new Employee();
emp.setName("A");
changeEmpName(emp);
public void changeEmpName(Employee employee){
employee.setName("B");
}
Then employees name becomes B.
This method will change original emp object , as it's reference was passed.
Upvotes: 1
Reputation: 729
This is the main difference between Java and C for example.In your case you don't send the exact item x you are jsut sending a "copy" of it to the function , so the result of the function doesn't modify x's adress just the local value of the copied object x.
The most common way of solving this is just assigning the result of the function to x
x=OnePlusNumber(x);
Upvotes: 0
Reputation: 965
Java uses reference. When u pass x
to OnePlusNumber
. It passes reference of x
, but in java , primitive types and string are immutable. X
is Integer
here.
so number+=1
will create new Integer
. but X
in original function , refers to old x
.
That's why you need to assign return value.
x = OnePlusNumber(x);
http://en.wikipedia.org/wiki/Primitive_wrapper_class
http://docs.oracle.com/javase/tutorial/java/data/numberclasses.html
also read about
http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
Upvotes: 0
Reputation: 353
The function OnePlusNumber(x);
return a Integer.
Replace it with x = OnePlusNumber(x);
Upvotes: 0
Reputation: 9437
you don't assign the value you return. change the following line:
OnePlusNumber(x);
to
x = OnePlusNumber(x);
Upvotes: 3