COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

82
COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014

Transcript of COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

Page 1: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110:Introduction to Programming

Tyler JohnsonMar 2, 2009

MWF 11:00AM-12:15PMSitterson 014

Page 2: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20092

Announcements

Midterm on WedHanded back on Friday

Key to practice midterm has been posted

Program 3 due today by 5pm

I’ll be out of town March 16 & 18John Hansen will be lecturing

Page 3: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20093

Midterm

No computers, notes, calculators etc.

You will be allowed a 1-page cheat-sheet

Page 4: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20094

Questions?

Page 5: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20095

Today in COMP 110

Review for Midterm

Page 6: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20096

Hardware vs. Software

HardwarePhysical machineCPU, Memory

Software Set of instructions for the machine to execute

Page 7: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20097

Memory

Holds data for the computer to processMain Memory (RAM – Random Access Memory)

Used for intermediate calculationsUsed to store the current program itself!Expensive

Auxiliary Memory (Secondary Memory)Disk drives, CDs, Flash drivesCheap

Page 8: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20098

What is a Byte?

Data, such as numbers and keyboard characters are stored as series of bitsA bit is a digit with value 1 or 0Examples

00111010 is a byte with value 5801000001 is a byte with value 6501100001 is a byte with value 97

A byte is composed of 8 bitsJust large enough to store a keyboard character

Page 9: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20099

Compiling & Running Java Programs

Java program

Java compiler

Bytecode program

Bytecode interpreter(Java JVM)

Machine code

Compiling a Java program

Running a Java program

Human-readable

Machine-readable

Java JVM-readable

Page 10: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200910

Comments in Java

Two Types

Single-line comment• Begins with “//”

int i; //this is a single-line comment, write whatever you want

Multi-line comment• Everything within /* */

