review chapters 1 to 4 instructor: scott kristjanson cmpt 125/125 sfu burnaby, fall 2013

44
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Upload: thomas-tucker

Post on 28-Dec-2015

238 views

Category:

Documents


1 download

TRANSCRIPT

ReviewChapters 1 to 4

Instructor: Scott Kristjanson

CMPT 125/125

SFU Burnaby, Fall 2013

Introduction to JavaChapters 1 and 2The Java Language – Section 1.1Data & Expressions – Sections 2.1 – 2.5

Instructor: Scott Kristjanson

CMPT 125/125

SFU Burnaby, Fall 2013

Wk04.1 Slide 3Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

3

Scott Kristjanson – CMPT 125/126 – SFU

The Java Programming Language

In the Java programming language:• a program is made up of one or more classes• a class contains one or more methods• a method contains program statements

These terms will be explored in detail throughout the course

A Java application always contains a method called main

Wk04.1 Slide 4Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

4

Scott Kristjanson – CMPT 125/126 – SFU

A Java Program

public class MyProgram

{

}

// comments about the class

public static void main(String[] args)

{

}

// comments about the method

method headermethod body

Wk04.1 Slide 5Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

5

Scott Kristjanson – CMPT 125/126 – SFU

//******************************************************************

// Lincoln.java Java Foundations

//

// Demonstrates the basic structure of a Java application.

//******************************************************************

public class Lincoln

{

//---------------------------------------------------------------

// Prints a presidential quote.

//---------------------------------------------------------------

public static void main(String[] args)

{

System.out.println("A quote by Abraham Lincoln:");

System.out.println("Whatever you are, be a good one.");

}

}

A Very Simple Java Program

class header

classbody

Comments about the method

method header

methodbody

Comments about the class

A quote by Abraham Lincoln:Whatever you are, be a good one.

Output:

Wk04.1 Slide 6Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

6

Scott Kristjanson – CMPT 125/126 – SFU

Identifiers

Sometimes we choose identifiers ourselves when writing a program (such as Lincoln)

Sometimes we are using another programmer's code, so we use the identifiers that he or she chose (such as println)

Often we use special identifiers called reserved words that already have a predefined meaning in the language

A reserved word cannot be used in any other way

Wk04.1 Slide 7Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

7

Scott Kristjanson – CMPT 125/126 – SFU

Reserved Words

Java reserved words:

Wk04.1 Slide 8Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

8

Scott Kristjanson – CMPT 125/126 – SFU

White Space

In Java:

• Spaces, blank lines, and tabs are called white space

• White space is used to separate words and symbols in a program

• A valid Java program can be formatted many ways

• Extra white space and indenting is ignored by the Java compiler

• Proper use of White Space is important – for people to understand it

• Programs should be formatted to enhance readability, using consistent indentation

Wk04.1 Slide 9Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

9

Scott Kristjanson – CMPT 125/126 – SFU

Chapter 2

Data & Expressions – Sections 2.1 – 2.5

Wk04.1 Slide 10Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

10

Scott Kristjanson – CMPT 125/126 – SFU

Character Strings

A string of characters can be represented as a string literal by putting double quotes around it

Examples:

"This is a string literal.""123 Main Street""X"

Every character string is an object in Java, defined by the String class

Every string literal represents a String object

Wk04.1 Slide 11Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

11

Scott Kristjanson – CMPT 125/126 – SFU

String Concatenation

The string concatenation operator (+) is used to append one string to the end of another

"Peanut butter " + "and jelly"

It can also be used to append a number to a string

A string literal cannot be broken across two lines in a program

Wk04.1 Slide 12Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

12

Scott Kristjanson – CMPT 125/126 – SFU

Variables

A variable is a name for a location in memory

Before it can be used, a variable must be declared by specifying its name and the type of information that it will hold

int total;

int count, temp, result;

Multiple variables can be created in one declaration

data type variable name

Wk04.1 Slide 13Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

13

Scott Kristjanson – CMPT 125/126 – SFU

Assignment

An assignment statement changes the value of a variableThe assignment operator is the = sign

The expression on the right is evaluated and the result is stored in the variable on the left

The value that was in total is overwritten

You can only assign a value to a variable that is consistent with the variable's declared type

total = 55;

Wk04.1 Slide 14Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

14

Scott Kristjanson – CMPT 125/126 – SFU

Primitive Data Types

There are eight primitive data types in Java

Four of them represent integers

•byte, short, int, long

Two of them represent floating point numbers

•float, double

One of them represents characters

•char

And one of them represents boolean values

•boolean

Wk04.1 Slide 15Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

15

Scott Kristjanson – CMPT 125/126 – SFU

Expressions

An expression is a combination of one or more operators and operands

Arithmetic expressions compute numeric results and make use of the arithmetic operators

• Addition +

• Subtraction -

• Multiplication *

• Division /

• Remainder %

