• United States
  • United Kingdom

Rafael del Nero

By Rafael del Nero , Java Developer, JavaWorld |

Tease your mind and test your learning, with these quick introductions to challenging concepts in Java programming.

Does Java pass by reference or pass by value?

You've probably heard that java passes by value, but what matters is how well you understand the concept and the code. find out what happens when you pass an object reference to a method in java..

basketball hoop score through the net java referencing by markus spiske via unsplash

Object references are passed by value

Are primitive types passed by value, passing immutable object references, passing mutable object references, take the object references challenge, what’s just happened, learn more about java.

Many programming languages allow passing parameters by reference or by value . In Java, we can only pass parameters by value . This imposes some limits and also raises questions. For instance, if the parameter value is changed in the method, what happens to the value following method execution? You may also wonder how Java manages object values in the memory heap. This Java Challenger helps you resolve these and other common questions about object references in Java.

All object references in Java are passed by value. This means that a copy of the value will be passed to a method. But the trick is that passing a copy of the value also changes the real value of the object. To understand why, start with this example:

What do you think the simpson.name will be after the transformIntoHomer method is executed?

In this case, it will be Homer! The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.

If you’re still not quite clear how this works, take a look at the figure below.

Like object types, primitive types are also passed by value. Can you deduce what will happen to the primitive types in the following code example?

If you determined that the value would change to 30, you are correct. It’s 30 because (again) Java passes object parameters by value. The number 30 is just a copy of the value, not the real value. Primitive types are allocated in the stack memory, so only the local value will be changed. In this case, there is no object reference.

What if we did the same test with an immutable String object?

The JDK contains many immutable classes. Examples include the wrapper types Integer , Double , Float , Long , Boolean , BigDecimal , and of course the very well known String class.

In the next example, notice what happens when we change the value of a String .

What do you think the output will be? If you guessed “” then congratulations! That happens because a String object is immutable, which means that the fields inside the String are final and can’t be changed.

Making the String class immutable gives us better control over one of Java’s most used objects. If the value of a String could be changed, it would create a lot of bugs. Also note that we’re not changing an attribute of the String class; instead, we’re simply assigning a new String value to it. In this case, the “Homer” value will be passed to name in the changeToHomer method. The String “Homer” will be eligible to be garbage collected as soon as the changeToHomer method completes execution. Even though the object can’t be changed, the local variable will be.

Unlike String , most objects in the JDK are mutable, like the StringBuilder class. The example below is similar to the previous one, but features StringBuilder rather than String :

Can you deduce the output for this example? In this case, because we’re working with a mutable object, the output will be “Homer Simpson.” You could expect the same behaviour from any other mutable object in Java.

You’ve already learned that Java variables are passed by value, meaning that a copy of the value is passed. Just remember that the copied value points to a real object in the Java memory heap. Passing by value still changes the value of the real object.

In this Java Challenger we’ll test what you’ve learned about object references. In the code example below, you see the immutable String and the mutable StringBuilder class. Each is being passed as a parameter to a method. Knowing that Java only passes by value, what do you believe will be the output once the main method from this class is executed?

Here are the options, check the end of this article for the answer key.

A : Warrior=null Weapon=null B : Warrior=Dragon Weapon=Dragon C : Warrior=Dragon Knight Weapon=Dragon Sword D : Warrior=Dragon Knight Weapon=Sword

The first parameter in the above example is the warriorProfession variable, which is a mutable object. The second parameter, weapon, is an immutable String :

Now let’s analyze what is happening inside this method. At the first line of this method, we append the Knight value to the warriorProfession variable. Remember that warriorProfession is a mutable object; therefore the real object will be changed, and the value from it will be “Dragon Knight.”

In the second instruction, the immutable local String variable will be changed to “Dragon Sword.” The real object will never be changed, however, since String is immutable and its attributes are final:

Finally, we pass null to the variables here, but not to the objects. The objects will remain the same as long as they are still accessible externally--in this case through the main method. And, although the local variables will be null, nothing will happen to the objects:

From all of this we can conclude that the final values from our mutable StringBuilder and immutable String will be:

The only value that changed in the changeWarriorClass method was warriorProfession , because it’s a mutable StringBuilder object. Note that warriorWeapon did not change because it’s an immutable String object.

The correct output from our Challenger code would be:

D : Warrior=Dragon Knight Weapon=Sword.

Video challenge! Debugging object references in Java

Debugging is one of the easiest ways to fully absorb programming concepts while also improving your code. In this video you can follow along while I debug and explain object references in Java.

Common mistakes with object references

  • Trying to change an immutable value by reference.
  • Trying to change a primitive variable by reference.
  • Expecting the real object won't change when you change a mutable object parameter in a method.

What to remember about object references

  • Java always passes parameter variables by value.
  • Object variables in Java always point to the real object in the memory heap.
  • A mutable object’s value can be changed when it is passed to a method.
  • An immutable object’s value cannot be changed, even if it is passed a new value.
  • “Passing by value” refers to passing a copy of the value.
  • “Passing by reference” refers to passing the real reference of the variable in memory.
  • Get more quick code tips: Read all of Rafael's articles in the InfoWorld Java Challengers series.
  • Check out more videos in Rafael's Java Challengers video playlist .
  • Find even more Java Challengers on Rafael's Java Challengers blog and in his book, with more than 70 code challenges .

