Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Topics

Recent Status Updates

View All Updates

- - - - -


java array

  • Please log in to reply
No replies to this topic

#1 mdebnath


    CC Newcomer

  • Member
  • PipPip
  • 17 posts
  • Programming Language:C, Java, C++
  • Learning:C, Java, C++

Posted 17 February 2013 - 02:35 AM

Arrays are a very important data structure encountered by programmers. It is basically a collection of related items and is of fixed length entries. The variable declaration we learned so far occupies a single location of memory, on the other hand array occupies a consecutive collection of memory. But the elements contained in the array must be of same type. In this article we shall demonstrate the ways in which arrays allow programmers to organize and manipulate data.

Declaring and Creating Arrays

Like any other objects arrays are also created with the keyword new. Programmer specifies the type of the array elements and the number of elements as part of an array creation expression. Such an expression return reference that can be stored in an array variable. Arrays can be created as follows:

int [] myarray = new int[ 5 ];


int [] myarray;

myarray = new int [ 5 ];


In the declaration above, the square brackets [ ] following the variable name a indicates that a is a variable that will refer to an array and is of size 5 elements with an index starting from 0 through 4. When an array is created in Java, each element of the array receives a default value – zero for numeric primitive type elements, false for boolean elements and null for references. One can create several arrays in a single declaration such as:


String [] color = new String[3], state[] = new

The above declaration has the same meaning as:

String [] color = new String[3];

String state[] = new String[4];

When an array is declared we can combine the square
bracket at the beginning of declaration, such as

double[] val1, val2
val1 = new double[10];
val2 = new double[20];

which is equivalent to the declaration

double val1[];
val1 = new double[10];

double val2[];
val2 = new double[20];
double[] val1;
val1 = new double[10];
double[] val2;
val2 = new double[20];


Note: You can declare arrays of any type but the values should be all of similar type or homogeneous. Every element of an int array is an int value, and every element of a String array is a reference to a String object

Array creation and initialization

Arrays can be initialized at the run time as well as compile time. At compile time arrays can be initialized with an array initializer, which comma separated list of values enclosed within braces, '{' and '}' such as


int [] numbers = {0,1,2,3,4,5,6,7,8};
String [] colors = {“red”, “green”, “blue”};

In this case, the array length is determined by the number of elements in the list. Let write a program to illustrate the point of array initialization at compile time as well as run time. Run time array initialization means values in the array will be feed when the program is running, lets say, in our we shall feed the array values from keyboard.

Example 1: Program to demonstrate array initialization, manipulation


import java.util.Scanner;

