Ask your own question, for FREE!
Computer Science 10 Online
OpenStudy (anonymous):

public class tester { public static void main(String [] args){ int[]gamma=new int[4]; for(int i=0; i<4; i++) gamma[i] = i+3; System.out.print(gamma[4]); } } Why is it out of bounds?

OpenStudy (espex):

At first glance I would say it is because you are printing gama[4] when only 0-3 exist.

OpenStudy (anonymous):

arrays use zero based referencing, so if you want the 4th element you'd say gamma[3], if you want the first you'd say gamma[0]

OpenStudy (anonymous):

You are asking it to print gamma[4] when it simply doesn't exist! You created an array of size 4 when you said int[]gamma=new int[4] This means you created an array that has indexes 0,1,2,3. Index 4 does not exist. If you wanted to print index 4 you would have had to create an array of size 5 ie(int[] gamma= new int[5] Hope this helps!

OpenStudy (anonymous):

The arrays in Java are Zero-Index based, i.e. they start with 0 index and end in [ Total Items - 1 ], So, your case you're getting Out-Of-Bounds error as the gamma[4] is exceeding the last index of your array.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!