+ All Categories
Home > Documents > Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Date post: 18-Jan-2016
Category:
Upload: william-sherman
View: 223 times
Download: 1 times
Share this document with a friend
Popular Tags:
44
Simple Arrays Simple Arrays Arrays of primitives and Arrays of primitives and Strings Strings Sections 7.1, 7.2 Sections 7.1, 7.2
Transcript
Page 1: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Simple ArraysSimple Arrays

Arrays of primitives and StringsArrays of primitives and Strings

Sections 7.1, 7.2Sections 7.1, 7.2

Page 2: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

ProblemProblem

Write a program to read six integers...Write a program to read six integers... ...& print them out in reverse order...& print them out in reverse order For example:For example:

Can’t use a single-variable loopCan’t use a single-variable loop need to remember all 6 numbersneed to remember all 6 numbers

Enter the six numbers below:5 3 7 2 99 41In reverse order they are:41, 99, 2, 7, 3, and 5

Reverse6.java

Page 3: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

SolutionSolution

int n1, n2, n3, n4, n5, n6;int n1, n2, n3, n4, n5, n6;S.o.pS.o.p(“Enter the six numbers below:\n”);(“Enter the six numbers below:\n”);n1 = kbd.nextInt();n1 = kbd.nextInt();n2 = kbd.nextInt();n2 = kbd.nextInt();n3 = kbd.nextInt();n3 = kbd.nextInt();n4 = kbd.nextInt();n4 = kbd.nextInt();n5 = kbd.nextInt();n5 = kbd.nextInt();n6 = kbd.nextInt();n6 = kbd.nextInt();kbd.nextLine();kbd.nextLine();S.o.pS.o.p(“In reverse order they are:\n”(“In reverse order they are:\n” + n6 + “, ” + n5 + “, ” + n4 + “, ”+ n6 + “, ” + n5 + “, ” + n4 + “, ” + n3 + “, ” + n2 + “, and ” + n1);+ n3 + “, ” + n2 + “, and ” + n1);

Page 4: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Related ProblemRelated Problem

Write a program to read six HUNDRED Write a program to read six HUNDRED integers & print them out in reverse orderintegers & print them out in reverse order

Need 600 ints: declare, input, & outputNeed 600 ints: declare, input, & output Individually named:Individually named:

int n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, int n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14, n15, n16, n17, n18, n19, n20, n21, n22, n23, n24, n14, n15, n16, n17, n18, n19, n20, n21, n22, n23, n24, n25, n26, n27, n28, n29, n30, n31, n32, n33, n34, n35, n25, n26, n27, n28, n29, n30, n31, n32, n33, n34, n35, n36, n37, n38, n39, n40, n41, n42, n43, n44, n45, n46, n36, n37, n38, n39, n40, n41, n42, n43, n44, n45, n46, n47, n48, n49, n50, n51, n52, n53, n54, n55, n56, n57, n47, n48, n49, n50, n51, n52, n53, n54, n55, n56, n57, n58, n59, n60, n61, n62, n63, n64, n65, n66, n67, n68, n58, n59, n60, n61, n62, n63, n64, n65, n66, n67, n68, n69, n70, n71, n72, n73, n74, n75, n76, n77, n78, n79, n69, n70, n71, n72, n73, n74, n75, n76, n77, n78, n79, n80, n81, n82, n83, n84, n86, n86, n87, n88, n89, n90, n80, n81, n82, n83, n84, n86, n86, n87, n88, n89, n90,

Reverse600HardWay.java

Page 5: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

A Better Way: ArraysA Better Way: Arrays

int[] n = new int[600]; int[] n = new int[600]; // creates 600 ints// creates 600 ints n is called an n is called an arrayarray ( (of intsof ints)) n has 600 n has 600 components components or or elementselements

each one is an int variableeach one is an int variable Their names are:Their names are:

n[0], n[1], n[2], n[3], n[4], ... , n[599]n[0], n[1], n[2], n[3], n[4], ... , n[599] Number in [brackets] is called the Number in [brackets] is called the indexindex

Page 6: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Multiple Variables Multiple Variables vsvs. Array. Array

int n0, n1, n2, n3, n4, n5, n6, n7, n8, n9;int n0, n1, n2, n3, n4, n5, n6, n7, n8, n9;

int[] n = new int[10];int[] n = new int[10]; n0

