Transcript
Page 1: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

INF 523QINF 523Q

Chapter 2: Objects and Chapter 2: Objects and Primitive DataPrimitive Data

Page 2: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

2

Objects and Primitive DataObjects and Primitive Data

Chapter 2 focuses on:Chapter 2 focuses on:• predefined objectspredefined objects

• primitive dataprimitive data

• the declaration and use of variablesthe declaration and use of variables

• expressions and operator precedenceexpressions and operator precedence

• class librariesclass libraries

Page 3: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

3

Introduction to ObjectsIntroduction to Objects

Initially, we can think of an Initially, we can think of an objectobject as a collection of services as a collection of services that we can tell it to perform for usthat we can tell it to perform for us

The services are defined by methods in a class that defines The services are defined by methods in a class that defines the objectthe object

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

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

objectobject methodmethodInformation provided to the methodInformation provided to the method

(parameters)(parameters)

Page 4: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

4

The println and print MethodsThe println and print Methods

The The System.outSystem.out object provides another service as well object provides another service as well

The The printprint method is similar to the method is similar to the printlnprintln method, method, except that it does not advance to the next lineexcept that it does not advance to the next line

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

E.g.: Countdown.java (p. 53)E.g.: Countdown.java (p. 53)

Page 5: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Countdown.java //************************************************************ // Countdown.java Author: Lewis and Loftus // Demonstrates the difference between print and println. //************************************************************ public class Countdown { // Prints two lines of output representing a rocket 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!"); // appears on first output line System.out.println ("Houston, we have a problem."); } }

Page 6: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

6

AbstractionAbstraction

An An abstractionabstraction hides (or ignores) the right details at the hides (or ignores) the right details at the right timeright time

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

We don't have to know how the We don't have to know how the printlnprintln method works in method works in order to invoke itorder to invoke it

A human being can only manage seven (plus or minus 2) A human being can only manage seven (plus or minus 2) pieces of information at one timepieces of information at one time

But if we group information into chunks (such as objects) But if we group information into chunks (such as objects) we can manage many complicated pieces at oncewe can manage many complicated pieces at once

Therefore, we can write complex software by organizing it Therefore, we can write complex software by organizing it carefully into classes and objectscarefully into classes and objects

Page 7: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

7

The String ClassThe String Class

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

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

The The string concatenation operatorstring concatenation operator (+) is used to append one (+) is used to append one string to the end of anotherstring to the end of another

It can also be used to append a number to a stringIt can also be used to append a number to a string A string literal cannot be broken across two lines in a A string literal cannot be broken across two lines in a

programprogram E.g.: Facts.java (p. 56)E.g.: Facts.java (p. 56)

Page 8: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

//************************************************************ // Facts.java Author: Lewis and 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");

Facts.javaFacts.java

Page 9: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

// A numeric value can be concatenated to a string System.out.println ("International dialing code for Anarctica: " + 672); System.out.println ("Year in which Leonardo da Vinci invented " + "the parachute: " + 1515); System.out.println ("Speed of ketchup: " + 40 + " km per year"); } }

Facts.java (cont.)Facts.java (cont.)Facts.java (cont.)Facts.java (cont.)

Page 10: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

10

String ConcatenationString Concatenation

The plus operator (+) is also used for arithmetic additionThe plus operator (+) is also used for arithmetic addition The function that the + operator performs depends on the The function that the + operator performs depends on the

type of the information on which it operatestype of the information on which it operates If both operands are strings, or if one is a string and one is If both operands are strings, or if one is a string and one is

a number, it performs string concatenationa number, it performs string concatenation If both operands are numeric, it adds themIf both operands are numeric, it adds them The + operator is evaluated left to rightThe + operator is evaluated left to right Parentheses can be used to force the operation orderParentheses can be used to force the operation order E.g.: Addition.java (p. 58)E.g.: Addition.java (p. 58)

Page 11: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

//*************************************************************

// Addition.java Author: Lewis and Loftus // Demonstrates the difference between the addition and string // concatenation operators. //

