1

So is it possible to reference another array element from within a different array?

Like this

String[] array1 = new String[] {"World"};
String[] array2 = new String[] {"Hello", array1[0]};

array1[0] = "David";

for(String element : array2)
   System.out.print(element);

When I try to print the array, it just prints HelloWorld and not HelloDavid

Is this possible? If not, is this possible using variables?

2
  • Sound like you want something like C++... Commented Mar 26, 2013 at 16:56
  • 1
    Does this give you a hint : String[] array1 = new String[] {"World"}; String[] array2 = new String[] {"Hello", array1[0]}; array1[0] = "David"; array2[1] = array1[0]; for(String element : array2) System.out.print(element); } Commented Mar 26, 2013 at 17:01

2 Answers 2

7

What you have is valid, but the output will be HelloWorld, not HelloDavid

Although array1[0] will have a new value, array1 will be unaffected as it stores the String value reference, not the array reference, so when the array reference gets updated the Strings referenced in the array are no altered

Edit

Following on from your question what you're looking for is pointer functionality (as provided by C++). The following multi-dimensional solution isn't exactly the same and its pretty clunky, but it would do what you wanted:

    String[] array1 = new String[]{"World"};
    String[][] array2 = new String[][]{new String[] {"Hello" }, array1};

    array1[0] = "David";

    for (String[] element : array2)
        System.out.print(element[0]);

    ==> output: HelloDavid
Sign up to request clarification or add additional context in comments.

1 Comment

So is there a way to edit array1[0] and than print array2 with the updated array1[0]?
0
String[] array2 = new String[] {"Hello", array1[0]};

In above code you are creating an array called array2 whose 0th index is containing the reference of String literal "Hello" and 1st index is containing the reference of String literal("World") present in StringPool to which array1[0] is also referencing . According to JLS3.10.5-1 array2[1] is changed by compiler as follows:

String[] array2 = new String[] {"Hello", "World"};

Now in line :

array1[0] = "David";

You make array[0] to contain the reference of the String "David" newly created in StringPool. But it is not going to change the element present at index 1 of array2. Since array2[1] is already referring to String literal "World" present in StringPool.
You would have get "HelloDavid" output if you make following changes in your code:

array1[0] = "David";
array2[1] = array1[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.