If either or both operands used by an arithmetic operator are floating point, then the result is a floating point

Wk04.1 Slide 16Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

16

Scott Kristjanson – CMPT 125/126 – SFU

Operator Precedence

Precedence among some Java operators:

Wk04.1 Slide 17Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

17

Scott Kristjanson – CMPT 125/126 – SFU

Operator Precedence

What is the order of evaluation in the following expressions?

a + b + c + d + e1 432

a + b * c - d / e3 241

a / (b + c) - d % e2 341

a / (b * (c + (d - e)))4 123

Wk04.1 Slide 18Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

18

Scott Kristjanson – CMPT 125/126 – SFU

Key Things to take away:

• The print and println methods are two services provided by the System.out object• In Java, the + operator is used both for addition and for string concatenation• An escape character can be used to represent a character that would otherwise cause a

compile error• A variable is a name for a memory location used to hold a value of a particular data type• Accessing data leaves them intact in memory, but an assignment statement overwrites old

data• One cannot assign a value of one type to a variable of an incompatible type• Constants hold a particular value for the duration of their existence• Java has two types of numeric values: integer and floating point. There are four integer data

types and two floating point data types• Java using 16-bit Unicode character set to represent character data• Expressions are combinations of operators and operands used to perform a calculation• The type of result produced by arithmetic division depends on the types of the operands• Java follows a well-defined set of precedence rules that governs the order in which

operators will be evaluated in an expression• Narrowing conversions should be avoided because they can lose information

Using Classes and ObjectsChapters 3Creating Objects – Section 3.1The String Class – Section 3.2The Scanner Class – Section 2.6

Instructor: Scott Kristjanson

CMPT 125/125

SFU Burnaby, Fall 2013

Wk04.1 Slide 20Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

20

Scott Kristjanson – CMPT 125/126 – SFU

Creating Objects

Generally, we use the new operator to create an object:

title = new String("James Gosling");

Creating an object is called instantiation

Instantiating an object allocates space in memory for it

An object is an instance of a particular class

This calls the String constructor, which isa special method that creates the object

Wk04.1 Slide 21Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

21

Scott Kristjanson – CMPT 125/126 – SFU

Object References

A primitive variable like num1 contains the value itself

An object variable link name1 contains the address of the object

An object reference can be thought of as a pointer to the location of the object

Rather than dealing with arbitrary addresses, we often depict a reference graphically

"Steve Jobs"name1

num1 38

Wk04.1 Slide 22Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

22

Scott Kristjanson – CMPT 125/126 – SFU

Assignment Revisited

The act of assignment takes a copy of a value and stores it in a variable

For primitive types:

num1 38

num2 96Before:

num2 = num1;

num1 38

num2 38After:

Wk04.1 Slide 23Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

23

Scott Kristjanson – CMPT 125/126 – SFU

Assignment Revisited

For object references, the address is copied:

name2 = name1;

name1

name2Before:

"Steve Jobs"

"Steve Wozniak"

name1

name2After:

"Steve Jobs"

Wk04.1 Slide 24Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

24

Scott Kristjanson – CMPT 125/126 – SFU

Key Things to take away:

• Object declarations create place holders which point to an object in memory

• The new operator instantiates a new instance of the class• Strings are immutable – changing a string creates a new instance

• A variable holds either a primitive type or a reference to an object

• Assigning variables of primitive types copies the value

• Assigning variables of class types copies a reference to the object

• The String class provides useful methods for working with strings• length• concat• substring• toUpperCase• Etc

• The System.in object represents the standard input stream• The Scanner Class provides methods for reading input values

Using Classes and ObjectsChapters 3Section 3.3 Packages Section 3.4 Random Class Section 3.5 Math ClassSection 3.7 Enumerated Types

Instructor: Scott Kristjanson

CMPT 125/125

SFU Burnaby, Fall 2013

Wk04.1 Slide 26Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

26

Scott Kristjanson – CMPT 125/126 – SFU

The Random Class

The Random class is part of the java.util package

It provides methods that generate pseudorandom numbers

A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values

If you specify the same initial seed value, you get the same sequence of random values

• Very useful for testing with the same “sequence” of random numbers

Wk04.1 Slide 27Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

27

Scott Kristjanson – CMPT 125/126 – SFU

The Random Class

Some methods of the Random class:

Wk04.1 Slide 28Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

28

Scott Kristjanson – CMPT 125/126 – SFU

The Math Class

The methods of the Math class are static methods

(also called class methods)

Static methods can be invoked through the class name only – no object of the Math class is needed

value = Math.cos(90) + Math.sqrt(delta);

We'll discuss static methods in more detail later

Wk04.1 Slide 29Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

29

Scott Kristjanson – CMPT 125/126 – SFU

Key Things to take away:

• The Java API contains standard set of class definitions

• Class definitions can be reused by importing packages

• Packages exist for creating random numbers, math, and formatting

• You can create your own set of libraries as a package

