java – software solutions…. chapter 2: objects and primitive data

63
Java – Software Solutions…. Chapter 2: Objects and Primitive Data

Upload: anissa-turner

Post on 01-Jan-2016

247 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

Java – Software Solutions….

Chapter 2: Objects and Primitive Data

Page 2: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

2

Objects and Primitive Data

Now we can explore some more fundamental programming concepts

Chapter 2 focuses on:

predefined objects primitive data the declaration and use of variables expressions and operator precedence creating and using objects class libraries

Page 3: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

3

Introductory Notions

Need ability to create and use objects. Provide ‘services’

Objects are fundamental to writing programs in an OOP language.

Objects ‘do’ all the things we want: Manipulate strings Make computations Do input/output Draw shapes…

Page 4: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

4

Introduction to Objects

An object represents something with which we can interact in a program

An object provides 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

A class represents a concept, and an object represents the embodiment of a class

A class can be used to create multiple objects

Page 5: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

5

Introduction to Objects

Objects also manage data Maybe primitive; maybe complex (like integers, floats…) Most complex data consists if primitive data…

A data type defines a set of values and operations that can be performed on those values. Think: integers; +, -, *, /, no division by zero…

Objects is defined by a class – an abstraction; a generalization. Objects are ‘instances’ of a class.

Operations (methods) are defined by methods in the class. Methods – a collection of programming statements with a

given name that perform some kind of operation

Page 6: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

6

Objects and Classes

Bank Account

A class(the concept)

Class = BankAccount

John’s Bank AccountBalance: $5,257

An object(a realization)

(an ‘instantiation’)

Bill’s Bank AccountBalance: $1,245,069

Mary’s Bank AccountBalance: $16,833

Multiple objects

from the same class

. Has attributes (data). Has methods (operations)

Classes ‘encapsulate’ attributes and methods.

Page 7: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

7

Inheritance

One class can be used to derive another via inheritance

Classes can be organized into inheritance hierarchies

Bank Account

Account

Charge Account

Savings Account

Checking

Account

Think: Gender

Men Women

Mothers non-Mothers

Page 8: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

8

Using Objects

The System.out object represents a destination to which we can send output

In the Lincoln program, we invoked the println method of the System.out object:

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

object methodinformation provided to the method(parameters)

Notice the ‘notation’ for referencing the method: object.methodWe are SENDING A MESSAGE to the object, System.out.We are requesting that the object perform a ‘service’ for us by invoking.the services of its method, println.

Page 9: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

9

The print Method

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 65)

Sending a message (fig. 2.2)

main

Countdown System.out

println//println//lprint// others…

Page 10: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

10

Abstraction An abstraction hides (or suppresses) the right details at the

right time. We ‘abstract out’ common characteristics.

An object is abstract in that we don't have to think about its internal details in order to use it.

encapsulate attributes and methods and provide services (have ‘responsibilities’) to other objects through the sending of messages. For example, we don't have to know how the println method

inside the object System.out actually works in order to invoke it.

We know when we send a message to the object System.out (we send messages by invoking its ‘methods’) with the parameters (“ “) the object will print out the contents enclosed in quotes.

Page 11: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

11

Abstraction (continued)

Of course, we have ‘levels’ of abstraction – germane to the problem at hand. Car

Ford Mustang

Red Mustang that belongs to ….. Are all levels of abstraction! Each is more and more

specific, but all have the ‘is-a’ characteristics. More later…..

Classes and their objects help us write complex software

Page 12: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

12

Character Strings

Every character string is an object in Java, defined by the String class

Every string literal, delimited by double quotation marks, represents a String object

Two fundamental string operations: 1) The string concatenation operator (+) is used to

append one string to the end of another

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 13: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

13

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 (associativity)

Parentheses can be used to force the operation order

See Addition.java (page 70); Let’s look at some code:

Page 14: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

14

//******************************************************************** // Facts.java Author: Lewis/Loftus // // Demonstrates the use of the string concatenation operator and the // automatic conversion of an integer to a string. //********************************************************************

