Download presentation
Presentation is loading. Please wait.
Published byDelilah Briggs Modified over 9 years ago
1
Introduction to Computing Concepts Note Set 21
2
Arrays Declaring Initializing Accessing Using with Loops Sending to methods
3
The Array Array - Group of variables that all have the same type and can be accessed with the same name and a given position In RAM, stored as a contiguous block of memory
4
Declaring an Array Arrays are objects in Java. Declare an array reference with brackets between data type and identifier General form ▫ dataType [] identifierName; Examples ▫ int[] ages; ▫ float [] grades ▫ JButton [] buttons;
5
Declaring an Array int [] values = new int[10]; Size of the array – how many elements it can hold Dictates the bounds of the array values Arrays are “zero-subscripted” – Counting starts at zero (0) instead of 1. 0 1 2 3 4 5 6 7 8 9
6
Accessing Can access an array by using the name/identifier and the location/index of the element of the array int [] values = new int[10]; values [3] = 27; values [9] = 33; What’s the max subscript of an array with 5 elements? … with 10 elements? … with n elements?
7
Accessing Can access an array by using the name/identifier and the location/index of the element of the array int [] values = new int[10]; values [3] = 27; values [9] = 33; int sum = values[3] + values[9];
8
Length of an array Arrays can tell you their length Useful with for-loops int [] values = new int[10]; int [] grades = new int [85]; System.out.println(values.length); System.out.println(grades.length); int [] values = new int[10]; for (int i = 0; i < values.length; i++) { System.out.print(“Enter a number: “); values[i] = myScanner.nextInt(); }
9
Arrays and methods public static void main (String [] args) { int [] arr = {1, 2, 3, 4, 5, 6}; //Initialization list int s = method(arr); //other stuff } public static int method(int [] vals) { int sum = 0; for (int i = 0; i < vals.length; i++) sum += vals[i]; return sum; }
10
May not use [0] sometimes Sometimes, the problem may lend itself to use subscripts 1 – n rather than subscripts 0 – (n – 1) ▫ Thinks months of the year ▫ String [] months = new String[13]; valid subscripts: Those used here:
11
Breakout 1
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.