n3

n1n2

n4n5n6n7n8n9

n

n[0]

n[3]

n[1]

n[2]

n[4]

n[5]

n[6]

n[7]

n[8]

n[9]

Page 7: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Thinking of Array ElementsThinking of Array Elements

n[0], n[1], n[2], ... are just better ways to n[0], n[1], n[2], ... are just better ways to write n0, n1, n2, ...write n0, n1, n2, ...

Why?Why? because you can say n[i] for the ibecause you can say n[i] for the ithth n… n… ……and then you can put it in a loopand then you can put it in a loop

for (int i = 0; i < 600; i++) {for (int i = 0; i < 600; i++) {… … n[i] …n[i] …

}}

Remember this!You’ll see it a LOT!

Page 8: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Using ArraysUsing Arrays

Reading and printing those 600 ints?Reading and printing those 600 ints?n[0] = kbd.nextInt();n[0] = kbd.nextInt();n[1] = kbd.nextInt();n[1] = kbd.nextInt();n[2] = ...n[2] = ...System.out.print(n[599] + ‘ ’ + n[598] + ‘ ’ …);System.out.print(n[599] + ‘ ’ + n[598] + ‘ ’ …);

No—use loopsNo—use loopsfor (int i = 0; i < 600; i++)for (int i = 0; i < 600; i++) n[i] = kbd.nextInt();n[i] = kbd.nextInt();for (int i = 599; i >= 0; i--)for (int i = 599; i >= 0; i--) System.out.print(n[i] + ‘ ’)System.out.print(n[i] + ‘ ’);;

Reverse600EasyWay.java

Page 9: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Notes on Array IndicesNotes on Array Indices

We declare We declare int[] n = new int[10]; int[] n = new int[10]; but there is no but there is no element called n[10]element called n[10] elements go from 0 to 9elements go from 0 to 9 any other number is any other number is out of boundsout of bounds

» crash with crash with ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException» crash message says what the wrong index wascrash message says what the wrong index was

Low numbers are at Low numbers are at frontfront or or toptop of the array of the array High numbers are at High numbers are at backback or or bottombottom

ArrayCrash.java

Page 10: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Notes on Array IndicesNotes on Array Indices

Index will Index will usuallyusually be a simple variable be a simple variable the loop control variable: the loop control variable:

for (int i = 0; i < MAX; i++) {for (int i = 0; i < MAX; i++) { ... ... num[i]num[i] ... ...}}

Index Index cancan be any int-valued expression be any int-valued expression ... num[i + 1] ...... num[i + 1] ... in an i loopin an i loop ... num[i – 1] ...... num[i – 1] ... in an i loopin an i loop ... num[10*r + c] ...... num[10*r + c] ... in nested r & c loopsin nested r & c loops

See, for example, StudentNames.java

Page 11: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Array Base TypesArray Base Types

Arrays can be of any Arrays can be of any base typebase type, any size, any sizeintint[] score = new [] score = new intint[600];[600];

doubledouble[] weight = new [] weight = new doubledouble[70];[70];

booleanboolean[] answers = new [] answers = new booleanboolean[10];[10];

StringString[] words = new [] words = new StringString[5000];[5000];

……any type at allany type at allScannerScanner[] scanners = new [] scanners = new ScannerScanner[2];[2];

StudentStudent[] myStudents = new [] myStudents = new StudentStudent[10];[10];

The text recommends singular names.I tend to use plural.

Page 12: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Array SizesArray Sizes

Remember to declare constants for numbers Remember to declare constants for numbers you use in multiple placesyou use in multiple places like in array declaration and loop!like in array declaration and loop! int[] nums = new int[int[] nums = new int[NUM_ITEMSNUM_ITEMS];]; for (int i = 0; i < for (int i = 0; i < NUM_ITEMSNUM_ITEMS; i++); i++) nums[i] = kbd.nextInt();nums[i] = kbd.nextInt();

Makes it easy to change the number laterMakes it easy to change the number later// # elements – change to 600 when debugged!// # elements – change to 600 when debugged!public static final int NUM_ITEMS = 6;public static final int NUM_ITEMS = 6;

Page 13: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Arrays Know Their Own LengthArrays Know Their Own Length

