In Java all variables of the standard types (as detailed in the section called “Data Types”) are passed by value - never by reference. For example:
public class Test { public void square(int x) { x = x*x; } public Test() { int y = 5; System.out.println(" The value of y is " + y); // outputs 5 square(y); System.out.println(" The value of y is " + y); // outputs 5 } public static void main(String[] args) { new Test(); } }
In Java if you pass an object to a method, you are always passing a reference to the object. This means that you are always operating on the original object. For Example:
1 2 3 public class SomeClass 4 { 5 public int x = 2; // just for demonstration - set public 6 } 7 8 public class Test 9 { 10 public void square(SomeClass s) { s.x = s.x * s.x; } 11 12 public Test() 13 { 14 SomeClass y = new SomeClass(); 15 System.out.println(" The value of SomeClass x is " + y.x); 16 // outputs 2 17 18 square(y); 19 System.out.println(" The value of SomeClass x is " + y.x); 20 // outputs 4 21 } 22 23 public static void main(String[] args) 24 { 25 new Test(); 26 } 27 } 28 29
When dealing with assignments in Java we have a very important difference between code written in C++ and code written in Java, that on initial inspection seems exactly the same.
Looking at the C++ version:
/* In C++ */ Account a(600); CurrentAccount b(500,5000); //bal = 500, overdraft = 5000 a = b; a.display(); // results in "I am an account" being displayed // with no mention of overdraft and a balance // of 500. The compiler would have prevented b = a;
Looking at the equivalent Java version:
/* In Java */ Account a; CurrentAccount b = new CurrentAccount(500,5000); a = b; a.display(); // results in "I am a current account" // with an overdraft of 5000 and a balance of 500
In C++ when we assign a=b;
the CurrentAccount
object is simply sliced into an
Account
object - i.e. "fitting into the box for an Account
object".
In Java we simply have a reference to the original object so that object never changes - there is no slicing performed.
© 2006
Dr. Derek Molloy
(DCU).