66
CSCI 1226 Fall 2014 Reviews Section B

CSCI 1226 Fall 2014 Reviews Section B. Computers Types of computers: Personal computers Embedded systems Servers Hardware: I/O devices: mice,

Embed Size (px)

Citation preview

Page 1: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

CSCI 1226 Fall 2014 Reviews

Section B

Page 2: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Computers

Types of computers: Personal computers Embedded systems Servers

Hardware: I/O devices: mice, keyboards, monitors, etc CPU (Central Processing Unit) Memory, Main/Primary vs secondary

Exam tip!Examples of each type?

Exam tip!What are the differences?

Page 3: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

…Computers

Software: Data & instructions

» Algorithm» Pseudo-code

Data hierarchy:» 8 bits byte» 1 or more bytes data value (field)» 1 or more data values/objects object (record)» data may be stored on secondary memory (file)

Exam tip!What are the differences?

Exam tip!An object can contain other objects!

Page 4: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Java Programming Basics

IDE: Integrated Development Environment Variables:

Data types Naming rules and conventions

Math and special assignment operators +, -, *, /, % +=, -=, *=, /=. %= ++, --

Page 5: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

…Java Programming Basics

Output: System.out.println() and System.out.print()

» Print spaces» With or without quotes » Concatenation (using +, with math expressions, etc)

User input: Scanner class: instantiation, import, etc next(), nextLine(), nextInt(), nextDouble(), etc Use nextLine() to

» flush the input buffer

Exam tip!How to pause a program using nextLine()? See Utilities.java

Exam tip!Print all values in one line or each value in one line

Page 6: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Conditionals

Syntax: if, if-else, if-else if, if-else if … else

Comparison operators ==, !=, <, >, <=, >=

Logical operators && (AND), || (OR), ! (NOT)

Page 7: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… Conditionals

Sequential and nested if-else: Convert one to the other

What’s the output?:

What’s the code? Possible outcomes: outcome #1: A, B, C, E, F outcome #2: A, D, E, F

System.out.print(“A”);if (. . .){ System.out.print(“B”);}if (. . .){ System.out.print(“C”); if (. . .) { System.out.print(“D”); } else { System.out.print(“E”); }}

Page 8: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

boolean variables

Can save the answer to a comparison use a boolean variableboolean workedOvertime = (hours > 40);

» you don’t need parentheses, but it’s easier to read

E.g.) Write Boolean expressions for whether… x is greater than 0 and y is less than 5 x is greater than zero or y is equal to z it’s not the case that x is greater than the

product of y and z Exam tip!“whether” boolean

Page 9: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… boolean variables

Break complex expressions downboolean failedMidterm = (midtermGrade < 50);boolean failedFinal = (finalGrade < 50);boolean failedBothTests = failedMidterm && failedFinal;

String comparisons (all return boolean values) oneString.equals(anotherString) oneString.equalsIgnoreCase(anotherString) oneString.startsWith(anotherString) oneString.endsWith(anotherString)

Exam tip!boolean a = true, b = false, c = false;!aa && b (a || c) && (!b && !c) (a && !b) || c

Page 10: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Loops

for and while loops Convert between them

Loop structure Initialize, test/condition, update, process

for (initialize; test; update){

process;}

initialize;while (test) {

process;update;

}

Exam tip!When asked for an algorithm, make sure to include all these 4 steps!

Page 11: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… Loops

Write loops to: Calculate sum, average, max, min, of numbers When to stop?

» Negative number» Yes/no

Track the variable’s values:

a = 1;a++;b = a + 6;b--;c = b * 5;c += a;a *= 10;b /= 2;c %= 4;a *= b + c;

Exam tip!Write the loops for these with or without arrays!

Page 12: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Named Constants

public static final data-type CONST_NAME = value

Naming conventions variableName CONSTANT_NAME

Page 13: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Nested structures

Loops with Conditionalswhile (num >= 0) { // say whether num is divisible by 5 if (num % 5 == 0) { System.out.println(num + “ is divisible by 5.”); } else { System.out.println(num + “ is not divisible by 5.”); } // get next number num = kbd.nextInt();}

Page 14: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… Nested structures

if inside if:System.out.println(“A”);if (condition1) { System.out.println(“B”); if (condition2) { System.out.println(“C”); }} possible output:

AABABC

pattern:always Asometimes Bwhen B, sometimes C

Page 15: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… Nested structures

Rewrite sequential-if to cascading-if

if (age < 18) {System.out.print(“Child”);

}if (age >= 18 && age < 65) {

System.out.print(“Adult”);}if (age >= 65) {

System.out.print(“Senior”); }

if (age < 18) {System.out.print(“Child”);

} else if (age < 65) {System.out.print(“Adult”);

} else {

System.out.print(“Senior”);}

Page 16: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… Nested structures

Loops inside loops: Review A05 Draw a rectangle:

» Get w and h from user Draw a tree:

» Given the base size

Exam tip!A05 Solution is posted! Check it out!

Page 17: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Scopes of a variable/parameter

Inside loops Inside if-else Inside method (variables and parameters) Inside class (instance and class variables)

Page 18: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Methods

void vs value-returning System.out.println()? Math.sqrt(25.5)? etc

Use method calls in expressionsroot = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a);