Instance variable lengthInstance variable lengthpublic static final int MAX_WORDS = 200;public static final int MAX_WORDS = 200;…… String[] word = new String[MAX_WORDS];String[] word = new String[MAX_WORDS]; if (if (word.lengthword.length != MAX_WORDS) { != MAX_WORDS) {

System.err.println(“Your computer is broken!”);System.err.println(“Your computer is broken!”);}}

NOTE: it’s not a method; it’s a public instance variable

Page 14: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Creating Arrays with ValuesCreating Arrays with Values

Create an array object by listing elementsCreate an array object by listing elementsint[] arr = int[] arr = new int[]{2, 3, 5, 7, 11};new int[]{2, 3, 5, 7, 11};

It knows its own length!It knows its own length!for(int i = 0; i < arr.length; i++) {for(int i = 0; i < arr.length; i++) {

System.out.print(arr[i] + “ ”);System.out.print(arr[i] + “ ”);}}

Can change the array laterCan change the array laterarr = arr = new int[]{13, 17, 19, 23};new int[]{13, 17, 19, 23};

2 3 5 7 11

Initialize.java

Page 15: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

What Do We Use Arrays For?What Do We Use Arrays For?

Lists, mostlyLists, mostly when we need to remember the earlier values when we need to remember the earlier values

after we’ve read the later onesafter we’ve read the later ones» otherwise we can just use one variable in a loopotherwise we can just use one variable in a loop

Example:Example: read a list of numbers, calculate its average, read a list of numbers, calculate its average,

then say how different each number is from the then say how different each number is from the averageaverage

Page 16: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Average and DifferencesAverage and Differences

// read and sum the numbers// read and sum the numbersint[] num = new int[NUM_ITEMS];int[] num = new int[NUM_ITEMS];int sum = 0;int sum = 0;S.o.p(“Enter the ” + NUM_ITEMS + “ items below”);S.o.p(“Enter the ” + NUM_ITEMS + “ items below”);for (int i = 0; i < NUM_ITEMS; i++) {for (int i = 0; i < NUM_ITEMS; i++) { num[i] = kbd.nextInt();num[i] = kbd.nextInt(); // remember the #// remember the # sum += num[i];sum += num[i]; // add it to sum// add it to sum}}// calculate the average// calculate the averagedouble ave = (double)sum / (double)NUM_ITEMS;double ave = (double)sum / (double)NUM_ITEMS;// print the difference from the average of each// print the difference from the average of eachfor (int i = 0; i < NUM_ITEMS; i++) {for (int i = 0; i < NUM_ITEMS; i++) { S.o.p((num[i] – ave));S.o.p((num[i] – ave));}}

WeeklyTemps.java

Page 17: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

ExerciseExercise

Declare this array of Strings:Declare this array of Strings:

print it out on one line (with spaces between)print it out on one line (with spaces between) DON’T COUNT THE WORDS!DON’T COUNT THE WORDS!

word“to”“be”“or”“not”“to”“be”

Page 18: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Java Arrays Created at Run TimeJava Arrays Created at Run Time

Can ask the user how big to make an arrayCan ask the user how big to make an array» can’t do that in C++can’t do that in C++

System.out.print(“How many students? ”);System.out.print(“How many students? ”);int numStu = kbd.nextInt();int numStu = kbd.nextInt(); kbd.nextLine();kbd.nextLine();String[] name = new String[numStu];String[] name = new String[numStu];System.out.println(“What are their names?”);System.out.println(“What are their names?”);for (int s = 0; s < numStu; s++) {for (int s = 0; s < numStu; s++) {

name[s] = kbd.nextLine();name[s] = kbd.nextLine();}}

StudentNames.java

Page 19: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Array Lengths are FinalArray Lengths are Final

Can’t change the size of an array after you Can’t change the size of an array after you create it(*)create it(*)int[] n = new int[10];int[] n = new int[10];System.err.println(“Oops! Need it bigger!”);System.err.println(“Oops! Need it bigger!”);n.length = 20;n.length = 20; // illegal// illegal

(*) But you (*) But you cancan change the variable to point change the variable to point to a new (larger) array!to a new (larger) array!int[] n = new int[10];int[] n = new int[10];System.err.println(“Oops! Need it bigger!”);System.err.println(“Oops! Need it bigger!”);n = new int[20];n = new int[20]; // OK!// OK! Bigger.java

Page 20: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