public class Facts { //----------------------------------------------------------------- // Prints various facts. //----------------------------------------------------------------- public static void main (String[] args) { // Strings can be concatenated into one long string System.out.println ("We present the following facts for your " + "extracurricular edification:");

System.out.println ();

// A string can contain numeric digits System.out.println ("Letters in the Hawaiian alphabet: 12");

// A numeric value can be concatenated to a string System.out.println ("Dialing code for Antarctica: " + 672);

System.out.println ("Year in which Leonardo da Vinci invented " + "the parachute: " + 1515);

System.out.println ("Speed of ketchup: " + 40 + " km per year"); } // end main } // end class Facts

Everything prints out in a straight line. See page 68 in textbook….

Page 15: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

15

Overloading Operators

Operators can be ‘overloaded’ Have different meanings depending on context. “+” can mean concatenation or addition

depending…. Remember the + operator ‘associates’ left to

right AND Remember parentheses always override the

‘normal’ hierarchical evaluation (later…)

Page 16: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

16

Escape Sequences

2) Second fundamental characteristic on Strings: the escape sequence.

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.");

This is a problem

Page 17: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

17

Escape sequences (continued)

An escape sequence is a series of characters that represents a special character – usually a single 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.");

Discuss…

Page 18: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

18

Escape Sequences

Some Java escape sequences:

Make sure you understand these, especially \n, \t, \” and maybe a couple of others… Let’s look at Roses.java

Escape Sequence

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

Meaning

backspacetab

newlinecarriage returndouble quotesingle quote

backslash

Page 19: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

19

Public Directory for Roses.java //******************************************************************** // Roses.java Author: Lewis/Loftus // // Demonstrates the use of escape sequences. //********************************************************************

