07. Array
07. Array
Topic: Array
Outlines
• Introduction
• Array Creation
• Array Initialization
• Array as an Argument
• Array as a return type
• Enumerations
Array
• Definition:
An array is a finite collection of variables of the same type
that are referred to by a common name.
• Arrays of any type can be created and may have one or more
dimensions.
• A specific element in an array is accessed by its index
(subscript).
• Array elements are stored in contiguous memory locations.
• Examples:
• Collection of numbers
• Collection of names
Examples
Array of numbers:
10 23 863 8 229
Array of names:
Array of suffixes:
ment tion ness ves
One-Dimensional Arrays
• A one-dimensional array is a list of variables of same
type.
• The general form of a one-dimensional array
declaration is:
type [] var-name; array-var = new type[size];
OR
type [] var-name = new type[size];
Example:
int [] num = new int [10];
Syntax
Declaration of array variable:
data-type variable-name[];
eg. int marks[];
This will declare an array named ‘marks’ of type ‘int’. But no memory is
allocated to the array.
Allocation of memory:
variable-name = new data-type[size];
eg. marks = new int[5];
This will allocate memory of 5 integers to the array ‘marks’ and it can store
upto 5 integers in it. ‘new’ is a special operator that allocates memory.
Accessing elements in the array:
• Specific element in the array is accessed by specifying
name of the array followed the index of the element.
• All array indexes in Java start at zero.
variable-name[index] = value;
Example:
marks[0] = 10;
This will assign the value 10 to the 1st element in the array.
marks[2] = 863;
This will assign the value 863 to the 3rd element in the array.
Example
STEP 1 : (Declaration)
int marks[];
marks null
STEP 2: (Memory Allocation)
marks = new int[5];
marks 0 0 0 0 0
marks[0] marks[1] marks[2] marks[3] marks[4]
• Default values:
– zero (0) for numeric data types,
– \u0000 for chars and
– false for Boolean types
– null for references
Now read the marks of all the subjects from the user
using Scanner class.
• Example:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
In first case, Only one array is created and two references arr1
and arr2 are pointing to the same array. While in second case
two different arrays are created.
Array as Argument
• Arrays can be passed as an argument to any method.
Example:
Example:
public int [] Result (int roll_No, int marks )
Assignment for Practice