But What About…But What About…

New, larger array is all zeroes!New, larger array is all zeroes! If you want to keep the old values, you need If you want to keep the old values, you need

to copy them into the new arrayto copy them into the new arrayint[] num = new int[]{1,2,3,4,5};int[] num = new int[]{1,2,3,4,5};int[] bigger = new int[2 * num.length];int[] bigger = new int[2 * num.length];for (int i = 0; i < num.length; i++) {for (int i = 0; i < num.length; i++) { bigger[i] = num[i];bigger[i] = num[i];}}num = bigger;num = bigger;

1 2 3 4 5 0 0 0 0 0 0 0 0 0 01 2 3 4 5

num bigger

BetterBigger.java

Page 21: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Command Line ArgumentsCommand Line Arguments

Remember how we declare main?Remember how we declare main?public static void main(String[] args)public static void main(String[] args) never really explained never really explained String[] argsString[] args it’s an array of Strings...it’s an array of Strings... ...passed into your program......passed into your program... ...from the “command line”...from the “command line”

prompt] java PrintArgs command line argumentsMy 3 command line arguments were: 0: “command” 1: “line” 2: “arguments”

Page 22: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Command Line ArgumentsCommand Line Arguments

Add words after the name of the classAdd words after the name of the class

They get passed to the programThey get passed to the program» (unless they start with < or >, or ...)(unless they start with < or >, or ...)

Appear in the String[] parameter of mainAppear in the String[] parameter of main each each wordword is a separate array element is a separate array element

prompt] java PrintArgs command lineMy 2 command line arguments were: 0: “command” 1: “line”

Page 23: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

NetBeans & the Command LineNetBeans & the Command Line

File > Project Properties…File > Project Properties… or right-click on project name in Projects paneor right-click on project name in Projects pane

Page 24: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Command Line ArgumentsCommand Line Arguments