public class Roses { //----------------------------------------------------------------- // Prints a poem (of sorts) on multiple lines. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("Roses are red,\n\tViolets are blue,\n" + "Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" + "So I'd rather just be friends\n\tAt this point in our " + "relationship."); } // end main } // end class Roses

Page 20: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

20

Variables A variable is a name for a location in memory

A variable must be declared by specifying the variable's name and the type of information that it will hold

int total;

int count, temp, result;

Multiple variables can be created in one declaration

data type variable name

Page 21: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

21

Variables

A variable can be given an initial value in the declaration

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

Look over PianoKeys.java (page 73) on your own.

int sum = 0;int base = 32, max = 149; // note syntax…

Page 22: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

22

Assignment

An assignment statement changes the value of a variable The assignment operator is the = signtotal = 55;

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

See Geometry.java (page 74) – will do….

The expression on the right is evaluated and the result is stored in the variable on the left

Page 23: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

23

Geometry example… /******************************************************************** // Geometry.java Author: Lewis/Loftus // // Demonstrates the use of an assignment statement to change the // value stored in a variable. //********************************************************************

public class Geometry { //----------------------------------------------------------------- // Prints the number of sides of several geometric shapes. //----------------------------------------------------------------- public static void main (String[] args) { int sides = 7; // declaration with initialization System.out.println ("A heptagon has " + sides + " sides.");

sides = 10; // assignment statement System.out.println ("A decagon has " + sides + " sides.");

sides = 12; System.out.println ("A dodecagon has " + sides + " sides."); } }

Page 24: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

24

Constants

A constant is an identifier that is similar to a variable except that it holds one value while the program is active

The compiler will issue an error if you try to change the value of a constant during execution

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

final int MIN_HEIGHT = 69;

Note: constants are written in caps to distinguish themselves from other ‘variables’ whose values can change. give names to otherwise unclear literal values facilitates updates of values used throughout a program prevent inadvertent attempts to change a value (Discuss: final float RATE = 0.15; only change value…)

Page 25: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

25

Primitive Data There are exactly eight primitive data types in Java

Four represent integers: byte, short, int, long (no fractions)

Two represent floating point numbers: float, double (contain decimals)

One represents characters: char

One represents boolean values: boolean All have different ‘sizes’ and ‘ranges’…..

Page 26: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

26

Numeric Primitive Data

Sizes and Ranges of storable values below. Use size as ‘appropriate’ but if in doubt, be

generous.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 27: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

27

Numeric Primitive Data

Default: int is 32 bits; but 45L or 45l => long

Default: for decimal data: assumes all literals are type double. To make ‘float’ 45.6F or 45.6f Can say, if desired, 45.6D or 45.6d, but

unnecessary.

Page 28: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

28

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'

‘7’ is not equivalent to 7 is not equivalent to “7”

Page 29: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

29

Characters The ASCII character set is older and smaller than Unicode, but is

still quite popular

Has evolved to eight-bits per byte.

(char is a ‘primitive data type’; String is a class)

Because String is a class, it has many methods (operations) that can be performed on String objects!)

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

letterslowercase letterspunctuationdigitsspecial symbolscontrol characters

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

Page 30: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

30

Boolean

A boolean value represents a true or false condition

A boolean also can 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 31: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

31

2.5 Arithmetic Expressions (p. 80)

An expression is a combination of one or more operands and their operators

Arithmetic expressions compute numeric results and make use of the arithmetic operators:

Addition +Subtraction -Multiplication *Division /Remainder % (modulus operator in C)

If operands are mixed, results are ‘promoted.’ 4.5 + 2 = 6.5 (double) Sometimes called “widened.”

Page 32: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

32

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

result is an integer (the fractional part is discarded)

If both or either parts are floating point, results are floating point.

14/3.0 = 14.0/3 = 14.0/3.0 = 3.5

The remainder operator (%) returns the remainder after dividing the second operand into the first and takes the sign of the numerator; only integers also

14 / 3 equals?

8 / 12 equals?

4

0

-14 % 3 equals?

8 % -12 equals?

-2

8 16.0 % 4.0 equals invalid operands

Page 33: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

33

Operator Precedence Operators can be combined into complex expressions

(variables or literals – doesn’t matter)

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 (‘associate left to right’)

Parentheses can be used to force the evaluation order

Can be nested too…..

Page 34: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

34

Operator Precedence

What is the order of evaluation in the following expressions?a + b + c + d + e

1 432a + b * c - d / e

3 241

a / (b + c) - d % e2 341

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

Page 35: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

35

Assignment Revisited

The assignment operator has a lower precedence than the arithmetic operators

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

Then the result is stored in the variable on the left hand sideNOTE: the ‘assignment operator (again) IS an operator – (merelyhas lower precedence than arithmetic operators….)

answer = sum / 4 + MAX * lowest;

14 3 2

What’s this?

Page 36: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

36

Assignment Revisited

The right and left hand sides of an assignment statement can contain the same variable

First, one is added to theoriginal value of count

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

count = count + 1;

KNOW THE OPERATOR PRECEDENCE TABLE ON PAGE 82. It will grow significantly!

Page 37: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

37

Data Conversions

Sometimes it is convenient to convert data types

For example, we may want to treat an integer as a floating point value during a computation

Be careful with conversions. Can lose information! (Why is one byte not enough to store 1000?)

Widening conversions; safest; tend to go from a small data type to a larger one (such as a short to an int) (more space (magnitude) normally; can lose precision – (int or long to float; long to double…) WHY?

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) (Can lose magnitude & precision!)

Page 38: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

38

Data Conversions

In Java, data conversions can occur in three ways: assignment conversion arithmetic promotion casting

Assignment conversion occurs when a value of one type is assigned to a variable of another Only widening (promoting) conversions can happen via

assignment

Arithmetic promotion happens automatically when operators in expressions convert their operands.

But be aware that this does NOT change the permanent value! Only changes it for the calculation.

Page 39: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

39

Data Conversions

Casting is the most powerful, and dangerous, technique for conversion Both widening and narrowing conversions can be

accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the

value being converted

For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total: result = (float) total / count;

DISCUSS!

Page 40: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

40

2.6 Creating Objects (p. 87)

A variable holds either a primitive type or a reference to an object

A class name can be used as a type to declare an object reference variable

String title;

No object is created with this declaration

Object reference variables hold memory addresses of object (point to the objects)

The object itself must be created separately

Page 41: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

41

Creating Objects - Constructors

Generally, use new ‘operator’ to create an objecttitle = new String ("Java Software Solutions");

This calls the String constructorconstructor - a special method that sets up the object.So, this statement allocates space for an object and initializes it via its constructor. (Constructor method is the same name as the class.) Creating an object is called instantiation An object is an instance of a particular class (here, String) Can combine these operations: (FREQUENTLY DONE!) of creating a reference variable and also the object itself with value in a single declaration…

String title = new String (“Java Software Solutions”);

The ‘object reference variable’ (title) stores the address of where the object physically resides in memory.

Page 42: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

42

Creating 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 works only for Strings

Once an object has been instantiated, we can use the dot operator to invoke its methods (format: object.method() )

title.length() as in

count = title.length(); (returns integer value of number of characters in the string, title – assigns that number to count. (assumes int count; )

Remember: the Constructor IS a method in all classes. When an object is created, its ‘constructor’ is called to set it up, initialize values, etc…. (Much more later on constructors)

Page 43: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

43

String Methods

The String class has several methods that are useful for manipulating strings. (Recall, classes have attributes and methods)

Many of the methods return a value, such as an integer - like length() or a new String object…

Some return a new String or a boolean value...when the lengths of strings are compared or their values are compared….

See the list of String methods on page 89 and in Appendix M

Page 44: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

44

// *************************************************************************// String Manipulation Example// *************************************************************************public class StringManipulation{

// ------------------------------------------------------// Prints a string and several mutations of it// ------------------------------------------------------public static void main (String [ ] args );{

String phrase = new String (“Change is inevitable”); // what does this do?String mutation1, mutation2, mutation3, mutation4; // what does this do?

System.out.println (“Original string: \”” + phrase + \”” );System.out.println (“Length of string: “ + phrase.length() );

mutation1 = phrase.concat (“, except from vending machines. “);// Note: many methods of objects of type String return new objects!!// See page 89. This is what is going on here….mutation2 = mutation1.toUpperCase();mutation3 = mutation1.replace(‘E’ , ‘X’);mutation4 = mutation1.substring(3,30);

// Print out resultsSystem.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: “ + mutation1.length());

}// end of main procedure} // end of public class StringManipulation

