Array

What is array:

Array is a special type of variable that is used for storing similar types of data. Suppose, 10 students are in a class. you can store name of the students in an array and retrieve any data.
Array can be declare by this syntax:
datatype[] arrayName;
datatype can be int, double, char, String anything and arrayName is name of array name. Array starts from [0] index. It has fixed storage size which need to be declared while storing data in array.

How to store data in array:

Process 1:
String[] array = {“data1″,”data2″,”data3″,”data4″,”data5”}

Process 2:
String[] array=new String[5] //declaring array size
array[0]=”data1″;
array[1]=”data2″;
array[2]=”data3″;
array[3]=”data4″;
array[4]=”data5″;

Example for process 1:

public class Main {
    public static void main(String[] args) {
        String[] array={"Rahim","Karim","Jamal","Kamal"};
        for (String name:array) {
            System.out.println(name);
        }
    }
}
Output:
Rahim
Karim
Jamal
Kamal

Example for process 2:

public class Main {
    public static void main(String[] args) {
        String[] array=new String[4];
        array[0]="Rahim";
        array[1]="Karim";
        array[2]="Jamal";
        array[3]="Kamal";

        System.out.println(array[0]);
        System.out.println(array[1]);
        System.out.println(array[2]);
        System.out.println(array[3]);

    }
}
Output:
Rahim
Karim
Jamal
Kamal

What is ArrayList:

ArrayList in Java is used to store dynamically sized collection of elements. It grows its size automatically when new elements are added to it.

Example of ArrayList:

import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<String> people = new ArrayList<>();

        // Adding new elements to the ArrayList
        people.add("Rahim");
        people.add("Karim");
        people.add("Jamal");
        people.add("Kamal");

        System.out.println(people);

        // Adding an element at a specific index in an ArrayList
        people.add(2, "Kader");

        System.out.println(people);
    }


}
Output:
[Rahim, Karim, Jamal, Kamal]
[Rahim, Karim, Kader, Jamal, Kamal]

Here is some examples for Array.


about author

admin

salmansrabon@gmail.com

If you like my post or If you have any queries, do not hesitate to leave a comment.

Leave a Reply

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