ARRAYS JAVA | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

ARRAYS JAVA

public class MyClass { public static void main(String[ ] args) { int a[ ] = new int[5]; System.out.println(a [1] ); } } Why output "0"????And if we change number to "5" - we will have error. Why?? Give me pls advise where I can get more information about ARRAYS?

4th Feb 2018, 9:09 PM
Grey King
Grey  King - avatar
3 Answers
+ 4
When you create an integer array, by default, java places 0 at each index of the array. You can find more information at official java documentation https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
4th Feb 2018, 9:14 PM
Yousaf
Yousaf - avatar
+ 2
a[5] is beyond the end of the array. When you create an array like: int a[] = new int[5]; this creates an array with 5 elements. Arrays are zero based, however, and the first element is at a[0] not a[1], making the last element a[4].
4th Feb 2018, 9:23 PM
ChaoticDawg
ChaoticDawg - avatar
0
First of all You should understand difference between index of array and length of array. index of array is start with 0 length of array is start with 1 So If you store the 5 elements to the array your length of array will be 5 the number which is inside of the square brackets represent length of the array If you want to get element from the array you will use index of array. For instance, 1- Apple 2- Orange 3- Banana if you want to print Apple, System.out.println(String[1-1]); if you want to print Orange System.out.println(String[2-1]); if you want to print Banana, System.out.println(String[3-1]); So, index of 0 will be first element index of 1 will be second element ...... index of 4 will be last element in the array
2nd Aug 2020, 3:38 AM
Dogan Aykurt
Dogan Aykurt - avatar