+ 3

How fix the error

public class Main { public static void main(String args[]){ int a[]=new int[5]; a[10]=50; System.out.println(a); } }

13th Oct 2017, 6:14 AM
Prashant Kumar
Prashant Kumar - avatar
9 Answers
+ 5
After the correct initialization (int a[] =new int[11], the array is printed with a loop: for (int i=0; i<a.length; i++) { System.out.println (a[i]) ; } or in shorter way : System.out.println (Arrays.toString (a)) ; but in this case you must import : import java.util.Arrays;
13th Oct 2017, 6:47 AM
LukArToDo
LukArToDo - avatar
+ 5
You are making an array which could hold 5 elements, and you are alloting the 9th slot as 50. Why? Can a 5 gallon tank hold 10 gallon stuff?
13th Oct 2017, 6:36 AM
Meharban Singh
Meharban Singh - avatar
+ 4
System.out.println(a[elemntNumber]);
13th Oct 2017, 6:43 AM
Meharban Singh
Meharban Singh - avatar
+ 4
Since you have nothing in that element slot. Try this int a[] = new int[5]; a[3] = 5; System.out.println(a[3]);
13th Oct 2017, 6:46 AM
Meharban Singh
Meharban Singh - avatar
+ 2
@Prashant Kumar You're welcome. Keep coding and good luck šŸ‘
13th Oct 2017, 6:52 AM
LukArToDo
LukArToDo - avatar
+ 1
int a[]=new int[11]
13th Oct 2017, 6:39 AM
Stepan Bauer
+ 1
@Meharban Singh problem is same if I allot 2nd or 3rd slot in range
13th Oct 2017, 6:41 AM
Prashant Kumar
Prashant Kumar - avatar
+ 1
again output is 0
13th Oct 2017, 6:45 AM
Prashant Kumar
Prashant Kumar - avatar
+ 1
@LukArToDo Thanx
13th Oct 2017, 6:48 AM
Prashant Kumar
Prashant Kumar - avatar