************************************************************* public class Addition { //----------------------------------------------------------------- // Concatenates and adds two numbers and prints the results. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("24 and 45 concatenated: " + 24 + 45); System.out.println ("24 and 45 added: " + (24 + 45)); } }

Addition.java

Page 12: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

12

Escape SequencesEscape Sequences

What if we wanted to print a double quote character?What if we wanted to print a double quote character? The following line would confuse the compiler because it The following line would confuse the compiler because it

would interpret the second quote as the end of the stringwould interpret the second quote as the end of the string

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

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

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

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

Page 13: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

13

Escape SequencesEscape Sequences

Some Java escape sequences:Some Java escape sequences:

E.g.: Roses.java (p. 59)E.g.: Roses.java (p. 59)

Escape Sequence

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

Meaning

backspacetab

newlinecarriage returndouble quotesingle quotebackslash

Page 14: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

14

VariablesVariables

A A variablevariable is a name for a location in memory is a name for a location in memory A variable must be A variable must be declareddeclared, specifying the variable's name , specifying the variable's name

and the type of information that will be held in itand the type of information that will be held in it

int total;

int count, temp, result;

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

data typedata type variable namevariable name

Page 15: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

VariablesVariables

A variable can be given an initial value in the declarationA variable can be given an initial value in the declaration

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

E.g.: PianoKeys.javaE.g.: PianoKeys.java

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

Page 16: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

PianoKeys.javaPianoKeys.java

//************************************************************* // PianoKeys.java Author: Lewis and Loftus // Demonstrates the declaration, initialization, and use of an integer variable. //************************************************************* public class PianoKeys { //----------------------------------------------------------------- // Prints the number of keys on a piano. //----------------------------------------------------------------- public static void main (String[] args) { int keys = 88; System.out.println ("A piano has " + keys + " keys."); } }

PianoKeys.javaPianoKeys.java

Page 17: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

17

AssignmentAssignment

An An assignment statementassignment statement changes the value of a variable changes the value of a variable The assignment operator is the The assignment operator is the == sign sign

total = 55;

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

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

The value that was in The value that was in totaltotal is overwritten is overwritten

E.g.: Geometry.java (p. 62)E.g.: Geometry.java (p. 62)

Page 18: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Geometry.javaGeometry.java //*************************************************************** // Geometry.java Author: Lewis and 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."); } }

Geometry.javaGeometry.java

Page 19: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

ConstantsConstants

A constant is an identifier that is similar to a variable A constant is an identifier that is similar to a variable except that it holds one value for its entire existenceexcept that it holds one value for its entire existence

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

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

final int MIN_HEIGHT = 69;

Constants:Constants:• give names to otherwise unclear literal valuesgive names to otherwise unclear literal values

• facilitate changes to the codefacilitate changes to the code

• prevent inadvertent errorsprevent inadvertent errors

Page 20: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Primitive DataPrimitive Data

There are exactly eight primitive data types in JavaThere are exactly eight primitive data types in Java

Four of them represent integers:Four of them represent integers:• bytebyte, , shortshort, , intint, , longlong

Two of them represent floating point numbers:Two of them represent floating point numbers:• floatfloat, , doubledouble

One of them represents characters:One of them represents characters:• charchar

And one of them represents boolean values:And one of them represents boolean values:• booleanboolean

Page 21: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Numeric Primitive DataNumeric Primitive Data

The difference between the various numeric primitive types The difference between the various numeric primitive types is their size, and therefore the values they can store:is their size, and therefore the values they can store:

Type

byteshortintlong

floatdouble

Storage

8 bits16 bits32 bits64 bits

32 bits64 bits

Min Value

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

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

Max Value

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

Page 22: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

22

CharactersCharacters

AA char char variable stores a single character from the variable stores a single character from the Unicode character setUnicode character set

A A character setcharacter set is an ordered list of characters, and each is an ordered list of characters, and each character corresponds to a unique numbercharacter corresponds to a unique number

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

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

Character literals are delimited by single quotes:Character literals are delimited by single quotes:

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

Page 23: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

23

CharactersCharacters

The The ASCII character setASCII character set is older and smaller than Unicode, is older and smaller than Unicode, but is still quite popularbut is still quite popular

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

uppercase letterslowercase letterspunctuationdigitsspecial symbolscontrol characters

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

Page 24: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

24

BooleanBoolean

AA boolean boolean value represents a true or false conditionvalue represents a true or false condition

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

The reserved wordsThe reserved words true true andand false false are the only valid are the only valid values for a boolean typevalues for a boolean type

boolean done = false;boolean done = false;

Page 25: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Arithmetic ExpressionsArithmetic Expressions

An An expressionexpression is a combination of operators and operands is a combination of operators and operands Arithmetic expressionsArithmetic expressions compute numeric results and make compute numeric results and make

use of the arithmetic operators:use of the arithmetic operators:

Addition +Subtraction -Multiplication *Division /Remainder %

If either or both operands to an arithmetic operator are If either or both operands to an arithmetic operator are floating point, the result is a floating pointfloating point, the result is a floating point

Page 26: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Division and RemainderDivision and Remainder

If both operands to the division operator (If both operands to the division operator (//) are integers, ) are integers, the result is an integer (the fractional part is discarded)the result is an integer (the fractional part is discarded)

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

14 / 3 equals?

8 / 12 equals?

4

0

14 % 3 equals?

8 % 12 equals?

2

8

Page 27: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Operator PrecedenceOperator Precedence

Operators can be combined into complex expressionsOperators can be combined into complex expressions

result = total + count / max - offset;

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

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

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

Parentheses can always be used to force the evaluation Parentheses can always be used to force the evaluation orderorder

Page 28: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Operator PrecedenceOperator Precedence

What is the order of evaluation in the following What is the order of evaluation in the following expressions?expressions?

a + b + c + d + e1 432

a + b * c - d / e3 241

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

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

Page 29: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Assignment RevisitedAssignment Revisited

The assignment operator has a lower precedence than the The assignment operator has a lower precedence than the arithmetic operatorsarithmetic operators

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

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

answer = sum / 4 + MAX * lowest;

14 3 2

Page 30: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Assignment RevisitedAssignment Revisited

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

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

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

count = count + 1;

Page 31: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Data ConversionsData Conversions

Sometimes it is convenient to convert data from one type to Sometimes it is convenient to convert data from one type to anotheranother

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

Conversions must be handled carefully to avoid losing Conversions must be handled carefully to avoid losing informationinformation

Widening conversionsWidening conversions are safest because they tend to go are safest because they tend to go from a small data type to a larger one (such as a from a small data type to a larger one (such as a shortshort to to an an intint))

Narrowing conversionsNarrowing conversions can lose information because they can lose information because they tend to go from a large data type to a smaller one (such as tend to go from a large data type to a smaller one (such as an an intint to a to a shortshort))

Page 32: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Data ConversionsData Conversions

In Java, data conversions can occur in three ways:In Java, data conversions can occur in three ways:• assignment conversionassignment conversion

• arithmetic promotionarithmetic promotion

• castingcasting

Assignment conversionAssignment conversion occurs when a value of one type is occurs when a value of one type is assigned to a variable of anotherassigned to a variable of another

Only widening conversions can happen via assignmentOnly widening conversions can happen via assignment

Arithmetic promotionArithmetic promotion happens automatically when happens automatically when operators in expressions convert their operandsoperators in expressions convert their operands

Page 33: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Data ConversionsData Conversions

CastingCasting is the most powerful, and dangerous, technique for is the most powerful, and dangerous, technique for conversionconversion

Both widening and narrowing conversions can be Both widening and narrowing conversions can be accomplished by explicitly casting a valueaccomplished by explicitly casting a value

To cast, the type is put in parentheses in front of the value To cast, the type is put in parentheses in front of the value being convertedbeing converted

For example, if For example, if totaltotal and and countcount are integers, but we are integers, but we want a floating point result when dividing them, we can want a floating point result when dividing them, we can cast cast totaltotal::

result = (float) total / count;

Page 34: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Creating ObjectsCreating Objects

A variable either holds a primitive type, or it holds a A variable either holds a primitive type, or it holds a referencereference to an object to an object

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

String title;

No object has been created with this declarationNo object has been created with this declaration An object reference variable holds the address of an objectAn object reference variable holds the address of an object The object itself must be created separatelyThe object itself must be created separately

Page 35: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Creating ObjectsCreating Objects

We use the We use the newnew operator to create an object operator to create an object

title = new String ("Java Software Solutions");

This calls the This calls the StringString constructorconstructor, which is, which isa special method that sets up the objecta special method that sets up the object

Creating an object is called Creating an object is called instantiationinstantiation

An object is an An object is an instanceinstance of a particular class of a particular class

Page 36: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Creating ObjectsCreating Objects

Because strings are so common, we don't have to use the Because strings are so common, we don't have to use the newnew operator to create a operator to create a StringString object object

title = "Java Software Solutions";

This is special syntax that only works for stringsThis is special syntax that only works for strings

Once an object has been instantiated, we can use the Once an object has been instantiated, we can use the dot dot operatoroperator to invoke its methods to invoke its methods

title.length()

Page 37: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

String MethodsString Methods

The The StringString class has several methods that are useful for class has several methods that are useful for manipulating stringsmanipulating strings

Many of the methods Many of the methods return a valuereturn a value, such as an integer or a , such as an integer or a new new StringString object object

See the list of See the list of StringString methods on page 75 and in Appendix methods on page 75 and in Appendix MM

E.g.: StringMutation.java (p. 77)E.g.: StringMutation.java (p. 77)

Page 38: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

StringMutation.javaStringMutation.java //**************************************************************** // StringMutation.java Author: Lewis and Loftus // Demonstrates the use of the String class and its methods. //**************************************************************** public class StringMutation { //----------------------------------------------------------------- // Prints a string and various mutations of it. //----------------------------------------------------------------- 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());

Page 39: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

StringMutation.java (cont.)StringMutation.java (cont.) mutation1 = phrase.concat (", except from vending machines."); mutation2 = mutation1.toUpperCase(); mutation3 = mutation2.replace ('E', 'X'); mutation4 = mutation3.substring (3, 30); // 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()); } }

Page 40: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Class LibrariesClass Libraries

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

There is a There is a Java standard class libraryJava standard class library that is part of any that is part of any Java development environmentJava development environment

These classes are not part of the Java language per se, but These classes are not part of the Java language per se, but we rely on them heavilywe rely on them heavily

The The SystemSystem class and the class and the StringString class are part of the class are part of the Java standard class libraryJava standard class library

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

Page 41: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

PackagesPackages

The classes of the Java standard class library are organized The classes of the Java standard class library are organized into packagesinto packages

Some of the packages in the standard class library are:Some of the packages in the standard class library are:

Package

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

Purpose

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

Page 42: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

The import DeclarationThe import Declaration

When you want to use a class from a package, you could When you want to use a class from a package, you could use its use its fully qualified namefully qualified name

java.util.Random

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

import java.util.Random;

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

import java.util.*;

Page 43: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

The import DeclarationThe import Declaration

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

That's why we didn't have to explicitly import the That's why we didn't have to explicitly import the SystemSystem or or StringString classes in earlier programs classes in earlier programs

The The RandomRandom class is part of the class is part of the java.utiljava.util package package It provides methods that generate pseudo-random numbersIt provides methods that generate pseudo-random numbers We often have to We often have to scalescale and and shiftshift a number into an a number into an

appropriate range for a particular purposeappropriate range for a particular purpose E.g. RandomNumbers.java (p. 82)E.g. RandomNumbers.java (p. 82)

Page 44: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

RandomNumbers.javaRandomNumbers.java //**************************************************************** // RandomNumbers.java Author: Lewis and Loftus // Demonstrates the import statement, and the creation of pseudo- // random numbers using the Random class. //**************************************************************** import java.util.Random; public class RandomNumbers { // Generates random numbers in various ranges. public static void main (String[] args) { Random generator = new Random(); int num1; float num2; num1 = generator.nextInt(); System.out.println ("A random integer: " + num1);

Page 45: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

RandomNumbers.java (cont.)RandomNumbers.java (cont.) num1 = Math.abs (generator.nextInt()) % 10; System.out.println ("0 to 9: " + num1);

num1 = Math.abs (generator.nextInt()) % 10 + 1; System.out.println ("1 to 10: " + num1);

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.0 to 5.999999 num1 = (int) num2 + 1; System.out.println ("1 to 6: " + num1); } }

Page 46: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Class MethodsClass Methods

Some methods can be invoked through the class name, Some methods can be invoked through the class name, instead of through an object of the classinstead of through an object of the class

These methods are called These methods are called class methodsclass methods or or static methodsstatic methods

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

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

Page 47: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

The Keyboard ClassThe Keyboard Class

The The KeyboardKeyboard class is NOT part of the Java standard class is NOT part of the Java standard class libraryclass library

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

Details of the Details of the KeyboardKeyboard class are explored in Chapter 8 class are explored in Chapter 8 For now we will simply make use of itFor now we will simply make use of it The The KeyboardKeyboard class is part of a package called class is part of a package called cs1cs1, and , and

contains several static methods for reading particular types contains several static methods for reading particular types of dataof data

E.g.: Echo.java (p. 86)E.g.: Echo.java (p. 86) E.g.: Quadratic.java (p. 87)E.g.: Quadratic.java (p. 87)

Page 48: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Echo.javaEcho.java //**************************************************************** // Echo.java Author: Lewis and Loftus // Demonstrates the use of the readString method of the Keyboard class. //**************************************************************** import cs1.Keyboard; public class Echo { // Reads a character string from the user and prints it. 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 + "\""); } }

Page 49: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Quadratic.javaQuadratic.java //**************************************************************** // Quadratic.java Author: Lewis and Loftus // Demonstrates a calculation based on user input. //**************************************************************** import cs1.Keyboard; public class Quadratic { // Determines the roots of a quadratic equation. public static void main (String[] args) { int a, b, c; // ax^2 + 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();

Page 50: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Quadratic.java (cont.)Quadratic.java (cont.) // Use the quadratic formula to compute the roots. // Assumes a positive discriminant. 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); System.out.println ("Root #2: " + root2); } }

Page 51: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Formatting OutputFormatting Output

The The NumberFormatNumberFormat class has static methods that return a class has static methods that return a formatter objectformatter object

getCurrencyInstance()

getPercentInstance()

Each formatter object has a method called Each formatter object has a method called formatformat that that returns a string with the specified information in the returns a string with the specified information in the appropriate formatappropriate format

E.g.: Price.java (p. 89)E.g.: Price.java (p. 89)

Page 52: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Price.javaPrice.java //**************************************************************** // Price.java Author: Lewis and Loftus // Demonstrates the use of various Keyboard and NumberFormat methods. //**************************************************************** import cs1.Keyboard; import java.text.NumberFormat; public class Price { // Calculates the final price of a purchased item using values // entered by the user. public static void main (String[] args) { final double TAX_RATE = 0.06; // 6% sales tax int quantity; double subtotal, tax, totalCost, unitPrice;

Page 53: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Price.java (cont.)Price.java (cont.) System.out.print ("Enter the quantity: "); quantity = Keyboard.readInt(); System.out.print ("Enter the unit price: "); unitPrice = Keyboard.readDouble();

subtotal = quantity * unitPrice; tax = subtotal * TAX_RATE; totalCost = subtotal + tax; // Print output with appropriate formatting NumberFormat money = NumberFormat.getCurrencyInstance(); NumberFormat percent = NumberFormat.getPercentInstance();

System.out.println ("Subtotal: " + money.format(subtotal)); System.out.println ("Tax: " + money.format(tax) + " at " + percent.format(TAX_RATE)); System.out.println ("Total: " + money.format(totalCost)); } }

Page 54: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

Formatting OutputFormatting Output

The The DecimalFormatDecimalFormat class can be used to format a class can be used to format a floating point value in generic waysfloating point value in generic ways

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

The constructor of the The constructor of the DecimalFormatDecimalFormat class takes a class takes a string that represents a pattern for the formatted numberstring that represents a pattern for the formatted number

E.g.: CircleStats.java (p. 91)E.g.: CircleStats.java (p. 91)

Page 55: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

CircleStats.javaCircleStats.java //**************************************************************** // CircleStats.java Author: Lewis and Loftus // Demonstrates the formatting of decimal values using the // DecimalFormat class. //**************************************************************** import 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;

Page 56: INF 523Q Chapter 2: Objects and Primitive Data. 2 Objects and Primitive Data b Chapter 2 focuses on: predefined objectspredefined objects primitive dataprimitive

CircleStats.java (cont.)CircleStats.java (cont.) System.out.print ("Enter the circle's radius: "); radius = Keyboard.readInt();

area = Math.PI * Math.pow(radius, 2); circumference = 2 * Math.PI * radius;

// 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(circumference)); } }


Top Related