Big Java - PowerPoint PPT Presentation

1 / 28
About This Presentation
Title:

Big Java

Description:

First 128 characters (i.e., English alphabet) are the same as ASCII. Also includes German umlauts, about 21000 Chinese ideographs and others ... – PowerPoint PPT presentation

Number of Views:26
Avg rating:3.0/5.0
Slides: 29
Provided by: cyndi8
Category:

less

Transcript and Presenter's Notes

Title: Big Java


1
Big Java
  • Chapters 3-6

2
Object-Oriented Concepts (review)
  • Encapsulation hiding unimportant details
  • Black box something that magically does its
    thing
  • Abstraction taking away inessential features
  • Example car
  • if engine control module fails, replace it
  • mechanic can provide inputs, test outputs
  • doesnt need to know how it works
  • OO challenge finding the right abstractions
    (what black boxes do we need to solve the
    problem at hand?)

3
Object-Oriented Concepts (review)
  • How would you represent
  • a bank account?
  • a book?
  • a library?
  • a customer?
  • an oil field?
  • a mutual fund?
  • an employee?

4
javadoc comments
  • Remember the API had a standard format.
    User-defined classes can easily create html
    documentation in that same format, by inserting
    comments that meet certain specifications
  • Start with /
  • First sentence describes purpose
  • _at_ tags specify information (e.g., _at_param,
    _at_return, _at_throws, _at_author, _at_version)
  • run javadoc from command line or Eclipse to
    generate html pages

5
BankAccount
  • See Eclipse notes for example of creating class
    with comments
  • As in C, constructors have name of class, can
    be overloaded
  • Instance fields should be made private, accessors
    and modifiers (getters/setters) are used
  • Additional methods are defined as needed

6
More on Variables
  • Instance variables
  • each object has its own copy (as in C)
  • objects are automatically garbage collected
    (unlike C!)
  • fields are initialized with a default value
    (e.g., 0, null) if not explicitly set in
    constructor. Still good to do your own
    initialization.
  • NullPointerException if you forget to call new
  • Local variables
  • must be explicitly initialized
  • only exist inside method (as in C)

7
Reading Assignment
  • Read Random Fact 3.1 (Electronic Voting Machines)
    on page 110 and be prepared to discuss
  • Read Shape Classes (3.9) and be prepared to
    discuss

8
  • On to Chapter 4
  • Fundamental Data Types

9
Numeric Data Types (review)
  • Integer values can be represented exactly, but
    numeric operations may result in overflow
  • Floating point values may not be exact, so
    rounding errors may occur (shouldnt use with
    floating point values, use tolerance)
  • double is therefore not appropriate for financial
    calculations
  • java.math has BigInteger and BigDecimal classes
    which are slow but have better size/precision.
    Must use add, subtract and multiply (no operator
    overloading in Java)
  • READ Random Fact 4.1, Pentium Floating-Point Bug
    on page 139

10
Constant values
  • preceded by keyword final (vs const in C)
  • naming convention is all uppercase
  • e.g.,
  • final double QUARTER_VALUE 0.25
  • if used in a class, often use keyword static,
    meaning constant belongs to the class
  • public static final double DIME_VALUE 0.1
  • Math class has some useful constants, e.g.,
  • double circumference Math.PI diameter
  • (vs MathPI in C)

11
Numeric Operations
  • , -, , /, - same precedence as C
  • Math class has a number of static functions
    (sqrt, pow, sin, cos, exp, log, round, max, min,
    etc.)
  • / of two integers yields an integer result (same
    as C)
  • Quality Tips
  • put space after every Java keyword, but not
    between a method name and parentheses
  • put space around all binary operators
  • factor out common code
  • example
  • x1(-bMath.sqrt (bb-4ac))/(2a)
  • x2(-b-Math.sqrt (bb-4ac))/(2a)
  • becomes
  • double root Math.sqrt(b b 4 a c)
  • x1 (-b root) / (2 a)
  • x2 (-b root) / (2 a)

12
Numeric Operations, continued
  • Remember that you may need to round floating
    point values
  • double f 4.35
  • int n (int) (100 f)
  • System.out.println(n) // prints 434!
  • Replace with
  • int n (int) Math.round(100 f)
  • Read How To 4.1, good review of how to design
    programs containing numeric computations

13
Unicode
  • C and other languages used ASCII to encode
    characters
  • Java uses a 16-bit encoding known as Unicode
  • First 128 characters (i.e., English alphabet) are
    the same as ASCII
  • Also includes German umlauts, about 21000 Chinese
    ideographs and others
  • Can encode as escape sequence, e.g. \u00E9 is e

