chapter 2 overview using primitive data types using classes anatomy of a program will use...

78
Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Post on 19-Dec-2015

220 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Chapter 2 Overview

Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Page 2: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Data Types Tells compiler what type of data is

stored in each memory cell. Data Type represents a particular

kind of information. Some come with Java

Primitive Data Types are not stored as objects

The String class is a data type which stores Objects

Some are defined by Programmers

Page 3: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Variables Variables serve 2 purposes

Reference objects Store values in memory

Declaration Statement Defines a variable name and its

associated data type.

Page 4: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Data Types Java has 8 built-in primitive data

types We will be using 4 of these

int double char boolean

As noted before, these primitive data types are not stored as objects

Page 5: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Example declarations int kids = 2; double bankBalance = 500.45; char firstLetter = ‘a’; boolean married = true;

Page 6: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Literals Example of declaration (with initialization)

int kids = 2;the variable is kidsthe primitive type is intthe initial value is the literal 2

What are the literals in the declarations below? double bankBalance = 500.45; char firstLetter = ‘a’; boolean married = true;

Page 7: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Values stored Table page 37 of text

int double char boolean

Page 8: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Syntax Display Form:

typeName variableName [ = value ]; Everything inside of [] is optional.

You need to be comfortable reading this syntax display, it will help you learn the Java language (and it’s good practice for learning the syntax of other languages).

Page 9: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Primitive Type int Positive or negative whole numbers. No sign is assumed to be positive Can perform math functions on these

Add, subtract, multiply, divide Do not use commas when writing

numbers in Java 1,000

1000

Page 10: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Primitive type double Real number Has integer part Has fractional part Can express via scientific notation

1.23 x 105

In Java as 1.23e5 1.23e+5

Page 11: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Primitive Type boolean Has only 2 possible values

true false

Used to represent conditional values

Will use more later in the semester

Page 12: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Primitive type char Represents a single character value

letter, digit, special character All character literals are enclosed in

‘’ why??

Can you add ‘5’ + ‘6’ ? How about special characters that

are not on keyboard See table page 39.

Page 13: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Data types enable Error Detection Java is a strongly typed language

Unlike C++ Can not add 2 boolean values Can not store a boolean in a

character Some you can, for instance an integer

into a double

Page 14: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Section 2.2 Processing Numeric Data Arithmetic Operators:

+ Addition 5 + 2 is 75.0 + 2.0 is 7.0

- Subtraction 5 – 2 is 35.0 – 2.0 is 3.0

* Multiplication

5 * 2 is 105.0 * 2.0 is 10.0

/ Division 5.0 / 2.0 is 2.55 / 2 is 2

% Remainder 5 % 2 is 1

Page 15: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Division Integer division is very different

than with real numbers. If both numbers are integers then

integer division is performed. If one or both numbers are reals

then real number division is performed.

Page 16: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Assignment Statement Form: variable = expression; Example: x = y + z; Read x is assigned the value of y +

z. See Example 2.2 Page 42 See Example 2.3 Page 43

Page 17: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Result of mixed type If one or more operands are double,

result is double. If both operands are int, result is int. Mixed type assignment statements.

Result is calculated, then assigned. int can be assigned to a double

See example 2.4 page 44

Page 18: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Type Casting Can use this to create one type

from another. double x = 7.8; int m; m = (int) x;

Can also be used for doubles (double) m;

Page 19: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Operator Precedence My Dear Aunt Sally x = 4 + 3 * 2

is it 10 or 14? Uses 2 rules to decide

Parentheses rule Operator precedence rule Left associative rule (equal then left to

right) We will consistently use fully

parenthesized equations.

Page 20: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Examples Review the examples on pages 46

–47 Must be able to convert math

formulas into Java syntax See examples page 48

Look at code on Page 49 running in JBuilder

Page 21: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Section 2.3 Introduction to Methods Methods of a class determine

operations that can be performed by the class.

The previous code example (Page 49) contains 2 methods main() println()

Methods are called to do some task.

Page 22: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Calling (activate) methods Call methods for multiple reasons

Change state of object. Calculate a result Retrieve a data item stored in an

object Get data from the user Display the results of an operation

Page 23: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Returning results Methods that:

calculate result retrieve a data item these are said to “return a result”

The main method is automatically called by the operating system. It is the initial method to run, you then write the code in that method to perform your work.

Page 24: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

println method Used to display output in the

console window. Provided for you by java. Is part of the System.out object.

Page 25: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Calling a method Call a method using dot notation:

objectName.methodName(); System.out.println();

