Arrays in Java

What is an array ?




  • An array is a container object that holds a fixed number of values of a single type. 
  • This is used to store fixed size sequential collection of same type data.
  • It means this is a simple type of data structure.

How to create an array ?



There are three steps when you are going to create an array
  1. Declare array
  2. Construct array
  3. Initialize array

Declare a array

Arrays can be declared as follows.

        Datatype [] Arrayname ;
        Datatype Arrayname [] ;

Look following the examples for understand.

        int marks[]; String names[]; int [] ages;

Construct an array

You can construct an arrays using new keyword. 

       Datatype [] Arrayname  = new Datatype [];

Please look at following examples.
      
       int marks[] = new int[10]; or you can use as follows.

       int marks[] ; 
       marks = new int[];

Initialize an array

Initialize means, fill the array. Look at followings.
       int marks[0] = 10;
       int marks[1] = 10;
       int marks[2] = 10;
       int marks[5] = 10;

Anonymous arrays

You can declare and initialize arrays in simple manner as follows.
         int marks [ ] =  {10,20,30,40};

You may look at following example to understand about arrays.

public class ArrayDemo {
 public static void main(String args[]) {

  int marks[] = new int[3];
  marks[0] = 10;
  marks[1] = 50;
  marks[2] = 80;
  System.out.println(marks[1]);

  String names[] = { "Ravi", "Sean", "John" };
  System.out.println(names[0]);

  char grade[] = { 'A', 'B', 'C' };
  System.out.println(grade[2]);
 }
}


Array length attribute

This can be used to get the length of a array.

public class ArrayLengthDemo {
 public static void main(String args[]) {

  int marks[] = new int[3];
  int ages [] = {26,28,24,30};

  System.out.println(marks.length);
  System.out.println(ages.length);
 }
}


2D arrays

Look at the following example. In this table it has columns and rows. Generally 2D arrays can be declare as follows.

         int [][] = new int [2][3];




You may look at the following example to understand about arrays. 


public class ArrayDemo{
 public static void main(String args[]) {

  int i, reg = 0, marks = 0;

  Scanner scn = new Scanner(System.in);
  int arr[][] = new int[10][2];

  for (i = 0; i < 5; i++) {
   System.out.print("Enter reg number: ");
   reg = scn.nextInt();
   arr[i][0] = reg;

   System.out.print("Enter your marks: ");
   marks = scn.nextInt();
   arr[i][1] = reg;
  }

  System.out.println("\n-----Marks table-----\n");
  System.out.println(" Reg No \t Marks");

  for (i = 0; i < 5; i++) {
   System.out.print(" " + arr[i][0]);
   System.out.println("\t\t " + arr[i][1]);
  }
 }
}

Arrays in Java Arrays in Java Reviewed by Ravi Yasas on 7:39 AM Rating: 5

No comments:

Powered by Blogger.