In order to print out C, shouldn't it be (myNames[3]) and not (myNames[2])? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

In order to print out C, shouldn't it be (myNames[3]) and not (myNames[2])?

public class Program { public static void main(String[] args) { String[ ] myNames = { "A", "B", "C", "D"}; System.out.println(myNames[2]); } }

20th Jul 2016, 9:05 AM
Peti Stoik
Peti Stoik - avatar
4 Answers
+ 2
no because arrays are zero-indexed. meaning the first element in the array starts at 0. myNames[0] is A, myNames[1] is B, myNames[2] is C, myNames[3] is D. there is no myNames[4]
20th Jul 2016, 12:30 PM
Edward
+ 2
just to add to Edwards answer, if you tried to reference the fourth element like so, myNames[4] Java will throw you an out of bounds exception since arrays are 0 indexed so for for items, they're be indexed 0,1,2&3. please note that arrays are unchecked therefore trying to reference an element that is out of bounds will result in an exception.
22nd Jul 2016, 3:16 AM
Eric Gitangu
Eric Gitangu - avatar
+ 2
no because array index start from zero your index is 0,1,2,3 value is A,B,C,D then your code is right and print C
27th Jul 2016, 11:54 AM
Mohammad Reza Karimi
Mohammad Reza Karimi - avatar
- 1
when everyone already answered yet you feel like answering again
29th Jul 2016, 1:35 AM
Edward