Most of the java developers get confused when it comes to the question that, is Java ‘pass-by-value’ or ‘pass-by-reference’.

The answer is that Java is pass-by-value. We will verify that in this blog under the section Pass-by-value for Object data types. Before jumping straight to the conclusion, let’s understand in detail how different variables work in java.

Common mistake done by Java developers

There is one most common mistake that java developers do. They try to update object value using “=” or “new” keyword.

Let’s look at an example where we want to change the color of box and square a number.

// Wrong – this will not return the updated value to calling method

public void changeToPink(Box boxToChange){

boxToChange = new Box(“Pink”);

}

public void square(int value){

value   =  value*value;

}

Topics we will be discussing

What is pass-by-value?

Passing variable by value means the value of the variable is copied into another variable. This copies the data into new memory.

Hence modifying new variable only updates the copy. The original variable value is not changed.

We will look in detail with examples later in this blog.

What is pass by reference?

Passing variable by reference means actual object reference or pointer is passed.

This means modifying the new reference object will update the original object.

Pass-by-value in java for primitive data types

Primitive variables are not objects. So primitive data types are pass-by-value. Which means only value is passed to new variable.

Lets look at the example for better understanding

objects references in stack for pass by value

In the above code we can see that the value of number variable is 5. Then we call the square function.

Even after calling the square function value of number variable is 5 and does not change. Because, we just updated the local(new) variable in square function. This local variable is created in the scope of the function and hence the original number variable is not updated.

How to update primitive parameter from function call?

The only way to update the original primitive variable is by returning value from the function.

Following code will update the value of number variable after calling the function.

public class Tester{
  public static void main(String args[]){
    int number = 5;         // number =5
    number = square(number):
    System.out.println(number); // number = 25
  }

  public void square(int value){
    value = value*value;    // value= 25
    return value;
  }
}

How objects are updated?

If we update the properties of object using any reference variable, values of all reference variables are updated.
In other words if you update the object not the reference variable then original object is updated.

Example if we use following code to update the color of object userBox

public class Box{ 
  String color;
    Number(String color){
    this.color = color;
  }
}

public class Tester{
  public static void main(String args[]){
    Box userBox = new Box("Purple");
    changeToPink(userBox);
    System.out.println(userBox);   // Purple 
  } 
  public staticvoid changeToPink(Box boxToChange){
    System.out.println(boxToChange);    // Purple 
    boxToChange.color="Pink"; 
    System.out.println(boxToChange);     // Pink
  }	
}
Block diagram for object reference

Using above method the object userBox in main method is also updated to pink color.

Pass-by-value in java for Object data types

In java even objects are pass by value. In fact it is passing reference as value. Even if it sounds confusing don’t worry, we can explain it.

In java every object has reference variables. So when we pass object to another function the reference variable is passed. So the references to the actual object is copied.
Now two different reference variables point to the same object. Point to be noted here is that we have two different reference variables.

public class Box{ 
  String color;
  Box(String color){
    this.color = color;
  }
}

public class Tester{ 
  public static void main(String args[]){ 
    Box userBox = new Box("Purple");
    changeToPink(userBox);
    System.out.println(userBox);   // Purple
  }

  public void changeToPink(Box boxToChange){
    System.out.println(boxToChange); // Purple
    boxToChange = new Box("Pink"); 
    System.out.println(boxToChange); // Pink
  }
}
New object workflow

In the above code we have object userBox with color “purple”. Now call the function changeToPink(). Even after calling the function changeToPink(), color of the user box remains “Purple”.

When you use new keyword new object is created. The new box with pink color is stored in local/new variable(boxToChange). Original object userbox remains with old color purple.

Conclusion

As we can see that the updated reference variable does not update the original object. So we can say when we call the function new reference to same objecect is created, so only reference address is passed as value .

Fast track reading

Related topics

“This” keyword in java is one of the most used and very important keywords.
“This” keyword in java is used to refer current class objects.
We can use this keyword to access current class object members.

Image of boy for understanding this keyword in java

So you might be wondering if we can access the current class member directly, Why do we need this keyword?

One of the answer is that, if we have same name for method level and class level variable, then there is an ambiguity for JVM. JVM can not use class variable and uses the local variable by default. In such a case we can use “this” keyword for referring the class level variable.

