-1

I'm trying to alter the variable value in java? The following code works, it changes x,y value from 0 to 100:

public void tricky(Point arg1)
{
  arg1.x = 100;
  arg1.y = 100;
}
public static void main(String [] args)
{
  Point pnt1 = new Point(0,0);
  System.out.println("X: " + pnt1.x + " Y: " +pnt1.y); 
  tricky(pnt1);
  System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); 
}

But why the following code doesn't work?

public class Solution {
    public static void tricky(int arg1)
    {
      arg1 = 100;
    }
    public static void main(String [] args)
    {
      int pnt1 = 0;
      System.out.println(pnt1); 
      tricky(pnt1);
      System.out.println(pnt1); 
    }
}
user2372074
  • 781
  • 3
  • 7
  • 18

2 Answers2

1

Java is a pass by value language. Variables that you pass to a method cannot be changed by that method beyond the scope of the method.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Not entirely correct. Java is pass by value for primitive types, but pass by reference for objects. – Kurt Du Bois Sep 30 '14 at 08:41
  • 1
    @KurtDuBois It's pass by value for object references too, which means you can't change the object reference passed to the method, but can change the state of the object. – Eran Sep 30 '14 at 08:43
  • For objects, you pass the object references as a value. – EpicPandaForce Sep 30 '14 at 08:45
0
public static void tricky(int arg1)
{
  arg1 = 100;
}

arg1 is a copy of the value that you provide for this method. It is not the actual variable, it is a copy of its value.

In the case of

public void tricky(Point arg1)
{
  arg1.x = 100;
  arg1.y = 100;
}

You send an Object over using a reference and modify its class variables. Thus, you are actually modifying the value, not a copy of it.

However, to demonstrate the difference,

public void tricky(Point arg1)
{
   Point arg2 = new Point(50,50);
   arg1 = arg2;
}

The variable you provided the method will not change outside of this method. You can do that only if you say

arg1 = tricky(arg1);

public Point tricky(Point arg1)
{
   Point arg2 = new Point(arg1.x / 2, arg1.y / 2);
   return arg2;
}

Aka return the new value as a return value.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428