Transcript Chapter 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
Variables
Variables serve 2 purposes
Reference objects
Store values in memory
Declaration Statement
Defines a variable name and its associated
data type.
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
Example declarations
int kids = 2;
double bankBalance = 500.45;
char firstLetter = ‘a’;
boolean married = true;
Literals
Example of declaration (with initialization)
int kids = 2;
the variable is kids
the primitive type is int
the initial value is the literal 2
What are the literals in the declarations
below?
double bankBalance = 500.45;
char firstLetter = ‘a’;
boolean married = true;
Values stored
Table page 37 of text
int
double
char
boolean
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).
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
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
Primitive Type boolean
Has only 2 possible values
true
false
Used to represent conditional values
Will use more later in the semester
Primitive type char
Represents a single character value
All character literals are enclosed in ‘’
letter, digit, special character
why??
Can you add ‘5’ + ‘6’ ?
How about special characters that are
not on keyboard
See table page 39.
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
Section 2.2 Processing
Numeric Data
Arithmetic Operators:
+
Addition
5 + 2 is 7
5.0 + 2.0 is 7.0
-
Subtraction
5 – 2 is 3
5.0 – 2.0 is 3.0
*
Multiplication 5 * 2 is 10
5.0 * 2.0 is 10.0
/
Division
5.0 / 2.0 is 2.5
5 / 2 is 2
%
Remainder
5 % 2 is 1
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.
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
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
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;
Operator Precedence
My Dear Aunt Sally
x=4+3*2
Uses 2 rules to decide
is it 10 or 14?
Parentheses rule
Operator precedence rule
Left associative rule (equal then left to right)
We will consistently use fully parenthesized
equations.
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
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.
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
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.
println method
Used to display output in the console
window.
Provided for you by java.
Is part of the System.out object.
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(argumentList);
Can be single or multiple values
See Page 49 println calls
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)
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.
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.
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.
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
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”)
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”);
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
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
Concatenate Strings with
Primitive Types
System.out.println(“First number is “ +
num1);
Concatenates one string and one
double
See examples Page 59-60
String Methods
See table String Methods Page 60
length
charAt
subString
indexOf
See examples pages 60 - 61
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
Storing result of method call
Method must return a value
int posBlank = text.indexOf(“ “);
String firstName = text.subString(0,
posBlank)
first blank in string text
if Mickey Mantle returns 6
pulls out first name
See example page 64
Display results of method call
System.out.printLn(“The First blank is
at position “ + text.indexOf(“ “));
Section 2.5 Input/Output
Will be using the following 2
approaches to Input/Output
JOptionPane
printLn()
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
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;
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
Examples Input dialog box
See examples on page 67 - 68
Displaying results in Console
Window
System.out.println(“what ever”);
See example page 68 bottom
Display results in dialog box
JOptionPane.showMessageDialog();
See example pages 69 - 70
Running code
See TwoNumbersDialog in JBuilder
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
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
Comments for each program
At the beginning of the program include
at a minimum
Name
Date
Class
Assignment
Program purpose
Example
/* John Wright
9/1/03
Minor Assignment 1
Computer Science I
This program will yada yada yada
yada yada */
Class Definitions
The class with the main method in it is
the starting class for an Application.
Classes have the form:
1.
2.
A header declaration
The class body
a.
b.
The data field declarations of the class
The method definitions of the class
public class PigLatinApp {…}
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.
Visibility
For the time being:
Make all methods public
Make all data fields private
Leave class visibility blank
Method main()
This is a “special” method that is called
by the operating system for
applications.
method header{
method body
{
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
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.
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.
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.
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.
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
Java Keywords
Also called reserve words
These can not be used in identifiers.
See list on page 81
Complete list in Appendix B
Identifiers
Is the name of a:
data field or variable
method
class
object
There are rules for valid identifier
names.
Identifiers
Java is case sensitive!!!!
Fred and fred are 2 different identifiers
Rules
1.
2.
3.
4.
must begin with letter, underscore or dollar sign.
Start all with letter
must consist of letters, digits, underscore, dollar
signs
Java reserve word can not be identifier
Can be any length
Identifier naming conventions
Classes
Use nouns
Start with capitol letter
Each new word is capitalized
SavingsAccount
PiggyBank
Identifier naming conventions
Variables
Start with lower case
Use Nouns
Each new Word is Capitalized
userName
pizzaPie
Identifier naming conventions
Methods
Start with lower case letter.
Use verb and prepositional phrases
Each new word is Capitalized
showInputDialog
performOutput
Identifier naming conventions
Contants
Use all capitols
Separate words with underscore
RETIREMENT_AGE
FEDERAL_TAX_RATE
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
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.
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.
Examples
Square Root 2.30 page 88
Random 2.31 page 88
Run and look at Section_2_8_1 in
JBuilder
Other Methods
These methods return whole numbers:
floor() whole number below real
ceil() whole number above real
rint() integer returned via rounding
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.
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
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
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
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