Write math expressions in Java y = a = z =

Exam tip!str.equals(), str.startsWith(), str.toUpperCase()kbd.next(), kbd.nextLine(), etc

Page 19: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… Methods

For reading data (kbd is a Scanner) kbd.nextInt()

kbd.nextDouble()kbd.next()kbd.nextLine()

For checking strings (resp is a String) resp.equals(“yes”)

resp.equalsIgnoreCase(“yes”)resp.startsWith(“y”)resp.toLowerCase()

Page 20: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Arguments

“Arguments” are given to the method» we also say that the method takes arguments

Math.sqrt(10) – 10 is the (only) argument» asks Math for the square root of 10

Math.pow(5, 2) – 5 and 2 are both arguments» asks Math for 5 to the power 2 (i.e. 52)

arguments must be in the right order!» Math.pow(2, 5) is 25, not 52

Page 21: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Argument Types

Arguments must be the right type! Math.pow(“fred”, true) makes no sense!

» the two arguments must be numbers» doubles are OK: Math.pow(3.7, 1.98)

resp.startsWith(7) makes no sense!» the argument must be a String: resp.startsWith(“7”)

And in the right order and there must be the right number of them!

» Math.pow(5) and Math.pow(1, 2, 3) make no sense!

Page 22: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Exercise

Assume the calls below are correct. What argument type(s) does each method take? Math.getExponent(3400.2) Math.ulp(2.6) Math.scalb(4.5, 2) str.split(“:”, “one:two:three:four”) str.length() str.regionMatches(true, 0, “this”, 7, 50)

Page 23: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Return Types

Methods can return any kind of value» (or even none)

Math.sqrt(10) returns a double value Math.max(3, 5) returns an int value kbd.nextInt() returns an int value kbd.next() returns a String value str.toUpperCase() returns a String value str.indexOf(“n”) returns an int value

Page 24: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Exercise

Assuming the code below is correct, what kind of value does each method return?double x, y = 3.2;int n = 42;String name = “Mark”;boolean good;name = name.replaceFirst(“a”, “o”);x = Math.exp(y);n = Math.getExponent(x);good = (name.equalsIgnoreCase(“mork”));

Page 25: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Exercise

Void or value-returning? & what kind of value does each VRM return?if (answer.startsWith(“Y”)) { double x = Math.pow(3, 6); int n = kbd.nextInt(); System.out.println(“Hello!”); myWin.setVisible(true); double cm = Converter.cmFromFeetInches(n, x); thingamajig.doStuff(cm, x, that.get(n));}

Note: there are two method calls on the last line.How can we find out what kind of value get returns?

Page 26: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Method declaration

Header:1. public/private2. static (or non-static)3. return-type (void, int, double, String, boolean, Class, etc)

4. methodName5. (paramType1 param1, paramType2 param2, …) E.g.)

» public static double fahrenheitFromCelsius(double degC) » public boolean equalsTo(int a[], int b[])» private int[] subtract(int a[], int b[])

Exam tip!Write a method that takes <int, double, String, array> and returns <int, double, String, array, etc>

Takes parametersReturns return type

Page 27: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Arguments and Parameters

Arguments are values (10, 15.4, “Hello”) Parameters are variables

need to be declared like variables» (double degC), (int ft, double in)

only differences are:» declarations are separated by commas, not ;s» every parameter needs its own type, even if they’re

all the same type:• (double x, double y, double z), (int a, int b)

Exam tip!Given a list of parameters, a method call needs to have corresponding argument list!

Page 28: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Method Body

The method body is where you tell the computer how to compute the value needed

» how to convert feet and inches to cm» how to convert Celsius to Fahrenheit» ...

Need to know how to do it...» feet times 12 plus inches, all multiplied by 2.54

...and translate it into Java:result = (ft * 12 + in) * 2.54;

Page 29: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… Method Body

Anything you can do in main… …you can do in a method

(local) variable declarations (including objects) assignment statements selection controls (if, if-else, if-else-if) repetition controls (while, for) method calls (other things we haven’t learned about yet)

Exam tip!Did you see the related question in midterm?

Page 30: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Method “Stubs”

Our methods need return commands need to return the right kind of thing we want to return exactly the right value but Java doesn’t care!

