Reputation:
I am having trouble with a relatively simple problem: I am trying to use a method from another class to add to an integer in my main class but the value of my integer is not increasing, the value stays the same, this is what the code looks like:
public class prog{
/**
* @param args
* @throws MidiUnavailableException
*/
public static void main(String[] args) {
int num = 11;
thing.add(num);
System.out.println(num);
}
}
and the class 'thing' being:
public class chords2 {
static void add(int val){
val = val+9;
}
}
any tips on how to get this to work is most appreciated
Upvotes: 0
Views: 1486
Reputation: 34146
What happens is that Java is always pass-by-value. So, in your example, if you modify the integer val
inside the method, it won't have effect outside.
What can you do?
You can declare your method to return an integer
, then you assign the result to the variable you want:
static int add(int val){
return val + 9;
}
and when you call it:
int num = 11;
num = SomeClass.add(num); // assign the result to 'num'
Upvotes: 1
Reputation: 75575
In Java, int
is passed by value. If you want to add
you should return the value and reassign it.
static int add(int val){
return val+9;
}
Then, to call it,
int num = 11;
num = thing.add(num);
Upvotes: 1
Reputation: 1150
You should have a private int val in your thing class, otherwise add "return" statement to your add() method and set the return value back in calling position.
Upvotes: 0