Java Out Parameter

Sheeraz Gul Apr 01, 2022
Java Out Parameter

Java doesn’t support keywords like out and ref like C# to pass by reference in the methods because values only pass parameters in Java. The value also passes even the references.

To achieve something like out and ref like C# to pass by reference in Java, we must wrap the parameters inside an object and pass that object reference as a parameter. This tutorial demonstrates how to achieve the same output as the out parameter of C# in Java.

the Out Parameter in Java

As mentioned above, Java doesn’t support the out parameter; we can achieve this C# functionality by wrapping a primitive to a class or using an array to keep multiple returned values. We can call back that value via passing by reference.

See an example; first, the C# program with the out keyword and the Java program perform the same by simply passing by value.

using System;
class Out_Parameter {
    static void Divide(int x, int y, out int divide_result, out int divide_remainder) {
        divide_result = x / y;
        divide_remainder = x % y;
    }
    static void Main() {
        for (int x = 1; x < 5; x++)
            for (int y = 1; y < 5; y++) {
                int result, remainder;
                Divide(x, y, out result, out remainder);
                Console.WriteLine("{0} / {1} = {2}r{3}", x, y, result, remainder);
            }
    }
}

The C# program above uses out parameters to calculate division and remainder.

Output:

1 / 1 = 1r0
1 / 2 = 0r1
1 / 3 = 0r1
1 / 4 = 0r1
2 / 1 = 2r0
2 / 2 = 1r0
2 / 3 = 0r2
2 / 4 = 0r2
3 / 1 = 3r0
3 / 2 = 1r1
3 / 3 = 1r0
3 / 4 = 0r3
4 / 1 = 4r0
4 / 2 = 2r0
4 / 3 = 1r1
4 / 4 = 1r0

Now let’s try to achieve the same out parameter functionality in Java by passing the parameter by value.

package delftstack;

public class Out_Parameter {
	static void divide(int x, int y, int divide_result, int divide_remainder) {
        divide_result = x / y;
        divide_remainder = x % y;
        System.out.println(x +"/"+ y + " = "+ divide_result + " r " + divide_remainder);
    }
    public static void main(String[] args) {
        for (int x = 1; x < 5; x++)
            for (int y = 1; y < 5; y++) {
                int result = 0, remainder = 0;
                divide(x, y, result, remainder);
            }
    }
}

The code above will give the same output as C# out.

1/1 = 1 r 0
1/2 = 0 r 1
1/3 = 0 r 1
1/4 = 0 r 1
2/1 = 2 r 0
2/2 = 1 r 0
2/3 = 0 r 2
2/4 = 0 r 2
3/1 = 3 r 0
3/2 = 1 r 1
3/3 = 1 r 0
3/4 = 0 r 3
4/1 = 4 r 0
4/2 = 2 r 0
4/3 = 1 r 1
4/4 = 1 r 0
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Java Parameter