public class Program { /*

This is a multi-line comment. The compiler will completely ignore this text*/public static void main(String[] args) {

Page 11: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200911

Algorithms and Pseudocode

Algorithm – a set of instructions for solving a problem

Pseudocode – combination of code and English used to express an algorithm before writing algorithm into code

Page 12: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200912

Variables

Used to store data in a program

The data currently in a variable is its value

Value can change throughout a program

Name of variable is an identifier

Choose variable names that are meaningful!

Page 13: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200913

How to Use Variables

Declare a variableint number;

Assign a value to the variablenumber = 37;

Change the value of the variablenumber = 513;

Page 14: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200914

Keywords

Reserved words with predefined meaningsYou cannot name your variables keywordsif, else, return, new

Page 15: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200915

Type

What kind of value the variable can holdTwo kinds of types

Primitive type - indecomposable values (single number or letter)• int, double, char, boolean

Class type - objects with both data and methods• Scanner, System

Page 16: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200916

Four Kinds of Primitive Types

Integer typesbyte, short, int, longRepresent whole numbers such as 0, 5, 1883443

Floating-point types float, doubleRepresent numbers with some fractional component such as 1.01, 3932.123532, 0.0

CharactercharRepresents a single character such as ‘A’, ‘;’, ‘8’

BooleanbooleanRepresents a single bit (on or off, true or false, 1 or 0)

Page 17: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200917

Java Primitive Types

Type Name

Kind of Value

Memory Used

Range of Values

byte Integer 1 byte -128 to 127

short Integer 2 bytes -32,768 to 32,768

int Integer 4 bytes -2,147,483,648 to 2,147,483,647

long Integer 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

float Floating-point 4 bytes ±3.40282347 x 10+38 to ±1.40239846 x 10-45

double Floating-point 8 bytes ±1.79769313486231570 x 10308 to ±4.94065645841246544 x

10-324

char Character 2 bytes 0 to 65,535

boolean boolean 1 bit True or False (0 to 1)

Page 18: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200918

How to Name Variables

Use a combination ofLetters, digits (0-9), underscore (_)

First character cannot be a digit

Java is case sensitive “myVariable” & “myvariable” are considered different identifiers

Page 19: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200919

Assignment Statements

Change a variable’s valueSyntax:

variable = expression;

Example:sleepNeeded = 8;sleepDesired = sleepNeeded * 2;

‘=’ sign is called the assignment operator

Page 20: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200920

Assignment Compatibilities

byte » short » int » long » float » double

A value of any type in the list can be assigned to a type further down the list

Exampleint iVar = 7;double dVar = iVar; //this is legal

Page 21: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200921

Type Casting

Type casting allows you to override assignment compatibilities

Exampledouble distance = 9.0;int points = (int)distance; //cast distance to an int

//distance is not changed in any way

//the value of points will be 9int x = (int)(6.0 + 5.5)

Page 22: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200922

Type Casting

Type casting is not rounding!The effect of a type cast is truncation

Any fractional portion is discardedJust like when you divide two integers

Exampledouble bill = 25.75;int dollars = (int)bill ; //cast bill to an int//bill is not changed in any way//the value of dollars will be 25

Page 23: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200923

Arithmetic Operators

Unary operators+, -, ++, --, !

Binary arithmetic operators*, /, %, +, -

Page 24: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200924

Division Operator

The division operator (/) behaves differently depending on the data types used!Example

9 / 2 = 4 • Truncation when used with integers

9.0 / 2 = 4.5• Maintains fractions when used with real numbers

Page 25: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200925

Remainder Operator

The remainder or modulo operator (%) gives the remainder when one whole number is divided by another

Examplei = 10%4; //the value of i will be 2j = 6%3; //the value of j will be 0k = 17%6; //the value of k will be 5

Page 26: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200926

Specialized Assignment Operators

+=

a += 3; //same asa = a + 3;

-=

a -= 4; //same asa = a – 4;

*=

a *= 2; //same asa = a * 2;

/=

a /= 3; //same asa = a / 3;

Page 27: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200927

Parentheses and Precedence

Expressions inside parentheses evaluated first

(cost + tax) * discountcost + (tax * discount)

Highest Precedence

First: the unary operators +, -, ++, --, !Second: the binary operators *, /, %Third: the binary operators +, -

Lowest Precedence

Page 28: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200928

Programming Errors

Syntax Error – Failure to follow the rules of the language

E.g. missing semi-colon

Run-time Error – An error that causes the program to halt and produce an error message

E.g. Program crashes

Logic Error – When a program fails to produce the correct result

E.g accidentally using addition when you meant to use subtractionHardest to locate!

Page 29: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200929

Strings

A string is a sequence of characters“Hello world!”“Enter a whole number from 1 to 99.”

String (capital S) is a class in Java, not a primitive type

Page 30: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200930

String Indices

Strings consist of a sequence of characters

Each character has a position in the String

U N C i s G r e a t

0 1 2 3 4 5 6 7 8 9 10

11

Positions

Characters

Page 31: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200931

String Concatenation

We can concatenate two Strings together using the (+) operator

Example

String name = “Bob”;String greeting = “Hi ” + name;System.out.println(greeting);//prints “Hi Bob” to the screen

Page 32: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200932

String Methods

string.length()string.equals(A_String)string.toLowerCase();

And others

Page 33: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200933

Escape Characters

\" Double quote

\' Single quote

\\ Backslash

\n New line

\r Carriage return

\t Tab

Page 34: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200934

Keyboard Input

Scanner kb = new Scanner(System.in);int num = kb.nextInt();double d = kb.nextDouble();

Page 35: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200935

Boolean Expressions

(result == 0) is a boolean expression

Boolean expressions evaluate to either true or false

Examples10 > 5, (true)4 > 6, (false)Integers are whole numbers, (true)

Page 36: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200936

If-Else Statement

An if-else statement allows us to make decisions in a program

int result = n % 2;

if(result == 0)System.out.println(“That number is even!”);

elseSystem.out.println(“That number is odd!”);

Page 37: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200937

Java Comparison Operators

Math

Java Name

= == Equal to

≠ != Not equal to

> > Greater than

≥ >= Greater than or equal to

< < Less than

≤ <= Less than or equal toExample expressions:

variable <= 6myInt > 55 == 3

Page 38: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200938

&&, || operators

AND

if ((temperature > 50) && (temperature < 75)) {// walk to school

}

OR

if (sunny || cloudy) {// walk to school

}

Page 39: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200939

The ! Operator (NOT)

Boolean negation!false is true!true is false

Example

boolean cloudy;

if (!cloudy) {// walk to school if it’s not cloudy

}

Page 40: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200940

Effect of Boolean Operators

A B A && B

A || B !A

true true true true false

true false false true false

false true false true true

false false false false true

Page 41: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200941

The Type boolean

Can be either true or false

boolean sunny = true;boolean cloudy = false;

if (sunny || cloudy) {// walk to school

}

41

Page 42: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200942

Nested If Statements

if(balance >= 0) {if(INTEREST_RATE >= 0) balance = balance +

INTEREST_RATE*balance;else

System.out.println(“Negative Interest!”);}else

balance = balance – FEE;

Page 43: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200943

Multi-Branch If Statements

if(score >=90)grade = ‘A’;

else if(score >=80)grade = ‘B’;

else if(score >=70)grade = ‘C’;

else if(score >=60)grade = ‘D’;

elsegrade = ‘F’;

Page 44: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200944

Switch Statement Example

int year;…switch(year) {

case 1: System.out.println(“You are a freshman”); break;

case 2: System.out.println(“You are a sophomore”);

break;case 3: System.out.println(“You are a junior”);

break;case 4: System.out.println(“You are a senior”); break;default: System.out.println(“This is a default case”); break;

}

Page 45: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200945

Enumerations

An enumeration allows us to give unique numeric values to a list of items

enum Flavor {Vanilla, Chocolate, Strawberry}

This statement assigns a unique numeric value to each of {Vanilla, Chocolate, Strawberry}

Page 46: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200946

Floating-Point Numbers

Consider the number 1/3 = 0.333333

Computers have finite storage and cannot store infinitely repeating decimals

In a computer, the number 1/3 is stored as 0.333333, with part of the fraction missing or truncated

Since 0.333333 is < 1/3, this representation is inexact

Page 47: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200947

Floating-Point Comparison

To compare two floating-point numbers, check if the difference is within some tolerance

float a,b;final float EPSILON = 1e-6; //10^-6…if(Math.abs(a – b) < EPSILON) //Math.abs() is absolute

valueSystem.out.println(“a and b are the same!”);

elseSystem.out.println(“a and b are different!”);

Page 48: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200948

Loops

A portion of a program that repeats some action is called a loop

Evaluate

i <= n ?

Execute

Print i

i = i + 1;

Execute

End Program

Start

i = 1false

true

Loop Body

Stopping Condition

A loop that counts up to a certain number n

Page 49: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200949

Types of Loops

Do-WhileWhen you want the body to be executed at least onceUseful for checking user input

ForMore convenient/readable when the number of iterations is known beforehand, e.g. stored in some counter variable

WhileSafest choice, can be used to create any kind of loopWhen it might be necessary for the loop to iterate zero times

Page 50: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200950

While Example

A program that counts up to a certain number

int number;

… //number is set to some value, e.g. user input

int count = 1;while(count <= number) {

System.out.print(count + ", ");count++;

} 1, 2, 3, 4, ….

Output

Page 51: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200951

Do-While Example

Read in a positive integer, if integer is negative, try again

int input;do {

System.out.println("Please enter a positive integer: ");input = keyboard.nextInt();

} while (input <= 0); //note the semicolon!

//input is guaranteed to be > 0 at this point

Page 52: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200952

For Loop Example

Pseudocode for a possible for loop

Do the following for each value of count from 1-3:Display count

Java codeint count;

for(count = 1; count <= 3; count++)System.out.println(count);

1 2 3

Output

Page 53: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200953

Infinite Loops

A loop that never ends is called an infinite loop

int count = 3;do {

System.out.println(count);count++;

} while(count >= 0);//execution will never reach this pointSystem.out.println("count after loop = " +

count);

Page 54: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200954

Ending a Loop

Count-controlled loopsIf you know the number of loop iterationsfor (count = 0; count < iterations; count++)

User-controlled loopsAsk-before-iteratingSentinel value

54

Page 55: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200955

Nested Loops

Example

int sum = 0;int i = 0;

while(i < 10) {

for(int j = 0; j < 20; j++) sum = sum + j; //executes 10 * 20 times

i++; //executes 10 times, i = [0, 9]}

Page 56: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200956

Classes, Objects, and Methods

Class: a definition of a kind of objectObject: an instance of a class

Contains instance variables (data) and methods

MethodsMethods that return a valueMethods that return nothing

56

Page 57: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200957

Classes

Car

- make: String- model: String- year: int- owner: String- location: String

+ accelerate(double pedalPressure): void+ brake(double pedalPressure): void+ sell(String newOwner): void+ start(): void

Class name

Attributes

Methods (actions)

A class is the definition of a kind of object

A UML Diagram

Page 58: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200958

Creating Objects

Create an object called “jack” of class “Student”

Student jack = new Student();

Create an objectAssign memory address of object to variable

Page 59: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200959

Instance Variables

The data members of a class are called instance variables

private String name;private int year;private double gpa; private String major;

private No direct access to the variables from outside the class

Page 60: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200960

Methods

Two kinds of methods

Methods that return a value• Examples

– string.substring()– string.charAt()

Methods that return nothing• Example

– System.out.println()

Page 61: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200961

Methods

public String getMajor() { return major;}

public void increaseYear() { year++;}

returns a String

returns nothing

return type

Page 62: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200962

Calling Methods that Return Nothing

Syntaxobject.method();

Use them like Java statementsStudent jack = new Student();jack.year = 1;

jack.increaseYear(); //year = 2jack.increaseYear(); //year = 3

System.out.println("Jack’s class year is " + jack.year);

Jack’s class year is 3

Output

Page 63: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200963

Methods that Return a Value

public String getClassYear() {

if(year == 1) return "Freshman"; else if(year == 2) return "Sophomore"; else if ...}

//add two numbers and return the resultpublic double getSum(double a, double b) {

return a+b;}

Page 64: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200964

Calling Methods that Return a Value

Syntaxobject.method();

Use as a variable of the method’s return type

Student jack = new Student();jack.name = "Jack Smith";jack.major = "Computer Science";

String m = jack.getMajor();

System.out.println("Jack’s full name is " + jack.getName());System.out.println("Jack’s major is " + m);

64

Page 65: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200965

Local/Instance Variables

public class Student {

public String name; public int year; // ...

public void printInfo() { String info = name + ": " + year; System.out.println(info); }

public void increaseYear() { year++; }

public void decreaseYear() { year--; }}

• year and name are instance variables• can be used in any method in this class

• info is a local variable declared inside method printInfo()• can only be used inside method printInfo()

Page 66: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200966

Methods with Parameters

Some methods need data as input in order to perform their function

Parameters can be used as (local) variables inside the method

public int square(int number) {

return number * number;}

Parameters go inside parentheses of method header

Page 67: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200967

Methods with Multiple Parameters

Multiple parameters separated by commas

public double getTotal(double price, double tax) { return price + price * tax;}

Page 68: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200968

Method Parameters and Arguments

Order, type, and number of arguments must match parameters specified in method heading

public String getMessage(int number, char c) { return number + ":" + character;

}

object.getMessage(7, 'c'); //okobject.getMessage(7, 'c', 7); //errorobject.getMessage(7.5, 'c'); //errorobject.getMessage(7, 6); //error

Page 69: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200969

Public vs Private

public void increaseYear()public int year;

public: there is no restriction on how you can use the method or instance variable

Page 70: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200970

Public vs Private

private double gpa;private int year;

private: can not directly use the method or instance variable’s name outside the class

Page 71: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200971

Example

public class Student { public int year; private String major;}

Student jack = new Student();

jack.year = 1;

jack.major = “Computer Science”;

OK, year is public

Error!!! major is private

Page 72: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200972

Information Hiding

A programmer using a method should only need to know what the method does, not how it does it

keyboard.nextInt()

Information hiding means hiding the details of the code from the programmer

Page 73: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200973

Accessors and Mutators

How do you access private instance variables?Accessor methods (a.k.a. get methods, getters)

Allow you to look at data in private instance variables

Mutator methods (a.k.a. set methods, setters)

Allow you to change data in private instance variables

Page 74: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200974

Example: Student

public class Student {

private String name; private int age;

public void setName(String studentName) { name = studentName; }

public void setAge(int studentAge) { age = studentAge; }

public String getName() { return name; }

public int getAge() { return age; }}

Accessors

Mutators

Page 75: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200975

Encapsulation

Hiding details of a class that are not necessary to understand how objects of the class are used

Two partsInterfaceImplementation

Page 76: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200976

Encapsulation

Implementation:

• Private instance variables• Private constants• Private methods• Bodies of public methods

Interface:

• Comments• Headings of public methods• Public named constants

Programmer Who Uses the Class:

• Create objects• Call methods

Page 77: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200977

Call-by-Value

Parameters in Java are passed by value

The value of a variable is passed, not the variable itselfVariables passed to a method can never be changed

public class Example {

public void setVariable(int a) {a = 7;

}

public static void main(String[] args) {Example example = new Example();int a = 5;//a == 5example.setVariable(a); //does not change the value of a//a == 5

}}

Different Variables!

Page 78: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200978

Parameters of a Primitive Type

public void increaseNum(int num) { num++;}

public void foo() { int x = 5; increaseNum(x); System.out.println(x);}

What is the output?5

Page 79: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200979

Variables of a Class Type

The value of a variable of a class type is a memory address

The address of the object it refers to

Student jack = new Student(); //jack holds the address of the newly created

//object of the Student class

The address to this other location is called a reference to the object

Class types are also called reference types

Page 80: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200980

Parameters of a Class Type

public void changeBook(Book book) { book = new Book("Biology");}

public void foo() { Book jacksBook = new Book("Java"); changeBook(jacksBook); System.out.println(jacksBook.getName());}

What is the output?Java

Page 81: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200981

Parameters of a Class Type

public void changeBook(Book book) { book.setName("Biology");}

public void foo() { Book jacksBook = new Book("Java"); changeBook(jacksBook); System.out.println(jacksBook.getName());}

What is the output?Biology

81

Page 82: COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200982

Wednesday

Midterm