6 uses of “this” keyword in java

  1. Accessing class level variable
  2. Accessing class methods – default
  3. For calling other constructor of same class
  4. Using ‘this’ keyword as return value
  5. Passing ‘this’ keyword as argument to method
  6. Passing this keyword as argument to constructor

1. Accessing class level variable

Assessing class level variable using this keyword is the most common use of “this” keyword.

Syntax: this.variableName

Most of the time we create some variable in class, then we can set the value from constructor or setter method. If we use same name for argument variable and class level variable then jvm will use local variable always, and it will not set the value to class level variable

lets take a look at example for better understanding,

public class Country{
private String name;
public Country(String name){
Wrong: name = name;
Right: this.name = name;
}
}

As shown in the above example if we just use name =name, value from argument will not be assigned to the class level variable. So the class level variable will always be null. This is because we set value to same variable not the class level variable.

The correct solution is to use this.name = name;

2. Accessing class methods using “this” keyword

For calling the same class method we can use this keyword.

However using this keyword for calling same class method is optional. Because even if you don’t use this keyword, jvm always calls the method from same class by default.

Syntax: this.methodName(arguments);

Following examples shows two cases of calling class method with and without this keyword. In both cases the same method is called.

public class Dog{
	public void testMethod(String[] args){
		printString();
		this.printString();
	}	
	public void printString(){
		System.out.println("Success);
	}
}

Output:

Success
Success

3. For calling other constructor of same class

“This” keyword in java can be used to call other constructor of same class.

Some times we have different constructors with different parameters then you can reuse existing constructor using “this” keyword.
We can call any type of constructor within any constructor. That is we can call default in parameterized, parameterized in defatul or parameterized in parameterized constructor.

Syntax: this() or this(args)

The most important thing to note is that the use of “this” for calling other constructor should be the first line in constructor.

Let’s assume we have a class, let’s call it SomeClass. In this class we have a default constructor and a constructor with variable.
There is some default code that is required for at object creation. So we have added this code in default constructor.
Now we need the same code from default constructor in parameterized constructor. So in this case we can call default constructor from another constructor using this();

public class SomeClass{
	private int variable ;

	public SomeClass(){
		// some code...
	}
	public SomeClass(int variable ){
		this()
		this.variable = variable ;
	}
}

Lets take look at real life examples for shape class. In this class we have length and breadth variables. we need two constructors.
Fist constructor will take two arguments for length and breadth.
Second constructor will take only one argument, this will be same value for length and breath.

public class Shape{
	private int length ;
	private int breadth;

	public Shape(int length ,int breadth){
		this.length = length ;
		this.breadth = breadth;
	}

	public Shape(int length ){
		this(length,length);
	}
}

In above examples we are reusing constructors using “this” keyword in java.

4. Using “this” keyword as return value in java

If you need to return current object instance we can use “this” keyword.
Builder design pattern is one of the most common example of this case.

Let’s look at an example for better understanding,

public class MenuBuilder{
	List<Menu> menus = new ArrayList<>();

	public MenuBuilder withAdd(){
		menus.add(new Menus("Add"))
		 return this;
	}
}

As you can see in the above example, we used “this” as return value in withAdd() Method. In above example withAdd() method returns the current class object.

5. Passing “this” keyword as argument to method

If we want to call some method and the method needs current class object as argument, we can use this keyword to pass the current class object instance.

We can pass this as argument to current class as well as another class methods.

public class City{
	private String name;
	private Country country;
	
	public City(String name){
		this.name= name;		
	}
	public void setCountry(Country country){
		this.country = country;		
	}
}
public class Country{
	private City capital;
	
	public void setCapital(String cityName){
		City capital = new City(cityName);

	// passing country class object using this keyword
		capital.setCountry(this);
		this.capital = capital;		
	}
}

As shown in the above example, we have City and Country class. In City class setCountry() method needs object of Country class. So we have passed Country class instance using “this” keyword from Country class.

6. Passing “this” keyword as argument to constructor

Similar to passing as argument to another method we can also pass “this” keyword as argument to constructor of another class.

We can pass this as argument to constructor of current class as well as to constructor of another class.

public class City{
	private String name;
	private Country country;
	
