0

When you create a String array and give it string values are the elements in the array just pointer to the string object or do the hold the object itself. So in below code are each of the element i.e. Days[0] just a pointer to a string objects which holds the string value or is the object in the array. Does each element point to a different string object or the same object? How would this differ from a primitive type array like int[] test= new int[6], do these actually hold the int values. Thanks

String[] days = new Array[7];
Days[0] = "Sunday";
Days[1] = "Monday";
Days[2] = "Tuesday";
Days[3] = "Wednesday";
Days[4] = "Thursday";
Days[5] = "Friday";
Days[6] = "Saturday";
1
  • 1
    Days is a typo, is it (of days)? Commented Mar 6, 2014 at 9:55

1 Answer 1

3

When you create a String array and give it string values are the elements in the array just pointer to the string object or do the hold the object itself.

Object arrays always contain references to the objects not the objects themselves.

Does each element point to a different string object or the same object?

In your example each array element references a different string and thus a different object. If let's say you'd set days[6] = "Sunday"; then days[0] and days[6] would reference the same interned string (because it is a literal), but in case of days[6] = new String( "Sunday" ); both elements probably reference different but equal strings.

How would this differ from a primitive type array like int[] test= new int[6], do these actually hold the int values.

Yes, primitive arrays hold their values directly, since there are no objects to reference.

Sign up to request clarification or add additional context in comments.

3 Comments

I feel like I want to mention the Java String Pool here too.
"Object arrays always contain references to the objects not the objects themselves" And so do all non-primitve variables!
You could remove the words "most probably" from the middle paragraph. Equal String literals always reference the same interned String.

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.