Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java method changes the variable which was passed to it

I was trying to implement encryption in my program and ran into some difficulties with methods. I have a unencrypted array, which should stay unencrypted and another array which I would like to encrypt. However, when I call the method it encrypts both arrays.

import java.util.Base64;

public class test {
    public static void main(String[] args) {
        String[] arr = {"1", "2"};
        String[] arrEncrypted = encryption(arr);
        System.out.println(arr[0]);
        System.out.println(arrEncrypted[0]);
    }
    public static String[] encryption(String[]  data) {
        for (int i = 0; i < data.length; i++) { // get each element of data
            String encodedString = Base64.getEncoder().encodeToString(data[i].getBytes()); // encryption
            data[i] = encodedString; // reassign
        }
        return data;
    }
}

I cannot find out an issue because in my understanding I return encrypted data and assign it to another array, but for some reason an array which I passed changes too.

Here is the output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

MQ== //has to be 1
MQ== //correct

Thanks in advance for the help!

>Solution :

When you invoke encryption(arr) you are passing the value of the reference for that object through, which means you end up directly mutating it. If you did not return data and declared encryption as void return, your input array would still be "encrypted."

If you’d like to solely return a new array without modifying the input, you can initialise a new, empty String[] of the same length as the input, and assign elements to it in your for loop.

For example,

    public static String[] encryption(String[]  data) {
        String[] encrypted = new String[data.length];
        for (int i = 0; i < data.length; i++) { // get each element of data
            String encodedString = Base64.getEncoder().encodeToString(data[i].getBytes()); // encryption
            encrypted[i] = encodedString; // reassign
        }
        return encrypted;
    }

Please see Is Java "pass-by-reference" or "pass-by-value"? for a thorough explanation of what’s going on under the hood when you pass in your data argument.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading