Do Java methods use pass-by-reference or pass-by-value?
Author: Deron Eriksson
Description: This tutorial describes how arguments are passed to methods in Java.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
Some confusion can be experienced by developers when they first start working with JavaSW method arguments. Are Java method arguments pass-by-reference or pass-by-value? They are pass-by-value, but this actually requires some clarification. This tutorial will use two Java classes to demonstrate this. The Test class contains our main method: Test.javapackage test; import java.io.IOException; public class Test { public static void main(String[] args) throws IOException { int a = 1; System.out.println("a (in main) is: " + a); doSomething(a); System.out.println("a (in main) is: " + a); MyTest myTest = new MyTest(); System.out.println("\nmyTest's x (in main) is: " + myTest.getX()); doSomething(myTest); System.out.println("myTest's x (in main) is: " + myTest.getX()); String s = "str1"; System.out.println("\ns (in main) is: " + s); doSomething(s); System.out.println("s (in main) is: " + s); try { MyTest myTest2 = new MyTest(); myTest2 = null; System.out.print("\nmyTest2's x (in main) is: "); System.out.println(myTest2.getX()); } catch (RuntimeException e) { System.out.println(e); } MyTest myTest3 = new MyTest(); System.out.println("\nmyTest3's x (in main) is: " + myTest3.getX()); doSomethingAndNull(myTest3); System.out.println("myTest3's x (in main) is: " + myTest3.getX()); } public static void doSomething(int a) { a = 2; System.out.println("a (in doSomething) is: " + a); } public static void doSomething(MyTest myTest) { myTest.setX(2); System.out.println("myTest's x (in doSomething) is: " + myTest.getX()); } public static void doSomething(String s) { s = "str2"; System.out.println("s (in doSomething) is: " + s); } public static void doSomethingAndNull(MyTest myTest3) { myTest3.setX(3); System.out.println("myTest3's x (in doSomethingAndNull) is: " + myTest3.getX()); myTest3 = null; } } The MyTest class is a basic Java class that contains an 'x' field and getter and setter methods for that field. MyTest.javapackage test; public class MyTest { int x; public MyTest() { x = 1; } public int getX() { return x; } public void setX(int x) { this.x = x; } } (Continued on page 2) |