1 / 24

Chapter 2

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:

Télécharger la présentation

Chapter 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 2 Using Primitive Data Types and Using Classes

  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 an int value (i.e.3), which is assigned to count • 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 integer division 7 / 2 gives the result 3 • the cast operator creates a double value (i.e., 3.0), which is assigned to x

  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 callhighest precedence - (unary) new, type cast *, /, % +, - (binary) =lowest precedence

  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

  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.

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

  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)

  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 .

  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 relationships pig Latin form = second letter to the end of the word+ first letter of the word+"ay"

  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 class name data fields or attributes methods or operations main()

  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.

  12. JOptionPane from javax.swing PigLatinApp application class class imported from javax.swing package readDouble() readInt() … main() association relationship (one class calls the other’s methods) • 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. time axis classes/ objects PigLatinApp JOptionPane notes (optional) object lifeline get a word from the user showInputDialog() generate its PigLatin form method call showInputDialog() display result method execution return from method (optional) UML class and sequence diagram • UML class diagram - describes the classes and their relationships.

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

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

  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

  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]classClassName{classBody} • Example: public class PigLatinApp{classBody} • Interpretation: The word public specifies that class ClassNamehas 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.

  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 cosa a = Math.sqrt(b * b + c * c - 2 * b * c * Math.cos(alpha * Math.PI / 180.0)); p convert angle to radians

  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;

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

  20. Sample run of class ArithmeticDrill

  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

  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.

  23. Some common syntax errors

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

More Related