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: -
Here us the output
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;
}
}
20
10
20 -- 10
No comments:
Post a Comment