So we can just put a “dummy” return in return something so that Java doesn’t complain worry about making it right later we call such a function a “stub” (it’s short)

Exam tip!As long as your methods compile with proper parameter lists and return types, your stubs are good enough (for this course)!

Page 31: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Converter Class with Stubs

public class Converter { public static double fahrenheitFromCelsius(double degC) { return 0.0; } public static double cmFromFeetInches(int ft, double in) { double result = 0.0; return result; }}

return statement is the last line of a method!

Page 32: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Naming Methods

Method names in mixed case capital letter for 2nd and subsequent words

The same as variable’s naming convention

Page 33: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Putting them together

public static returnType methodName(pType1 p1, pType2 p2) {

body...

return result;

}

returnType, pType1 and pType2 are int, or double, or String, or Class, or an array, or any data type we’ve seen!

methodName is the name of the method p1 and p2 are the parameters

body is for the commands calculating the result static is only needed for class (static) methods

Page 34: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Classes vs. Objects

Classes can be used right awayUtilities.printTitle(“Utilities Demo”);

» so long as we can “see” them

Objects need to be created» except for Strings, which are so massively useful…

Scanner kbd = new Scanner(System.in);objects contain datadifferent objects have different datamethods are mostly about that data

Exam tip!static methods!

Page 35: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Declaring Objects

Most Java objects created using new» usually with arguments» arguments depend on the class

kbd = new Scanner(System.in);rover = new Animal(Animal.DOG); // I made this up!c1 = new Color(255, 127, 0); // This is orangeokButton = new JButton(“OK”);

» not Strings, tho’s1 = “Strings are special!”;s2 = new String(“But this works, too!”);

Remember to import java.awt.Color;import javax.swing.JButton;

Page 36: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Student Class (Start)

public class Student {

private String aNumber; // A00...

private String name; // family name, givens

private int pctGrade; // 0..100

}

Exam tip!instance variables are declared private (not public)no “static”; no “final”!

Page 37: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Java modifiers

Access modifiers public private

Non-access modifiers static final

Page 38: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Which modifiers?

Instance variables private dataType

Class variables private static dataType

Instance constant public final dataType

Class constant public static final dataType

Exam tip!Class staticConstant final

Page 39: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Constructors

Constructor “builds” the object gives a value to each of the instance variables

private String aNumber; // A00…

private String name; // Last, First

private int grade;// 0 .. 100

public Student(String a, String n, int g) { aNumber = a; name = n; grade = g;

}a, n, and g are the parameters: the values the caller wants to use;

aNumber, name, and grade are the instance variables: the values we will use.

Page 40: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… Constructors

Generally declared public anyone can build a Scanner, a Student, …

Name is exactly the same as the class name class Student constructor named “Student” class Animal constructor named “Animal”

No return type not even void!

Argument for each instance variable (often)

Page 41: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… Constructors

Their job is to give a value to each instance variable in the class and so often just a list of assignment commands

» instanceVariable = parameter;aNumber = a;name = n;grade = g;

But may want to check if values make sense so maybe a list of if-else controls

Page 42: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Checking Values

If given value makes no sense, use a default» but still instanceVariable = (something);

public Student(String a, String n, int g) { if (a.startsWith(“A”) && a.length() == 9) { aNumber = a; } else { aNumber = “(illegal)”; } name = n; …}

Exam tip!Given object instantiation, write a constructor!

int r, g, b;r = g = b = 0;Colour col = new Colour(r,g,b);

• Set values of r, g, b if between [0,255]• Otherwise zero

Page 43: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Create a Student object

Student stu = new Student(“A00000000”, “Dent, Stu”, 100);

The argument list should match the parameter list of the constructor (String a, String n, int g)

The same as any other method callspublic static boolean equalsTo(int a[], int b[])

int[] a = new int[len];int[] b = new int[len];if (ArrayOperations.equalsTo(a, b)) {}

Page 44: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Getters and Setters

Getters:public String getANumber() { return aNumber;}

Setters:public void setPctGrade(int newGrade) { if (0 <= grade && grade <= 100) { pctGrade = newGrade; }}

Exam tip!Getters:

public!Anyone can ask!

Return type!Never void!

Non-static!Each student has own

name!Just return the instance variable!

Exam tip!Setters:

public!Anyone can change!

Return type!(usually) void!

Non-static!Each student has own

grade!Set the value (with some conditions)

Page 45: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

this keyword

Text definition:

“Within a method definition, you can use the keyword this as a name for the object receiving the method call.”

Page 46: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… this keyword

public class SomeClass {

private int var;

public SomeClass(){

this.var = 0;//instance variable

var = 0;//instance variable

}

public void incrementVar(int var){

this.var++;//instance variable

var++;//local parameter!!!

}

public void printVar(){

System.out.println(this.var);//instance variable

System.out.println(var);//instance variable

}}

