0

The program below prints (20,10) but I do not understand why it is not (10,20), as the foo method should switch the variables.

Could somebody please explain this? Thank you

public class Test
{
  public static void main(String[] args)
  {
    int x = 20;
    int y = 10;
    foo(x,y);
    System.out.println(x + " , "+y);
  }
  public static void foo(int x, int y)
  {
    int tmp = x;
    x = y;
    y = tmp;
  }

}
Dr. John A Zoidberg
  • 888
  • 2
  • 10
  • 23
  • This is because Java is pass by value. See the linked question. – Tim B Jun 09 '14 at 10:30
  • [this](http://stackoverflow.com/a/40523/2764279) and **Linked Questions** may help you...and why +1 for this question??? – earthmover Jun 09 '14 at 10:31
  • This is because Java primitive are passes by value. So the params that you passe to "foo" function only change de values on is context, and nothing more. If x and y were instances of ca class Integer, the figures would be exchanged, they would be passed by reference and not by value. – Cold Jun 09 '14 at 10:37
  • @ColdHack - Java object references are also pass-by-value. – Hot Licks Jun 09 '14 at 11:06
  • Yeah, like you said, the reference are passed, so, if the reference are passed, the operation will be done on the referenced memory space allocated for the variable. You can see a good explanation here: http://www.cs.utoronto.ca/~dianeh/tutorials/params/ – Cold Jun 09 '14 at 11:16
  • @HotLicks you are right. Even they was an Instance of a wrapper this will not work. Thanks – Cold Jun 09 '14 at 11:42

0 Answers0