Page 45: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

45

2.7 Class Libraries (p.91)

A class library is a collection of classes that we can use when developing programs

The Java standard class library is part of any Java development environment – but NOT part of Java language.

Other class libraries can be obtained through third party vendors, or you can create them yourself

Class library = clusters of related classes, called Java APIs or Application Programmer Interface. Look these over!!!

Many “APIs” like the Java Database API which contains sets of classes that help us when we are dealing with databases.

Java Swing API – helps us when we are dealing with GUIs…

Page 46: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

46

Packages Classes of the Java standard class library are organized

into packages

The package organization is more fundamental and language-based than the API names. Use packages extensively!!!!

Some packages in the standard class library are:Package

java.langjava.appletjava.awtjavax.swingjava.netjava.utiljavax.xml.parsers

Purpose

General support // Always get this. No need to import Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities - will use this a lot XML document processing

Page 47: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

47

The import Declaration

To use class(es) from a package, we must ‘import’ the package. import java.util.*;

(imports package and all of its classes)

Or you can import only the class you are interested in:

import java.util.Random;

(imports the class Random from the package, util)

Import all classes in a particular package, you can use the * wildcard character. (Need > 1? Import entire package.)

Page 48: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

48

The import Declaration

All classes of the java.lang package are imported automatically into all programs

So, String and System weren’t explicitly imported… and didn’t need to import them in earlier examples.

The Random class is part of java.util package

Among other things, java.util package has a Random class that generates pseudorandom numbers if needed. (very popular class)

Page 49: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

49

Random Class from java.util package

Be certain to study figure 2.12 and listing 2.9 for public class RandomNumbers.

Be sure to understand how this works! Note: There is a Random class in java.util.

Generates a ‘pseudo random number’ Seeded! Some Random methods: (page 96)

Random () – Constructor; creases a new pseudorandom number generator.

float nextFloat() – returns a random number between 0.0 and 1.0 (exclusive) (Can cast to get an int, …)

int nextInt () – returns a random number ranging over all positive and negative values

int nextInt (int num) Returns a random number in range of 0 to num-1.

Page 50: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

50

2.8 Class Methods (p. 98) Some methods can be invoked through the class name, instead of

through an object of the class

Means you can use them directly and do not have to have objects of that class declared to get methods!

Called class methods or static methods (have class variables too…)

Method must be defined as static in the class though….and note (p. 99) all methods are static and ‘double.’

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);

Note: there is a random() static method in Math class. cos is a class or static method. Notation: class.method. Note: double temp;

Page 51: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

51

The Keyboard Class The Keyboard class is NOT part of the Java standard class

