Home Java Javatutorial Array in Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Array in Java

Advertisement
An Array is the static memory allocation that holds a fixed number of values of same type in memory. The size or length of an array is fixed when the array is created. Each item in an array is called an element. First element of an array starts with zero. Different types of array used in Java are One-dimensional, Two-dimensional and multi-dimensional.

An Array is the static memory allocation that holds a fixed number of values of same type in memory.

The size or length of an array is fixed when the array is created. Each item in an array is called an element. First element of an array starts with zero.

The elements are accessed by their numerical index.

Different types of array used in Java are One-dimensional, Two-dimensional and multi-dimensional.

One-dimensional arrays:

int[] i;
int[] i = new int[5];
int[] = {50,60,70,80,90};

Two-dimensional arrays:

Two-dimensional arrays are "an array of arrays".

We can have an array of ints, an array of Strings, or an array of Objects. For example:

int[][] i;
int[][] i = new int[3][4];
int[][] i = new int[3][4] {50,60,70}{80,90,100,110};

3 steps are followed while using an array in a program:

  • Declaration of an Array
  • Construction of an Array
  • Initialization of an Array

Arrays in Java for different data types can be declared as follows:

  • int[] i;
  • byte[] b;
  • short[] s;
  • long[] l;
  • float[] f;
  • double[] d;
  • boolean[] bol;
  • char[] c;
  • String[] str;

*You can also declare above arrays in different way, like:

int i[];

Construction of an array in Java:

int[] i = new int[5];

Initialization of an array in Java:

int[] = {50,60,70,80,90};

The size of this array will be 5 elements.

*There is another way to assign a value in an array:

int[0] = 50;
int[1] = 60;
int[2] = 70;
int[3] = 80;
int[4] = 90;

Example of array in Java:

import java.util.*;

public class  array{
  public static void main(String[] args){
  int num[] = {50,20,45,82,25,63};
  int l = num.length;
  int i,j,t;
  System.out.print("Given number : ");
  for (i = 0;i < l;i++ ){
  System.out.print("  " + num[i]);
  }
  System.out.println("\n");
  System.out.print("Accending order number : ");
  Arrays.sort(num);
    for(i = 0;i < l;i++){
  System.out.print("  " + num[i]);
  }
  }
}

The output of the above program will be:

Given number: 50 20 45 82 25 63

Ascending order number: 20 25 45 50 63 82

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 20, 2013

Ask Questions?    Discuss: Array in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com