Exam tip!this is only needed to disambiguate things.

Page 47: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Instance (non-static) and class (static)

Instance variables/methods Belongs to a particular object Each instance/object of the class has its own

value IM uses object’s values (IV)

Class (static) variables/methods Belongs to a particular class All the instances/objects of the class point to

the same CV (hence, the same value) CM uses CV (static) values

Page 48: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

final and Non-final

final means once it’s assigned a value, you cannot change it (immutable)!

Can be static and final (class constant) Or non-static and final (instance constant)

Page 49: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Class (static) Variables

public class Student {public final String A_NUMBER;private String name;private int pctGrade;

private static int nextANumber = 1;

nextANumber belongs to Student class not to each Student, but to every Student

Page 50: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Assigning Student Numbers

To create a student: assign the next available number update the next available number (continue setting other IVs)public Student(String n, int g) {

A_NUMBER = String.format(“A%08d”, nextANumber);++nextANumber;…

}

String.format is like System.out.printf, BUT it makes the String, it doesn’t print it

Page 51: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… Assigning Student Numbers

Student s1, s2;

s1 = new Student("Akiyama, Yasushi",75);

s2 = new Student("Cooper, Ray",90);

System.out.println(s1.A_NUMBER);

System.out.println(s2.A_NUMBER);

Output:A00000001A00000002

Page 52: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Car class

public class Car {

public final String VIN;

private static int numCars = 0;

//other constants and variables

public Car(double tankSize, double fuelConsumption) {

this.numCars++;

VIN = String.format("CSCI1226%04d", this.numCars);

//other operations

}

Page 53: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

… Car class

// create a few cars

Car car1 = new Car(45.0, 7.5);

Car car2 = new Car(45.0, 6.8);

Car car3 = new Car(40.0, 6.2);

System.out.println(car3.VIN);Output:

CSCI12260003

Page 54: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

toString() method

@Overridepublic String toString() { return name + “ (” + A_NUMBER + “)”}

Call it explicitly:Student s = new Student(“Pat”, 80);System.out.println(s.toString());

Or implicitly:Student s = new Student(“Pat”, 80);System.out.println(s);

Page 55: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Arrays

Page 56: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Array Base Types

Arrays can be of any base type, any sizeint[] score = new int[600];double[] weight = new double[70];boolean[] answers = new boolean[10];String[] words = new String[5000];

…any type at allScanner[] scanners = new Scanner[2];Student[] myStudents = new Student[10];

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

Exam tip!Make sure you know how to declare and create arrays of any data type!

Page 57: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Array Sizes

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

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

Page 58: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Arrays Know Their Own Length

Array length public static final int MAX_WORDS = 200;… String[] word = new String[MAX_WORDS]; if (word.length != MAX_WORDS) {

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

Exam tip!Don’t confuse with String’s length() method! arr.length is not a method, hence no (), and it’s final so cannot be changed!(public final field length;)

Page 59: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Creating Arrays with Values

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

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

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

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

2 3 5 7 11

Initialize.java

Page 60: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Average and Differences

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

WeeklyTemps.java

Page 61: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Arrays as Parameters

Methods can have [] parameters, just declare the parameter to be an array!public static int sumArray(int[] arr)

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

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

Page 62: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Method to Sum an Array

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

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

ArrayMethod.java

Page 63: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Returning Arrays

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

Like any other object-returning method, the object/array to be returned is newint[] result = new int[howMany];…return result;

ArrayReturn.java

Page 64: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Exercise

Be able to write: equalsTo subtract max min

from ArrayOperations.java

Page 65: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Final Exam (Section A)

Saturday, December 6, 2014, 7:00 pm - 10:00 pm ME Auditorium Hand-written test -- bring pen & whiteout or pencil &

eraser. No electronic devices allowed You may bring a reference sheet:

A single 8.5x11 (A4) sheet of paper. It may be hand-written or printed. You may use both sides of the sheet. You can prepare it alone or with friends, but bring your own copy (no

sharing copies during the test). If your sheet is too large (or otherwise breaks the rules), it will be

confiscated.

Page 66: CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,

Final Exam (Section B)

Friday, December 12, 2014, 9:00 am - 12:00 pm Atrium 101 Hand-written test -- bring pen & whiteout or pencil &

eraser. No electronic devices allowed You may bring a reference sheet:

A single 8.5x11 (A4) sheet of paper. It may be hand-written or printed. You may use both sides of the sheet. You can prepare it alone or with friends, but bring your own copy (no

sharing copies during the test). If your sheet is too large (or otherwise breaks the rules), it will be

confiscated.