177k views
2 votes
Java Array question.

Thank you for help!

Give the contents of the val array after running the following code:

int [] val = { 3, 10, 44 };
int i = 1;
val[i] = val[i + 1];
Question 2 options:

1) 3 2 44

2) 2 10 44

3) 3 44 44

4) 3 11 44

User Qasta
by
4.8k points

1 Answer

4 votes

Answer:

3) 3 44 44

Step-by-step explanation:

Given data

int [] val = { 3, 10, 44 };

The total number of parameters of given array are 3, so total length of array is also 3.

The indexing of array starts with '0', Therefore the indexes of array with length zero are: {0,1,2}

The value of array at index 0 is = 3

similarly

value at index 1 = 10

value at index 2 = 44

Here, Int i = 1 is storing the value '1' in integer variable i.

In addition to that, any value of index 'i' of an array is selected using array[i].

Therefore,

val[i] is selecting the value of array located at index '1' because i = 1.

val[i] = val[1] = 10

val[i+1] is selecting the value of array located at index 'i+1' that is (1+1) =2

val[i+1] = val[2] = 44

Finally,

val[i] = val[i + 1]; is copying the value placed at index 2 (44) to value placed at index 1 (10). Hence, the output would be {3 44 44}. So 3rd option is correct.

User PeeS
by
4.2k points