• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

OCAJP – Pass by Value or Pass by Reference

November 12, 2015 //  by Krishna Srinivasan//  Leave a Comment

One of the most debated topic on Java is whether the method arguments are pass by reference or pass by value. In this tutorial, I would like to explain the same old concept with respect to the OCAJP certification. In Java, everything is pass by value. Here is the exam objective for OCAJP 7 and OCAJP 8:

6.6 – Determine the effect upon object references and primitive values when they are passed into methods that change the values

If you are here, then probably you would have heard many other saying that in Java primitive types are pass by value and objects are pass by  references. Java is a “pass-by-value” language. This means that a copy of the variable is created and the method receives that copy. Assignments made in the method will not affect the caller. In this post, I would explain that in very detail. At the end of this post, I have few mock exam questions using the same topic.

Here I will be giving you a simple example to understand what is Pass by Value and what is Pass by Reference.

Java Pass By Value

What is Pass by Reference?

Let’s say if I want to share useful information from a web page to my colleagues. If I am providing the URL to my colleagues to refer that web page, I am passing them a reference to check the web page. If I make any changes to that page, that is always reflected to that URL whenever they open for the reference.

This is known as pass by reference in the programming world. In the technical terms, passing by reference means the called methods parameter will be the same as the callers passed argument (not the value, but the identity and the variable itself)

What is Pass by Value?

In contrast, if I am providing them a print out copy of that web page for the reference, that is completely disconnected copy of that web page where the changes updated in the page (original copy) is not at all reflected to the copy. If they don’t want that copy, they can destroy that safely and it will not impact the original source.

This is known as pass by value in programming world. In the technical terms, pass by value means the called methods parameter will be a copy of the callers’ passed argument. The value will be the same, but the identity – the variable – is different. In Java, everything is strictly pass by value without any question.

In the subsequent sections I am going to explain the pass by value in Java for primitive types and object references with simple examples.

Primitive Types

Understanding primitive type is very simple and straight forward anyone who have the basic knowledge of Java. Let’s look at the following example:

public class Application {
	public static void main(String args[]) {
		int x = 10;
		int y = 20;
		swap(x,y);
		System.out.println(x);
		System.out.println(y);
		
	}
	public static void swap(int i, int j){
		int temp = i;
		i = j;
		j = temp;
	}
}

When you run the above example program, the values are not swapped and values of x and y are the same after executing the swap method. What happened behind the scene is that, copy of the x and y are passed to the method and stored in new address. Hence any changes inside that method will not affect the original values.

Object References

Most of the confusion around object references are lack of understanding on object manipulation and assignment. When you pass object reference to a method, the entire copy of the reference is passed to the method. That means, content of the reference (address / location of the actual object) is sent to the method and any changes to the object will reflect in the original object.

Look at the following example:

public class ObjectReferenceMockExam {
	public static void main(String args[]) {
		StringBuilder builder = new StringBuilder("Wonderful");
		changeStr(builder);
		System.out.println(builder.toString());
	}
	public static void changeStr(StringBuilder builder){
		builder.append(" World");
		StringBuilder builder2 = new StringBuilder("Amazing World");
		builder = builder2;
	}
}

When you run the above program, you will get the output of “Wonderful World” and not “Amazing World”. This proves that object references are pass by value.

When you create a original object StringBuilder builder= new StringBuilder("Wonderful")
Here the reference “builder” would contain the memory address say “14345”. This is just the memory address (or say remote control for accessing the StringBuilder object content). When you pass to a method, the value (memory address) 14345 is actually passed. This itself not an object content, it is just a handler for modifying the object content. Then when you create a new object inside the method with reference “builder2”, say this may contain another memory location “16785”. The replacement just swap the memory location and not the content of the object.

I hope that this is good enough to understand this concept for the exam. If you are looking for further explanation, let’s look at our friend Joe has explained nicely in his post here. In the next section we will go through few mock exam.

OCAJP Mock Exam

1. Consider the following code:

public class Main {
	public static void main(String args[]) {
		int x = 10;
		int y = 20;
		swap(x,y);
		System.out.println(x);
		System.out.println(y);
		
	}
	public static void swap(int i, int j){
		int temp = i;
		i = j;
		j = temp;
	}
}

If you run the above program, what will be the output?

A. 10 20
B. 20 10
C. 20 20
D. 10 10

2. Consider the following code:

public class Main {
	private static String str = "Hello";
	public static void main(String args[]) {
		changeStr(str);
		System.out.println(str);
	}
	public static void changeStr(String str){
		str = "Hello World";
	}
}

What will be the output of the above program?

A. Hello World
B. Hello
C. Compiler Error
D. Runtime exception

3. Consider the following code:

public class ObjectReferenceMockExam {
	public static void main(String args[]) {
		StringBuilder builder = new StringBuilder("Wonderful");
		changeStr(builder);
		System.out.println(builder.toString());
	}
	public static void changeStr(StringBuilder builder){
		builder.append("World");
		StringBuilder builder2 = builder;
		builder2.append(" for everyone");
	}
}

What will be the output of the above program?

A. Wonderful
B. Wonderful World
C. Wonderful World for everyone
D. Compiler Error

Correct Answers:

1. A

In Java, primitives are pass by value. When you call the methods, any assignment inside the method are local to that method and it doesnot affect the actual variable x and y.

2. B

The object references are pass by value, hence any assignment inside the method will not change the original value in the caller method.

An example:
Object o1 = new Object(); //Let us say, the object is stored at memory location 15000. Since o1 actually stores the address of the memory location where the object is stored, it contains 15000. Now, when you call someMethod(o1); the value 15000 is passed to the method. Inside the method someMethod(): someMethod( Object localVar) { localVar now contains 15000, which means it also points to the same memory location where the object is stored. Therefore, when you call a method on localVar, it will be executed on the same object. However, when you change the value of localVar itself, for example if you do localVar=null,
it then it starts pointing to a different memory location. But the original variable o1 still contains 15000 so it still points to the same object.

3. C

When you pass object reference in a method arguments, you actually passing the copy of that reference. That means the memory location where that actual object is stored. Any changes to the value stored in that reference would affect the original object. In the above example, though you are assigning to a local variable “builder2”, you are trying to modify the content of that reference since it modified the StringBuilder object itself.

Category: OCAJP

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « OCAJP – Static Methods and Fields
Next Post: Java Exceptions Tutorial java»

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact