As I'm relatively new to Java, i'm still not sure about the basic pass-by-value/pass-by-reference thing. I've read this question on SO: Is Java “pass-by-reference” or “pass-by-value”?, which seems to have some very good answers. One of the articles referenced in one such answer was Java is Pass-by-Value, Dammit!.
After reading the answers, and the article, I thought:
- Everything in Java is pass by value, there's no pass by reference (follows from the readings).
- Primitives are always passed by value (my thought)
- Objects are passed by reference (my thought)
- The point above(3) is actually wrong and Object references are passed by value (follows from the article).
So now, I'm struggling between points 3 and 4. I wrote this simple class to clear things a bit:
package Chap_1;
/**
* Created by user1 on 7/18/15.
*/
public class JavaTest1 {
private double balance;
public JavaTest1(double amt) {
balance = amt;
}
public double getBalance() {
return balance;
}
public void method1() {
JavaTest1 obj1 = new JavaTest1(300.00);
System.out.println("Balance in method1 before method2= " + obj1.getBalance());
method2(obj1);
System.out.println("Balance in method1 after method2 = " + obj1.getBalance());
}
public void method2(JavaTest1 o) {
o.balance -= 100.00;
}
public static void main(String[] args) {
JavaTest1 j1 = new JavaTest1(500.00);
System.out.println("Balance in main before= " + j1.getBalance());
j1.method1();
System.out.println("Balance in main after = " + j1.getBalance());
}
}
With this code, I get the output:
Balance in main before= 500.0
Balance in method1 before method2= 300.0
Balance in method1 after method2 = 200.0
Balance in main after = 500.0
My observations are:
- In main, things get started with one
JavaTest1
objectj1
, with a starting balance of 500.j1
then callsmethod1()
. - In
method1()
, anotherJavaTest1
object is created, with starting a balance of 300.method1()
then callsmethod2()
. - In
method2()
, an object of typeJavaTest1
is passed. This method then deducts 100 from the balance of the object reference that was passed to it. - When I run the code, I see that the balance of the object created in
method1
is reduced to 200 inmethod2()
.
Now this is where my confusion lies. If object references are passed as values, then the balance deduction in method2()
should not have modified the object created in method1()
. But since it did modify the balance, doesn't it essentially say that objects are always passed as references, proving that both method1()
and method2()
operate on the same object. Otherwise, method2(JavaTest1 o)
should have created another object of type JavaTest1
with it's reference being called o
.