5/27/2012

All about arrays in java

  •  Arrays are way to store a list of items. Each slot of an array holds an individual element, and you can place into or change the contents of those slots as you need to.
  • Arrays can contain any type of element value(primitive types or objects), but you cant store different types in single array. You can have array of integers, or arrays of string.
  • To create an array in Java, you use three steps :
  1.        Declare a variable to hold the array. 
  2.        Create a new array object and  assign it to the array variable.
  3.        Store things in that array. 

Declaring array variables:
  • The first step in creating an array is creating an variable that will hold the array, just as you would any other variable.
  • Array variables indicate the type of object the array will hold and the name of the array, followed by empty square brackets [].
  • Following are the examples of Array declarations:
                int values[];
                float cost[];
                String months[];
  • There is another way to declare the array allowed in java as shown below:
                String[] names;
                int[] numbers;

Creating array object:
         The second step is to create an array object and assign it to that variable. There are two ways to do this :
  • using new
  • Directly initializing the contents of that array
The first way is to use the new operator to create new instance of an array:
      int[] values=new values[10];
This will creates anew array of int with size10.
  • When you create a new array object using new, you must indicate how many slots that array will hold.
  • You can create & initialize array at same time. Instead of using new to create the new array object, enclose the elements of the array inside braces, separated by commas:
                   int[] values={1,2,3,4,5};
  • Each of the elements inside the braces must be of the same type as the variable that holds that array.
  • An array the size of the number of elements you've included will be automatically created for you.
Accessing array elements:
  • Once you have array with an initial values, you can test and change the values in each subscript of that array. To get a value stored within an array, use the array subscript expression:
                      arrayname[subscript];
  • The arrayname is the name of array. The subscript is index of array elements stored in array. Array subscript starts with 0. So an array with 10 elements has 10 array elements accessed using subscript 0 to 9.
  • Note that all array subscripts are checked to make sure that they are inside the boundaries of the array. Note the following two statements, for example:
                       String[] arr=new String[10];
                       arr[10]="Ashish";
  • A program with that last statement in it produces acompiler error at that linewhen you try to compile it. The array stored in arr has size as 10, the element at subscript 10 doesn't exist, and java compiler will check for that.
  • If the array subscript calculated  at run-time & ends up outside the boundaries of the array, the java interpreter also produces an error.
Changing array elements:
  • To assign a particular value array slot, merely put an assignment statement after the array access expression:
                            values[2]= 45;
                            months[3]="March";

Example of arrays:
//program of sorting of array
class IntSorting
{
         public static void main(String args[])
        {
                  int num[]={55,40,80,65,01,71};
                  int n=num.length;
                  System.out.print("Give list as :");
                  for(int i=0 ; i<n ; i++)
                          System.out.print(" "+num[i]);
                  System.out.println("\n");

                  for(int i=0; i<n ; i++)
                  {
                          for(int j=i+1; j<n; j++)
                          {
                                   if(num[i]>num[j])
                                    {
                                              int temp=num[i];
                                              num[i]=num[j];
                                              num[j]=temp;
                                    }
                          }
                  }

                  System.out.print("Sorted list: ");
                  for(int k=0; k<num.length; k++)
                          System.out.print(" "+num[k]);
                  System.out.println("\n");
        } 
}

Output:
Given list: 55 40 80 65 1 71
Sorted list: 1 40 55 65 71 80

No comments:

Post a Comment