Array in Java

What you will learn here about Array in Java

  • What is array in java
  • Array declaration in java
  • can array store heterogeneous data?

What is array in java

  • Array is similar to variables only thing is that it can store multiple values of same data type. In simple words array can store homogeneous data means we store primitive data such as int or float or String or double etc. or we can store objects also.
  • Arrays are fixed in size
  • Array is index based. So Array elements are accessed by using index.

Array declaration in java:

In java we can declare array in 3 ways

First way :

public class FirstWay{
	public static void main(String[] args)
	{
		int[] array1={1,2,3};// Array size is number of value entered
		System.out.println(array1);//[1,2,3]
	}
}

Second way:

public class SecondWay{
	public static void main(String[] args)
	{
		int[] array2=new int[5]; // array with size 10 and all elements are initialized with default value
		array2[0]=10;
		array2[1]=20;
		array2[2]=30;
		array2[3]=40;
		array2[4]=50;
		System.out.println(array2);//[10,20,30,40,50]
	}
}

3rd way

public class ThirdWay{
	public static void main(String[] args)
	{
		int[] array3=new int{1,2,3,4}; // no need to mention array size. it takes based on values
		System.out.println(array3);//[1,2,3,4]
	}
}

Can array store heterogeneous data?

Yes, we can store heterogeneous data in array. This is possible using Object class. The example of adding heterogeneous data in array is given below:

public class heterogeneousExample{
	public static void main(String[] args)
	{
		Object[] HE=new Object[5]; // no need to mention array size. it takes based on values
		HE[0]=1;
		HE[0]="nice";
		HE[0]='A';
		HE[0]=100;
		HE[0]=10.5;
		System.out.println(HE);  //[1,"nice",'A',100,10.5]
	}
}

key points:

if array is initializing at the time of declaration then no need to mention array size
example:
int[] num=new int[] {1,2,4,5,6,7,9};

if array is not initializing at the time of declaration then we need to mention array size at the declaration time
example:
int[] num=new int[5];
array2[0]=10;
array2[1]=20;
array2[2]=30;
array2[3]=40;
array2[4]=50;

You may also like...