56
Topics Chapter 2: Data conversion Chapter 3 Object creation and object references The String class and its methods The Java standard class library The Math class Formatting output Chapter 5: Simple Flow of Control

Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Embed Size (px)

Citation preview

Page 1: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Topics• Chapter 2:

– Data conversion

• Chapter 3– Object creation and object references– The String class and its methods– The Java standard class library– The Math class– Formatting output

• Chapter 5:– Simple Flow of Control

Page 2: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Exercise• What is the value of the variable unitPrice?

int totalPrice = 12;

int quantity = 5;

double unitPrice = 0;

unitPrice = totalPrice / quantity;

Page 3: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Casting• 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

Page 4: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Casting• For example, if total and count are integers, but we want

a floating point result when dividing them, we can cast total:

result = (double) total / count;

• Another example:

– double num = 0.9; int result = (int) num;

– Convert 0.9 to an int value: 0, truncating any fractional part.

Page 5: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Exercise• What is the value of the variable unitPrice?

int totalPrice = 12;

int quantity = 5;

double unitPrice = 0;

unitPrice = (double)totalPrice / quantity;

Page 6: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Object Creation and Object References

Page 7: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Creating Objects• A variable holds either a primitive type or a

reference to an object

"Steve Jobs"name1

num1 38

Page 8: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Creating Objects• A class name can be used as a type to declare an object

reference variable

String title;

• An object reference variable holds the address of an object

• The object itself must be created separately

Page 9: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Creating Objects• Generally, we use the new operator to create an object

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

This calls the String constructor, which isa special method that sets up the object

• Creating an object is called instantiation

• An object is an instance of a particular class

Page 10: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

References• An object reference can be thought of as a pointer

to the location of the object

"Steve Jobs"name1

num1 38

Page 11: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Assignment Revisited

• The act of assignment takes a copy of a value and stores it in a variable

• For primitive types:

num1 38

num2 96Before:

num2 = num1;

num1 38

num2 38After:

Page 12: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Reference Assignment

• For object references, assignment copies the address:

name2 = name1;

name1

name2Before:

"Steve Jobs"

"Steve Wozniak"

name1

name2After:

"Steve Jobs"

Page 13: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

The String Class

Page 14: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

The String Class• Because strings are so common, we don't have to

use the new operator to create a String object

String title = "Java Software Solutions";

• This is special syntax that works only for strings• Each string literal (enclosed in double quotes)

represents a String object

Copyright © 2012 Pearson Education, Inc.

Page 15: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

String Indexes• It is occasionally helpful to refer to a particular

character within a string

• This can be done by specifying the character's numeric index

• The indexes begin at zero in each string

• In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4

Page 16: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

String Methods• Once a String object has been created, neither

its value nor its length can be changed

• However, several methods of the String class return new String objects that are modified versions of the original

Page 17: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Method• What is a method?

– A group of statements that is given a name.

• How to invoke a method?– When a method is invoked, only the method’s name and

the parameters are needed.

• What happens when a method is invoked?– When a method is invoked, the flow of control transfers

to that method and the statements of that method are executed.

• How to interpret a method listing as follows?– int length()

Returns the number of characters in this string.

return type method name

Page 18: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Invoking Methods• We've seen that once an object has been instantiated, we

can use the dot operator to invoke its methods

String title = "Data";

int count = title.length();

• A method may return a value, which can be used in an assignment or expression

• A method invocation can be thought of as asking an object to perform a service

Page 19: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Some Methods of the String Class• int length()

– Returns the number of characters in this string.

• String concat (String str)– Returns a new string consisting of this string concatenated with str.– Example: title= title.concat(" Structures");

• String toUpperCase ()– Returns a new string identical to this string except all lowercase

letters are converted to their uppercase equivalent.– Example: newTitle = title.toUpperCase();

Page 20: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Some Methods of the String Class• String replace (char oldChar, char newChar)

– Returns a new string that is identical with this string except that every occurrence of oldChar is replaced by newChar.

– Example: String replaced = title.replace('a', 'z');

• String substring (int beginIndex, int endIndex)– Returns a new string that is a subset of this string starting at

beginIndex and extending through

endIndex -1. Thus the length of the substring is

