Is java pass by value or pass by reference

Is java pass by value or pass by reference ???

This is a confusing question, but I found a link that neatly explains things.

Try this:)

http://javadude.com/articles/passbyvalue.htm

Java is pass by value for Primitives but it is pass by reference for objects.

Here is the proof: -



public class PassTest {

    public static void main (String args []) {
        int x = 10;
        System.out.println(passByValue(x));
        System.out.println(x);
        Point p = new Point (10, 10);
        passByReference(p);
        System.out.println(p.getX() + " -- "+ p.getY());
    }
   
    public static class Point {
        private int x;
        private int y;
       
        public Point (int a, int b) {
            x= a;
            y =b;
        }
       
        public int getX() {
            return x;
        }
        public void setX(int x) {
            this.x = x;
        }
        public int getY() {
            return y;
        }
        public void setY(int y) {
            this.y = y;
        }
    }
   
    public static int passByValue (int x) {
        return x + 10;
    }
   
    public static Point passByReference (Point p) {
        p.setX(p.getX() + 10);
        return p;
    }
}



Here us the output

20
10

20 -- 10

No comments:

 Python Basics How to check the version of Python interpreter mac terminal

Popular in last 30 days