We can pass data to methods via the argument list: objectName.methodName(argumentL

ist); Can be single or multiple values See Page 49 println calls

Page 26: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Method arguments are like function arguments In algebra f(x) means function f

with argument x. f(x) is x2 + x + 1

f(0) is 1 (0 + 0 + 1) f(1) is 3 (1 + 1 + 1) f(2) is 7 (4 + 2 + 1)

Can also have f(x, y) (bottom pg 53)

Page 27: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Instance versus class methods Java has 2 different types of methods

instance class

println is an instance method, it belongs to an instance of System.out

Class methods belong to a class, not an instance of the class Math.sqrt(15.0) is class method. Use name of class (Math) rather than

instance name.

Page 28: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Section 2.4 the String Class Strings are a sequence of characters. Used to store, names, addresses,

……. String is not a primitive data type in

Java One powerful feature of object

orientation is the ability to create your own data types.

Page 29: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

The String Class Working with objects is similar but

slightly different than primitive data types.

Declare string variables: String name; String flower;

These can reference a String object, but have no value

Notice that it is String not string.

Page 30: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Creating String objects Use Constructors to create String

object name = new String(“Dustin”); name = new String(“Rose”);

The new operator creates a new instance of the string object. This is called an instantiation. Object is an instance of a class

Page 31: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Constructor The new operator calls the

constructor for the object. The constructor is a special method

with the same name as the class. Gets called automatically when

create an new instance of the class. We pass an argument to the

constructor method (“Dustin”)

Page 32: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Class instantiation Form: variableName = new

className(arguments); Example: flower = new

String(“rose”); Can declare variable and

instantiate it at the same time: String flower = new String(“rose”);

Page 33: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Reference Variable Primitive data type storage

locations contain the value of the data type.

A reference variable storage location contains an address of where the object is stored.

See Page 57 top

Page 34: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Strings Properties Strings slightly different than

classes you create. Can create string via:

String flower = “Rose”; Can use + with String

(concatenation) name + “ “ + flower

concatenates 3 strings together

Page 35: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Concatenate Strings with Primitive Types System.out.println(“First number is

“ + num1); Concatenates one string and one

double See examples Page 59-60

Page 36: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

String Methods See table String Methods Page 60

length charAt subString indexOf

See examples pages 60 - 61

Page 37: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

subString() method Gets a portion of a string

One argument gets from that position to end of String

Two arguments gets from first position for the length in second argument.

See examples page 62-63

Page 38: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Storing result of method call Method must return a value int posBlank = text.indexOf(“ “);

first blank in string text if Mickey Mantle returns 6

String firstName = text.subString(0, posBlank) pulls out first name

See example page 64

Page 39: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Display results of method call System.out.printLn(“The First

blank is at position “ + text.indexOf(“ “));

Page 40: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Section 2.5 Input/Output Will be using the following 2

approaches to Input/Output JOptionPane printLn()

Page 41: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Packages Packages are created for you to

reuse existing code. Contain many useful functions A large number of packages exist to

extend the functionality of Java Strong feature of Java

Page 42: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

import Statement Used to import and use an existing

package. import javax.swing.*; This imports the swing package which

facilitates creating GUIs. This gives access to all classes in swing To only use JOptionPane can do

import javax.swing.JOptionPane;

Page 43: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

JOptionPane.showInputDialog() Part of swing package. Always easy input and output.

Input reading in data from user Output presenting results for user

String name = JOptionPane.showInputDialog(“Enter your name”);

Displays dialog box, see page 67 Stores result in name

Page 44: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Examples Input dialog box

See examples on page 67 - 68

Page 45: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Displaying results in Console Window System.out.println(“what ever”); See example page 68 bottom

Page 46: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Display results in dialog box JOptionPane.showMessageDialog(); See example pages 69 - 70

Page 47: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Running code See TwoNumbersDialog in JBuilder

Page 48: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Section 2.6 Problem Solving For each assignment you turn in you

must also turn in Documentation. This documentation revolves around

what is presented in the text book: Problem Analysis Design Implementation Testing

Page 49: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Section 2.7 Anatomy of program Comments 2 types of comments exist:

// means a comment to end of line /* comments in here */ comment

delimiter Used to make program easier to

understand Use to clarify difficult code

Page 50: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Comments for each program At the beginning of the program

include at a minimum Name Date Class Assignment Program purpose

Page 51: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Example

/* John Wright 9/1/03 Minor Assignment 1

Computer Science I This program will yada yada yada

yada yada */

Page 52: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Class Definitions The class with the main method

