0

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

1

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Not just int, everything is pass by value.
@Keppil, True, but most objects are references, and I did not want to go into an extended discussion about reference vs value types. So I made a true statement which is slightly incomplete.
Fair enough, I suppose.
Thanks I just needed to re-assign the value this one worked perfectly
1

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'

4 Comments

@AmirBawab why are you saying that?
Yes @Amir, everything in Java is pass by value.
@AmirBawab I will recommend you to read this.
Yes, it's confusing. Despite that, my answer is correct, so if you downvoted, please undo it. Also, you say "value mean, copy of the data inside the variable...", but note that an object's value is a reference.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.