We cannot proceed with the discussion of Java without discussing an important concept and that is of ‘Arrays’. We have already spoken about the different data types in Java. To refresh, the different data types are:

  • short
  • int
  • long
  • float
  • double
  • char
  • boolean
  • byte

These data types can be used to store different values such as integer, decimal point values, character, true/false and more.

What are ‘Arrays’?

Now,what if we would like to store more items as a list so that we can iterate over them? This can be done by means of ‘Arrays’.

As an example, we can store temperatures of a place on various dates and find the hottest day or coldest day in a season with the help of ‘Arrays’.

‘Arrays’ store a list of items that can be referenced later. We can store integer values or floating point values(decimal values) or boolean values(true/false) in an array. The only constraint is that arrays can only be used to store values of the same type. This is known as ‘homogenous array’.

The size of the array should also be specified earlier. There are essentially two steps when working with arrays – they are :

a. creating the array

int a[]; //we are creating an integer array here

b. allocating memory to the array

a=new int[5]; //allocating memory to the array

These two statements can be combined as:

int a[]=new int[5]; //this creates an integer array which can hold 5 elements

It is also to be noted that the index of an array starts from ‘0’.

These are salient features of an array:

Arrays are used to store elements of same data type in contiguous memory locations

The index of an array begins from ‘0’

The size of an array should be specified earlier

There can be multi- dimensional arrays too

Let us see a simple program to declare an array, store elements in it and print them out:

 

I have hard coded the elements of an array and have printed them out by means of a ‘for’ loop. We will discuss the ‘for’ loop in the ‘Looping’ chapter….

We have seen the concept of ‘Homogenous Arrays’ in this post. If it is still mind boggling…sit tight – we will still explore it more to understand the concepts further… 🙂

Coming up tomorrow – ‘Interfaces’ in Java!! 🙂

I’m participating in #BlogchatterA2Z by Blogchatter 

(Visited 109 times, 1 visits today)

Related Posts

2 thoughts on “Homogeneous ‘Array’

Leave a Reply