Home > Net >  Java method changes the variable which was passed to it
Java method changes the variable which was passed to it

Time:04-03

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

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

Thanks in advance for the help!

CodePudding user response:

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.

CodePudding user response:

Three things:

  1. You can't "pass a variable", you can only pass the value of a variable.

  2. The variable "arr" is not the array, it has a value which is a reference to the array.

  3. And therefore the variable "data" gets a copy of the value of "arr", which is a reference to the same array.

You should allocate a new array for the output, something like

String[] outData = new String[data.length];
  • Related