Chapter 2

24
Copyright © 2003 Pearson Education, Inc. Slide 2-1 Chapter 2 Using Primitive Data Types and Using Classes

description

Chapter 2. Using Primitive Data Types and Using Classes. Type casting. Casting: the most general form of conversion in Java. A cast is a Java operator specified by a type in parentheses, that is applied to the value of an expression . Type casting syntax: - PowerPoint PPT Presentation

Transcript of Chapter 2

Copyright © 2003 Pearson Education, Inc. Slide 2-1

Chapter 2

Using Primitive Data Types and Using Classes

Copyright © 2003 Pearson Education, Inc. Slide 2-2

Type casting

• Casting: the most general form of conversion in Java. A cast is a Java operator specified by a type in parentheses, that is applied to the value of an expression.Type casting syntax:Form: (type) value Example: double cost; int dollars;

dollars = (int) cost;Interpretation: The cast in the example creates an int value by converting cost to an integer (which truncates any fractional part). The content of cost remains unchanged.

• More type casting examples:int count;count = (int) 3.6;

int m = 7; int n = 2; double x;x = (double) m / n;

int m = 7; int n = 2; double x;x = (double) (m /n); • the cast operator creates a double value (i.e., 7.0)

• n is converted to a double by arithmetic promotion• division produces the result 3.5, which is assigned to x

the cast operator creates an int value (i.e. 3), which is assigned to count

• the integer division 7 / 2 gives the result 3• the cast operator creates a double value (i.e., 3.0),

which is assigned to x

Copyright © 2003 Pearson Education, Inc. Slide 2-3

Rules for Evaluating Expressions

• Parentheses rule: Evaluate expressions in parentheses separately. Evaluate nested parens from the inside out.

• Operator precedence rule: Operators in the same expression are evaluated in the order determined by their precedence (from the highest to the lowest). Operator Precedence

• Left associative rule: Operators in the same expression and at the same precedence level are evaluated in left-to-right order.

method call highest precedence- (unary)new, type cast*, /, %+, - (binary)= lowest precedence

Copyright © 2003 Pearson Education, Inc. Slide 2-4

2.3 Methods

• Change the state of an object; i.e., change the information stored in an object

Calculate a result (returns a result) Retrieve a particular data item that is stored in an object

(returns a result) Get data from the user

• Display the result of an operation

Copyright © 2003 Pearson Education, Inc. Slide 2-5

Dot notation

• A call to an object's method has the form: objectName.methodName()

• This form is called dot notation and it tells the Java compiler to call method methodName() of object objectName.

i.e., method methodName() is applied to object objectName.

Copyright © 2003 Pearson Education, Inc. Slide 2-6

Method call with Argument list

objectName.methodName(argumentList)

• Evaluate the argumentList of methodName() and pass this information to the method. An argumentList can contain a single argument or multiple arguments separated by commas.

• Example:

System.out.println("First number is " + num1);

• Effect: Java calls method println() of object System.out (the console window) using the argument shown in parentheses. The argument is evaluated and the result is appended as a new line to object System.out .

• If a method has no arguments, its name is followed by empty parentheses ().

Copyright © 2003 Pearson Education, Inc. Slide 2-7

Instance methods and class methods

• Method println() is an instance method because it belongs

to an object instance and is applied to an object

(System.out).

• Class methods belong to the class rather than to individual class

instances (objects).

• Class methods are not applied to an object. We prefix the

method name with the class name instead of an object name:

ClassName.methodName(argumentList)

Copyright © 2003 Pearson Education, Inc. Slide 2-8

Syntax display for method call

• Form: objectName.methodName(argumentList)

ClassName.methodName(argumentList)

• Example: System.out.println(

"I like studying Java");

Math.sqrt(15.0)

• Interpretation: For instance method, apply method methodName of object objectName, passing in the value of each argument in argumentList .

• Interpretation: For class method, apply method methodName of class ClassName, passing in the value of each argument in argumentList .

Copyright © 2003 Pearson Education, Inc. Slide 2-9

2.6 Pig Latin translator

• PROBLEM

Write a program that reads in a word and displays it in pig Latin.

• ANALYSIS

The problem input will be the word that is read and the problem output will be its pig Latin form.

Data Requirements– Problem Inputs

an English word– Problem Output

its pig Latin form

Relevant Formulas and relationshipspig Latin form = second letter to the end of the word +

first letter of the word + "ay"

Copyright © 2003 Pearson Education, Inc. Slide 2-10

Analysis, contd.

• Class PigLatinApp

Data fields

none

Methods

main() - interacts with the program user to get the word; builds and displays its pig Latin

form

Classes used

String, JOptionPane• UML class notation: PigLatinApp

main()

class name

data fields or attributes

methods or operations

Copyright © 2003 Pearson Education, Inc. Slide 2-11

Design

• Class PigLatinApp is an application class. An application class contains a method called main() that is used by the Java interpreter as a starting point for program execution.

Algorithm for main() 1. Get a word to translate to pig Latin.2. Store the word and its pig Latin form in a message string.3. Display the message string.

Copyright © 2003 Pearson Education, Inc. Slide 2-12

UML class and sequence diagram

• UML class diagram - describes the classes and their relationships.

• UML sequence diagram - describes the collaboration between objects (classes) during the execution of the program. It shows how the objects (classes) are calling each other’s methods.

PigLatinApp

main()

JOptionPanefrom javax.swing

readDouble()readInt()…

class imported from javax.swing package

association relationship (one class calls the other’s methods)

application class

PigLatinApp JOptionPane

showInputDialog()get a word from the user

generate its PigLatin form

display resultshowInputDialog()

classes/ objects

method call

