Arrays in java

 Array:

  • An array is a collection of similar data items, that are stored under a common name.
  • It is denoted by index or subscript enclosed in square brackets, i.e. [].
  • Array value is starting with 0.
  • It is similar to the table structure.

  • It is used to reduce memory space.

Types of arrays:
  • Single dimensional arrays
  • Multidimensional arrays
1. Single dimensional arrays:
  • The collection of items can be stored under one variable name using only one subscript, such a variable is called ‘one-dimensional array or single dimensional array’.
Syntax:

 Declaring array:

Data_type array_name[];

Allocate memory:

Array_name = new data_type[size];

Example:

int a[];

a=new int[3];//There are three value can store here.

Initialize array:

Data_type []={values};

Example:

int a[]={5,8,7};

Example:
int a[5]={5,10,2,1,4};
Explanation:

Example program single dimensional array:

import java.util.Scanner;

public class One_Dimenstional_Array {

    public static void main(String args[])

    {

        int a[];

        a=new int[3];

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter two number : ");

        a[0]=sc.nextInt();

        a[1]=sc.nextInt();

        a[2]=a[0]+a[1];

        System.out.println("Additions of two number is : "+a[2]); 

    }

}

Output:
2. Multidimensional arrays:
  • Multidimensional arrays are used in a situation where a table of value needs to be stored in an array.
Array declaration of syntax:

 Data_type array_variable [row size][column size];

Example:
int a[3][3];
Explanation:
Example program multidimensional array:

import java.util.Scanner;

public class Two_Dimensional_array {

    public static void main(String args[]) {

        int std[][] = new int[4][2];

        int i, j;

        for (i = 0; i < std.length - 1; i++) {

            Scanner sc = new Scanner(System.in);

            System.out.println("Enter " + i + " student roll number and mark: ");

            std[i][0] = sc.nextInt();

            std[i][1] = sc.nextInt();

        }

        for (i = 0; i < std.length - 1; i++) {

            System.out.println("Student " + i + " roll number " + std[i][0] + 

            " and mark " + std[i][1]);

        }

    }

}

Output:
Explanation:
Share:

No comments:

Post a Comment

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me