Jan 7, 2022

What is Arrays in Java

Basically an array in java is a collection of homogeneous elements that simply means array can store elements of same type or we can say it can store elements of same data types. means if we declare integer type array so we can store only integer data type elements in array or if we declared array of character type so we can store only character's in it. 

What is arrays in java, what are arrays in java, java programming examples and syntax



For Example: 

int arr[];

or 

char c[];


In above example I have shown syntax to declare an array.


  Java Program to Declare and Initialize an Array:


public class ArrayExample {

	public static void main(String[] args) {
		//declaring and Initializing an array
		int  arr[]= {10,20,30,40,50};
		//printing array elements
		for(int i=0;i<arr.length;i++)
		System.out.print(arr[i]+" ");
	}

}

Above program will show the following output:

10 20 30 40 50



Arrays are fixed in size that means one's we create an array of size 10 so we cannot change its value.


  Syntax to create an array with some size:

data_type   array_name = new  data_type[10];


For Example:

int arr[] = new int[10];

In above example we can see that we have declared one array with size 10 so in this array we can store only 10 elements and if we try to store 11th element it will throw an  IndexOutOfBoundsException.


  Program which demonstrates the array IndexOutOfBoundsException :


public class ArrayExample2 {

	public static void main(String[] args) {
		//declaring and allocation size
		int  arr[]= new int[5];

		arr[0] = 1;
		arr[1] = 2;
		arr[2] = 3;
		arr[3] = 4;
		arr[4] = 5;
		arr[5] = 6;//will throw an error
		
		for(int i=0;i<arr.length;i++)
		System.out.println(arr[i]);
	}

}


  Output of the above program is :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 at ArrayExample2.main....



Below is the list of some array examples in Java, You can practice and compile it on your computer and see how it works.

 

  List of Array Examples In Java :

Share This:    Facebook Twitter

0 Comments:

Post a Comment

If you have any doubts, please discuss here...