×

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep in mind in this situation is that pass-by-value is used when passing a primitive type to a method. Java enables pass by value; pass by reference cannot be used to directly provide primitive types to a method.

However, pass-by-reference is always used to implicitly pass all non-primitive types, which include objects of any class.

Passing a variable by value essentially means sending its actual value, whereas passing a variable by reference essentially means sending the memory location of the variable where it is stored.

Refer the following example to understand how pass-by-reference work:

PassByReference.java

class PassByReference {
     /* we are creating a class named passByReference through which we access the
      * objects of this class
      * we pass the ojects with the help of this class name to the instance
      * methods of the same class.
      * this means with the passed object reference we access the instance 
      * variables of this class
      */
    int a = 10;
    void refer(PassByReference pbr) {
        pbr.a = pbr.a+10; // accessing or updating instance variable with object 
                          // reference
    }
    public static void main(String[] args) {
        PassByReference pbr = new PassByReference();
        System.out.println("Before pass-by-reference: " + pbr.a);
        //value before upadating 
        pbr.refer(pbr);
        System.out.println("After pass-by-reference: " + pbr.a);
         //after updating through object reference
    }
}

Output:

Java Pass-by-Reference

Generally, primitive data types are passed by value, but they can be accessed through object reference.

This can be done in three ways:

  • Inside a class, make the member variable public.
  • Return a value from a method and update the same inside the class.
  • Make a single element array and send it to the method as a parameter.

Mistakes to be rectified with object reference:

  • attempting to reference-modify an immutable value.
  • attempting to reference-modify a primitive variable.
  • When you modify a mutable object argument in a method, the expected behaviour of the real object remains unchanged.

Points to be noted:

  • Java always sends value-based parameter variables.
  • Java object variables always refer to the actual object's memory heap location.
  • When an object is passed to a method, its value can be altered.
  • Even if a new value is supplied to an immutable object, its value cannot be altered.
  • Passing a copy of the item is referred to as "passing by value."
  • Passing a variable's actual memory reference is referred to as "passing by reference."

Related Topics

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

What are Array strings in Java?

In normal programming, An array is a group and a collection of identical forms of data that are stored in a sequential memory region and may be accessed using their...

4 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Various Operation on Queue using Linked List in Java

We keep track of front and rear pointers in a queue data structure. The head of the line points to the first item, and the back to the last. Rear is...

3 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.