	public City(String name, Country country){
		this.name= name;		
		this.country = country;		
	}
}
public class Country{
	private City capital;
	
	public void setCapital(String cityName){
	// passing country class object using this keyword
		City capital = new City(cityName,this);
		this.capital = capital;	
	}
}

As shown in the above example, we have City and Country class. In City class constructor needs object of Country class. So we have passed Country class instance using “this” keyword from Country class.

Fast track reading

  • This keyword in java is used to refer current class objects
  • Using this keyword we can access current class instance variable, methods, or constructor
  • We can pass this keyword as argument to another method or constructor
  • We can return current class instance using this keyword

Related topics

Super keyword in java is one of the most used and very important keyword.

In java super keyword refers immediate super(parent) class objects.

Image of father and son for understanding super keyword in java

In java super keyword is only used in case of Inheritance. Whenever we create instance of class, parent class instance is also created. The parent class instance can be accessed by ‘ super’ keyword.

So you might be wondering, if we have inheritance then we can access the parent class member directly. So why do we need super keyword?

The answer is, if we have same member in derived(child) and parent class, then there is an ambiguity for JVM. JVM can not use parent class member so it uses the child class member by default. In such a case we can use super keyword for referring the parent object members.

3 use cases of super keyword in java

Accessing parent class

  1. Variables
  2. Methods
  3. Constructor

Accessing parent class variables

If we have variable with same name in parent and child class, then we need to use super keyword to access parent class variable.

Lets see an example for better understanding:

class Father {
    String hairColor = "Black";
}

class Son extends Father {
    String hairColor = "Blonde";

    public void printHairColor() {
        System.out.println("Parent hair color: " + super.hairColor);
        System.out.println("Child hair color: " + hairColor);
    }
}

public class Tester {
    
    public static void main(String[] args) {
        Son son = new Son();
        son.printHairColor();
    }
}

Output:

Parent hair color: Black
Child hair color: Blonde

In the above example we can see that we are having hairColor variable in Father and Son class. So in Son class we used super.hairColor to access variable from father class.

Accessing parent class methods

If we have any method with same name in parent and child class, then we need to use super keyword to access parent class method.

Lets see an example for better understanding:

class Father {
    String getHairColor(){
	return "Blonde";
    }
}

class Son extends Father {
    String getHairColor(){
	return "Blonde";
    }
    public void printHairColor() {
        System.out.println("Parent hair color: " + super.getHairColor());
        System.out.println("Child hair color: " + getHairColor());
    }
}
public class Tester {

    public static void main(String[] args) {
        Son son = new Son();
        son.printHairColor();
    }
}

Output:

Parent hair color: Black
Child hair color: Blonde

In the above example we can see that we are having getHairColor() method in Father and Son class. So in child class we have used super.getHairColor() to access method from father class.

Accessing parent class constructor

Super keyword can be used to call the parent class constructor. Using super we can call default or parameterized keyword.

In java every time we create an object of a class it calls the parent class constructor even if you don’t specify. This is called as constructor chaining.

If we specify which constructor (default or parameterized) from parent class to call, it will call the specified constructor of parent class. If you don’t specify which constructor to call, it always calls the default constructor of parent class. And if parent class does not have default constructor, then JDK throws compile time error.

We can call the parent class default constructor using super() similarly parameterized constructor using super(arg1, arg2…).

It is important that the super() should be the first line in the child class constructor.

Lets see an example for better understanding:

class Father {
    String hairColor = "Black";
	
    public Father(String hairColor) {
        this.hairColor = hairColor;
    }
    public void printHairColor() {
        System.out.println("Hair color is : " + hairColor);
    }
}
class Son extends Father {

    public Son() {
        super("Blonde");
    }
}

public class Tester {

    public static void main(String[] args) {
        Son son = new Son();
        son.printHairColor();
    }
}

Output:

Hair color is : Blonde

In the above example we can see that we are having public Father(String hairColor) in parent class. So in child Son class we used super(“Blonde”) to access parent class constructor.

Fast track reading

  • In java super keyword refers immediate parent class objects
  • In java super keyword is only used in case of Inheritance
  • Super keyword in java accesses parent class variables, methods or constructor
  • Super call for the parent class constructor should be the first line in the child class constructor
  • If you don’t specify super() in child class, JVM will provide it implicitly

References