library

It is provided by the authors of the textbook to make reading input from the keyboard easy

Details of the Keyboard class - Chapter 5

The Keyboard class is part of a package called cs1 – created by authors.

It contains several static methods for reading particular types of data

BUT: we are going to do the real deal!

Page 52: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

52

Keyboard Input

The Keyboard class introduced in Chapter 2 facilitates capturing input from the keyboard

The Keyboard class was written by the authors of the book; hence, not commonly available to Java users.

The Keyboard class hides various aspects of Java input processing

Keyboard class obscured how Java really does keyboard input/output.

Page 53: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

53

Reading Keyboard Input Java I/O is accomplished using objects that represent streams of

data

A stream is an ordered sequence of bytes

The System.out object represents a standard output stream, which defaults to the monitor screen

This is always ‘character’ output…

Reading keyboard input is much more complicated

Recognize that input data coming from the keyboard is always in a character format (as are almost all files we process…)

E.g., 567 (entered on keyboard…) is the character 5 followed by character 6 followed by the character 7. It is NOT 567!... If we WANT 567, we must convert these characters to an integer!

Page 54: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

54

BufferedReader Class and its methods p. 287-288

The input stream is made up of multiple objects:

BufferedReader in = new BufferedReader (new InputStreamReader (System.in));

The System.in (object passed as a parameter) object is used by the InputStreamReader object to create an InputStreamReader object

The InputStreamReader object is then used as a parameter by BufferedReader to create a BufferedReader object – which is named ‘in.’

This creates an input stream that treats input as characters and buffers them so that input can be read one line at a time

The readLine method of the BufferedReader class (invoked via in.readLine() reads an entire line of input as a String

Page 55: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

55

Wrapper Classes

We have methods called “Wrapper class methods” (many of these are static methods or class methods….) that can be used to convert text (character) input into desired numeric input

Problems that arise in reading or converting a value manifest themselves as “Exceptions.”

The throws clause of a method header indicates what exceptions it may throw. (Much more later on these…)

I/O and exceptions are explored further in Chapter 8

All ‘primitive data types’ have Wrapper classes!!!!

Let’s look at some code…

Page 56: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

56

//********************************************************************// Wages2.java Author: Lewis/Loftus from Chapter 5 examples….// Demonstrates the use of Java I/O classes for keyboard input.//********************************************************************import java.io.*; import java.text.NumberFormat;

public class Wages2{ // Reads pertinent information and calculates wages. public static void main (String[] args) throws IOException { BufferedReader in = new BufferedReader (new InputStreamReader (System.in));

// creates a standard input stream object (a BufferedReader object) in a useful form….// name if input stream object is ‘in.’ ‘in’ is an object of type (class) BufferedReader.// Creates an input stream that accepts input as characters and buffers the input so that it

// can be read one line at a time. ‘in’ now has all the methods defined in BufferedReader. String name; // what does this do? int hours; // what does this do? double rate, pay;

System.out.print ("Enter your name: "); name = in.readLine ();

// The readLine method of ‘in’, an object of class BufferedReader, reads an entire line of// input as a String (line terminated by ‘Enter’ ). To treat input as an integer (next

statement…), // we must convert the input String into a numeric form, that is, an integer. Consider: System.out.print ("Enter the number of hours worked: "); hours = Integer.parseInt (in.readLine());

// parseInt is a static method of the Integer wrapper class – used to convert String input to int. System.out.print ("Enter pay rate per hour: "); rate = Double.parseDouble (in.readLine());

// ditto for parseDouble – a static method (class method) for the Double wrapper class.

Page 57: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

57

Continuing…

System.out.println ();

pay = hours * rate;

NumberFormat fmt = NumberFormat.getCurrencyInstance();

// Whoa! NumberFormat is a class!!!

// fmt is a ‘formatter object’ returned by the static class, getCurrencyInstance().

// This formatter object, fmt, returned by getCurrencyInstance() has a method

// we will use, namely ‘format.’ See below.

System.out.println (name + ", your pay is: " + fmt.format(pay));

}// end main

} // end Wages2

So, we need to discuss NumberFormat and DecimalFormat classes.

Page 58: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

58

2.9 Formatting Output (p. 103) Remember: some classes contain static (class) methods (and

attributes too). (more later in course)

