arrays.pdf, Lecture notes of Statistics

In Java, arrays are objects so they contain more information, but the data is stored ... Suppose we want to copy the elements of one array to another array.

Typology: Lecture notes

2022/2023

Uploaded on 03/01/2023

tomseller
tomseller šŸ‡ŗšŸ‡ø

4.6

(16)

271 documents

1 / 33

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Arrays:
•An array is a data structure that stores a sequence of values of the same type.
•The data type can be any of Java’s primitive types:
•int, short, byte, long, float, double, boolean, char
•The data type can also be any class:
•String, SolidBoxes, etc.
•Each variable in the array is an element.
•An index specifies the position of each element in the array.
•Useful for many applications:
•Collecting statistics.
•Representing the state of a game.
•Etc.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21

Partial preview of the text

Download arrays.pdf and more Lecture notes Statistics in PDF only on Docsity!

Arrays:

  • An array is a data structure that stores a sequence of values of the same type.
  • The data type can be any of Java’s primitive types:
    • int, short, byte, long, float, double, boolean, char
  • The data type can also be any class:
    • String, SolidBoxes, etc.
  • Each variable in the array is an element.
  • An index specifies the position of each element in the array.
  • Useful for many applications:
    • Collecting statistics.
    • Representing the state of a game.
    • Etc.

Java Arrays vs Python Lists:

  • The closest structure to an array in Python is the List, but there are many

differences.

  • An array has a fixed size but the size of a Python List can change.
  • All the elements of an array must be the same type, but a Python List can have

elements of many types.

  • You may insert into the middle of a Python List , but not into an array
  • You may concatenate a Python List , but not an array
  • Why would we even have something like an array when a list is so much more

flexible?

  • Answer: Nothing is free. Arrays are more efficient than lists.

Declaring and Instantiating Arrays:

  • Arrays are objects.
  • Creating an array requires two steps:

1. Declaring the reference to the array

2. Instantiating the array.

  • To declare a reference to the array: datatype [] arrayName;
  • To instantiate an array: arrayName = new datatype[ size ];
    • size is an int and is the number of elements that will be in the array. int [] zapNumbers; zapNumbers = new int [ 173 ]; float [] grades; grades = new float[ 22 ] ; String [] names; names = new String[ 20 ];
  • Examples:
  • Declaring and instantiating arrays of primitive types: double [] dailyTemps; // elements are doubles dailyTemps = new double[ 365 ]; // 365 elements boolean [] answers; // elements are booleans: true, false answers = new boolean[ 20 ]; // 20 elements int [] cs127A, cs252; // two arrays, each containing integers cs127A = new int[ 310 ]; // 310 elements for cs127A cs252 = new int[ 108 ]; // 108 elements for cs
  • The declaration and instantiation can be done in the same step. double [] dailyTemps = new double[ 365 ]; ... can now use the dailyTemps array in my code ... dailyTemps = new double[ 173 ]; ... can now use the new size of dailyTemps array in my code ... int numberOfQestions = 30; boolean [] answers = new boolean[ numberOfQuestions ]; int [] cs127 = new int[ 240 ], cs252 = new int[ 75 ]; String [] studentNames = new String[ 42 ]; int numPlayers = 25; int numTeams = 10; BaseballStats [] myTeam = new BaseballStats[ numPlayers * numTeams ];
  • When an array is instantiated, the elements are assigned default values as follows: Array data type Default value byte, short, int, long 0 float, double 0 char nul character boolean false Any object reference (for example, a String) null

Assigning initial values to arrays:

  • Arrays can be instantiated by specifying a list of initial values.
    • Syntax: datatype [] arrayName = { value0, value1, …}; - where valueN is an expression evaluating to the data type of the array and is assigned to element at index N.
  • Examples:
    • Create an array of integers. The array will have 10 elements, since there are 10 values

supplied:

int magic = 13; int [] oddNumbers = {1, 3, 5, 7, 9, magic, magic + 2, 17, 19, 21}; System.out.println( oddNumbers[7] ); // prints 17 System.out.println( oddNumbers[4] ); // prints 9 System.out.println( oddNumbers[magic - 4 ] ); // prints 21 System.out.println( oddNumbers[5] - magic ); // prints 0

  • Notes:
    • The new keyword is not used.
    • The [ ]’s are empty; do not put in the size of the array.
      • The Java compiler will count the number of elements inside the { }’s and use that as the size of the array.
  • However, you can use Anonymous Arrays to assign values: double[] dailyMiles; dailyMiles = new double {170.3, 278.9, 283.2, 158.0, 433.3};
  • The code above works. The last statement is shorthand for: double[] anonymous = {170.3, 278.9, 283.2, 158.0, 433.3}; dailyMiles = anonymous;

Accessing Array Elements :

  • To access an element of an array, use: arrayName[exp] - where exp is evaluates to an int that is >= 0.
  • exp is the element’s index; it’s position within the array.
  • The index of the first element in an array is 0.
  • Each array has a read-only integer instance variable named length.
    • length holds the number of elements in the array.
    • Examples: int [] numbers = { 34, 42, 76, 98, - 109, 10 }; System.out.println( numbers[0] + " is the element at position 0"); System.out.println("The array numbers has " + numbers.length + " elements");
  • Notice the difference between the string method length and the

array instance variable length

String myName = new String("Peter Parker"); System.out.println("My name has " + myName.length() + "characters.");

  • How to access the last element in the array?
    • The elements in the array are numbered starting at 0.
    • The length instance variable will tell us the number of elements. int lastElement; lastElement = numbers.length - 1; System.out.println("last element of numbers is " + numbers[lastElement] );
  • Trying to access an element at a position < 0 , or at a position >= arrayName.length

will generate an error:

System.out.println("Element at location - 1 is " + numbers[-1]);

  • Gives the following error at runtime: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: - 1 at Sample.main(Sample.java:16)
  • Trying to execute: System.out.println("Element at location length is " + numbers[numbers.length]);
  • Gives the following error at runtime: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at Sample.main(Sample.java:18)

Reading data into an array:

  • We can read data from the user to put into an array: import java.util.Scanner; public class ReadDoubles { public static void main(String[] args) { Scanner inputScan = new Scanner(System.in); int i; double[] numbers = new double[10]; for (i = 0; i < numbers.length; i++) { System.out.print("Enter a number: "); numbers[i] = inputScan.nextDouble(); } System.out.println(); for (i = 0; i < numbers.length; i++) { System.out.print("numbers[" + i + "] is "); System.out.println( numbers[i] ); } } // end of method main } // end of class ReadDoubles

Summing elements of an array:

  • Once we have the values in an array, we can use loop(s) to perform calculations. For

example, we can extend the previous example to find the average of the numbers

the user enters:

double sum; double average; double [] numbers = new double[ ]; ... read in the numbers from the user ... sum = 0.0; for (i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; } if ( numbers.length != 0 ) average = sum / numbers.length; else average = 0.0; System.out.println("average is " + average);