This story, "Does Java pass by reference or pass by value?" was originally published by JavaWorld .

Next read this:

  • Why companies are leaving the cloud
  • 5 easy ways to run an LLM locally
  • Coding with AI: Tips and best practices from developers
  • Meet Zig: The modern alternative to C
  • What is generative AI? Artificial intelligence that creates
  • The best open source software of 2023
  • Programming Languages

Copyright © 2020 IDG Communications, Inc.

java assignment by value or reference

DZone

  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
  • Manage My Drafts

Data Engineering: Work with DBs? Build data pipelines? Or maybe you're exploring AI-driven data capabilities? We want to hear your insights.

Modern API Management : Dive into APIs’ growing influence across domains, prevalent paradigms, microservices, the role AI plays, and more.

Programming in Python: Dive into the Python ecosystem to learn about popular libraries, tools, modules, and more.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

  • Singleton: 6 Ways To Write and Use in Java Programming
  • Creating a Deep vs. Shallow Copy of an Object in Java
  • Java String: A Complete Guide With Examples
  • Java: A Time-Tested Programming Language Still Going Strong
  • Leveraging Apache Airflow on AWS EKS (Part 2): Implementing Data Orchestration Solutions
  • Vector Databases: Unlocking New Dimensions in Video Streaming
  • RocksDB: The Bedrock of Modern Stateful Applications
  • Dynamic Query Building Spring Boot With JPA Criteria Queries

Passing by Value vs. Passing by Reference in Java

While many languages put information passing into the hands of developers, all data is passed by value in java. see how to turn that restriction to your advantage..

Justin Albano user avatar

Join the DZone community and get the full member experience.

Understanding the technique used to pass information between variables and into methods can be a difficult task for a Java developer, especially those accustomed to a much more verbose programming language, such as C or C++. In these expressive languages, the developer is solely responsible for determining the technique used to pass information between different parts of the system. For example, C++ allows a developer to explicitly pass a piece of data either by value, by reference, or by pointer. The compiler simply ensures that the selected technique is properly implemented and that no invalid operation is performed.

In the case of Java, these low-level details are abstracted, which both reduces the onus on the developer to select a proper means of passing data and increases the security of the language (by inhibiting the manipulation of pointers and directly addressing memory). In addition, though, this level of abstraction hides the details of the technique performed, which can obfuscate a developer's understanding of how data is passed in a program. In this article, we will examine the various techniques used to pass data and deep-dive into the technique that the Java Virtual Machine (JVM) and the Java Programming Language use to pass data, as well as explore some examples that demonstrate in practical terms what these techniques mean for a developer.

Terminology

In general, there are two main techniques for passing data in a programming language: (1) passing by value and (2) passing by reference. While some languages consider passing by reference and passing by pointer two different techniques, in theory, one technique can be thought of as a specialization of the other, where a reference is simply an alias to an object, whose implementation is a pointer.

Passing by Value

The first technique, passing by value, is defined as follows:

Passing by value constitutes copying of data, where changes to the copied value are not reflected in the original value

For example, if we call a method that accepts a single integer argument and the method makes an assignment to this argument, the assignment is not preserved once the method returns. While one might expect that the assignment is preserved after the method returns, the assignment is lost because the value placed on the call stack was a copy of the value passed into the method, as illustrated in the snippet below:

If we execute this code, we obtain the following output:

We see that the change made to the argument passed into the process function was not preserved after we exited the scope of the function. This loss of data was due to the fact that a copy of the value held by the someValue variable was placed on the call stack prior to the execution of the process function. Once the process function exited, this copy was popped from the call stack and the changes made to it were lost, as illustrated in the figure below:

Image title

Additionally, the action of popping the call stack at the completion of the process method is illustrated in the figure below. Note that the value copied as the argument to the process method is lost (reclaimed) once the call stack is popped, and therefore, all changes made to that value are in turn lost during the reclamation step.

Image title

Passing by Reference

The alternative to passing by value is passing by reference, which is defined as follows:

Passing by reference consitutes the aliasing of data, where changes to the aliased value are reflected in the original value

Unlike passing by value, passing by reference ensures that a change made to a value in a different scope is preserved when that scope is exited. For example, if we pass a single argument into a method by reference, and the method makes an assignment to that value within its body, the assignment is preserved when the method exits. This can be demonstrated using the following snippet of C++ code:

If we run this code, we obtain the following output:

In this example, we can see that when we exit the function, the assignment we made to our argument that was passed by reference was preserved outside of the scope of the function. In the case of C++, we can see that under-the-hood, the compiler has passed a pointer into the function that points to the someValue variable. Thus, when this pointer is dereferenced (as happens during reassignment), we are making a change to the exact location in memory that stores the someValue variable. This principle is demonstrated in the illustrations below:

Image title

Passing Data in Java

Unlike in C++, Java does not have a means of explicitly differentiating between pass by reference and pass by value. Instead, the Java Language Specification ( Section 4.3 ) declares that the passing of all data, both object and primitive data, is defined by the following rule:

All data is passed by value

Although this rule may be simple on the surface, it requires some further explanation. In the case of primitive values, the value is simply the actual data associated with the primitive (.e.g 1 , 20.7 , true , etc.) and the value of the data is copied each time it is passed. For example, if we define an expression such as int x = 7 , the variable x holds the literal value of 7 . In the case of objects in Java, a more expanded rule is used:

The value associated with an object is actually a pointer, called a reference, to the object in memory

