-1

Why a1==a2 is true after assignment a1=a2 in the main method, but a1==a2 returns false if we do the same in another static method m?

class A {};
public class Program
{
    static void m(A a1, A a2){
        a1=a2;
    }
    public static void main(String[] args) {
        A a1=new A();
        A a2=new A();
        a1=a2;
        System.out.println(a1==a2);
    }
}

Output: true

class A {};
public class Program
{
    static void m(A a1, A a2){
        a1=a2;
    }
    public static void main(String[] args) {
        A a1=new A();
        A a2=new A();
        m(a1,a2);
        System.out.println(a1==a2);
    }
}

Output: false

galmeriol
  • 461
  • 4
  • 14
Ada
  • 1
  • 2

1 Answers1

0

The answer to your question is, in java everything is pass by value. In the method you are using local variables and that will not change the actual variables outside method. You can check this answer for detailed information on Pass by Value. I hope this will clarify your doubt.

Ravi Lohan
  • 73
  • 6