Java Tutorial 4
Java Tutorial 4
(/) About (/about)
C# (http://www.learncs.org) Jobs (/recruitcodersjobs)
(/cn/) (/en/)
Welcome (/en/Welcome) / Arrays
Arrays
Arrays in Java are also objects. They need to be declared and then created. In order to declare a variable that
will hold an array of integers, we use the following syntax:
int[] arr;
Execute Code
Notice there is no size, since we didn't create the array yet.
arr = new int[10];
Execute Code
This will create a new array with the size of 10. We can check the size by printing the array's length:
System.out.println(arr.length);
Execute Code
We can access the array and set values:
arr[0] = 4;
arr[1] = arr[0] + 5;
Execute Code
Java arrays are 0 based, which means the first element in an array is accessed at index 0 (e.g: arr[0], which
accesses the first element). Also, as an example, an array of size 5 will only go up to index 4 due to it being 0
based.
Code Window Run Reset Solution
int[] arr = new int[5]
//accesses and sets the first element
Output Window Expected Output Show Code Window
arr[0] = 4;
(http://www.dmca.com/Protection/Status.aspx?ID=fd56e7e29e1f43ccbe7ce1023cb5781c)
Copyright © LearnJavaOnline.org. Read our Terms of Use (/tos) and Privacy Policy (/privacy)
Execute Code
We can also create an array with values in the same line:
int[] arr = {1, 2, 3, 4, 5};
Execute Code
Don't try to print the array without a loop, it will print something nasty like [I@f7e6a96.
Exercise
Change the values in numbers so it will not raise an error.
Start Exercise
(http://www.spoj.com/?utm_campaign=permanent&utm_medium=banner&utm_source=learnx)
(http://www.dmca.com/Protection/Status.aspx?ID=fd56e7e29e1f43ccbe7ce1023cb5781c)
Copyright © LearnJavaOnline.org. Read our Terms of Use (/tos) and Privacy Policy (/privacy)