Wednesday, 24 March 2021

1D and 2D arrays in java

1D arrays in java

  1. Syntax to declare an integer array in java
    int []a;  or int a[];   or int[] a;
  2. Allocating memory to store 3 integers (instantiation)
    a=new int[3];
    you can declare and instantiate in same line by writing int a[]=new int[3];
  3.  Initialization or giving values
    a[0]=2;
    a[1]=12;
    a[2]=5;
    (or) take array values from user
    for(int i=0; i< a.length;i++)
                a[i]=sc.nextInt();
    here sc is an object of Scanner class
  4. you can declare, instantiate and initialize in same line as int a[]={1,2,3,4};
  5. Displaying all elements of array using for each loop
    for(int ele: a)
            System.out.println(ele);
  6.  Displaying elements using for loop
    for(int i=0; i< a.length;i++)
                System.out.println(a[i]);
    here length is a property of arrays that will return the size of array
  7. Linear Search function in java that returns index if search element found otherwise returns -1
    public static int linearSearch(int a[],int key)
    {
           for(int i=0;i<a.length;i++)
           {
                     if(a[i] == key)
                            return i;
            }
            return -1;
    }

2D arrays in java

Declaration:
int[][] a;  or int[][] a;   or int [][]a;

Instantiation:
a = new int[3][3];
We can do declaration and instantiation in same line by writing int a[][] = new int[3][3];

Initialization and giving values
for(int i=0;i<a.length;i++)
{
           for(int j=0;j<a[i].length;j++)
                     a[i][j]=sc.nextInt();
}
here  a.length will give number of rows and a[i].length gives number of columns in each row.
and sc is object of Scanner class

Initialization, instantiation and initialization in single line
int a[][]={{1,2,3},{4,5,6},{7,8,9}};

No comments:

Post a Comment