For example, if we define an expression such as Foo foo = new Foo() , the variable foo does not hold the Foo object created, but rather, a pointer value to the created Foo object. The value of this pointer to the object (what the Java specification calls an object reference , or simply reference) is copied each time it is passed. According to the Objects section (Section 4.3.1) of the Java Language Specification, only the following can be performed on an object reference:

  • Field access, using either a qualified name or a field access expression
  • Method invocation
  • The cast operator
  • The string concatenation operator  + , which, when given a  String operand and a reference, will convert the reference to a  String by invoking the  toString method of the referenced object (using  "null" if either the reference or the result of  toString is a null reference), and then will produce a newly created  String that is the concatenation of the two strings
  • The instanceof operator
  • The reference equality operators == and !=
  • The conditional operator  ? :

In practice, this means that we can change the fields of the object passed into a method and invoke its methods, but we cannot change the object that the reference points to. Since the pointer is passed into the method by value, the original pointer is copied to the call stack when the method is invoked. When the method scope is exited, the copied pointer is lost, thus losing the change to the pointer value.

Although the pointer is lost, the changes to the fields are preserved because we are dereferencing the pointer to access the pointed-to object: The pointer passed into the method and the pointer copied to the call stack are identical (although independent) and thus point to the same object. Thus, when the pointer is dereferenced, the same object at the same location in memory is accessed. Therefore, when we make a change to the dereferenced object, we are changing a shared object. This concept is illustrated in the figure below:

Image title

This should not be confused with passing by reference: If the pointer were passed by reference, the variable foo would be an alias to someFoo and changing the object that foo points to would also change the object that someFoo points to. In this case, though, a copied pointer is passed into the function, and thus, the change to the pointer value is lost once the call stack it popped.

While it is crucial to understand the concepts behind passing data in a programming language (Java in particular), many times it is difficult to solidify these theoretical ideas without concrete examples. In this section, we will cover four primary examples:

  • Assigning primitive values to a variable
  • Passing primitive values to a method
  • Assigning object values to a variable
  • Passing object values to a method

For each of these examples, we will explore a snippet of code accompanied by print statements that show the value of the primitive or object at each major step in the assignment or the argument-passing process.

Primitive Type Example

Since Java primitives are not objects, primitives and objects are treated as two separate cases with respect to data binding (assignment) and argument-passing. In this section, we will focus on binding primitive data to a variable and passing primitive data to a simple method.

Assigning Values to Variable

If we assign an existing primitive value, such as someValue , to a new variable, anotherValue , the primitive value is copied to the new variable. Since the value is copied, the two variables are not aliases of one another, and therefore, when the original variable, someValue , is changed, the change is not reflected in anotherValue :

If we execute this snippet, we receive the following output:

Passing Values to Method

Similar to making primitive assignments, the arguments for a method are bound by value, and thus, if a change is made to the argument within the scope of the method, the changes are not preserved when the method scope is exited:

If we run this code, we see that the original value of 7 is preserved when the scope of the process method is exited, even though that argument was assigned a value of 50 within the method scope:

Object Type Example

While all values, both primitive and object, are passed by value in Java, there are some nuances in passing objects by value that are made explicit when seen in an example. Just as with primitive types, we will explore both assignment and argument binding the following examples.

The variable binding semantics of for objects and primitives are nearly identical, but instead of binding a copy of the primitive value, we bind a copy of the object address. We can see this in action in the following snippet:

In this example, we expect that assigning a new Ball object to someBall (after assigning someBall to anotherBall ) does not change the value of anotherBall , since anotherBall holds a copy of the address for the original someBall . When the address stored at someBall changes, no change is made to anotherBall because the copied value in anotherBall is completely independent of the address value stored in someBall . If we execute this code, we see our expected results (note that the address of each Ball object will vary between executions, but the address in line 1 and line 3 should be identical, regardless of the specific address value):

Passing Values to Methods

The last case we must cover is that of passing an object into a method. In this case, we see that we are able to change the fields associated with the passed in object, but if we try to reassign a value to the argument itself, this reassignment is lost when the method scope is exited.

If we execute this code, we see the following output:

Although there is a large volume of output, if we take each line one at a time, we see that when we make a change to the fields of a Vehicle object passed into a method, the field changes are preserved, but when we try to reassign a new Vehicle object to the argument, the change is not preserved once we leave the scope of the method.

In the former case, the address of the Vehicle created outside the method is copied to the argument of the method, and thus both point to the same Vehicle object. If this pointer is dereferenced (which occurs when the fields of the object are accessed or changed), the same object is changed. In the latter case, when we try to reassign the argument with a new address, the change is lost because the argument is only a copy of the address of the original object, and thus, once the method scope is exited, the copy is lost.

A secondary principle can be formed from this mechanism in Java: Do not reassign arguments passed into a method (codified by Martin Fowler in the refactoring Remove Assignments to Parameters ). To ensure that no such reassignment of method arguments is made, the arguments can be marked as final in the method signature. Note that a new local variable can be used instead of the arguments if reassigned is required:

Although fundamental principles such as data binding schemes and data passing schemes can seem abstract in the realm of daily programming, these concepts are essential in avoiding subtle mistakes. Unlike other programming languages (such as C++), Java simplifies its data binding and passing scheme into a single rule: Data is always passed by value. Although this rule can be a harsh restriction, its simplicity, and understanding how to apply this simplicity, can be a major asset when accomplishing a slew of daily tasks.