14
Reading Input and Formatting Numbers
  • // required for input from keyboard
  • import java.util.Scanner
  • // required for formatting
  • import java.text.NumberFormat
  • public class SalesTax
  • public static void main(String args)
  • final double TAX_RATE 0.06
  • // 6 sales tax
  • double subtotal, tax, totalCost
  • // Calculated values
  • // Set up Scanner for keyboard
  • Scanner scan new Scanner
    (System.in)
  • System.out.print("Enter the price
    ")
  • double price scan.nextDouble()
  • System.out.print("Enter the quantity
    ")
  • // Create desired formatting objects
  • NumberFormat fmt1 NumberFormat.getCurrencyInstan
    ce()
  • NumberFormat fmt2 NumberFormat.getPercentInstanc
    e()
  • // Print messages using formatting objects
  • 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))
  • // Can also use System.out.printf for formatted
  • // output similar to C printf
  • // System.out.printf(Total 5.2f, totalCost)

15
Simple Dialog Boxes
  • /   MaxDialog.java/import
    javax.swing.public class MaxDialog      
    public static void main(String args)   
     String numStr    int max0    int num,
    more    do           numStr
    JOptionPane.showInputDialog("Enter an
    integer")      num Integer.parseInt(numStr) 
    // must extract integer from string      if
    (num gt max)          max num        //
    parentComponent is null, uses default frame     
    JOptionPane.showMessageDialog(null, "Max so far
    " max)      more JOptionPane.showConfirmDia
    log (null, "Check Another?")     while (more
    JOptionPane.YES_OPTION) 

16
  • On to Chapter 5
  • Decisions

17
Decisions
  • if, if-else and nested if-else just like C
  • use of braces for compound statements just like
    C
  • Relational operators (gt gt lt lt !) just like
    C
  • switch is just like C (remember break!)
  • dangling else is a problem in Java, just as in
    C
  • logical operators (, , !) just like C
  • short-circuit evaluation applies

18
Comparing Strings
  • To compare contents of strings, use equals
  • if (string1.equals(string2)) . . .
  • May prefer to ignore case
  • if (string1.equalsIgnoreCase(string2)) . . .
  • Can use compareTo to find out the relationship
    (lt0 if first is less, 0 if same, gt0 if first is
    greater)
  • if (string1.compareTo(string2)) lt 0) . . .
  • Order numbers lt uppercase lt lowercase
  • shorter strings lt longer strings (e.g., car lt
    cargo

19
String subtlety
  • String nickname Rob
  • // Creates a literal string Rob
  • if (nickname Rob) // succeeds
  • But
  • String name Robert
  • String nickname name.substring(0, 3)
  • if (nickname Rob) // fails

20
Enumerated Types
  • public enum FilingStatus SINGLE,MARRIED
  • FilingStatus status FilingStatus.SINGLE
  • if (status FilingStatus.SINGLE) . . .
  • Often declared inside a class
  • if (status TaxReturn.FilingStatus.SINGLE) . .
    .
  • An enumerated type variable can be null

21
De Morgans Law
  • !(A B) !A !B
  • !(A B) !A !B
  • Example
  • !(0 lt amount amount lt 1000)
  • !(0 lt amount) !(amount lt 1000)
  • (0 gt amount) (amount gt 1000)
  • NOTE opposite of lt is gt, not gt

22
Reading/Homework Assignment
  • Read
  • Section 5.5 Test Coverage on page 212
  • 5.3 Calculate Sample Data Manually on page 213,
    and
  • 5.4 Prepare Test Cases Ahead of Time on page 214
  • Questions to answer
  • What is black-box testing?
  • What is white-box testing?
  • What are boundary tests?
  • Design a set of test cases for the TaxCalculator
    program. That is, list the exact inputs you
    would test along with the expected outputs.
  • Turn in this assignment in a .txt file on
    Blackboard.

23
  • On to Chapter 6
  • Iteration

24
Loops in Java
  • while loops same as C
  • same common errors infinite loops, off-by-one
  • do loops same as C
  • for loops same as C (but with another useful
    syntax for collections)
  • same common errors forget semicolon if need
    empty body, or include semicolon on for statement
  • Quality tip for loops are best for counting
    loops. Use a while loop for other types (see 6.1
    on page 241)

25
Loops in Java (continued)
  • nested Loops same as in C
  • Quality tip dont use ! to test the end of a
    range, better to use lt, lt etc.
  • sentinel loops same as in C

26
Reading Assignment 1
  • How to 6.1 Implementing Loops, page 250
  • Quality Tip 6.3 Symmetric and Asymmetric Bounds
  • Quality Tip 6.4 Count Iterations
  • Advanced Topic 6.3 Loop and a Half Problem
  • Advanced Topic 6.4 break and continue
  • Reflect on your own coding style as you read, and
    be ready to discuss next time.

27
Reading Assignment 2
  • Advanced Topic 6.5 Loop Invariants, page 261
  • Random Fact 6.2 Correctness Proofs, page 263
  • Thought question what loops have you
    seen/written where this technique might be
    applicable?

28
Exercise
  • Bring your books to class!
  • Download Word.java and SyllableCounter.java from
    Blackboard
  • Work through 6.7 Sample Debugging Session
Write a Comment
User Comments (0)
About PowerShow.com