method execution

tim

e ax

is

object lifeline

notes (optional)

return from method (optional)

Copyright © 2003 Pearson Education, Inc. Slide 2-13

Implementation

/* * PigLatinApp.java Author: Koffman and Wolz * Generates the pig Latin form of a word */import javax.swing.JOptionPane;

public class PigLatinApp { public static void main(String[] args) { // Get a word to translate to pig Latin String word = JOptionPane.showInputDialog( "Enter a word starting with a consonant");

// Store word and its pig Latin form in message String message = word + " is " + word.substring(1) +

word.charAt(0) + "ay" + " in pig Latin";

Copyright © 2003 Pearson Education, Inc. Slide 2-14

Implementation, contd.

// Display the message string JOptionPane.showMessageDialog(null, message); }}

Copyright © 2003 Pearson Education, Inc. Slide 2-15

2.7 Anatomy of a Program

• Multi-line comments

/* * PigLatinApp.java Authors: Koffman & Wolz * Generates the pig Latin form of a word */

• Single line Comment

// Get a word to translate to pig Latin• Comment at the end of a Line

String word; // word being translated

Copyright © 2003 Pearson Education, Inc. Slide 2-16

Parts of a Class definition

1. A header declaration

2. The class body in braces

2.1 The data field declarations of the class

2.2 The method definitions of the class

• Form: [visibility] class ClassName {classBody}

• Example: public class PigLatinApp{classBody}

• Interpretation: The word public specifies that class ClassName has public visibility. The square brackets indicate that the visibility may be omitted. If so, the class can be referenced only by other classes defined in the same package as this one.

Copyright © 2003 Pearson Education, Inc. Slide 2-17

2.8 Computations with class Math

• Code reusability: reuse whenever possible code that has already been written and tested. Java promotes reusability by providing many predefined classes.

• Example of methods in class Math (see Table 2.11, page 87):abs(x), sqrt(x), pow(x, y), exp(x), log(x), sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), random(x), round(x), ceil(x), floor(x), rint(x), max(x, y), min(x, y)

• Examples of using Math methods: – the root of a quadratic equation ax2 + bx +c = 0

root1 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);– the side of a triangle: a2 = b2 + c2 - 2bc cos

a = Math.sqrt(b * b + c * c - 2 * b * c * Math.cos(alpha * Math.PI / 180.0));

convert angle to radians

Copyright © 2003 Pearson Education, Inc. Slide 2-18

Class ArithmeticDrill

/* * ArithmeticDrill.java Authors: Koffman & Wolz * Generates and solves a multiplication problem */import javax.swing.JOptionPane;

public class ArithmeticDrill {

public static void main(String[] args) { // Generate 2 random integerss int multiplier = (int) (10 * Math.random()

+ 1); int multiplicand = (int) (10 *

Math.random() + 1);

// Calculate the product int product = multiplier * multiplicand;

Copyright © 2003 Pearson Education, Inc. Slide 2-19

Class ArithmeticDrill, contd.

// Ask the user for the product String answerStr = JOptionPane.showInputDialog( "What is " + multiplier + " * " + multiplicand);

// Display the answer JOptionPane.showMessageDialog(null, "The correct answer is " + product); }}

Copyright © 2003 Pearson Education, Inc. Slide 2-20

Sample run of class ArithmeticDrill

Copyright © 2003 Pearson Education, Inc. Slide 2-21

2.9 Common errors & debugging

• Syntax error: a violation of the Java grammar rules detected during program translation. Some common causes of syntax errors:

• Incorrect data types (in operations, assignments, returned values, etc.)

• Incorrect use of quotation marks (not in pairs)• Errors in use of comments (“dangling” comments)

• Run-time error: an attempt to perform an invalid operation detected during program execution:

• No object file error: the name of a class does not match the name of the file containing it (sometimes due to case sensitivity)

• Class path errors: the compiler doesn’t find the source files• Data entry errors: user enters the wrong type of data

Copyright © 2003 Pearson Education, Inc. Slide 2-22

Errors and debugging, contd.

• More Run-time errors:• Arithmetic overflow: attempt to store in a variable a

value that is too large and does not fit in memory allocated for variable

• Attempt to divide by zero

• Logic errors: caused by a program that follows an incorrect algorithm (no syntax or run-time error, but the program output is incorrect). Test the program thoroughly, compare its output with the expected results.

Copyright © 2003 Pearson Education, Inc. Slide 2-23

Some common syntax errorsSample message Syntax error

Incompatible type for * Using an operator with an incorrect data type (for example,using operator * with char or String)

Undefined variable Forgetting to declare a variable or misspelling its name

Incompatible type for = In assignment statement, variable type is not compatiblewith expression type

String not terminated at end ofline OR ‘;’ expected

Missing string delimiter

Invalid expression statement Referencing a private data field from outside the class thatdeclares it

Method not found Forgetting to declare a method or misspelling its name

Incompatible type for method Incorrect argument type in a method call

Incompatible type for return Method returning a value of the wrong type

Return required at end of method Missing return at the end of a non-void method

No matching method found inclass

Calling a private method from outside the class defining it

Method not found OR Can’t makestatic reference to method

Call to a public method of a class omitting the object nameto which the method is applied, from another class

Copyright © 2003 Pearson Education, Inc. Slide 2-24

Debugging

• IDE Debugger tool helps programmers debug their programs:– control program execution: step through the code line-by-

line, or run to a given point– set breakpoints in the program– monitor data values with watches and inspectors, etc.

• A simple technique for debugging is to insert diagnostic output statements in methods for displaying intermediate results.For example, display messages in the console window as follows:

System.out.println ("intermediate result: " + value);