Arrays in JAVA

If the information to be stored in a computer is minimum,  a variable can be used. If information to be stored and retrieved is huge then use of a variable for storing and retrieving becomes inefficient.

In order to efficiently manage the data, arrays can be used.

Array is collection of homogenous type of data stored in contiguous manner.
Array datatype can be int, float, char

The steps involved in declaring an array are:

  1. Declare an array using a variable.
    int array[];   or   int []array  or int[] a;
  2. Using new operator allocates the required no. of blocks.
    array = new int[10];
  3. The address returned by the new operator must be collected by the array variable.
    array new int[10];
Syntax:  datatype arrayname[] = new datatype[ size ];
Example: int[] a = new int[10];

Here arrays are not normal variables, we need to treat array in a different way. Here arrays can be accessed by index. They are stored according to the index showed in the following image. Arrays are stored in a linear manner are also called as 1-D array or One Dimensional array. 

1-d array

The index is assigned from [0] to [size – 1] | in the following example a[0] to a[9]. The data can be stored according to the data type we assign. It is accessible through the index we assigned, for example, to print the data at 6th position means 5th index

System.out.println(a[5]); // it will give output : 6

To process the array element or to assign values and access the values in array follow, this example.

Array values can be assigned in two ways:

  1. Compile the time [in program only while writing] in curly braces like:
    int[] a={1,2,3,4,5,6,7,8,9,10};
  2. Run time[ after executing your program form used ]
    as taking values from user involve the Scanner class  that we will discuss in the upcoming topics. For now, we learnt how to manually store data in an array.

For printing or accessing the data or element in array

class ArrayDemo {
   public static void main(String args[]) {
      int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };// manual storing element
      for (int i = 0; i < 10; i = i + 1) { 
      System.out.print(a[i] + " "); // will print values with space
Output: 1 2 3 4 5 6 7 8 9 10



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by

Up ↑

%d bloggers like this: