Title: Chapter 2: Objects and Primitive Data
1Chapter 2 Objects and Primitive Data
2Objects and Primitive Data
- We can now explore some more fundamental
programming concepts - Chapter 2 focuses on
- predefined objects
- primitive data
- the declaration and use of variables
- expressions and operator precedence
- class libraries
- Java applets
- drawing shapes
3Software Engineering
- Goal
- to make software reliable and maintainable
- As the complexity of a program increases, its
cost to develop and revise grows exponentially
cost
complexity
4Software Components
- Programs are easier to construct and modify if
- they are made up of separate components
- A software component can be thought of
- any program element that transforms input into
output
Input
Component
Output
15 38 16
Compute average
22
5Software Components
- Components can be combined to make larger
components
6Object-Oriented Programming
- Java is object-oriented language
- Programs are made from software components called
objects - Initially, we can think of an object as
- data for it and a collection of services
- Object
- contains data and methods to provide the service
7Object-Oriented Programming
- Class
- A class represents a concept
- An object is defined by a class
- Multiple objects can be created from the same
class
8Object-Oriented Programming
- A class represents a concept and
- an object represents the realization of that
concept
Objects
Class
Car
9Introduction to Objects
- Recall the Lincoln program,
- We invoked the println method of the System.out
object
System.out.println ("Whatever you are, be a good
one.")
10Input and Output
- Java I/O is based on input streams and output
streams - There are three predefined standard streams
- The print and println methods write to standard
output
Stream System.in System.out System.err
Purpose reading input writing output writing
errors
Default Device keyboard monitor monitor
11The println and print Methods
- The System.out object provides another service as
well - 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 - See Countdown.java (page 53)
12Countdown.java
- class Countdown
- public static void main (String args)
- System.out.print ("Three... ")
- System.out.print ("Two... ")
- System.out.print ("One... ")
- System.out.print ("Zero... ")
- System.out.println ("Liftoff!")
- System.out.println ("Houston, we have a
problem.") - // method main
- // class Countdown
13The String Class
- Every character string is an object in Java,
defined by the String class - Every string literal represents a String object
- A string literal cannot be broken across two
lines in a program
14String Concatenation and Addition
- The operator serves two purposes
- When applied to two strings,
- they are combined into one (string
concatenation) - When applied to a string and a number,
- that value is converted to a string and
concatenated - When applied to two numeric types,
- they are added together arithmetically
- See Antarctica.java and Sum.java
15Antarctica.java
- class Antarctica
- public static void main (String args)
- System.out.print ("The international "
"dialing code ") - System.out.println ("for Antarctica is "
672) - // method main
- // class Antarctica
16Sum.java
- class Sum
- public static void main (String args)
- System.out.println ("The sum of 16 and 9 is
" (169)) - System.out.println (16 and 9 concatenated"
16 9) - // method main
- // class Sum
17Variables
- A variable is a name for a location in memory
- A variable must be declared before use
- its 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
declaration
18Variables
- A variable can be given an initial value in the
declaration
int sum 0 int base 32, max 149
- When a variable is referenced in a program, its
current value is used
- See PianoKeys.java (page 60)
19Piano_Keys.java
- class Piano_Keys
- public static void main (String args)
- int keys 88
- System.out.println ("The number of piano
keys " keys) - // method main
- // class Piano_Keys
20Assignment
- 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
- Assigned values must be consistent with the
variable's declared type
21Assignment Statements
- class United_States
- public static void main (String args)
- int states 13
- System.out.println ("States in 1776 "
states) - states 50
- System.out.println ("States in 1959 "
states) - // method main
- // class United_States
22Primitive Data Types
- Data type
- A set of values and the operators you can perform
on them - Each value stored in memory is associated with a
particular data type - Primitive data types
- The Java language has 8 predefined data types
- Reserved words for primitive types
- byte, short, int, long, float, double, boolean,
char
23Primitive Data
- 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
24Integers
- There are four separate integer primitive data
types - They differ by the amount of memory used to store
them
Type byte short int long
Storage 8 bits 16 bits 32 bits 64 bits
Min Value -128 -32,768 -2,147,483,648
Max Value 127 32,767 2,147,483,647 9 x 1018
25Floating Point
- There are two floating point types
- The float type stores 7 significant digits
- The double type stores 15 significant digits
Approximate Min Value -3.4 x 1038 -1.7 x 10308
Approximate Max Value 3.4 x 1038 1.7 x 10308
Type float double
Storage 32 bits 64 bits
26Characters
- A char value stores a single character from the
Unicode character set - A character set is an ordered list of characters
- The Unicode character set uses sixteen bits per
character, allowing for 65,536 unique characters - Character literals are delimited by single
quotes - 'a' 'X' '7' '' ',' '\n'
27Characters
- The ASCII character set is still the basis for
many other programming languages - ASCII is a subset of Unicode, including
uppercase letters lowercase letters punctuation di
gits special symbols control characters
A, B, C, a, b, c, period, semi-colon, 0, 1,
2, , , \, carriage return, tab, ...
28Boolean
- A boolean value represents a true or false
condition - The reserved words
- true and false are the only valid values for a
boolean type - boolean done false
29Wrappers
- Wrapper class(?? ???) for each primitive type
- Wrapper classes are useful in situations where
you need an object instead of a primitive type - They also contain some useful methods
Primitive Type int double char boolean
Wrapper Class Integer Double Character Boolean
30Constants
- A constant is similar to a variable except that
they keep the same value throughout their
existence - They are specified using the reserved word final
- For example
- final double PI 3.14159
- final int STUDENTS 25
31Constants
- When appropriate, constants are better than
variables - they prevent inadvertent errors because their
value cannot change - They are better than literal values because
- they make code more readable by giving meaning to
a value - they facilitate change because the value is only
specified in one place
32Expressions
- An expression is a combination of operators and
operands - every expression has its result value.
- The arithmetic operators
- , -, , /, , ...
- Operands
- literal values, variables, or other sources of
data - The programmer usually
- store or print the result of an expression.
33Division
- Division A/B
- If A and B are both integers, the result is an
integer (the fractional part is truncated) - If one or more operands are floating point
values, the result is a floating point value - The remainder operator AB
- returns the integer remainder after dividing
- The operands to the operator must be integers
- The remainder result takes the sign of the
numerator - See Division.java
34Division.java
- class Division
- public static void main (String args)
- int oper1 9, oper2 4
- double oper3 4.0
- System.out.println ("Integer division "
oper1/oper2) - System.out.println ("Floating division "
oper1/oper3) - System.out.println ("Modulus division "
oper1oper2) - // method main
- // class Division
35Division
Expression 17 / 5 17.0 / 5 17 / 5.0 9 / 12 9.0
/ 12.0 6 2 14 5 -14 5
Result 3 3.4 3.4 0 0.75 0 4 -4
36Operator Precedence
- Operator precedence
- The order in which operands are evaluated in an
expression - Associativity
- Operators at the same level of precedence are
evaluated - (left to right ) or (right to left)
- Parentheses can be used to force precedence
- See Appendix D
37Operator Precedence
- Multiplication, division, and remainder have a
higher precedence than addition and subtraction - Both groups associate left to right
5 12 / 5 - 10 3 6
Expression Order of evaluation Result
4
3
2
1
38Operator Precedence
- What is the order of evaluation in the following
expressions?
a b c d e
a b c - d / e
1
4
3
2
3
2
4
1
a / (b c) - d e
2
3
4
1
a / (b (c (d - e)))
4
1
2
3
39Operator Precedence
Expression 2 3 4 / 2 3 13 2 (3 13)
2 3 (13 2) 4 (11 - 6) (-8 10) (5 (4
- 1)) / 2
Result 8 41 41 45 40 7
40Assignment Revisited
- The assignment operator has a lower precedence
than the arithmetic operators
First the expression on the right hand side of
the operator is evaluated
answer sum / 4 MAX lowest
1
4
3
2
Then the result is stored in the variable on the
left hand side
41Assignment Revisited
- The right and left hand sides of an assignment
statement can contain the same variable
First, one is added to the original value of count
count count 1
Then the result is stored back into
count (overwriting the original value)
42Data Conversions
- Sometimes it is convenient to convert data from
one type to another - For example, we may want to treat an integer as a
floating point value during a computation - Conversions must be handled carefully to avoid
losing information
43Data Conversions
- Widening conversions are safest
- they tend to go from a small data type to a
larger one (such as a short to an int) - Narrowing conversions can lose information
- they tend to go from a large data type to a
smaller one (such as an int to a short)
44Data Conversions
- In Java, data conversions can occur in three
ways - assignment conversion(ONLY WIDENING)
- arithmetic promotion(ONLY WIDENING)
- casting
- Assignment conversion occurs
- when a value of one type is assigned to a
variable of another - Arithmetic promotion happens automatically
- when operators in expressions convert their
operands
45Data Conversions
- Casting is the most powerful, and dangerous,
technique for conversion - Both widening and narrowing conversions
- To cast, the type is put in parentheses in front
of the value being converted. - result (float) total / count
46Creating Objects
- A variable either holds a primitive type, or it
holds a reference to an object - A class name can be used as a type to declare an
object reference variable - String title
- No object has been created with this declaration
- An object reference variable holds the address of
an object - The object itself must be created separately
47Creating Objects
- We use the new operator to create an object
title new String ("Java Software Solutions")
This calls the String constructor, which is a
special method that sets up the object
- Creating an object is called instantiation
- An object is an instance of a particular class
48Creating Objects
- Because strings are so common, we don't have to
use the new operator to create a String object - title "Java Software Solutions"
- This is special syntax that only works for
strings - Once an object has been instantiated, we can use
the dot operator to invoke its methods - title.length()
49String Methods
- The String class has several methods that are
useful for manipulating strings - Many of the methods return a value, such as an
integer or a new String object - See the list of String methods on page 75 and in
Appendix M - See StringMutation.java (page 77)
50StringMutation.java
- public class StringMutation
-
- public static void main (String args)
-
- String phrase new String ("Change is
inevitable") - String mutation1, mutation2, mutation3,
mutation4 - System.out.println ("Original string \""
phrase "\"") - System.out.println ("Length of string "
phrase.length()) - mutation1 phrase.concat (", except from
vending machines.") - mutation2 mutation1.toUpperCase()
- mutation3 mutation2.replace ('E', 'X')
- mutation4 mutation3.substring (3, 30)
51StringMutation.java
- // Print each mutated string
- System.out.println ("Mutation 1 "
mutation1) - System.out.println ("Mutation 2 "
mutation2) - System.out.println ("Mutation 3 "
mutation3) - System.out.println ("Mutation 4 "
mutation4) - System.out.println ("Mutated length "
mutation4.length()) -
-
52Class Libraries
- The Java API is a class library,
- a group of classes that support program
development - The classes in the Java API is separated into
packages - The System class, for example, is in package
java.lang - Each package contains a set of classes that
relate in some way
53Packages
- The classes of the Java standard class library
are organized into packages
54The Java API Packages
- Other packages in the Java API
java.applet java.awt java.beans java.io java.lang
java.math
java.net java.rmi java.security java.sql java.text
java.util
55Importing Packages
- (1) Using a class from Java API by a fully
qualified name - java.lang.System.out.println ()
- (2) Package can be imported using an import
statement - import java.applet.
- import java.util.Random
- to import all classes in a particular package
56The import Declaration
- All classes of the java.lang package are
automatically imported into all programs - System or String classes
- The Random class is part of the java.util package
- It provides methods for pseudo-random numbers
- scale and shift a number into an appropriate
range - See RandomNumbers.java (page 82)
57RandomNumbers.java
- import java.util.Random
- public class RandomNumbers
-
- public static void main (String args)
-
- Random generator new Random()
- int num1
- float num2
- num1 generator.nextInt()
- System.out.println ("A random integer "
num1) - num1 Math.abs (generator.nextInt()) 10
- System.out.println ("0 to 9 " num1)
58RandomNumbers.java
- num1 Math.abs (generator.nextInt()) 20
10 - System.out.println ("10 to 29 " num1)
- num2 generator.nextFloat()
- System.out.println ("A random float
between 0-1 " num2) - num2 generator.nextFloat() 6 // 0 to
5 - num1 (int) num2 1
- System.out.println ("1 to 6 " num1)
-
-
59Class Methods
- class methods or static methods
- can be invoked through the class name, instead of
through an object of the class - The Math class contains many static methods,
- absolute value, trigonometry functions, square
root, etc. - temp Math.cos(90) Math.sqrt(delta)
60The Keyboard Class
- The Keyboard class is NOT part of the Java API
- by the authors to make reading input from the
keyboard easy - contains several static methods for reading
particular types of data - The Keyboard class is part of a package called
cs1 - For now we will simply make use of it
- Details of the Keyboard class are explored in
Chapter 8 - See Echo.java (pp 86) and Quadratic.java (pp 87)
61Echo.java
- import cs1.Keyboard
- public class Echo
-
- public static void main (String args)
-
- String message
- System.out.println ("Enter a line of
text") - message Keyboard.readString()
- System.out.println ("You entered \""
message "\"") -
-
62Quadratic.java
- import cs1.Keyboard
- public class Quadratic
-
- public static void main (String args)
-
- int a, b, c // ax2 bx c
- System.out.print ("Enter the coefficient of
x squared ") - a Keyboard.readInt()
- System.out.print ("Enter the coefficient of
x ") - b Keyboard.readInt()
- System.out.print ("Enter the constant ")
- c Keyboard.readInt()
- double discriminant Math.pow(b, 2) - (4
a c) - double root1 ((-1 b)
Math.sqrt(discriminant)) / (2 a) - double root2 ((-1 b) -
Math.sqrt(discriminant)) / (2 a) - System.out.println ("Root 1 " root1)
63Formatting Output
- The NumberFormat class has static methods that
return a formatter object - getCurrencyInstance()
- getPercentInstance()
- Each formatter object has a method called format
that returns a string with the specified
information in the appropriate format - See Price.java (page 89)
64Price.java
- import cs1.Keyboard
- import java.text.NumberFormat
- public class Price
-
- public static void main (String args)
-
- final double TAX_RATE 0.06 // 6 sales
tax - int quantity
- double subtotal, tax, totalCost, unitPrice
- System.out.print ("Enter the quantity ")
- quantity Keyboard.readInt()
- System.out.print ("Enter the unit price
") - unitPrice Keyboard.readDouble()
65Price.java
- subtotal quantity unitPrice
- tax subtotal TAX_RATE
- totalCost subtotal tax
- // Print output with appropriate formatting
- NumberFormat money
NumberFormat.getCurrencyInstance() - NumberFormat percent NumberFormat.getPerce
ntInstance() - System.out.println ("Subtotal "
money.format(subtotal)) - System.out.println ("Tax "
money.format(tax) " at " - percent.format(TAX_RAT
E)) - System.out.println ("Total "
money.format(totalCost)) -
-
66Formatting Output
- The DecimalFormat class can be used to format a
floating point value in generic ways - For example, you can specify that the number be
printed to three decimal places - The constructor of the DecimalFormat class takes
a string that represents a pattern for the
formatted number - See CircleStats.java (page 91)
67CircleStats.java
- import cs1.Keyboard
- import java.text.DecimalFormat
- public class CircleStats
-
- public static void main (String args)
-
- int radius
- double area, circumference
- System.out.print ("Enter the circle's
radius ") - radius Keyboard.readInt()
- area Math.PI Math.pow(radius, 2)
- circumference 2 Math.PI radius
-
68CircleStats.java
- // Round the output to three decimal places
- DecimalFormat fmt new DecimalFormat
("0.") - System.out.println ("The circle's area "
fmt.format(area)) - System.out.println ("The circle's
circumference " - fmt.format(circumferen
ce)) -
-
69Input and Output
- The Java API allows you to create many kinds of
streams to perform various kinds of I/O - To read character strings, we will convert the
System.in stream to another kind of stream using - BufferedReader stdin new BufferedReader
- (new InputStreamReader (System.in))
- This declaration creates a new stream called
stdin - We will discuss object creation in more detail
later
70Numeric Input
- Converting a string that holds an integer into
the integer value using Integer wrapper class - value Integer.parseInt (my_string)
- A value can be read and converted in one line
- num Integer.parseInt (stdin.readLine())
- See Addition.java and Addition2.java
71Escape Sequences
- See Echo.java
- An escape sequence is a special sequence of
characters preceded by a backslash (\) - They indicate some special purpose, such as
Escape Sequence \t \n \" \' \\
Meaning tab new line double quote single
quote backslash
72Echo.java
- import java.io.
- class Echo
- public static void main (String args) throws
IOException - BufferedReader stdin new BufferedReader
- (new InputStreamReader(System.in))
- String message
- System.out.println ("Enter a line of text")
- message stdin.readLine()
- System.out.println ("You entered \""
message "\"") - // method main
- // class Echo
73Java Applets
- A Java applet
- a Java program that is intended to be sent across
a network and executed using a Web browser - A Java application is a stand alone program
- Applications have a main method, but applets do
not - Special methods of applets
- The paint method, for instance, is automatically
executed and is used to draw the applets contents - Applets are derived from the java.applet.Applet
74Java Applets
- Links to applets can be embedded in HTML
documents - actually the bytecode version of the program that
is transported across the web - The applet is executed by a Java interpreter that
is part of the browser(Netscape or Explorer) - Appletviewer in JDK
- appletviewer xxx.html
75Execution of Java Applets
local computer
Java compiler
Java source code
Java bytecode
Web browser
remote computer
Java interpreter
76Applets
- The paint method accepts a parameter that is an
object of the Graphics class - A Graphics object defines a graphics context on
which we can draw shapes and text - The Graphics class has several methods for
drawing shapes - See Einstein.java (page 93)
77Einstein.java
- import java.applet.Applet
- import java.awt.
- public class Einstein extends Applet
-
- // Draws a quotation by Albert Einstein among
some shapes. - public void paint (Graphics page)
-
- page.drawRect (50, 50, 40, 40) //
square - page.drawRect (60, 80, 225, 30) //
rectangle - page.drawOval (75, 65, 20, 20) //
circle - page.drawLine (35, 60, 100, 120) // line
- page.drawString ("Out of clutter, find
simplicity.", 110, 70) - page.drawString ("-- Albert Einstein", 130,
100) -
78Drawing Shapes
- A shape can be filled or unfilled, depending on
which method is invoked - fillArc( ), fillOval( ), fillRect( )
- The method parameters specify coordinates and
sizes - Java coordinate system has the origin in the
upper left corner - Many shapes with curves, like an oval, are drawn
by specifying its bounding rectangle - An arc can be thought of as a section of an oval
79Drawing a Line
10
150
20
45
80Drawing a Rectangle
50
20
page.drawRect (50, 20, 100, 40)
81Drawing an Oval
175
20
bounding rectangle
page.drawOval (175, 20, 50, 80)
82The Color Class
- A color is defined in a Java program using an
object created from the Color class - The Color class also contains several static
predefined colors - Every graphics context has a current foreground
color - Every drawing surface has a background color
- See Snowman.java (page 99-100)
83Snowman.java
- import java.applet.Applet
- import java.awt.
- public class Snowman extends Applet
-
- public void paint (Graphics page)
-
- final int MID 150
- final int TOP 50
- setBackground (Color.cyan)
- page.setColor (Color.blue)
- page.fillRect (0, 175, 300, 50) // ground
- page.setColor (Color.yellow)
- page.fillOval (-40, -40, 80, 80) // sun
-
84Snowman.java
- page.setColor (Color.white)
- page.fillOval (MID-20, TOP, 40, 40)
// head - page.fillOval (MID-35, TOP35, 70, 50)
// upper torso - page.fillOval (MID-50, TOP80, 100, 60)
// lower torso - page.setColor (Color.black)
- page.fillOval (MID-10, TOP10, 5, 5) //
left eye - page.fillOval (MID5, TOP10, 5, 5) //
right eye - page.drawArc (MID-10, TOP20, 20, 10, 190,
160) // smile - page.drawLine (MID-25, TOP60, MID-50,
TOP40) // left arm - page.drawLine (MID25, TOP60, MID55,
TOP60) // right arm - page.drawLine (MID-20, TOP5, MID20,
TOP5) // brim of - page.fillRect (MID-15, TOP-20, 30, 25)
// top of hat -
-