You can use args like any other arrayYou can use args like any other array ask it its lengthask it its length loop thru its elementsloop thru its elements ask for some elementask for some elementSystem.out.println(“My ” + args.length + “ arguments:”);System.out.println(“My ” + args.length + “ arguments:”);for (int i = 0; i < args.length; i++) {for (int i = 0; i < args.length; i++) {

System.out.println(i + “:\t\"” + args[i] + “\"”);System.out.println(i + “:\t\"” + args[i] + “\"”);}}args

“command”“line”

My 2 arguments: 0: "command" 1: "line"

Page 25: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

args is a String[]args is a String[]

OK to have a String[]OK to have a String[] can have an array of can have an array of anythinganything (pretty much) (pretty much)

Even if you type in numbers!Even if you type in numbers!

» you can use Integer.parseInt(args[i]) to get the you can use Integer.parseInt(args[i]) to get the integer value of args[i]integer value of args[i]

prompt] java PrintArgs 5 10My 2 command line arguments were: 0: “5” 1: “10”

see AddArgs.java

Page 26: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Arrays as ParametersArrays as Parameters

args is a String[] parameter for mainargs is a String[] parameter for main Other methods can have [] parameters, tooOther methods can have [] parameters, too

just declare the parameter to be an array!just declare the parameter to be an array!public static int sumArray(int[] arr)public static int sumArray(int[] arr)

It’s just like any other parameterIt’s just like any other parameter gets its value from the method callgets its value from the method call

It’s just like any other arrayIt’s just like any other array it knows how long it isit knows how long it is

Page 27: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Method to Sum an ArrayMethod to Sum an Array

Array comes from callerArray comes from callerint[] n = new int[]{2, 3, 5, 7, 11};int[] n = new int[]{2, 3, 5, 7, 11};int addedUp = int addedUp = sumArray(n)sumArray(n);;

Method adds up its elementsMethod adds up its elementspublic static int sumArray(public static int sumArray(int[] arrint[] arr) {) { int sum = 0;int sum = 0; for (int i = 0; i < for (int i = 0; i < arr.lengtharr.length; i++) {; i++) { sum += sum += arr[i]arr[i];; }} return sum;return sum;}}

ArrayMethod.java

Page 28: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

ExerciseExercise

Write a method that receives an array of Write a method that receives an array of words and prints them out one per line.words and prints them out one per line.

Write a method that receives an array of Write a method that receives an array of doubles and returns the largest value in itdoubles and returns the largest value in it

Page 29: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Returning ArraysReturning Arrays

Methods can return arraysMethods can return arrays return type is an array typereturn type is an array typepublic public int[] int[] dice(int howMany) { … }dice(int howMany) { … }public public String[] String[] wordsFrom(String line) { … }wordsFrom(String line) { … }

The array to be returned is (usually) newThe array to be returned is (usually) newint[] result = new int[howMany];int[] result = new int[howMany];for (int d = 0; d < howMany; ++d) {for (int d = 0; d < howMany; ++d) { result[i] = 1 + (int)(6 * Math.random());result[i] = 1 + (int)(6 * Math.random());}}return result;return result;

ArrayReturn.java

Page 30: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

ExerciseExercise

Make a method that returns a specified Make a method that returns a specified number of copies of a word in an arraynumber of copies of a word in an array for example:for example:String[] items = copies(6, "Hello");String[] items = copies(6, "Hello");

items“hello”“hello”“hello”“hello”“hello”“hello”

Page 31: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Printing an ArrayPrinting an Array

Can’t just use System.out.print:Can’t just use System.out.print:int[] a = new int[]{1,2,3,4};int[] a = new int[]{1,2,3,4};System.out.println(a);System.out.println(a); they don’t have a toString method of their ownthey don’t have a toString method of their own we can’t add one to themwe can’t add one to them

Could write a methodCould write a method but we’d need lots of them…but we’d need lots of them… ……and that’s such a pain.and that’s such a pain.

[I@1db9742

Page 32: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

The Arrays ClassThe Arrays Class

java.util.Arrays has helper methods:java.util.Arrays has helper methods: toString method for arraystoString method for arraysint[] a = new int[]{1,2,3,4};int[] a = new int[]{1,2,3,4};System.out.println(Arrays.toString(a));System.out.println(Arrays.toString(a)); works for any kind of array!works for any kind of array! needs to be importedneeds to be imported

java.util.Arrays also includes methods to java.util.Arrays also includes methods to copycopy, , searchsearch, , fillfill, , comparecompare and and sortsort arrays! arrays!

[1, 2, 3, 4]

[1.0, 2.2][word1, word2]

Page 33: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Sorting an ArraySorting an Array

Just give the array to Arrays.sortJust give the array to Arrays.sort It’ll come back sortedIt’ll come back sorted

int[] a = new int[]{4, 2, 7, 1, 9, 9, 4};int[] a = new int[]{4, 2, 7, 1, 9, 9, 4};Arrays.sort(a);Arrays.sort(a);System.out.println(Arrays.toString(a));System.out.println(Arrays.toString(a));

Works for (almost) any kind of arrayWorks for (almost) any kind of array works for Strings – works for Strings – sort ofsort of

» it’s not quite what you’d expectit’s not quite what you’d expect

[1, 2, 4, 4, 7, 9, 9]

ArraySorter.java

Page 34: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Modifying ArraysModifying Arrays

Arrays can be modified by methodsArrays can be modified by methodsint[] a = new int[] {1, 2, 3, 4};int[] a = new int[] {1, 2, 3, 4};doubleEachElement(a);doubleEachElement(a);System.out.println(Arrays.toString(a));System.out.println(Arrays.toString(a));

Just a normal methodJust a normal methodpublic static void doubleEachElement(int[] arr) {public static void doubleEachElement(int[] arr) {

for (int i = 0; i < arr.length; ++i) {for (int i = 0; i < arr.length; ++i) { arr[i] *= 2; arr[i] *= 2;}}

}}

[2, 4, 6, 8]

ArrayDoubler.java

Page 35: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Reference TypesReference Types

Variables in Java are Variables in Java are referencesreferences » except primitive types like int, double, boolean, …except primitive types like int, double, boolean, …

they they point to point to objectsobjectsint[] a = new int[]{1, 2, 3, 4};int[] a = new int[]{1, 2, 3, 4};Student s = new Student(“Jo”);Student s = new Student(“Jo”);String word = “Hi!”;String word = “Hi!”;

&

a

1

2

3

4

&

s

&

word

“Hi!”

A00000001

“Jo”

0

Page 36: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Co-ReferenceCo-Reference

Two variables can refer to the same objectTwo variables can refer to the same objectCar myCar = new Car(blue);Car myCar = new Car(blue); // new Car// new CarCar stevesCar = new Car(blue);Car stevesCar = new Car(blue); // new Car, same // new Car, same colourcolourCar disCar = myCar;Car disCar = myCar; // same // same CarCar as myCar as myCardisCar.setColor(green);disCar.setColor(green); // // myCarmyCar is now green is now green

&myCar:

&disCar:

&stevesCar:

Car variables Car objects

disCar and myCar are not two different cars. They’re two different names for the same

car.

Page 37: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Array (and Object) ParametersArray (and Object) Parameters

Method call passes Method call passes referencereference to object to object parameter points to same object as argumentparameter points to same object as argument thus method can change the objectthus method can change the objectint[] a = new int[] {1, 2, 3, 4};int[] a = new int[] {1, 2, 3, 4};doubleEachElement(a);doubleEachElement(a);……public static void doubleEachElement(int[] arr) {public static void doubleEachElement(int[] arr) {

for (int i = 0; i < arr.length; ++i) {for (int i = 0; i < arr.length; ++i) { arr[i] *= 2; arr[i] *= 2;}}

}}

&

a1

2

3

4

&

arr

2

4

6

8

ArrayDoubler.java

Page 38: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Doesn’t Work for PrimitivesDoesn’t Work for Primitives

Method call passes Method call passes actual valueactual value parameter has same parameter has same valuevalue as argument as argument thus method cannot change argument variablethus method cannot change argument variableint a = 3;int a = 3;doubleValue(a);doubleValue(a);……public static void doubleValue(int n) {public static void doubleValue(int n) {

n *= 2;n *= 2;}}

a

3

3

n

6ArrayDoubler.java

Page 39: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Can’t Change Argument VariableCan’t Change Argument Variable

Method call passes Method call passes referencereference to object to object parameter points to same object as argumentparameter points to same object as argument but it’s NOT the same variable!but it’s NOT the same variable!int[] a = new int[] {1, 2, 3, 4};int[] a = new int[] {1, 2, 3, 4};changeTheArray(a);changeTheArray(a);……public static void changeTheArray(int[] arr) {public static void changeTheArray(int[] arr) {

arr = int[] {5, 6, 7, 8};arr = int[] {5, 6, 7, 8};}}

&

a1

2

3

4

&

arr

5

6

7

8 ArrayDoubler.java

Page 40: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Variable Variable vsvs. Object. Object

UsuallyUsually think of them as the same thing think of them as the same thing but they’re but they’re notnot actuallyactually the same thing the same thing

Variable is used to refer to an objectVariable is used to refer to an object essentially a name we use for the objectessentially a name we use for the object

The object is a separate thingThe object is a separate thing it has the data in itit has the data in it it’s the one you talk to when you use the dot (.)it’s the one you talk to when you use the dot (.)

» but before the dot is the name we use for the objectbut before the dot is the name we use for the object

Page 41: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Null ReferencesNull References

A reference variable can refer to nothingA reference variable can refer to nothingint[] a = null;int[] a = null;Student s = null;Student s = null;String word = null;String word = null; it’s not pointing at any objectit’s not pointing at any object can make it point to an object latercan make it point to an object latera = new int[]{3, 4, 5};a = new int[]{3, 4, 5};

/

a

/

s

/

word

3

4

5

&

a

Page 42: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Null Pointer ExceptionNull Pointer Exception

Can’t talk to things that don’t existCan’t talk to things that don’t exist» Java won’t let youJava won’t let you

can’t use . with a null variablecan’t use . with a null variable» can’t use […] eithercan’t use […] either» program will program will crashcrash

int[] a = null;int[] a = null;for (int i = 0; i < for (int i = 0; i < a.lengtha.length; ++i) {; ++i) { a[i]a[i] = (i + 1); = (i + 1);}}

/

a

Exception in thread "main" java.lang.NullPointerException

Page 43: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Array Exceptions You Might SeeArray Exceptions You Might See

ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException you tried to get an array element …you tried to get an array element … … … but that element doesn’t existbut that element doesn’t exist

NullPointerExceptionNullPointerException you tried to get an array element …you tried to get an array element … … … but that but that arrayarray doesn’t exist doesn’t exist

When your program crashes, read the When your program crashes, read the message and try to understand it!message and try to understand it!

Page 44: Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

QuestionsQuestions


Recommended