in it is the starting class for an Application.

Classes have the form:1. A header declaration2. The class body

a. The data field declarations of the classb. The method definitions of the class

public class PigLatinApp {…}

Page 53: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Syntax diagram Form: [visibility] class class-name {…} public class PigLatinApp {…}

Body typically lists data declarations first, then methods.

We will discuss visibility in more detail as we progress through the book.

Page 54: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Visibility For the time being:

Make all methods public Make all data fields private Leave class visibility blank

Page 55: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Method main() This is a “special” method that is

called by the operating system for applications.

method header{method body

{

Page 56: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Method headers Contains a lot of information public static void main(String[] args) public = visibility static = not applied to object (only 1

copy) void = returns no value main = method name String[] args = parameter list

Page 57: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Body of main First line in main

String word = JOptionPane.showInputDialog(“Enter a word starting with a consonant”);

This brings up the initial dialog box prompting the user to enter a word.

The value they enter is then passed back to the program and into the variable word via the method call.

Page 58: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Continue We then “glue” together the output

via this statement:String message = word + “ is “ +

word.subtring(1) + word.charAt(0) + “ay” + “ in pig Latin”

Then display this in an output dialog box.

Page 59: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Program Style and Conventions The syntax of the language is

dictated by the designers of Java Each organization typically has a

set of programming conventions. Conventions are not enforced by

the compiler, rather they are used for readability.

Page 60: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Conventions You must follow programming

conventions in your programs. We will follow those from the text. See options for braces in text book

on page 80. I use option 1, but either is

acceptable, just be consistent.

Page 61: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Line breaks White space is ignored by the compiler. Use white space to make you programs

more readable. Only one java statement per line

int x = 5; double y = 5.3;

Compiler does not care

Page 62: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Java Keywords Also called reserve words These can not be used in

identifiers. See list on page 81 Complete list in Appendix B

Page 63: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Identifiers Is the name of a:

data field or variable method class object

There are rules for valid identifier names.

Page 64: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Identifiers Java is case sensitive!!!!

Fred and fred are 2 different identifiers Rules

1. must begin with letter, underscore or dollar sign. Start all with letter

2. must consist of letters, digits, underscore, dollar signs

3. Java reserve word can not be identifier4. Can be any length

Page 65: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Identifier naming conventions Classes

Use nouns Start with capitol letter Each new word is capitalized SavingsAccount PiggyBank

Page 66: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Identifier naming conventions Variables

Start with lower case Use Nouns Each new Word is Capitalized userName pizzaPie

Page 67: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Identifier naming conventions Methods

Start with lower case letter. Use verb and prepositional phrases Each new word is Capitalized showInputDialog performOutput

Page 68: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Identifier naming conventions Contants

Use all capitols Separate words with underscore RETIREMENT_AGE FEDERAL_TAX_RATE

Page 69: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Section 2.8 Class Math The class Math is a library of

methods to perform various math functions.

For instance Square Root. double y = Math.sqrt(x); You pass it a value in x It returns a value that you are

storing in y

Page 70: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Math is different You do not need to instantiate the

class Math in order to use it. Review example 2.28 and 2.29 on

page 85.

Page 71: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Methods in Class Math This class has many essential

methods already programmed for your use.

See table in page 87 for some of the methods that are a part of the math library.

Page 72: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Examples Square Root 2.30 page 88 Random 2.31 page 88 Run and look at Section_2_8_1 in

JBuilder

Page 73: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Other Methods These methods return whole

numbers: floor() whole number below real ceil() whole number above real rint() integer returned via rounding

Page 74: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Section 2.9 common errors Debugging is removing of errors

from you program. It is the rare program that runs

correctly the first time you try. You must become good at

eliminating errors from your program.

Page 75: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Syntax errors Syntax errors are caused by

improperly formed Java statements. See table of common errors Page 93. Incorrect data types Incorrect use of quotations marks Errors in use of comments Errors in use of methods

Page 76: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

System errors Application class and the file it is

stored in must have the same name.

JBuilder does this for you Class path errors.

Compiler can not find the appropriate file

Page 77: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Run-time errors Occur when the program is running

Divide by zero Data being input into wrong variable Arithmetic overflow, value to large to

fit into variable

Page 78: Chapter 2 Overview Using Primitive Data Types Using Classes Anatomy of a Program Will use JOptionPane and Math classes

Logic Errors Errors in the design of your program Program is not doing what you

expected it to do. Can use println() and

showMessageDialog() to discover how your program is running.

Logic errors can be the hardest to locate