Arrays in Java

Arrays are used to store collection of data. In other words, arrays are collection of variables stored under one name by manipulating indexes. Instead of declaring var1, var2, var3… you can declare one array¬†var[0],var[1], var[2]… to represent indivisual variables.

Single Dimension Array

Declaring Array

Creating Array

Declaration and Creation in one step

Initializing Array

Declaring, creating and initializing in one step

or

Single Dimension Array

Single Dimension Array[1]

Note :
  • Once an array is created then its size is fixed. To find the size of an array you can use
  • Declaration style dataType[] arrayRefVar; is preffered.
  • In array creation process, its elements are assigned default values such as 0 for numeric and false for boolean
  • The indices of array are 0-based, its start from 0 to (n-1) where n is the size of an array
  • Each element in the array is represented using the following syntax, known as an indexed variable arrayRefVar[index];
  • Shorthand code must be in one statement

Double Dimension Array / Multi Dimensional Array

To represent a table or matrix you can use double dimensional array.

Declaring Array

Creating Array

Declaration and Creation in one step

Initializing Array

Declaring, creating and initializing in one step

or

Ragged Array

Every row in two dimensional array represents a single dimension array. In this case, the size of two rows can be different. Such arrays are known as ragged array. Have a look at this example, size of first row is 3, size of 2nd row is 2 and 3rd size is 1.

Ragged Array [1]

Ragged Array [1]

Determin the size of each row [1]

Determin the size of each row [1]

Reference

[1] Introduction to Java Programming, Comprehensive Version plus MyProgrammingLab with Pearson eText (9th Edition)

No Responses

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.