Java Arrays

 

Array is an object that contains a collection of elements.

What are the characteristics of an Array?
1. Array elements must be of the same data type.
2. Array size must be fixed and cannot be changed.

How to create an array?

int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

String[] names;
names = new String[3];
names[0] = "Folau";
names[1] = "Kinga";
names[2] = "Laulau";

int[] ids = {1,2,3};

How to access array elements?
Use the position of the element in the array to access the element.

int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

int sum = numbers[0] + numbers[1] + numbers[2];
System.out.println("sum: "+sum);//60

Advantages of arrays
1. We can access the elements at any position.

Disadvantages of arrays
1. Size of the array does not grow at runtime.

There are two types of arrays:
1. Single dimensional array
2. Multidimensional array

Single Dimensional Array
A single dimensional array is what we have been using so far.

Multidimensional Array

int[][] numbers = new int[2][2];
numbers[0][0] = 1;
numbers[0][1] = 2;
numbers[1][0] = 3;
numbers[1][1] = 4;

 

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *