0

I made 2 classes one is :

public class JavaApplication5 {
  public static void main(String[] args) {
    int y=0;
    cats catobject = new cats();
    catobject.ma(y);
    System.out.println(y);
  }
}

the other is :

class cats {

  public void ma(int x){
    x=x+9;
  }
}

it's supposed to print out 9 since the method ma should have added 9 to the integer y , but instead it prints out 0. why?

nhouser9
  • 6,730
  • 3
  • 21
  • 42
Polat
  • 57
  • 4

1 Answers1

1

When you pass an integer to a method in java, the method receives a copy of that integer. It does not modify the original. For more info on this see this link: http://javapapers.com/core-java/java-pass-by-value-and-pass-by-reference/

To make your code work, modify it to return an int. Like this:

public class JavaApplication5 {
  public static void main(String[] args) {
    int y=0;
    cats catobject = new cats();
    y = catobject.ma(y);
    System.out.println(y);
  }
}

class cats {
  public int ma(int x){
    return x+9;
  }
}
nhouser9
  • 6,730
  • 3
  • 21
  • 42