Transcript wk04.3

Review
Chapters 1 to 4
Instructor: Scott Kristjanson
CMPT 125/125
SFU Burnaby, Fall 2013
Introduction to Java
Chapters 1 and 2
The Java Language – Section 1.1
Data & Expressions – Sections 2.1 – 2.5
Instructor: Scott Kristjanson
CMPT 125/125
SFU Burnaby, Fall 2013
The Java Programming Language
3
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 3
A Java Program
4
//
comments about the class
public class MyProgram
{
//
comments about the method
public static void main(String[] args)
{
method body
method header
}
}
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 4
A Very Simple Java Program
5
//******************************************************************
// Lincoln.java
Java Foundations
Comments about the class
//
// Demonstrates the basic structure of a Java application.
//******************************************************************
class header
public class Lincoln
{
Comments about the method
//--------------------------------------------------------------method header
// Prints a presidential quote.
//--------------------------------------------------------------method
public static void main(String[] args)
body
{
System.out.println("A quote by Abraham Lincoln:");
class
body
System.out.println("Whatever you are, be a good one.");
}
}
Output:
A quote by Abraham Lincoln:
Whatever you are, be a good one.
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 5
Identifiers
6
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 6
Reserved Words
7
Java reserved words:
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 7
White Space
8
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 8
9
Chapter 2
Data & Expressions – Sections 2.1 – 2.5
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 9
Character Strings
10
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 10
String Concatenation
11
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 11
Variables
12
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
variable name
data type
int total;
int count, temp, result;
Multiple variables can be created in one declaration
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 12
Assignment
13
An assignment statement changes the value of a variable
The assignment operator is the = sign
total = 55;
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 13
Primitive Data Types
14
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 14
Expressions
15
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 15
Operator Precedence
16
Precedence among some Java operators:
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 16
Operator Precedence
17
What is the order of evaluation in the following expressions?
a + b + c + d + e
1
2
3
4
a + b * c - d / e
3
1
4
2
a / (b + c) - d % e
2
1
4
3
a / (b * (c + (d - e)))
4
3
2
1
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 17
Key Things to take away:
18
• 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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 18
Using Classes and Objects
Chapters 3
Creating Objects
– Section 3.1
The String Class
– Section 3.2
The Scanner Class – Section 2.6
Instructor: Scott Kristjanson
CMPT 125/125
SFU Burnaby, Fall 2013
Creating Objects
20
Generally, we use the new operator to create an object:
title = new String("James Gosling");
This calls the String constructor, which is
a special method that creates the object
Creating an object is called instantiation
Instantiating an object allocates space in memory for it
An object is an instance of a particular class
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 20
Object References
21
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
num1
38
"Steve Jobs"
name1
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 21
Assignment Revisited
22
The act of assignment takes a copy of a value and stores it in
a variable
For primitive types:
Before:
num1
38
num2
96
num2 = num1;
After:
num1
38
num2
38
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 22
Assignment Revisited
23
For object references, the address is copied:
Before:
name1
"Steve Jobs"
name2
"Steve Wozniak"
name2 = name1;
name1
After:
"Steve Jobs"
name2
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 23
Key Things to take away:
24
• 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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 24
Using Classes and Objects
Chapters 3
Section 3.3
Section 3.4
Section 3.5
Section 3.7
Packages
Random Class
Math Class
Enumerated Types
Instructor: Scott Kristjanson
CMPT 125/125
SFU Burnaby, Fall 2013
The Random Class
26
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 26
The Random Class
27
Some methods of the Random class:
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 27
The Math Class
28
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 28
Key Things to take away:
29
•
•
•
•
•
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 29
Conditionals and Loops
Chapter 4
Instructor: Scott Kristjanson
CMPT 125/125
SFU Burnaby, Fall 2013
Flow of Control
31
Statement execution is linear unless specified otherwise
Public static void main(String[] args)
{
Flow of Control
Statement 1;
Statement 2;
Statement 3;
…
Statement N;
}
The order of statement execution is called the flow of control
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 31
Conditional Statements
32
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 32
Equality and Relational Operators
33
Often, conditions are based equality operators or relational
operators:
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 33
Logical Operators
34
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)
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 34
Logical Operators
35
Expressions can be evaluated using truth tables
For example, let’s evaluate the following using a truth table:
!done && (count > MAX)
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 35
Short-Circuited Operators
36
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!
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 36
The if-then-else Statement
37
An else clause can be added to an if statement to make an if-then-else
statement
if ( condition )
statement1;
else
statement2;
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 37
Block Statements
38
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 38
Comparing Data
39
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 39
The switch Statement
40
An example of a switch statement:
switch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 40
The while Loop
41
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
1 zero or more times
Therefore, the body of a while loop will execute
2
3
How many times does this loop execute?
4
5 times
5
What is the output?
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 41
The do Loop
42
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 42
The for Loop
43
The for loop has the following syntax:
The initialization
is executed once
before the loop begins
The statement is
executed while the
condition remains true
for ( initialization ; condition ; increment )
statement;
The increment portion is executed at the
end of each iteration
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 43
Key Things to take away:
44
•
•
•
•
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk04.1 Slide 44