public class ArrayDemo {
    public static void main(String[] args) {
        //array initialized at compile time through initializer and the same values are displayed when the program is running.
        int array[] = { 12, 34, 56, 78, 89, 32, 56, 22 };
        for (int i = 0; i < array.length; i++) {
        System.out.println("Value " + array[i] + " is at array[" + i + "]");
// array initialized at run time from keyboard input
        Scanner input = new Scanner(System.in);
        String colors[] = new String[3];
        for (int j = 0; j < colors.length; j++) {
            System.out.println("Enter color: ");
            colors[j] = input.nextLine();
        // values are displayed when the program is running.
        for (int k = 0; k < colors.length; k++) {
        System.out.println("Color " + colors[k] + " is at colors[" + k +"]");

Note: Every array object knows its own length in Java and maintains this information in a length field. Thus the expression, for example colors.length accesses colors' length field to determine the length of the array.

Example 2: Program to find the sum of all array elements


public class ArraySum {
    public static void main(String[] args) {
        int sum = 0;
        int array[] = { 12, 34, 56, 78, 89, 32, 56, 22 };
        for (int i = 0; i < array.length; i++) {
            sum += array[i]; // same as writing sum =sum + array[i]
        System.out.println("Sum is :"+ sum);

Example 3: Program to create a bar chart from the list of array elements


public class ArrayDemo {
    public static void main(String[] args) {
        int sum = 0;
        int array[] = { 10, 0, 5, 7, 1, 0, 12, 22 };
        for (int i = 0; i < array.length; i++) {
            for(int j = 0; j < array[i]; j++){

Multidimensional arrays


Arrays which have rows and columns are called two-dimensional, similarly there are three-dimensional, four-dimensional in fact arrays may be declared as n-dimensional. But practically visualizing arrays of more than two-dimension is difficult and rarely used. Java does not support multidimensional arrays directly, but it does allow the programmer to specify one dimensional arrays whose elements are also one-dimensional arrays, thus achieving the same effect. Two dimensional arrays, analogically, is more like a table and to identify a particular table element, we
must specify two indices. The first identifies the row element and second its column.


Like one dimensional arrays, multidimensional arrays can be initialized with array initializers in declaration. A two-dimensional array with two rows and two columns could be declared and initialized as follows:

int array[][] = { { 11, 22, 66 }, { 33, 44, 99, 77 }};


A multidimensional array with the same number of columns in every row can be created with an array creation expression as follows:

int array[][];
array = new int[3][4];

In this case, we use literal 3 and 4 to specify the number of rows and columns respectively. But if we want a multidimensional array in which each row has a different number of columns, we can create it as follows:

int array[][];
array = new int[2][];
array[0] = new int[7];

array[1] = new int[5];

Thus the statements create a two-dimensional arrays with two rows where row 0 has seven columns and row 1 has five columns.

Example 3: Program to demonstrate two-dimensional arrays

import java.util.Scanner;
public class Array2DDemo {
    public static void main(String[] args) {   
        int array2d[][] = {{11,22},{33},{44,55,66}};
        System.out.println("Values in the array are");
        for(int row = 0;row<array2d.length;row++){
            for(int col=0;col<array2d[row].length;col++){
                System.out.print(array2d[row][col]+" ");


Passing arrays to methods

To pass an array argument to a method, specify the name of the array without any brackets. For example if array price is declared as

double price[]=new double[5];

then the method call


passes the array price to method addTax. For a method to receive an array reference through a method call, the method's parameter list must specify an array parameter. For example, the method header for method addTax might be written as void addTax(double p[]), which indicates that addTax receives the reference of an double array in parameter p. The method call passes price's reference, so when the called method uses the array variable p, it refers to that same array object as price in the calling method.

Example 4: Program to demonstrate passing arrays to methods and modifying the elements



public class ArrayToMethodDemo {
    public static void main(String[] args) {
        double price[] = { 12.20, 45.25, 78.10, 35.40, 78.50 };
        System.out.println("Price before tax imposed");
        System.out.println("Price after 12.75% tax imposed");
    public static void addTax(double p[]) {
        for (int i = 0; i < p.length;i++) {
            p[i] = p[i] + p[i] * 0.1275;
    public static void display(double p[]) {
        for (int i=0; i < p.length; i++) {

On passing arguments to methods

Many programming language have two ways to pass arguments in method calls: pass-by-value (or call-by-value) and pass-by-reference(call-by-reference). When a argument is called by value, a copy of the argument's value is passed to the called method. The called method works exclusively with the copy. Any changes made to the copy do not affect the original variable's value in the caller. On the other hand, when an argument is called by reference, the called method can access the argument's value in the caller directly and modify the data. However, Java does not give programmer much of a choice. All arguments are passed by value in Java.

Example 5: Program to demonstrate passing arguments by value

public class PassByValueDemo {
    public static void main(String[] args) {
        float value = 2.5f;
        System.out.println("Value before modification " + value);
        System.out.println("Value after modification " + value);
    public static void changeValue(float f) {
        f *= 2;
        System.out.println("Modified value " + f);


About String[] args in main

Java allows arguments to be passed from command line to an application by including a parameter of type String[]in the parameter list of main. When an application is executed, Java passes the command line arguments that appear after the class name in the java command to the application's main method as strings in the array args. For example

java MyApp Hello world


passes two command line argument to application MyApp. MyApp's main method receives the two element array args in which args[0] contains the String “Hello” and args[1] contains the String “world”.




 1. List and table of values can be stored in
(1) variables
(2) table
(3) arrays
(4) program

 2. An array is a group of
(1) variables
(2) table
(3) arrays
(4) program

 3. The word homogeneous with respect to array refers to
(1) element of same size
(2) element of same type
(3) data type
(4) variables

 4. What allows programmer to iterate through the elements in an array
(1) conditional statements
(2) functions
(3) loops
(4) only for loop

 5. An array that uses two indices is called
(1) one dimensional array
(2) two dimensional array
(3) three dimensional array
(4) four dimensional array

 6. command line arguments are stored in
(1) main
(2) String[] args
(3) Java
(4) stack

 7. Array length is denoted by the field
(1) size()
(2) length()
(3) max()
(4) length

 8. Can an array index be of type float
(1) yes
(2) no

 9. Given the command java abc xyz, the first command line argument is
(1) java
(2) abc
(3) xyz
(4) none of the above

 10. String is a primitive data type
(1) true
(2) false



Task: Try yourself

  • Write a program to copy elements in one array to another array.
  • Write a program to simulate a stack with the help of an array
  • Write a program to reverse the element in an array
  • Write a program to search an element in an array


Previous: Methods | Next: Introduction to classes and objects | Back to Table of content

Edited by mdebnath, 09 March 2013 - 06:26 AM.

  • 0

Also tagged with one or more of these keywords: java, array

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download