Opinions expressed by DZone contributors are their own.

Partner Resources

  • About DZone
  • Send feedback
  • Community research
  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone
  • Terms of Service
  • Privacy Policy
  • 3343 Perimeter Hill Drive
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

All you need to know on by reference vs by value

All you need to know on by reference vs by value

by Szilard Magyar

gfKoji1a50mprGtRT9KEL4gPh6fNi6RGJ9CK

When it comes to software engineering there are quite a few misunderstood concepts and misused terms. By reference vs by value is definitely one of them.

I remember back in the day when I read up on the topic and every source I went through seemed to contradict the previous one. It took some time to get a solid grasp of it. I had no choice as it is a fundamental subject if you are a software engineer.

I ran into a nasty bug a few weeks back and decided to write an article so other people may have easier time figuring this whole thing out.

I code in Ruby on a daily basis. I also use JavaScript pretty often, so I have chosen these two languages for this presentation.

To understand all the concepts though we will use some Go and Perl examples as well.

To grasp the whole topic you have to understand 3 different things:

  • How the underlying data structures are implemented in the language (objects, primitive types, mutability,).
  • How variable assignment/copying/reassignment/comparison work

How variables are passed to functions

Underlying data types.

In Ruby there are no primitive types and everything is an object including integers and booleans.

And yes there is a TrueClass in Ruby.

These objects can be either mutable or immutable.

Immutable means there is no way you can change the object once it is created. There is just one instance for a given value with one object_id and it stays the same no matter what you do.

By default in Ruby the immutable object types are: Boolean , Numeric , nil , and Symbol .

In MRI the object_id of an object is the same as the VALUE that represents the object on the C level. For most kinds of objects this VALUE is a pointer to a location in memory where the actual object data is stored.

From now on we will use object_id and memory address interchangeably.

Let’s run some Ruby code in MRI for an immutable Symbol and a mutable String:

As you see while the symbol version keeps the same object_id for the same value, the string values belong to different memory addresses.

Unlike Ruby, JavaScript has primitive types.

They are — Boolean , null , undefined , String , and Number .

The rest of the data types go under the umbrella of Objects ( Array , Function , and Object) . There is nothing fancy here it is way more straightforward than Ruby.

Variable assignment , copying , reassignment and comparison

In Ruby every variable is just a reference to an object (since everything is an object).

When you assign a variable, it is a reference to an object not the object itself. When you copy an object b = a both variables will point to the same address.

This behavior is called copy by reference value .

Strictly speaking in Ruby and JavaScript everything is copied by value.

When it comes to objects though, the values happen to be the memory addresses of those objects. Thanks to this we can modify values that sit in those memory addresses. Again, this is called copy by reference value but most people refer to this as copy by reference.

It would be copy by reference if after reassigning a to ‘new string’, b would also point to the same address and have the same ‘new string’ value.

EDUJJ3qKxslYQaQU4HGqSfr4CJH5gwgu2e10

The same with an immutable type like Integer:

When you reassign a to the same integer, the memory address stays the same since a given integer always has the same object_id.

As you see when you compare any object to another one it is compared by value. If you wanna check out if they are the same object you have to use object_id.

Let’s see the JavaScript version:

Except the comparison — JavaScript uses by value for primitive types and by reference for objects. The behavior looks to be the same just like in Ruby.

Well, not quite.

Primitive values in JavaScript will not be shared between multiple variables . Even if you set the variables equal to each other. Every variable representing a primitive value is guaranteed to belong to a unique memory location.

This means none of the variables will ever point to the same memory address. It is also important that the value itself is stored in a physical memory location.

In our example when we declare b = a , b will point to a different memory address with the same ‘string’ value right away. So you don’t need to reassign a to point to a different memory address.

This is called copied by value since you have no access to the memory address only to the value.

-KYjFr8QIDdsGNMvjrsUac-V5KI6soar-ex3

Let’s see a better example where all this matters.

In Ruby if we modify the value that sits in the memory address then all the references that point to the address will have the same updated value:

You might think in JavaScript only the value of a would change but no. You can’t even change the original value as you don’t have direct access to the memory address.

You could say you assigned ‘x’ to a but it was assigned by value so a ’s memory address holds the value ‘x’, but you can’t change it as you have no reference to it.

The behavior of JavaScript objects and implementation are the same like Ruby’s mutable objects. Both copy be reference value.

JavaScript primitive types are copied by value. The behavior is the same like Ruby’s immutable objects which are copied by reference value .

Again, when you copy something by value it means you can’t change (mutate) the original value since there is no reference to the memory address. From the perspective of the writing code this is the same thing like having immutable entities that you can’t mutate.

If you compare Ruby and JavaScript the only data type that ‘behaves’ differently by default is String (that’s why we used String in the examples above).

In Ruby it is a mutable object and it is copied/passed by reference value while in JavaScript it is a primitive type and copied/passed by value.

When you wanna clone (not copy) an object you have to do it explicitly in both languages so you can make sure the original object won’t be modified:

It is crucial to remember this otherwise you will run into some nasty bugs when you invoke your code more than once. A good example would be a recursive function where you use the object as argument.

Another one is React (JavaScript front-end framework) where you always have to pass a new object for updating state as the comparison works based on object id.

This is faster because you don’t have to go through the object line by line to see if it has been changed.

