ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

Arrays

Arrays

Arrays can be thought of as homogeneous collection of variables of same type. Arrays are index based. The first index is 0,next 1 and so on till desired.We can have desired values in the desired index.While declaring arrays we need to specify the data type and name of the array.
Example:
int a[]; or
int []a;
We can create an array using new operator.

Arrays in java can be single dimensional or multi-dimensional.
1.Single dimensional arrays
Example

  1. class singled
  2. {
  3. public static void main(String args[])
  4. {
  5. int x[]=new int[6];
  6. x[0]=1;//initialization
  7. x[1]=2;
  8. x[2]=7;
  9. x[3]=4;
  10. x[4]=5;
  11. x[5]=6;
  12. for(int i=0;i<x.length;i++)
  13. System.out.println(x[i]);
  14. }
  15. }

Output:

1
2
3
4
5
6

In the above example we have created an array using new.We have declared a variable x which creates an array of 6 elements of int type.
Thereafter we have initialized and printed the values.

Now instead of declaring and initializing them as above we can also do it as
int x[]={1,2,3,4,5,6};
We can print it as given in the above example,

Passing arrays to methods:
We can pass the array to method in java.
Example:

  1. class Pass
  2. {
  3. static void max(int arr[])
  4. {
  5. int max=arr[0];
  6. for(int i=1;i<arr.length;i++)
  7. if(max<arr[i])
  8. max=arr[i];
  9.  
  10. System.out.println(max);
  11. }
  12.  
  13. public static void main(String args[])
  14. {
  15. int x[]={84,429,47,534};
  16. max(x);//passing array to method
  17.  
  18. }
  19. }

2.Multi-dimensional array
Example:

  1. class MultiD
  2. {
  3. public static void main(String args[])
  4. {
  5. int arr[][]={{1,2,3},{4,5,6},{7,8,9}}; //Declaration and initialization of 2-D array.
  6. //printing 2D array
  7. for(int i=0;i<3;i++){
  8. for(int j=0;j<3;j++){
  9. System.out.print(arr[i][j]+" ");
  10. }
  11. System.out.println();
  12. }
  13.  
  14. }

Output:
1 2 3
4 5 6
7 8 9
The Arrays class

The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements.

Example:
public static int binarySearch(Object[] x, Object key)
This searches the specified array of Object ( Byte, int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (-(insertion point + 1).

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!