0% found this document useful (0 votes)
2 views

Lect 3 Arrays

Uploaded by

Ramsha Imran
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lect 3 Arrays

Uploaded by

Ramsha Imran
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 21

CLO-2

Object Oriented
Programming
Techniques
Lecture 3: Arrays In Java
Arrays - Introduction
• An array is a group of contiguous or related data items that
share a common name.
• Used when programs have to handle large amount of data
• Each value is stored at a specific position
• Position is called a index or superscript. Base index = 0
• The ability to use a single name to represent a collection of
items and refer to an item by specifying the item number
enables us to develop concise and efficient programs. For
example, a loop with index as the control variable can be
used to read the entire array, perform calculations, and print
out the results.

2
Arrays - Introduction

0 69
1 61
index
2 70
3 89 values
4 23
5 10
6 9

3
Declaration of Arrays
• Like any other variables, arrays must declared and created
before they can be used. Creation of arrays involve three
steps:
• Declare the array
• Create storage area in primary memory.
• Put values into the array (i.e., Memory location)
• Declaration of Arrays:
• Form 1:
Type arrayname[]
• Form 2:
• Type [] arrayname;

• Examples:
int[] students;
int students[];
• Note: we don’t specify the size of arrays in the declaration.

4
Creation of Arrays
• After declaring arrays, we need to allocate
memory for storage array items.
• In Java, this is carried out by using “new”
operator, as follows:
• Arrayname = new type[size];
• Examples:
• students = new int[7];

5
Initialisation of Arrays
• Once arrays are created, they need to be
initialised with some values before access their
content. A general form of initialisation is:
• Arrayname [index/subscript] = value;
• Example:
• students[0] = 50;
• students[1] = 40;
• Like C, Java creates arrays starting with
subscript 0 and ends with value one less than
the size specified.
• Unlike C, Java protects arrays from overruns
and under runs. Trying to access an array
beyond its boundaries will generate an error
message.

6
Arrays – Length
• Arrays are fixed length
• Length is specified at create time
• In java, all arrays store the allocated
size in a variable named “length”.
• We can access the length of arrays as
arrayName.length:
e.g. int x = students.length; // x = 7
• Accessed using the index
e.g. int x = students [1]; // x = 40

7
Sample Program
class MinAlgorithm
{
public static void main ( String[] args )
{
int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ;
int min=array[0]; // initialize the current minimum
for ( int index=0; index < array.length; index++ )
if ( array[ index ] < min )
min = array[ index ] ;
System.out.println("The minimum of this array is: " + min );

}
}
Example:
MonthDays.java
public class MonthDays
{
public static void main(String[] args)
{
String[] months = { "January", "February", "March", "April", "May",
"June", "July",
"August", "September", "October", "November",
"December" };
int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for (int index = 0; index < months.length; index++)
{
System.out.println(months[index] + " has " + days[index] + "
days.");
}
}
}
Arrays of Arrays
• Two-Dimensional arrays
• float[][] temperature=new float[10][365];
• 10 arrays each having 365 elements
• First index: specifies array (row)
• Second Index: specifies element in that
array (column)
• In JAVA float is 4 bytes, total
Size=4*10*365=14,600 bytes
Graphical Representation

Sample[0] 0 1 2 3 4 5 6 7 8 9

Sample[1] 0 1 2 3 4 5 6 7 8 9

Sample[2] 0 1 2 3 4 5 6 7 8 9
Initializing Array of Arrays

int[][] array2D = { {99, 42, 74, 83,


100}, {90, 91, 72, 88, 95}, {88, 61, 74,
89, 96}, {61, 89, 82, 98, 93}, {93, 73,
75, 78, 99}, {50, 65, 92, 87, 94}, {43,
98, 78, 56, 99} };
//5 arrays with 5 elements each
Arrays of Arrays of Varying
Length
• All arrays do not have to be of the same
length
float[][] samples;
samples=new float[6][];//defines # of arrays
samples[2]=new float[6];
samples[5]=new float[101];

• Not required to define all arrays


Initializing Varying Size Arrays

int[][] uneven = { { 1, 9, 4 }, { 0,
2}, { 0, 1, 2, 3, 4 } };
//Three arrays
//First array has 3 elements
//Second array has 2 elements
//Third array has 5 elements
Array of Arrays Length
long[][] primes = new long[20][];

primes[2] = new long[30];

System.out.println(primes.length); //Number of arrays

System.out.println(primes[2].length);//Number of elements in the


second array

OUTPUT:

20

30
Sample Program
class unevenExample3
{
public static void main( String[] arg )
{ // declare and construct a 2D array
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
// print out the array
for ( int row=0; row < uneven.length; row++ ) //changes row
{
System.out.print("Row " + row + ": ");
for ( int col=0; col < uneven[row].length; col++ ) //changes
column
System.out.print( uneven[row][col] + " ");
System.out.println();
}
}
}
Output

Row 0: 1 9 4
Row 1: 0 2
Row 2: 0 1 2 3 4
18
Compiled By:Umme laila

Array Copy
public class ArrayCopy {
public static void main(String[] args)
{ char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
String Arrays
• If an initialization list is not provided, the new keyword
must be used to create the array: String[] names = new
String[4];

The names variable holds


the address to the array.
Address

names[0] null
names[1] null
names[2] null
names[3] null
String Arrays
• When an array is created in this manner, each element of
the array must be initialized.

The names variable holds names[0] = "Bill";


the address to the array. names[1] = "Susan";
Address names[2] = "Steven";
names[3] = "Jean";
names[0] null
names[1] null “Bill”
names[2] null “Susan”
names[3] null “Steven”
“Jean”
Example
public class ArrayOfArraysDemo {
public static void main(String[] args)
{
String[][] cartoons = { { "Flintstones", "Fred", "Wilma", "Pebbles“
, "Dino" }, { "Rubbles", "Barney", "Betty", "Bam Bam" },
{ "Jetsons", "George", "Jane", "Elroy", "Judy", "Rosie", "Astro" },
{ "Scooby Doo Gang", "Scooby Doo", "Shaggy", "Velma", "Fred",
"Daphne" } };
for (int i = 0; i < cartoons.length; i++)
{ System.out.print(cartoons[i][0] + ": ");
for (int j = 1; j < cartoons[i].length; j++)
{ System.out.print(cartoons[i][j] + " "); }
System.out.println();
}}}

You might also like