• Java provides wrapper classes for primitive data types so they can be used just like any other object

Conditionals and LoopsChapter 4

Instructor: Scott Kristjanson

CMPT 125/125

SFU Burnaby, Fall 2013

Wk04.1 Slide 31Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

31

Scott Kristjanson – CMPT 125/126 – SFU

Flow of Control

Statement execution is linear unless specified otherwise

Public static void main(String[] args){ Statement 1; Statement 2;Statement 3;

… Statement N;}

The order of statement execution is called the flow of control

Flow of Control

Wk04.1 Slide 32Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

32

Scott Kristjanson – CMPT 125/126 – SFU

Conditional Statements

A conditional statement lets us choose which statement will be executed next

Therefore they are sometimes called selection statements

Conditional statements give us the power to make basic decisions

The Java conditional statements are the

• if statement

• if-then-else statement

• switch statement

Wk04.1 Slide 33Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

33

Scott Kristjanson – CMPT 125/126 – SFU

Equality and Relational Operators

Often, conditions are based equality operators or relational operators:

Wk04.1 Slide 34Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

34

Scott Kristjanson – CMPT 125/126 – SFU

Logical Operators

Conditions can also use logical operators:

They all take boolean operands and produce boolean results

Logical NOT is a unary operator (it operates on one operand)

Logical AND and logical OR are binary operators (each operates on two operands)

Wk04.1 Slide 35Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

35

Scott Kristjanson – CMPT 125/126 – SFU

Logical Operators

Expressions can be evaluated using truth tables

For example, let’s evaluate the following using a truth table:

!done && (count > MAX)

Wk04.1 Slide 36Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

36

Scott Kristjanson – CMPT 125/126 – SFU

Short-Circuited Operators

The processing of logical AND and logical OR is short-circuited

If the left operand is sufficient to determine the result, the right operand is not evaluated

// This is safe to call even if count equals 0

// thanks to the wonders of short-circuited boolean logic!

if (count != 0 && total/count > MAX)

System.out.println("Testing");

This type of processing must be used carefully

And can be very useful!

Wk04.1 Slide 37Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

37

Scott Kristjanson – CMPT 125/126 – SFU

The if-then-else Statement

An else clause can be added to an if statement to make an if-then-else statement

If condition evaluates to true, then statement1 is executed

otherwise condition must be false, so statement2 is executed

One or the other will be executed, but not both

if ( condition ) statement1;else statement2;

Wk04.1 Slide 38Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

38

Scott Kristjanson – CMPT 125/126 – SFU

Block Statements

Several statements can be grouped together into a block statement delimited by braces {}

if (sum > MAX)

{ delta = sum – MAX;

System.out.println("The sum is " + sum);

}

A block statement can be used wherever a statement can be used in the Java syntax rules

Wk04.1 Slide 39Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

39

Scott Kristjanson – CMPT 125/126 – SFU

Comparing Data

When comparing data using boolean expressions, it's important to understand the nuances of certain data types

We will examine some key situations:

• comparing floating point values for equality• comparing characters• comparing strings (alphabetical order)• comparing object vs. comparing object references

Wk04.1 Slide 40Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

40

Scott Kristjanson – CMPT 125/126 – SFU

The switch Statement

An example of a switch statement:

switch (option){ case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break;}

Wk04.1 Slide 41Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

41

Scott Kristjanson – CMPT 125/126 – SFU

The while Loop

Example:

int count = 1;while (count <= 5){ System.out.println (count); count++;}

If the condition of a while loop is false initially, the statement is never executed

Therefore, the body of a while loop will execute zero or more times

How many times does this loop execute?

5 times

What is the output?

12345

Wk04.1 Slide 42Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

42

Scott Kristjanson – CMPT 125/126 – SFU

The do Loop

An example of a do loop:int count = 0;

do

{

count++;

System.out.println (count);

} while (count < 5);

The body of a do loop is executed at least once

How many times does count get printed?

5

Wk04.1 Slide 43Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

43

Scott Kristjanson – CMPT 125/126 – SFU

The for Loop

The for loop has the following syntax:

for ( initialization ; condition ; increment ) statement;

The initializationis executed once

before the loop begins

The statement isexecuted while the

condition remains true

The increment portion is executed at the end of each iteration

Wk04.1 Slide 44Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase

44

Scott Kristjanson – CMPT 125/126 – SFU

Key Things to take away:

• Flow of Control determines which statements get executed• Expressions can form complex conditions using logical operators• AND and OR evaluation are short-circuited in Java• Selection statements chose different execution paths based on conditions

• If <condition> then <statement>;• If <condition> then <statement1> else <statement2>;• Switch <integer value> {Case 1, Case 2, … Case N}

• Java supports two styles of Indefinite Loops:• While <condition> <statement>;• Do <statement> while <condition>;

• Java suports two styles of definite Loops:• for ( initialization ; condition ; increment ) <statement>;• For-each using Iterators