The NumberFormat class (in java.text package) has several static methods; Two of these static methods ‘return’ a ‘formatter object’ of type NumberClass as

NumberFormat money = NumberFormat.getCurrencyInstance(); and

NumberFormat percent = NumberFormat.getPercentInstance();

Since ‘money’ is an object of type NumberFormat, it ‘gets’ everything in NumberFormat, including a format method – SEE PAGE 104 top!

This format method is invoked through a formatter object (money.format(argument) ) and returns a String (page 104…) that contains the number formatted in the appropriate manner. (See outputs, page 105)

Page 59: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

59

More…Stated a little differently…

We have requested a special kind of object from one of NumberFormat’s static methods (getCurrencyInstance) Will explain why we do this later… Two such static methods from which we can request objects

are getCurrencyInstance and getPercentInstance(). These methods, when invoked, return a special kind of object – called a ‘formatter’ object.

When such an object is called using its ‘format’ method (see top page 104) the argument is formatted appropriately (getCurrencyInstance() produces an output that looks like dollars and cents; getPercentInstance() produces an output with a % sign.

These objects use the ‘format’ method defined in NumberFormat, since each of these formatter objects “is_a” NumberFormat object. (Inheritance)

Page 60: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

60

//********************************************************************// Price.java Author: Lewis/Loftusimport cs1.Keyboard; // We will not use this!import java.text.NumberFormat;public class Price{ public static void main (String[] args) // purged comments for space….. { 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(); // we will use BufferedReader object ‘in’ ….. System.out.print ("Enter the unit price: "); unitPrice = Keyboard.readDouble(); // we will use BufferedReader and Double wrapper class…

subtotal = quantity * unitPrice; tax = subtotal * TAX_RATE; totalCost = subtotal + tax;

// Print output with appropriate formatting NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); // returns an object – a ‘formatter’ object NumberFormat fmt2 = NumberFormat.getPercentInstance(); // returns an object – a ‘formatter’ object… // fmt1 and fmt2 are objects of type NumberFormat and each have a method ‘format’ to perform // formatting…..Their responsibilities are to format currency or percentages respectively… System.out.println ("Subtotal: " + fmt1.format(subtotal)); System.out.println ("Tax: " + fmt1.format(tax) + " at " + fmt2.format(TAX_RATE)); System.out.println ("Total: " + fmt1.format(totalCost)); } // end main} // end Price class

Page 61: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

61

More on Formatting Output The DecimalFormat class can be used to format a floating

point value in generic ways

For example, you can specify that the number should be printed to three decimal places

Unlike the NumberFormat class with its static methods, the use of DecimalFormat requires instantiating objects in the usual way.

The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number. (Means, when the object is created, it is given an initial value by the Constructor, and this value is an alphanumeric ‘pattern.’)

These ‘patterns’ can be quite involved. More later.

Page 62: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

62

//********************************************************************// CircleStats.java Author: Lewis/Loftusimport cs1.Keyboard;import java.text.DecimalFormat;

public class CircleStats{ //----------------------------------------------------------------- // Calculates the area and circumference of a circle given its // radius. //----------------------------------------------------------------- public static void main (String[] args) { int radius; double area, circumference;

System.out.print ("Enter the circle's radius: "); radius = Keyboard.readInt(); // we will use BufferedReader objects… and Wrappers…

area = Math.PI * Math.pow(radius, 2); //look at the static Math attributes and methods! circumference = 2 * Math.PI * radius;

// Round the output to three decimal places DecimalFormat fmt = new DecimalFormat ("0.###"); //fmt is an object of type DecimalFormat

// string 0.### indicates that at least one digit should be to the left of the decimal, and // should be a zero if the integer position of the value is zero. Also indicates that the // fractional part should be rounded to three digits. System.out.println ("The circle's area: " + fmt.format(area)); //Where did this ‘format’ come from??? System.out.println ("The circle's circumference: " + fmt.format(circumference)); } // end main} // end CircleStats

Page 63: Java – Software Solutions…. Chapter 2: Objects and Primitive Data

63

Summary

Chapter 2 has focused on:

predefined objects primitive data the declaration and use of variables expressions and operator precedence creating and using objects class libraries Read way Java does Keyboard class…. NumberFormat and DecimalFormat classes