endIndex – beginIndex.– Example: String sub = title.substring(5, 7);

Page 21: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Exercise• What output is produced by the following code

fragment?

String m1, m2, m3, m4;

m1 = "Programming Language";

m2 = m1.toLowerCase();

m3 = m1 + " " + "Java";

m4 = m3.replace('a', 'm');

System.out.println(m4.subString(2, 5));

Page 22: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Some Methods of the String Class• int indexOf(String str) 

    Returns the index within this string of the first occurrence of the specified substring.

• Exercise: Write a program that reads in a line of text, a search string, a replace string. The program will output a line of text with the first occurrence of the search string changed to the replace string.

Page 23: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Packages

Page 24: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Class Libraries• 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; Its classes are not part of the Java language, but we rely on them heavily

• Various classes we've already used (System , Scanner, String) are part of the Java standard class library

Page 25: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Packages• The classes of the Java standard class library are

organized into packages

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

Package

java.langjava.awtjavax.swingjava.netjava.util

Purpose

General supportGraphics and graphical user interfacesAdditional graphics capabilitiesNetwork communicationUtilities

Page 26: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

The import Declaration• When you want to use a class from a package, you

can import the class, and then use just the class name

import java.util.Scanner;

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

import java.util.*;

Page 27: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

The import Declaration• All classes of the java.lang package are imported

automatically into all programs

• It's as if all programs contain the following line:

import java.lang.*;

• That's why we didn't have to import the System or String classes explicitly in earlier programs

Page 28: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

The Math Class

Page 29: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

The Math Class• The Math class is part of the java.lang package

• The Math class contains methods that perform various mathematical functions

• These include:

– absolute value, square root, exponentiation

– trigonometric functions

Page 30: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

The Math Class• The methods of the Math class are static methods (also

called class methods)

• Static methods can be invoked through the class name – no object of the Math class is needed

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

Page 31: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Some Methods of the Math Class• static int abs (int num)

– Returns the absolute value of num.

• static double sin (double angle)

– Returns the sine of angle measured in radians.

• static double ceil (double num)

– Returns the ceiling of num, which is the smallest whole number greater than or equal to num.

Page 32: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Some Methods of the Math Class

• static double pow (double num, double power)

– Returns the value num raised to the specified power.

• static double sqrt (double num)

– Returns the square root of num, which must be positive

Page 33: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Quadratic.java Author: Lewis/Loftus//// Demonstrates the use of the Math class to perform a calculation// based on user input.//********************************************************************

import java.util.Scanner;

public class Quadratic{ //----------------------------------------------------------------- // Determines the roots of a quadratic equation. //----------------------------------------------------------------- public static void main (String[] args) { int a, b, c; // ax^2 + bx + c double discriminant, root1, root2;

Scanner scan = new Scanner (System.in);

System.out.print ("Enter the coefficient of x squared: "); a = scan.nextInt();

continued

Page 34: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Copyright © 2012 Pearson Education, Inc.

continued

System.out.print ("Enter the coefficient of x: "); b = scan.nextInt();

System.out.print ("Enter the constant: "); c = scan.nextInt();

// Use the quadratic formula to compute the roots. // Assumes a positive discriminant.

discriminant = Math.pow(b, 2) - (4 * a * c); root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a); root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);

System.out.println ("Root #1: " + root1); System.out.println ("Root #2: " + root2); }}

Page 35: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Imprecision of Floating-point Numbers• Floating-point numbers are not real numbers. There

are a finite number of them.

• There are maximum and minimum values they can represent. Most importantly, they have limited, though large, precision and are subject to round-off error.

Page 36: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Formatting Output

Page 37: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Formatting Output• It is often necessary to format values in certain ways so that

they can be presented properly

• The Java standard class library contains classes that provide formatting capabilities

• For example, a currency formatter can be used to format 5.8792 to monetary value $5.88 and a percent formatter can be used to format 0.492 to 49%.

Copyright © 2012 Pearson Education, Inc.

Page 38: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Formatting Output• The NumberFormat class allows you to format

values as currency or percentages

• The DecimalFormat class allows you to format values based on a pattern

• Both are part of the java.text package

Page 39: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Formatting Output• The NumberFormat class has static methods that return a

