-1

Recently I faced this question the answer was kinda wiered to me

public class Q22 {
    public void doIt(int x, Person y){
        x=5;
        y.number=8;
    }
    public static void main(String[] args) {
        Person p = new Person();
        int x = 0;
        new Q22().doIt(x, p);
        System.out.println(x+" , "+p.number);
    }
}

class Person{
    public int number;
}

Outputs : 0 , 8 instead of 5, 8

Why on the earth this happens? Could someone please explain to me with thanks.

Azad Omer
  • 49
  • 4
  • I read the other question I didn't understand really! Can you please help me solve my question, I know java pass by value always that all I understood – Azad Omer Feb 19 '21 at 21:51

1 Answers1

-3

It’s because primitive types parameters are passed by value and reference types are passed by reference.

So inside the method the x parameter points to a new space in memory and the y parameter points to the original memory space.