Arrays in Java

An array is simple data structure to store same type of elements stored sequentially in memory.

One Dimensional Arrays
Declaration: Below is syntax to declare an one dimensional float array of size 10

float arr[] = new float[10];

Below is an example to reverse an one dimensional array

public class ReverseArray {
public static void main(String args[])
	int marks[] = {10,20,30,40,50,60};

	int tmp, n = marks.length;

	for(int i=0;i<n/2;i++)
		tmp = marks[i];
		marks[i] = marks[n-i-1];
		marks[n-i-1] = tmp;

	for(int i=0;i<n;i++)
		System.out.print(marks[i]+" ");
60 50 40 30 20 10

Below is an example showing how to store objects in an array

class A2{
	private String city;
	private float temperature;

	public A2(String mycity, float mytemperature)
		city = mycity;
		temperature = mytemperature;

	public String getCity()
		return city;

	public float getTemperature()
		return temperature;

public class ArrayDemo {

	public static void main(String[] args) {

	A2 arr[] = new A2[3];

	A2 oa = new A2("Bangalore",34.3f);
	arr[0] = oa;

	arr[1] = new A2("Chennai",36.3f);

	arr[2] = new A2("Mumbai",35.3f);

	for(int i=0;i<arr.length;i++)
		System.out.println(arr[i].getCity()+" "+arr[i].getTemperature());



Two or Multi dimensional Arrays
Declaration: Below is syntax to declare two dimensional double array of 5 rows and 10 columns

double darr[][] = new double[5][10];

initialize two dimensional arrays
int abc[][] = {{1,2},{3,4},{5,6}};

abc.length gives number of rows
abc[0].length gives number of columns

You may also like to read:
How to store configuration settings in Java
What is Comparable in Java?
Example of Comparator
What is Generic class, and how it can be used with HashSet

2 thoughts on “Arrays in Java”

Leave a Reply