0
public class MyClass {
public static void main(String[ ] args) {
    int x = 5;
    addOneTo(x);
    System.out.println(x);       
}

static int addOneTo(int num) {
    return  num + 1;
}

}

I expected it to return 6!! But it do return 5

Why

  • Java is 'pass by value' -- nothing you do to a parameter affects the variable which was used by the caller as a parameter. You are discarding the return value of addToOne. – tgdavies Jul 04 '20 at 06:34

2 Answers2

0

You have just added 1 to the int variable and returning it and you didnt assign it back to int variable in main method.

sai
  • 109
  • 2
  • 13
0

Check this one

public class MyClass {
public static void main(String[ ] args) {
    int x = 5;
    System.out.println(addOneTo(x));       
}

static int addOneTo(int num) {
    return  num + 1;
}
Thiluxan
  • 177
  • 4
  • 13