Passing variables to functions is working the same way like copying for the same data types in most of the languages.

In JavaScript primitive types are copied and passed by value and objects are copied and passed by reference value.

I think this is the reason why people only talk about pass by value or pass by reference and never seem to mention copying. I guess they assume copying works the same way.

Now in JavaScript:

If you pass an object (not a primitive type like we did) in JavaScript to the function it works the same way like the Ruby example.

Other languages

We have already seen how copy/pass by value and copy/pass by reference value work. Now we will see what pass by reference is about and we also discover how we can change objects if we pass by value.

As I looked for pass by reference languages I couldn’t find too many and I ended up choosing Perl. Let’s see how copying works in Perl:

Well this seems to be the same just like in Ruby. I haven’t found any proof but I would say Perl is copied by reference value for String.

Now let’s check what pass by reference means:

Since Perl is passed by reference if you do a reassignment within the function it will change the original value of the memory address as well.

For pass by value language I have chosen Go as I intend to deepen my Go knowledge in the foreseeable future:

If you wanna change the value of a memory address you have to use pointers and pass around memory addresses by value. A pointer holds the memory address of a value.

The & operator generates a pointer to its operand and the * operator denotes the pointer’s underlying value. This basically means that you pass the memory address of a value with & and you set the value of a memory address with * .

How to evaluate a language:

  • Understand the underlying data types in the language. Read some specifications and play around with them. It usually boils down to primitive types and objects. Then check if those objects are mutable or immutable. Some languages use different copying/passing tactics for different data types.
  • Next step is the variable assignment, copying, reassignment and comparison. This is the most crucial part I think. Once you get this you will be able to figure out what’s going on. It helps a lot if you check the memory addresses when playing around.
  • Passing variables to functions usually is not special. It usually works the same way like copying in most languages. Once you you know how the variables are copied and reassigned you already know how they are passed to functions.

The languages we used here:

  • Go : Copied and passed by value
  • JavaScript : Primitive types are copied/passed by value, objects are copied/passed by reference value
  • Ruby : Copied and passed by reference value + mutable/immutable objects
  • Perl : Copied by reference value and passed by reference

When people say passed by reference they usually mean passed by reference value. Passing by reference value means that variables are passed around by value but those values are references to the objects .

As you saw Ruby only uses pass by reference value while JavaScript uses a mixed strategy. Still, the behavior is the same for almost all the data types due to the different implementation of the data structures.

Most of the mainstream languages are either copied and passed by value or copied and passed by reference value. For the last time: Pass by reference value is usually called pass by reference.

In general pass by value is safer as you won’t run into issues since you can’t accidentally change the original value. It is also slower to write because you have to use pointers if you want to change the objects.

It’s the same idea like with static typing vs dynamic typing — development speed at the cost of safety. As you guessed pass by value is usually a feature of lower level languages like C, Java or Go.

Pass by reference or reference value are usually used by higher level languages like JavaScript, Ruby and Python.

When you discover a new language go through the process like we did here and you will understand how it works.

This is not an easy topic and I am not sure everything is correct what I wrote here. If you think I have made some mistakes in this article, please let me know in the comments.

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Javatpoint Logo

Java Object Class

Java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

Example of call by value in java

Another example of call by value in java.

In case of call by reference original value is changed if we made changes in the called method. If we pass object in place of any primitive value, original value will be changed. In this example we are passing object as a value. Let's take a simple example:

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Home

Last Minute Java Object Assignment and Object Passing By Value or Reference Explained Tutorial

Java Object Assignment and Object Passing by Value or Reference Infographic

In Java, we create Classes. We create objects of the Classes. Let us know if it is possible to assign a Java Object  from one variable to another variable by value or reference in this Last Minute Java Tutorial. We also try to know whether it is possible to pass Java Objects to another method by Value or Reference in this tutorial.

You may also read about Introduction to Java Class Structure .

Java Object Assignment by Value or Reference Explained

In Java, objects are always passed by Reference. Reference is nothing but the starting address of a memory location where the actual object lies. You can create any number of references to just One Object. Let us go by an example.

We create a Class "Cloud" with a single Property called "color". It is a String object. We create 3 objects of the Cloud type.

Notice that all three references obj1, obj2 and obj3 are pointing to the same Cloud object. Thus the above example outputs the same color-property value " RED ". Later, we made the references obj2 and obj3 to point to the null location. Still the original object pointed or referenced by obj1 holds the value. So the final PRINT statement outputs "RED" as usual.

Note : Reference is also called a Variable whether Primitive or Object.

This concludes that a Java object assignment happens by Reference . But the actual value of memory location pointed by References are copied by Value only. So we are actually copying memory locations from one Reference variable to another Reference variable by Value . Interviewers ask this famous Java question just to test your knowledge. If someone asks in C language point of view , say that it is by Reference . If they ask in Java point of view , say that it is by Value. 

Java Object Passing by Value or Reference to a Method Explained

You already learnt that Object assignment in Java happens by Reference. Let us try to pass Objects to another method as a parameter or argument. We try to know whether Objects are passed by Value or Reference to another Method using the below example.

In the above example, we have created an object "obj1" of type Tractor. We assigned value of 100 to the property "height". We printed the value before passing the object to another method. Now, we passed the object to another method called "change" from the calling-method " main ". We modified the height property to 200 in the called-method . Now, we tried to print the value of the property in the Calling method. It shows that the Object is modified in the called-method.

