outline questions / review predefined objects variables primitive data arithmetic expressions...

49
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Upload: poppy-shepherd

Post on 12-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Page 2: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Decision Making Interactive Programs Assignments

Page 3: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Introduction to Objects Initially, we can think of an object as a collection

of services that we can tell it to perform for us The services are defined by methods in a class

that defines the object Below we are invoking the println method of the System.out object:

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

objectobject methodmethodInformation provided to the methodInformation provided to the method

(parameters)(parameters)

Page 4: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

The print Method The print method is another service

provided by the System.out object

The print method is similar to the println method, except that it does not advance to the next line

Therefore anything printed after a print statement will appear on the same line

Page 5: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

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

Page 6: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

String Concatenation The plus operator (+) is also used for

arithmetic addition The function that the + operator performs

depends on the type of the information on which it operates

If both operands are strings, or if one is a string and one is a number, it performs string concatenation

If both operands are numeric, it adds them The + operator is evaluated left to right, but

parentheses can be used to force the operation order

Page 7: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Escape Sequences What if we wanted to print a double quote

character? The following line would confuse the compiler

because it would interpret the second quote as the end of the string

System.out.println ("I said "Hello" to you.");

An escape sequence is a series of characters that represents a special character

An escape sequence begins with a backslash character (\), which indicates that the character(s) that follow should be treated in a special way

System.out.println ("I said \"Hello\" to you.");

Page 8: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Escape Sequences Some Java escape sequences:

Escape Sequence

\b\t\n\r\"\'\\

Meaning

backspacetab

newlinecarriage returndouble quotesingle quotebackslash

Page 9: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

The printf Method The printf method is another service

provided by the System.out object

The printf method is used to display formatted data

Format string Fixed text Format specifier – placeholder for a value

Format specifier %s – placeholder for a string

System.out.printf ("%s\n%s\n", "Welcome to", "Java Programming!");

Page 10: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Page 11: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Variables A variable is a name for a location in memory A variable must be declared, specifying the

variable's name and the type of information that will be held in it

int total;

int count, temp, result;

Multiple variables can be created in one declarationMultiple variables can be created in one declaration

data typedata type variable namevariable name

Page 12: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Variable Initialization A variable can be given an initial value in the

declaration

When a variable is referenced in a program, its current value is used

int sum = 0;int base = 32, max = 149;

Page 13: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Assignment An assignment statement changes the value of a

variable The assignment operator is the = sign

total = 55;

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

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

Page 14: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Constants A constant is an identifier that is similar to a

variable except that it holds one value for its entire existence

The compiler will issue an error if you try to change a constant

In Java, we use the final modifier to declare a constant

final int MIN_HEIGHT = 69;

Constants: give names to otherwise unclear literal values facilitate changes to the code prevent inadvertent errors

Page 15: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Page 16: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Primitive Data There are exactly 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

Page 17: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Numeric Primitive Data The difference between the various numeric

primitive types is their size, and therefore the values they can store:

Type

byteshortintlong

floatdouble

Storage

8 bits16 bits32 bits64 bits

32 bits64 bits

Min Value

-128-32,768-2,147,483,648< -9 x 1018

+/- 3.4 x 1038 with 7 significant digits+/- 1.7 x 10308 with 15 significant digits

Max Value

12732,7672,147,483,647> 9 x 1018

Page 18: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Characters A char variable stores a single character from

the Unicode character set A character set is an ordered list of characters,

and each character corresponds to a unique number

The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters

It is an international character set, containing symbols and characters from many world languages

Character literals are delimited by single quotes:

'a' 'X' '7' '$' ',' '\n'

Page 19: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Characters The ASCII character set is older and

smaller than Unicode, but is still quite popular

The ASCII characters are a subset of the Unicode character set, including:uppercase letters

lowercase letterspunctuationdigitsspecial symbolscontrol characters

A, B, C, …a, b, c, …period, semi-colon, …0, 1, 2, …&, |, \, …carriage return, tab, ...

Page 20: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Boolean A boolean value represents a true or

false condition

A boolean can also be used to represent any two states, such as a light bulb being on or off

The reserved words true and false are the only valid values for a boolean type

boolean done = false;

Page 21: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Page 22: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Expressions An expression is a combination of 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 to an arithmetic operator are floating point, the result is a floating point

Page 23: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Division and Remainder If both operands to the division operator (/) are

integers, the result is an integer (the fractional part is discarded)

The remainder operator (%) returns the remainder after dividing the second operand into the first

14 / 3 equals?

8 / 12 equals?

14 % 3 equals?

8 % 12 equals?

Page 24: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Operator Precedence Operators can be combined into complex

expressions

result = total + count / max - offset;

Operators have a well-defined precedence which determines the order in which they are evaluated

Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation

Arithmetic operators with the same precedence are evaluated from left to right

Parentheses can always be used to force the evaluation order

Page 25: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Operator Precedence What is the order of evaluation in the

following expressions?a + b + c + d + e a + b * c - d / e

a / (b + c) - d % e

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

Page 26: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Example What is the value of x?

Show the order of evaluation

x = 7 + 3 * 6 / 2 – 1;

Page 27: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Assignment Revisited The assignment operator has a lower

precedence than the arithmetic operators

First the expression on the right handFirst the expression on the right handside of the = operator is evaluatedside of the = operator is evaluated

