Java Arrays PDF
Java Arrays PDF
Java Arrays It's possible to declare and allocate memory of an array in one
statement. You can replace two statements above with a single
An array is a container that holds data (values) of one single type. For statement.
example, you can create an array that can hold 100 values
of int type.Array is a fundamental construct in Java that allows you to int[] age = new int[5];
store and access large number of values conveniently.
double[] data;
0
0
0 Let's write a simple program to print elements of this array.
0
0
1. class ArrayExample {
There is a better way to access elements of an array by using looping 2. public static void main(String[] args) {
construct (generally for loop is used). 3.
1. class ArrayExample { 4. int[] age = {12, 4, 5, 2, 5};
2. public static void main(String[] args) { 5.
3. 6. for (int i = 0; i < 5; ++i) {
4. int[] age = new int[5]; 7. System.out.println("Element at index " + i
5. +": " + age[i]);
6. for (int i = 0; i < 5; ++i) { 8. }
7. System.out.println(age[i]); 9. }
8. } 10. }
9. }
10. } When you run the program, the output will be:
int[] age = {12, 4, 5, 2, 5}; You can easily access and alter array elements by using its numeric
index. Let's take an example.
When you run the program, the output will be: Sum = 36
Average = 3.6
Element at index 0: 34
Element at index 1: 0 Couple of things here.
Element at index 2: 14 • The for..each loop is used to access each elements of the array.
Element at index 3: 0
Learn more on how for...each loop works in Java.
Element at index 4: 0
• To calculate the average, int values sum and arrayLength are
converted into double since average is double. This is type casting.
Learn more on Java Type casting.
Example: Java arrays
• To get length of an array, length attribute is used.
The program below computes sum and average of values stored in an
Here, numbers.length returns the length of numbers array.
array of type int.
1. class SumAverage {
Multidimensional Arrays
2. public static void main(String[] args) {
Arrays we have mentioned till now are called one-dimensional arrays.
3.
In Java, you can declare an array of arrays known as
4. int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9,
multidimensional array. Here's an example to declare and initialize
8, 12};
multidimensional array.
5. int sum = 0;
6. Double average; Double[][] matrix = {{1.2, 4.3, 4.0},
7.
8. for (int number: numbers) {
9. sum += number; {4.1, -1.1}
10. }
11.
12. int arrayLength = numbers.length; };
13.
14. // Change sum and arrayLength to double as
average is in double
{4, 5, 6, 9},
} 1
-2
3
}; 2
3
4
-4
Basically, 3d array is an array of 2d arrays.Similar like 2d arrays, -5
rows of 3d arrays can vary in length. 6
9
1
Example: Program to print elements of 3d array using loop 2
1. class ThreeArray { 3
2. public static void main(String[] args) {
3.
4. // test is a 3d array
5. int[][][] test = {
6. {
7. {1, -2, 3},