It was simple when we had to store just five integer numbers and now lets assume we have to store 5000
integer numbers. Is it possible to use 500 variable? NO
So, to handle this situations, in almost all programming language we have a concept called Array.
Array is a data structure use to store a collection of data.
Syntax:
datatype[] variable_name = new datatype[size];
Examples
// we want to store roll numbers
int[] rollnos = new int[5];
// OR
int[] rollnos = {1,2,3,4,5};
int[] rollnos; → declaration of array.
↓
rollnos are getting defined in stack
rollnos = new int[5]; → initialization
↓
actual memory allocation happens here. Here, object is being created in heap memory.
The above concept is known as Dynamic memory allocation which means at runtime or execution time memory is allocated
int[] arr = new int[5];
used to create an object
Arrays.toString(array) → internally uses for loop and gives the output in proper format.
import java.util.Arrays
public class Arrays{
psvm(){
int[] arr = {1,2,3,4,5};
sout(Arrays.toString(arr));
}
}
output
[1, 2, 3, 4, 5]Printing 2d Array
import java.util.Arrays;
public class MultiDimensionArr {
public static void main(String[] args) {
int[][] arr = {
{1,2,3},
{4,5,6},
{7,8,9}
};
// first way
for (int i = 0; i < arr2.length; i++) {
for(int j = 0; j<arr2[i].length;j++){
System.out.print(arr2[i][j]+" ");
}
System.out.println(" ");
}
System.out.println(Arrays.toString(arr2));
// second way
// for each method
for(int [] a : arr2){
System.out.println(Arrays.toString(a));
}
}
}
Arraylist is a part of collection framework and is present in java.util.package. It provide ws with dynamic arrays in Java. It is slower then standart arrays.
Syntax
import java.util.ArrayList;
ArrayList<Integer> list = new ArrayList<>();
// Integer - class wrapper
Case
Elements in 2D array
int[][] multiArr = {
{1,2,3},
{4,5},
{6,7,8,9,10}
}
↑ Reason why we have to specify number of rows when we initialize 2D array is that we need fix number to define rows and number of column doesn't matter as it can be different.
// 1D array
import java.util.ArrayList;
public class ArrayListEx {
public static void main(String[] args) {
// we use arraylist when we don't know how much is size of row
// syntax
// ArrayList name = new ArrList<>();
ArrayList list = new ArrayList<>();
list.add(99);
list.add(100);
list.add(122);
list.add(123);
System.out.println(list);
list.set(0,101);
System.out.println(list);
}
}
// 2D array
import java.util.ArrayList;
import java.util.Scanner;
public class MultiArrList {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
// Initialization
for(int i = 0; i<3 ; i++){
list.add(new ArrayList<>());
}
// add elements
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
list.get(i).add(in.nextInt());
}
}
// Print
System.out.println(list);
}
}