Can i refer an element of one array from another array in java?

Java 8Object Oriented ProgrammingProgramming

Yes, you can −

int [] myArray1 = {23, 45, 78, 90, 10};
int [] myArray2 = {23, 45, myArray1[2], 90, 10};

But, once you do so the second array stores the reference of the value, not the reference of the whole array. For this reason, any updating in the array will not affect the referred value −

Example

Live Demo

import java.util.Arrays;

public class RefferencingAnotherArray {
   public static void main(String args[]) {
      int [] myArray1 = {23, 45, 78, 90, 10};
      int [] myArray2 = {23, 45, myArray1[2], 90, 10};
      System.out.println("Contents of the 2nd array");
      System.out.println(Arrays.toString(myArray2));
     
      myArray1[2] = 2000;
      System.out.println("Contents of the 2nd array after updating ::");
      System.out.println(Arrays.toString(myArray2));
      System.out.println("Contents of the 1stnd array after updating ::");
      System.out.println(Arrays.toString(myArray1));
   }
}

Output

Contents of the 2nd array
[23, 45, 78, 90, 10]
Contents of the 2nd array after updating ::
[23, 45, 78, 90, 10]
Contents of the 1stnd array after updating ::
[23, 45, 2000, 90, 10]
raja
Published on 09-Jan-2018 16:28:29
Advertisements