logo
logo1 Home latestLatest cenCentral enggEngineering defenceDefence newsNEWS menu

Java Arrays

The Array Concept in Java is used to store multiple values similar data types in single variables of fixed size. This gives the freedom of storing similar data types under one entity. This makes memory efficient, and datas stored in contiguous memory location. The length of the array is determined during creation and it is fixed. Arrays in java is index based starts from 0.

Java Array Syntax

datatype[] array;
datatype array[];
* To create Java Array Object/ Instantiation of Array Object
datatype[] array = new datatype[];
datatype array[] = new datatype[];

* To create String array object/instantiation in java
String[] arr = {"dog","cat","birds"}
* To create integer array object/instantiation in java
int[] arr = new int[];
int arr[] = new arr[];

*Similarly, you can declare arrays of other types:
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;

Array Example

  public class ArrayDemo1 
{

  public static void main(String[] args) 
  {
    int arr[] = new int[5];
    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    arr[3] = 4;
    arr[4] = 5;
    for(int i=0;i<arr.length;i++) 
    {
      System.out.println(arr[i]);
    }

  }

}
Output :
1
2
3
4
5

Types of Java Array

1. Single Dimention Array
2. Multi Dimention Array
3. Jagged Array

Java Array :Single Dimention

import java.util.Scanner;
public class ArrayDemo 
{

  public static void main(String[] args) 
  {
      int[] arr = new int[3];
      Scanner sc = new Scanner(System.in);
      for(int i=0;i<3;i++) 
      {
        System.out.println("Enter the value "+i);
        arr[i] = sc.nextInt();
      }
      System.out.println("Output");
      for (int j=0;j<arr.length;j++) 
      {
        System.out.println(arr[j]);
      }

  }

}

  
Output
Enter the value 0
1
Enter the value 1
2
Enter the value 2
3


1 2 3

Advantages of Java Array

* Can store similar elements in a single varible,
* Simple to store large amount of data,
* Data can be accessable through index value in of an array,
* Can get the length of an array by using length()

Disadvantages of Java Array

* As the array is static or fixed in size,
* Only similar datatypes is storeable in java array.

About Us / Contact