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

8 - Lec - Arrays in Java Part-1

The document discusses arrays in Java including how to declare and initialize arrays, access array elements using indexes, iterate through arrays using for loops, check array bounds, and examples of using arrays to count letter frequencies in a string.

Uploaded by

Aqeel Abbas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

8 - Lec - Arrays in Java Part-1

The document discusses arrays in Java including how to declare and initialize arrays, access array elements using indexes, iterate through arrays using for loops, check array bounds, and examples of using arrays to count letter frequencies in a string.

Uploaded by

Aqeel Abbas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Arrays in Java

Dr. Shariq Hussain


Motivation
• How to organize 100 Student objects?
• 100 different Student object names?
• Organize data for efficient access
–Class: different data types in one object
–Array: multiple objects of the same type
Overview
• An array
– a single name for a collection of data values
– all of the same data type
– subscript notation to identify one of the values
• A carryover from earlier programming languages
• More than a primitive type, less than an object
– like objects when used as method parameters and return
types
– do not have or use inheritance
• Accessing each of the values in an array
– Usually a for loop
Creating Arrays
• General syntax for declaring an array:

Base_Type[] Array_Name = new Base_Type[Length];

• Examples:
80-element array with base type char:
char[] symbol = new char[80];

100-element array of doubles:


double[] reading = new double[100];

70-element array of Species:


Species[] specimen = new Species[70];
Three Ways to Use [ ] (Brackets) with an Array Name
1. Declaring an array: int[] score
• creates a name of type "int array"
– types int and int[] are different
• int[]: type of the array
• int : type of the individual values

2. To create a new array, e.g. score = new int[100];

3. To refer to a specific element in the array


- also called an indexed variable, e.g.

score[3] = keyboard.nextInt();
System.out.println("You entered" + score[3]);
Arrays
• An array is an ordered list of values
The entire array Each value has a numeric index
has a single name

0 1 2 3 4 5 6 7 8 9
scores 79 87 94 82 67 98 87 81 74 91

An array of size N is indexed from zero to N-1

This array holds 10 values that are indexed from 0 to 9

7-6
Arrays
• A particular value in an array is referenced using the array name
followed by the index in brackets
• For example, the expression

scores[2]
refers to the value 94 (the 3rd value in the array)
• That expression represents a place to store a single integer and can be
used wherever an integer variable can be used

7-7
Arrays • For example, an array element can be assigned a value,
printed, or used in a calculation:
scores[2] = 89;
scores[first] = scores[first] + 2;
mean = (scores[0] + scores[1])/2;
System.out.println ("Top = " + scores[5]);

7-8
• The values held in an array are called array elements
Arrays
• An array stores multiple values of the same type – the
element type
• The element type can be a primitive type or an object
reference
• Therefore, we can create an array of integers, an array
of characters, an array of String objects, an array of
Coin objects, etc.
• In Java, the array itself is an object that must be
instantiated

7-9
Arrays • Another way to depict the scores array:

scores 79
87
94
82
67
98
87
81
74
91

7-10
Declaring Arrays
• The scores array could be declared as follows:
int[] scores = new int[10];
• The type of the variable scores is int[] (an array of integers)
• Note that the array type does not specify its size, but each object of
that type has a specific size
• The reference variable scores is set to a new array object that can
hold 10 integers
• An array is an object, therefore all the values are initialized to
default ones (here 0)

7-11
Declaring Arrays
• Some other examples of array declarations:

float[] prices = new float[500];


boolean[] flags;
flags = new boolean[20];
char[] codes = new char[1750];

7-12
Using Arrays
• for loop can be used when processing array elements

for (int i = 0; i < scores.length; i++)


System.out.println (scores[i]);

7-13
final int LIMIT = 15, MULTIPLE = 10;

int[] list = new int[LIMIT];

// Initialize the array values


for (int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;

list[5] = 999; // change one array value

// Print the array values


for (int index = 0; index < LIMIT; index++)
System.out.print (list[index] + " ");
7-14
Bounds Checking
• Once an array is created, it has a fixed size
• An index used in an array reference must specify a valid element
• That is, the index value must be in range 0 to N-1
• The Java interpreter throws an
ArrayIndexOutOfBoundsException if an array index is out of
bounds
• This is called automatic bounds checking

7-15
Bounds Checking
• For example, if the array codes can hold 100 values, it can be indexed using only
the numbers 0 to 99
• If the value of count is 100, then the following reference will cause an exception
to be thrown:
System.out.println (codes[count]);
• It’s common to introduce off-by-one errors when using arrays

problem

for (int index=0; index <= 100; index++)


codes[index] = index*50 + epsilon;

7-16
Bounds Checking
• Each array object has a public constant called length that stores the size of the
array
• It is referenced using the array name. e.g.

scores.length
• Note that length holds the number of elements, not the largest index

7-17
ReverseOrder
Scanner scan = new Scanner (System.in);

double[] numbers = new double[10];

System.out.println ("The size of the array: " + numbers.length);

for (int index = 0; index < numbers.length; index++) {


System.out.print ("Enter number " + (index+1) + ": ");
numbers[index] = scan.nextDouble();
}

System.out.println ("The numbers in reverse order:");

for (int index = numbers.length-1; index >= 0; index--)


System.out.print (numbers[index] + " ");

7-18
Char type
String st = "abcd";
for(int i =0; i < st.length (); i++ ) {
char c = st.charAt (i);
System.out.print(c); Output:
System.out.print(" ");
a 97 0
System.out.print((int) c);
b 98 1
System.out.print(" ");
c 99 2
System.out.println(c - 'a');
}

7-19
Letter Count
// program to count upper case, lower case, and other characters
final int NUMCHARS = 26; // number of alphabets

Scanner scan = new Scanner (System.in);

int[] upper = new int[NUMCHARS]; //each element store count


int[] lower = new int[NUMCHARS];

char current; // the current character being processed


int other = 0; // counter for non-alphabetics

System.out.println ("Enter a sentence:");


String line = scan.nextLine(); // read a sentence from user
7-20
Letter Count (contd.)
// Count the number of each letter occurence
for (int j = 0; j < line.length(); j++) //string method .length()
{
current = line.charAt(j);
if (current >= 'A' && current <= 'Z')
upper[current-'A']++;
else
if (current >= 'a' && current <= 'z')
lower[current-'a']++;
else
other++;
}

7-21
Letter Count (contd.)
// Print the results
System.out.println ();
for (int letter=0; letter < upper.length; letter++)
{
System.out.print ( (char) (letter + 'A') );
System.out.print (": " + upper[letter]);
System.out.print ("\t\t" + (char) (letter + 'a') );
System.out.println (": " + lower[letter]);
}

System.out.println ();
System.out.println ("Non-alphabetic characters: " + other);
7-22

You might also like