Then the result is stored in theThen the result is stored in thevariable on the left hand sidevariable on the left hand side

answer = sum / 4 + MAX * lowest;

14 3 2

Page 28: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Assignment Revisited The right and left hand sides of an

assignment statement can contain the same variable

First, one is added to theFirst, one is added to theoriginal value of original value of countcount

Then the result is stored back into Then the result is stored back into countcount(overwriting the original value)(overwriting the original value)

count = count + 1;

Page 29: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Printing Integers Format specifier %d

Placeholder for an int valueSystem.out.printf( "Sum is %d\n: " , sum ); // display sum

Calculations can also be performed inside printf

System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) );

Parentheses around the expression number1 + number2 are not required

Page 30: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Floating-Point Number Precision float

Single-precision floating-point numbers

Seven significant digits double

Double-precision floating-point numbers

Fifteen significant digits

Page 31: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Common Programming Error

Using floating-point numbers in a manner that assumes they are represented precisely can lead to logic errors. For example: Compare two

floating-point numbers using a range, instead of using ==

double x = 3.0, y = 9.0 / 3.0;if (x == y) // May not work

Page 32: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Printing Floats Format specifier %f

Used to output floating-point numbers

Place a decimal and a number between the percent sign and the f to mandate a precision

For example: %5.2f means the number will take up at least 5 spaces (including the decimal place) and 2 of the spaces will be after the decimal place. => 12.34

Page 33: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Page 34: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Class Libraries A class library is a collection of classes

that we can use when developing programs There is a Java standard class library

that is part of any Java development environment These classes are not part of the Java language

per se, but we rely on them heavily The System, String, and Scanner classes are

part of the Java standard class library Other class libraries can be obtained

through third party vendors, or you can create them yourself

Page 35: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Packages The classes of the Java standard class library are

organized into packages Some of the packages in the standard class library

are:Package

java.langjava.appletjava.awtjavax.swingjava.netjava.util

Purpose

General supportCreating applets for the webGraphics and graphical user interfacesAdditional graphics capabilities and componentsNetwork communicationUtilities

Page 36: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

The import Declaration When you want to use a class from a package,

you could use its fully qualified name

java.util.Scanner

Or you can import the class, then just use the class name

import java.util.Scanner;

To import all classes in a particular package, you can use the * wildcard character

import java.util.*;

Page 37: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

The import Declaration All classes of the java.lang package are

automatically imported into all programs That's why we didn't have to explicitly import

the System or String classes in earlier programs

It's as if all programs contain the following line:

import java.lang.*;

The Scanner class is part of the java.util package, and therefore must be imported

Page 38: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Class Methods Some methods can be invoked through the

class name, instead of through an object of the class

These methods are called class methods or static methods

The Math class contains many static methods, providing various mathematical functions, such as absolute value, trigonometry functions, square root, etc.

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

Page 39: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Interactive Programs Programs generally need input on which

to operate

The Scanner class provides convenient methods for reading input values of various types

A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard

Keyboard input is represented by the System.in object

Page 40: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Reading Input The following line creates a Scanner

object that reads from the keyboard:

Scanner scan = new Scanner (System.in);

The new operator creates the Scanner object

Once created, the Scanner object can be used to invoke various input methods, such as:

answer = scan.nextLine();

Page 41: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Reading Input The Scanner class is part of the java.util class library, and must be imported into a program to be used

The nextLine method reads all of the input until the end of the line is found

Page 42: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Input Tokens Unless specified otherwise, white space is

used to separate the elements (called tokens) of the input

White space includes space characters, tabs, new line characters

The next method of the Scanner class reads the next input token and returns it as a string

Methods such as nextInt and nextDouble read data of particular types

Page 43: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Page 44: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

The if Statement

The if statement has the following syntax:

if ( condition ){ statement;}

ifif is a Java is a Javareserved wordreserved word

The condition must be a The condition must be a boolean expressionboolean expression..It must evaluate to either true or falseIt must evaluate to either true or false..

If the condition is true, the statement is executed.If the condition is true, the statement is executed.If it is false, the statement is skipped.If it is false, the statement is skipped.

Page 45: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Logic of an if statement

conditionevaluated

falsefalse

statement

truetrue

Page 46: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

46

Boolean Expressions

Equality operators or relational operators all return boolean results:

== equal to!= not equal to< less than> greater than<= less than or equal to>= greater than or equal to

Note the difference between the equality operator (==) and the assignment operator (=)

Page 47: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

The if Statement An example of an if statement:if (sum > MAX){ delta = sum - MAX;}System.out.println ("The sum is " + sum);

First, the condition is evaluated. The value of First, the condition is evaluated. The value of sumsumis either greater than the value of is either greater than the value of MAXMAX, or it is not., or it is not.

If the condition is true, the assignment statement is executed.If the condition is true, the assignment statement is executed.If it is not, the assignment statement is skipped.If it is not, the assignment statement is skipped.

Either way, the call to println is executed next.Either way, the call to println is executed next.

Page 48: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Page 49: Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments

Assignments Read: Chapter 1, Appendix D

Lab: Try.java Echo.java Calculate.java Lab 1: Circle.java

Homework 1: Shapes.java Write the program, compile it, run it, and

mail your source code to me.