Similarly, we can pass Java objects to the Constructor using Pass by Reference or simply Reference . 

This concludes that Java Objects are passed to methods by Reference . Here also, we pass the memory location pointed by one Reference variable to another Reference variable of a Called method as a Value only. So, you are actually passing Values (memory locations represented by integer or long data type). But the actual passed-object can only be referenced by a Reference variable. Interviewers take advantage of this tricky logic to confuse you. If someone asks in C language point of view , say that it is by Reference . If they ask in Java point of view , say that it is by Value .

Let us know more about Java Classes with different Constructors and Methods in coming chapters.

Share this Last Minute Java  Tutorial explaining Java Object Assignment using Reference and Java Object Passing with Pass by Reference with your friends and colleagues to encourage authors.

Java Class Structure Tutorial

Java Method Signature Rules Tutorial

Java, A Beginner's Guide, 5th Edition, 5th Edition by Herbert Schildt

Get full access to Java, A Beginner's Guide, 5th Edition, 5th Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Reference Variables and Assignment

In an assignment operation, object reference variables act differently than do variables of a primitive type, such as int . When you assign one primitive-type variable to another, the situation is straightforward. The variable on the left receives a copy of the value of the variable on the right. When you assign one object reference variable to another, the situation is a bit more complicated because you are changing the object that the reference variable refers to. The effect of this difference can cause some counterintuitive results. For example, consider the following fragment:

Image

At first glance, it is easy to ...

Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

java assignment by value or reference

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Reference Variable in Java

  • 'this' reference in Java
  • Scope of Variables In Java
  • Types of References in Java
  • Using Variables in JShell of Java 9
  • Passing Strings By Reference in Java
  • Java Variables
  • Final local variables in Java
  • final variables in Java
  • Final static variable in Java
  • Using Static Variables in Java
  • Variable Arguments (Varargs) in Java
  • var keyword in Java
  • Can Two Variables Refer to the Same ArrayList in Java?
  • C/C++ Pointers vs Java References
  • Rules For Variable Declaration in Java
  • Method References in Java with examples
  • Environment Variables in Java
  • Scope of Variables In Scala
  • References in C++

Before We Started with the Reference variable we should know about the following facts.

1. When we create an object (instance) of class then space is reserved in heap memory. Let’s understand with the help of an example.

Demo D1 = new Demo();

Reference Variable

Now, The space in the heap Memory is created but the question is how to access that space? .  

Then, We create a Pointing element or simply called Reference variable which simply points out the Object(the created space in a Heap Memory).  

Heap Memory

Understanding Reference variable 

1. Reference variable is used to point object/values.

2. Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java. Reference variables hold the objects/values of reference types in Java.

3. Reference variable can also store null value. By default, if no object is passed to a reference variable then it will store a null value.

4. You can access object members using a reference variable using dot syntax.

<reference variable name >.<instance  variable_name / method_name>

   

Let us see what is actually happening step by step.

1. When we create an object of demo class new DEMO(); , the default constructor is called and returns a reference of the object, and simply this reference will be stored to the reference variable D1 (As we know that associativity is Right-hand side to left-hand side).

2. The value of a reference variable is a reference. When we attempt to print the value of a reference variable, the output contains the name of the class which has been instantiated concatenated by @ and the hash code created for it by Java: the string Demo@214c265e tells us that the given variable is of type Name and its hexadecimal format of hash code is 214c265e.

3. At this point we will access the methods display() of the class demo using our custom reference variable that we created.

BINDING UP : The constructor call returns a value that is a reference to the newly-created object. The equality sign tells the program that the value of the right-hand side expression is to be copied as the value of the variable on the left-hand side. The reference to the newly-created object, returned by the constructor call, is copied as the value of the variable.

Reference accessing varibale

Note: Here we pass G1 and Q1 reference variable point out the same object respectively. Secondly At Point 1 we try to get the value of the object with G1 reference variable which shows it as 25 and At Point 2 we try to get the value of an object with D1 reference variable which shows it as 25 as well. This will prove that the modification in the object can be done by using any reference variable but the condition is it should hold the same reference.  

More on Reference Variable

1. Reference Variable as Method Parameters:

As the value of a primitive variable is directly stored in the variable, whereas the value of a reference variable holds a reference to an object. We also mentioned that assigning a value with the equality sign copies the value (possibly of some variable) on the right-hand side and stores it as the value of the left-hand-side variable. A similar kind of copying occurs during a method call. Regardless of whether the variable is primitive or reference type, a copy of the value is passed to the method’s argument and copied to that argument.

Note: Java only supports pass by value.

But we know that the reference variable holds the reference of an instance(OBJECT) so a copy of the reference is passed to the method’s argument.  

Changing Data in Heap Memory

Now, What is going on here, when we pass the reference to the method it will copy to the reference variable defined in the method signature and After that, they also have access to the object members. Here, We defined two instances named C and D . Afterwards we pass C and D to the method which further gives reference to A and B

At Point 1: A will update the value of x from 10 to 95, hence C.display() will show 95 20 but in another object D we update the value of x through D only from y =20 to 55, hence D, display() will show 10 and 55.

Note: Any Object Updation will not affect the other object’s member.

2. What if we swap the reference variables with the help of the Swap Method?

