0
Why x does not equal 6
public class MyClass { public static void main(String[ ] args) { int x = 5; addOneTo(x); System.out.println(x); } static void addOneTo(int num) { num = num + 1; } }
3 Answers
+ 4
You did not return the value in the method addOne and assign the result back in the main method.
If you return the value, change the return value of addOne to int instead of void.
If you don't want to create a new variable to receive the result from addOne, you can just print it immediately:
System.out.println(addOneTo(x));
+ 4
In your case you have to return num + 1:
public class MyClass {
public static void main(String[ ] args) {
int x = 5;
x = addOneTo(x);
System.out.println(x);
}
static int addOneTo(int num) {
return num + 1;
}
}
+ 3
Another example:
public class Num {
public int x;
public void addOneTo(int x) {
this.x = x + 1;
//the public int x = x from your method + 1
}
}
public class Program
{
public static void main(String[] args) {
int a = 5;
//create a object of Num
Num number = new Num();
number.addOneTo(a);
System.out.println(number.x);
}
}
In this case you have a class Num with the public int x and the method addOneTo (int x)
If you call the method, for example addOneTo (5) you change the public int x inside your class Num.
I