formatter object

NumberFormat fmt1 = NumberFormat.getCurrencyInstance();

NumberFormat fmt2 = NumberFormat.getPercentInstance();

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

Page 40: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Formatting Output• The fractional potion of the value will be rounded

up.

• String format (double number)

– Returns a string containing the specified number formatted according to this object’s pattern.

Page 41: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Purchase.java Author: Lewis/Loftus//// Demonstrates the use of the NumberFormat class to format output.//********************************************************************

import java.util.Scanner;import java.text.NumberFormat;

public class Purchase{ //----------------------------------------------------------------- // 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;

Scanner scan = new Scanner (System.in);

continued

Page 42: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Copyright © 2012 Pearson Education, Inc.

continued

NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); NumberFormat fmt2 = NumberFormat.getPercentInstance();

System.out.print ("Enter the quantity: "); quantity = scan.nextInt();

System.out.print ("Enter the unit price: "); unitPrice = scan.nextDouble();

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

// Print output with appropriate formatting 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)); }}

Page 43: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Formatting Output

• The DecimalFormat class can be used to format a floating point value in various ways

• The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number, for example,

DecimalFormat fmt = new DecimalFormat("0.###");

Indicates the fractional portion of the value should be rounded to three digits

Page 44: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Formatting Output• String format (double number)

– Returns a string containing the specified number formatted according to the current pattern.

• For example, you can specify that the number should be rounded to three decimal digits. For example, 65.83752->65.838

Page 45: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// CircleStats.java Author: Lewis/Loftus//// Demonstrates the formatting of decimal values using the// DecimalFormat class.//********************************************************************

import java.util.Scanner;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;

Scanner scan = new Scanner (System.in);

continued

Page 46: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Copyright © 2012 Pearson Education, Inc.

continued

System.out.print ("Enter the circle's radius: "); radius = scan.nextInt();

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

Page 47: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Exercise• Suppose we have read in a double value num

from the user. Write code statements that print the result of raising num to the fourth power. Output the results to 2 decimal places.

Page 48: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

5-48

Flow of Control• The order of statement execution is called the flow

of control

• Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence

Page 49: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

5-49

The if Statement

• The if statement has the following syntax:

if ( condition ) statement;

if is a Javareserved word

The condition must be aboolean expression. It mustevaluate to either true or false.

If the condition is true, the statement is executed.If it is false, the statement is skipped.

Page 50: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

5-50

Logic of an if statement

conditionevaluated

statement

truefalse

Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Page 51: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

5-51

Boolean Expressions• A condition often uses one of Java's equality

operators or relational operators, which all return boolean results:

== equal to

!= not equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

Page 52: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

5-52

//********************************************************************// Age.java Author: Lewis/Loftus//// Demonstrates the use of an if statement.//********************************************************************

import java.util.Scanner;

public class Age{ //----------------------------------------------------------------- // Reads the user's age and prints comments accordingly. //----------------------------------------------------------------- public static void main (String[] args) { final int MINOR = 21;

Scanner scan = new Scanner (System.in);

System.out.print ("Enter your age: "); int age = scan.nextInt();

continue

Page 53: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

5-53

continue

System.out.println ("You entered: " + age);

if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy.");

System.out.println ("Age is a state of mind."); }}

Page 54: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

5-54

Exercise• Write a conditional statement that assigns 10,000

to the variable bonus if the value of the variable goodsSold is greater than 500,000 .

Page 55: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

5-55

Comparing Strings• Remember that in Java a character string is an object

• The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order

• The equals method returns a boolean result

if (name1.equals(name2)) System.out.println ("Same name");else System.out.println(“Not same”);

Page 56: Topics Chapter 2: –Data conversion Chapter 3 –Object creation and object references –The String class and its methods –The Java standard class library

Readings and Assignments• Reading: Chapter 2.5, 3.1-3.6, 3.8 • Lab Assignment: Java Lab 3

• Self-Assessment Exercises:– Self-Review Questions Section

• SR2.34, 2.35, 3.6, 3.7, 3.21, 3.23, 3.28– After Chapter Exercises

• EX2.11 g, h, i, j, k, l, m, 3.4, 3.11