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";
user1156718
  • 59
  • 1
  • 1
  • 7

1 Answers1

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.

Thomas
  • 87,414
  • 12
  • 119
  • 157
  • 1
    I feel like I want to mention the [Java String Pool](http://stackoverflow.com/questions/2486191/java-string-pool) here too. – Dan Temple Mar 06 '14 at 10:01
  • "Object arrays always contain references to the objects not the objects themselves" And so do all non-primitve variables! – piet.t Mar 06 '14 at 10:09
  • You could remove the words "most probably" from the middle paragraph. Equal String literals always reference the same interned String. – Dawood ibn Kareem Mar 06 '14 at 10:10