The fact is if we try to swap the reference variable, then they just swap their Pointing element there is no effect on the address of reference variable and object(Instance) Space. Let’s Understand It with the help of an example:  

Here we created, two instances of demo class and passes it to swap method, further those C and D will copy their references to A and B respectively.Before swapping A point to C’s(Object) and B point to D’s(Object). After we perform swapping on A and B, A will now point D’s(Object) and B will Point C’s Object. As described in the figure.

Swapping references

 Note: There is no swapping between Variables, They only change their References.

3. What if we pass arrays to the method will it be able to update the Actual Array’s values, even we know that a copy of the array is a pass to the formal Array?

The answer is YES, the values will be updated by Formal parameter, The Fact is, When we create an Array, a memory is assigned to the array of the desired size, and it returns the reference of the first array’s element that is the base address that will store to the Formal Array(Method argument). As we learned earlier every pointing reference variable can change or update the object.

Arrays

4. this and super keywords are also Pointing Elements.

this keyword. In java, this is a reference variable that refers to the current object.

this in Java

super is used to refer immediate parent class instance variable. We can use the super keyword to access the data member or field of the parent class. It is used if parent class and child class have the same fields.

this and super

 5. null value of a reference variable.

Demo obj = null ;  

A. The null reference can be set as the value of any reference type variable.

B. The object whose name is obj is referred to by nobody. In other words, the object has become garbage . In the Java programming language, the programmer need not worry about the program’s memory use. From time to time, the automatic garbage collector of the Java language cleans up the objects that have become garbage. If the garbage collection did not happen, the garbage objects would reserve a memory location until the end of the program execution.

Here, we try to access objects’ members by a reference variable that is pointing nothing(null), and hence it shows NullPointerException. Now if you get the error, the first step is to look for variables whose value could be null. Fortunately, the error message is useful: it tells which row caused the error. Just try it out yourself!

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

Home

The Difference Between Values and References in JavaScript

In JavaScript, you can pass by value and by reference.

The main difference between the two is that passing by value happens when assigning primitives while passing by reference when assigning objects.

Let's discuss values and references in more detail in this post.

1. Understanding primitive and objects

JavaScript provides 2 categories of data types: primitives and objects .

The primitives are numbers, booleans, strings, symbols, and special values null and undefined .

The second category is objects. Particularly the plain object, arrays, functions, and more — are all objects.

Saying it differently, anything that is not a primitive value is an object.

The simple rule of passing by value is that all primitive values in JavaScript are passed by value. Simple as that.

Passing by value means that every time you assign a value to a variable, a copy of that value is created. Every single time.

Let me show you how pass by value manifests itself.

Let's say you have 2 variables a and b :

The first statement let a = 1 defines a variable a initialized with the number 1 .

The second statement let b = a defines another variable b and initializes it with the value of a variable — which is passing by value. Simpler, a copy of the number 1 is assigned to b .

Later, b = b + 2 increases by 2 and becomes 3 . b variable changes, and this change doesn't affect the value of a .

3. References

The pass by reference, however, manifests itself differently.

When creating an object you're given a reference to that object. If 2 variables hold the same reference, then changing the object reflects in both variables.

Let's check the following code sample:

The first statement let x = [1] creates an array, defines a variable x , and initializes the variable with a reference to the created array.

Then let y = x defines a variable y , and initializes y with the reference stored in x variable. This is a pass by reference.

y.push(2) mutates the array by pushing an item 2 . Because x and y variables reference the same array, this change is reflected in both variables.

Note: for simplicity, I say that variables hold references to objects. But strictly saying variables in JavaScript hold values that are references to objects .

4. Comparing values and comparing references

Understanding the difference between values and references is important when you want to compare objects.

When using the strict comparison operator === , 2 variables having values are equal if they have the same value. All of the below comparisons are equal:

one and oneCopy have the same value 1 . The operator === evaluates to true as longs as both operands are 1 , no matter where the value is taken from: a literal 1 , variable's value, expression 2 - 1 .

But the comparison operator === works differently when comparing references. 2 references are equal only if they reference exactly the same object.

ar1 and ar2 hold references to different array instance:

ar1 and ar2 reference arrays of the same structure, however ar1 === ar2 evaluates to false because ar1 and ar2 reference different array objects.

The comparison operator returns true only when comparing references pointing to the same object: ar1 === ar11 or ar1 === ar1 .

In JavaScript primitive types are passed around as values: meaning that each time a value is assigned, a copy of that value is created.

On the other side objects (including plain objects, array, functions, class instances) are references. If you modify the object, then all variables that reference that object are going to see the change.

The comparison operator distinguishes comparing values and references. 2 variables holding references are equal only if they reference exactly the same object, but 2 variables holding values are equal if they simply have 2 same values no matter where the value originates: from a variable, literal, etc.

Often, however, you might want to compare objects by their structure rather than by reference. Check out the post How to Compare Objects in JavaScript .

Like the post? Please share!

Dmitri Pavlutin

About Dmitri Pavlutin

Popular posts.

IMAGES

  1. Paso de Parámetros en Java » ¿Paso por Referencia o Paso por Valor?

    java assignment by value or reference

  2. Is Java pass by value? or pass by reference? explained in detail

    java assignment by value or reference

  3. Passing by Value vs. Passing by Reference in Java

    java assignment by value or reference

  4. Call by Value and Call by Reference in Java

    java assignment by value or reference

  5. Java Variables Passing Examples

    java assignment by value or reference

  6. Object in java Assignment and Object Passing By Value

    java assignment by value or reference

