Friday, September 9, 2016

JAVA: Object type Pass-By-Value vs Pass-By-Reference

The code below basically makes changes to an object inside a method, and the changes are reflected in the original object too.

This is because when we are passing an object via method arguments, we pass an alias to that object. Now, any member of the object accessed and changed inside the called method will have permanent effects.
Running the code below returns that Java passes values by reference. This is only true for object data types.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Ideone
{
 public static void main( String[] args ){
    Dog aDog = new Dog("Max");
    foo(aDog);

    if (aDog.getName().equals("Max")) { //true
        System.out.println( "Java passes by value." );

    } else if (aDog.getName().equals("Fifi")) {
        System.out.println( "Java passes by reference." );
    }
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true

    d.name = "Fifi";//<--One can use setters too. Same result
    d.getName().equals("Fifi"); // true
}
}
class Dog{
 public String name;
 
 public Dog(String name){
  this.name = name;
 }
 
 public String getName(){
  return this.name;
 }
 public void setName(String name){
  this.name = name;
 }
}





Now run this code. It'll return saying that Java passes by value. This is because once the control returns to main() method, the object reference aDog points to its previous assignment.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Ideone
{
 public static void main( String[] args ){
    Dog aDog = new Dog("Max");
    foo(aDog);

    if (aDog.getName().equals("Max")) { //true
        System.out.println( "Java passes by value." );

    } else if (aDog.getName().equals("Fifi")) {
        System.out.println( "Java passes by reference." );
    }
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true

    d = new Dog("Fifi");//<--This right here is limited to the scope of this function
    d.getName().equals("Fifi"); // true
}
}
class Dog{
 public String name;
 
 public Dog(String name){
  this.name = name;
 }
 
 public String getName(){
  return this.name;
 }
 public void setName(String name){
  this.name = name;
 }
}

2 comments:

  1. Titianium Art - TiGARIA Online Art
    Titianium Art is titanium element a premium art created by Titi and created with a mind-blowing sense of personal citizen promaster titanium art. Titianium Art is a titanium wok unique titanium chords canvas painting titanium headers for

    ReplyDelete