Docsity

Lecture Notes on Arrays - Object-Oriented Program I | CMSC 131, Study notes of Computer Science

Toggle sidebar
bg1
CMSC 131: Chapter 14 (Supplement)
CMSC 131: Chapter 14 (Supplement)
Arrays
Arrays
Arrays
Arrays
Array: A structure used for storing and processing a collection of data all of a
common type.
Example: Store a list of 100 integer scores.
–How to store them? We could create 100 variables: score0, score1, score2, … but
this would be quite tedious.
–Array: Allows us to store a collection of items under a single name, and refer to
individual items by an integer index.
–Array indices: Array indices start with 0.
So a 100-element array would be indexed
from 0 to 99.
–Array elements: Are accessed and manipulated
just as any variable.
Creating Arrays
Creating Arrays
An array is a special type of object.
– The notation “[ ]” is Java’s way of declaring an identifier to be an array.
– We must invoke “new” to allocate storage for each array that we want to use.
– When we allocate a new array, we need to specify how many elements we want in the
array. This value is put in square brackets.
Example: This declares score to be a 100-element array of int’s.
int[ ] score = new int[100];
int[ ] score; // this is equivalent to the above
score = new int[100];
pf3
pf4
pf5

Partial preview of the text

Download Lecture Notes on Arrays - Object-Oriented Program I | CMSC 131 and more Study notes Computer Science in PDF only on Docsity!

CMSC 131: Chapter 14 (Supplement)CMSC 131: Chapter 14 (Supplement)

Arrays Arrays

ArraysArrays

Array: A structure used for storing and processing a collection of data all of a

common type.

Example: Store a list of 100 integer scores.

  • How to store them? We could create 100 variables: score0, score1, score2, … but this would be quite tedious.
  • Array: Allows us to store a collection of items under a single name, and refer to individual items by an integer index.
  • Array indices: Array indices start with 0. So a 100-element array would be indexed from 0 to 99.
  • Array elements: Are accessed and manipulated just as any variable.

Creating Arrays Creating Arrays

An array is a special type of object.

  • The notation “[ ]” is Java’s way of declaring an identifier to be an array.
  • We must invoke “new” to allocate storage for each array that we want to use.
  • When we allocate a new array, we need to specify how many elements we want in the array. This value is put in square brackets. Example: This declares score to be a 100-element array of int’s. int[ ] score = new int[100]; int[ ] score; // this is equivalent to the above score = new int[100];

Square BracketsSquare Brackets

Don’t confuse the three uses of square brackets:

  • Declare a variable to an array: int score[ ]; The base type of the array is int.
  • Specify the size of a newly created array: score = new int[100];
  • Access an individual element of the array: System.out.println( “Last score: ” + score[99] );

ExampleExample

Example: Input a list of 4 doubles and print them in reverse order.

double[ ] value = new double[4]; for ( int i = 0; i < 4; i++ ) value[i] = readDouble( ); for ( int i = 3; i >= 0; i-- ) System.out.println( value[i] ); public static double readDouble( ) { return Double.parseDouble( JOptionPane.showInputDialog( "Next value:" ) ); }

Alternate Declaration SyntaxAlternate Declaration Syntax

Java provides two ways to declare a variable to be an array:

  • Java style: int[ ] grade;
  • C and C++ style (old, but still Java allows): int grade[ ];
  • Java style is preferred (but old C and C++’s programmers sometimes slip into the old style). int[ ] a, b, c; // a, b, c are all int arrays int a[ ], b, c[ ]; // a and c are int arrays, and b is just an int

Array Initializers Array Initializers

An array can be initialized when it is declared. This is done by giving an

initializer list.

int[ ] cutOffs = { 90, 82, 75, 66 };

This does a number of things:

  • Counts the number of elements in the initializer (4 in this case) and automatically invokes new: “new int[4]”.
  • Initializes the array values.
  • Returns a reference to the array (stored in cutOffs). int[ ] cutOffs = new int[4]; cutOffs[0] = 90; cutOffs[1] = 82; cutOffs[2] = 75; cutOffs[3] = 66;

If not initialized: array elements are set to their Java default values (0, 0.0, false,

null).

ExampleExample

A static method that is given an integer numeric score from 0 to 100, and converts it

into a letter grade according to a given set of cut-offs. A grade of ‘F’ is given if it is

less than the lowest score.

public static char letterGrade( int numeric ) { int[ ] cutOffs = { 90, 82, 75, 66 }; char[ ] letters = { 'A', 'B', 'C', 'D' }; for ( int i = 0; i < cutOffs.length; i++ ) { if ( numeric >= cutOffs[i] ) { return letters[i]; } } return 'F'; }

Arrays of Characters and Strings Arrays of Characters and Strings

String != char[ ]: In some programming languages, a string is the same as an array

of chars. Not in Java.

String: String str = "Hello"; Array of chars: char[ ] chr = "Hello"; // Illegal! Type mismatch. char[ ] chr = { 'H', 'e', 'l', 'l', 'o' };

Other differences:

Operation String char[ ] Result Get length str.length( ) chr.length 5 Get char str.charAt[4] chr[4] ‘o’ Set char (not possible) chr[0] = ‘J’; “Jello”

Converting char[ ] to String: The String constructor is overloaded to allow a

char[ ] parameter:

String str3 = new String( chr );

Array Argument Example 2Array Argument Example 2

Example: A static method, squareValues, that is given an array of doubles and

replaces each value with its square.

public static void squareValues( double[ ] v ) { for ( int i = 0; i < v.length; i++ ) v[i] = v[i] * v[i]; } double[ ] height = { 6.42, 7.10, 4.83 }; squareValues( height ); printDoubles( height );

Pass by Value: Only the array reference, height, is passed. This reference cannot

be changed, but the array contents can be.

Array Argument Example 3Array Argument Example 3

Example: A static method, doubleSize, that is given an array b of char’s, creates a new array b2 of twice the size of the original. It copies the values of b to b2, and sets the remainder to ‘ ’. It returns b2. public static char[ ] doubleSize( char[ ] b ) { char[ ] b2 = new char[ 2 * b.length ]; for ( int i = 0; i < b.length; i++ ) b2[i] = b[i]; for ( int i = b.length; i < b2.length; i++ ) b2[i] = ' '; return b2; } Usage: char[ ] buffer = { 'J', 'a', 'v', 'a' }; char[ ] newBuffer = doubleSize( buffer );

(More to Come)(More to Come)