VIDEO

  1. #20. Assignment Operators in Java

  2. Core

  3. Java

  4. Java Interview Questions #29

  5. #026 call by reference in java

  6. Assignment Operators in Java

COMMENTS

  1. Is Java "pass-by-reference" or "pass-by-value"?

    103. Java is always pass by value, not pass by reference. First of all, we need to understand what pass by value and pass by reference are. Pass by value means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.

  2. Does Java pass by reference or pass by value?

    Object references are passed by value. All object references in Java are passed by value. This means that a copy of the value will be passed to a method. But the trick is that passing a copy of ...

  3. Pass-By-Value as a Parameter Passing Mechanism in Java

    2.1. Pass-by-Value. When a parameter is pass-by-value, the caller and the callee method operate on two different variables which are copies of each other. Any changes to one variable don't modify the other. It means that while calling a method, parameters passed to the callee method will be clones of original parameters.

  4. Java is Pass by Value, Not Pass by Reference

    The method accesses the actual parameter. Often, the confusion around these terms is a result of the concept of the object reference in Java. Technically, Java is always pass by value, because even though a variable might hold a reference to an object, that object reference is a value that represents the object's location in memory.

  5. Passing by Value vs. Passing by Reference in Java

    Unlike in C++, Java does not have a means of explicitly differentiating between pass by reference and pass by value. Instead, the Java Language Specification ( Section 4.3) declares that the ...

  6. Is Java pass by Value or Reference?

    Java is always pass-by-value, NOT by reference. Unfortunately, we never handle an object at all, instead of juggling object handles called references (which are passed by value of course).

  7. All you need to know on by reference vs by value

    As you saw Ruby only uses pass by reference value while JavaScript uses a mixed strategy. Still, the behavior is the same for almost all the data types due to the different implementation of the data structures. Most of the mainstream languages are either copied and passed by value or copied and passed by reference value. For the last time ...

  8. Call by Value and Call by Reference in Java

    Another Example of call by value in java. In case of call by reference original value is changed if we made changes in the called method. If we pass object in place of any primitive value, original value will be changed. In this example we are passing object as a value. Let's take a simple example: class Operation2 {. int data=50;

  9. Java Object Assignment and Object Passing By Value or Reference

    This concludes that Java Objects are passed to methods by Reference. Here also, we pass the memory location pointed by one Reference variable to another Reference variable of a Called method as a Value only. So, you are actually passing Values (memory locations represented by integer or long data type). But the actual passed-object can only be ...

  10. java

    Object obj1=Object() Object obj2=obj1; two objects will be created. That is property values of obj1 are copied to obj2. If you do not want to create a new object, you should use pointers. Ex: Object obj1=Object() Object *obj1ref=&obj1; //this is like assigning reference in java.

  11. Reference Variables and Assignment

    Reference Variables and Assignment. In an assignment operation, object reference variables act differently than do variables of a primitive type, such as int. When you assign one primitive-type variable to another, the situation is straightforward. The variable on the left receives a copy of the value of the variable on the right.

  12. Java Assignment Operators with Examples

    Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.

  13. Reference Variable in Java

    Reference variables hold the objects/values of reference types in Java. 3. Reference variable can also store null value. By default, if no object is passed to a reference variable then it will store a null value. 4. You can access object members using a reference variable using dot syntax.

  14. Java Assignment Operators

    Compound Assignment Operators. Sometime we need to modify the same variable value and reassigned it to a same reference variable. Java allows you to combine assignment and addition operators using a shorthand operator. For example, the preceding statement can be written as: i +=8; //This is same as i = i+8; The += is called the addition ...

  15. Pass By Value and Pass By Reference In Java

    value type assignment and reference type assignment in java | pass by value vs pass by reference in java | value type assignment in java | Reference type ass...

  16. reference

    When a variable is used as argument to a method, it's content is always copied. (Java has only call-by-value.)What's important to understand here, is that you can only refer to objects through references. So what actually happens when you pass a variable referring to an object, is that you pass the reference to the object (by value!).

  17. Java Operators

    The canonical reference for building a production grade API with Spring ... We use assignment operators to assign values to variables. Next, let's see which assignment operators we can use in Java. 9.1. The Simple Assignment Operator. The simple assignment operator (=) is a straightforward but important operator in Java. ...

  18. Difference Between == and equals() in Java

    We'll start by understanding reference comparison, which is represented by the equality operator ( == ). Reference equality occurs when two references point to the same object in the memory. 2.1. Equality Operator With Primitive Types. We know that the primitive types in Java are simple, non-class raw values.

  19. Java Object Assignment

    Because java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "0".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

  20. The Difference Between Values and References in JavaScript

    The first statement let a = 1 defines a variable a initialized with the number 1.. The second statement let b = a defines another variable b and initializes it with the value of a variable — which is passing by value. Simpler, a copy of the number 1 is assigned to b.. Later, b = b + 2 increases by 2 and becomes 3.b variable changes, and this change doesn't affect the value of a.

  21. About assignment by reference and value in JAVA [duplicate]

    The first case creates two different Objects, each one with its own reference/entity in memory.Instances from the same Class, but different Objects anyway. In the second case, you assign the same Object reference to the new Dog instance: they both refer to the same Object.; The == operator compares the references of objects. In your second case, they both reference the same Dog.