Docstoc

Introduction to Java Java Introduction to Objects Objects and Classes

Document Sample
Introduction to Java Java Introduction to Objects Objects and Classes Powered By Docstoc
					                                                                     Java
                                                                     n   A programming language specifies the words
                                                                         and symbols that we can use to write a
              Introduction to Java                                   n
                                                                         program
                                                                         A programming language employs a set of
                                                                         rules that dictate how the words and symbols
                                                                         can be put together to form valid program
                Selim Aksoy                                              statements
             Bilkent University                                      n   The Java programming language was created
                                                                         by Sun Microsystems, Inc.
    Department of Computer Engineering                               n   It was introduced in 1995 and it's popularity
                                                                         has grown quickly since
          saksoy@cs.bilkent.edu.tr
                                                                     n   It is an object-oriented language
                                                                     Summer 2004                    CS 111                            2




Introduction to Objects                                              Objects and Classes
n   An object represents something with which                           A class                                              An object
                                                                     (the concept)                                       (the realization)
    we can interact in a program
n   An object provides a collection of services                                     Bank                     John’s Bank Account
    that we can tell it to perform for us                                          Account                     Balance: $5,257

n   The services are defined by methods in a                                                                  Bill’s Bank Account
    class that defines the object                                                                            Balance: $1,245,069
                                                                               Multiple objects
n   A class represents a concept, and an object                               from the same class
                                                                                                             Mary’s Bank Account
    represents the embodiment of a class                                                                      Balance: $16,833
n   A class can be used to create multiple objects

Summer 2004                   CS 111                             3   Summer 2004                    CS 111                            4




Inheritance                                                          Abstraction
n   One class can be used to derive another via                      n   An abstraction hides (or suppresses) the right
    inheritance                                                          details at the right time
                                                                     n   An object is abstract in that we do not have to
n   Classes can be organized into inheritance                            think about its internal details in order to use it
    hierarchies         Account                                      n   If we group information into chunks (such as
                                                                         objects) we can manage many complicated
                                                                         pieces at once
                Credit Card                  Bank                    n   Classes and objects help us write complex
                 Account                    Account
                                                                         software
                                                                     n   A class is used to model
                                                                         n   all attributes/properties of an abstraction
                                  Savings             Checking
                                  Account             Account
                                                                         n   all behaviors/operations of an abstraction
Summer 2004                   CS 111                             5   Summer 2004                    CS 111                            6
Encapsulation                                                  Java Program Structure
n   Classes support a particular kind of abstraction:          n   In the Java programming language:
    encouraging separation between an object’s
    operations and their implementations                           n    A program is made up of one or more classes
n   Objects are regarded as “black boxes” whose                    n    A class contains one or more methods
    internals are hidden                                           n    A method contains program statements
n   Separation of contract (i.e. which operations              n   Attributes/properties correspond to fields (or
    are available) and implementation of those                     variables)
    operations
    n   A class can be viewed as a contract; the contract      n   Behaviors/operations correspond to methods
        specifies which operations are offered by the class    n   A Java application always contains a method
        A class can be viewed as an implementation; the
    n

        implementation specifies how the desired behavior is       called main
        produced
Summer 2004                  CS 111                       7    Summer 2004                      CS 111                     8




Java Program Structure                                         Java Program Structure
    // comments about the class                                    //       comments about the class
    public class MyProgram                                         public class MyProgram
    {                                                              {
                                      class header                      //    comments about the method
                                                                         public static void main (String[] args)

               class body                                               {
                                                                                                          method header
                                                                                  method body
                                                                        }
                Comments can be placed almost anywhere
    }                                                              }


Summer 2004                  CS 111                       9    Summer 2004                      CS 111                    10




JCreator IDE                                                   Comments
                                                               n   Comments in a program are called
                                                                   inline documentation
                                                               n   Java comments can take three forms:
                                                                        // this comment runs to the end of the line

                                                                        /* this symbol runs to the terminating
                                                                        symbol, even across line breaks */

                                                                        /** this is a javadoc comment */
Summer 2004                  CS 111                      11    Summer 2004                      CS 111                    12
Identifiers                                                         Identifiers
n   Identifiers are the words a programmer uses                     n    Sometimes we choose identifiers ourselves
    in a program                                                         when writing a program (such as Lincoln)
n   An identifier can be made up of letters, digits,
    the underscore character ( _ ), and the dollar                  n    Sometimes we are using another
    sign                                                                 programmer's code, so we use the identifiers
n   Identifiers cannot begin with a digit                                that they chose (such as println)
n   Java is case sensitive - Total, total,                          n    Often we use special identifiers called
    and TOTAL are different identifiers
                                                                         reserved words that already have a
n   By convention, Java programmers use                                  predefined meaning in the language
    different case styles for different types of
    identifiers, such as                                            n    A reserved word cannot be used in any other
    n   title case for class names - Lincoln                             way
    n   upper case for constants - MAXIMUM
Summer 2004                   CS 111                           13   Summer 2004                            CS 111                        14




Reserved Words                                                      White Space
n   The Java reserved words:                                        n    Spaces, blank lines, and tabs are called white
                                                                         space
    abstract     else             interface    super
    boolean      extends          long         switch               n    White space is used to separate words and
    break
    byte
                 false
                 final
                                  native
                                  new
                                               synchronized
                                               this                      symbols in a program
    case
    catch
                 finally
                 float
                                  null
                                  package
                                               throw
                                               throws
                                                                    n    Extra white space is ignored
    char         for              private      transient            n    A valid Java program can be formatted in
    class        goto             protected    true
    const        if               public       try                       many ways
                                                                         Programs should be formatted to enhance
    continue     implements       return       void
    default      import           short        volatile             n
    do           instanceof       static       while                     readability, using consistent indentation
    double       int              strictfp


Summer 2004                   CS 111                           15   Summer 2004                            CS 111                        16




Poorly Formatted Example                                            Poorly Formatted Example
//************************************************************      //********************************************************************
// Lincoln2.java        Author: Lewis/Loftus                        // Lincoln3.java        Author: Lewis/Loftus
//                                                                  //
                                                                    // Demonstrates another valid program that is poorly formatted.
// Demonstrates a poorly formatted, though valid, program.          //********************************************************************
//************************************************************
                                                                                 public            class
public class Lincoln2{public static void main(String[]args){                Lincoln3
System.out.println( "A quote by Abraham Lincoln:");                     {
System.out.println( "Whatever you are, be a good one.");}}                                public
                                                                        static
                                                                             void
                                                                        main
                                                                               (
                                                                    String
                                                                                 []
                                                                         args                       )
                                                                      {
                                                                      System.out.println         (
                                                                    "A quote by Abraham Lincoln:"           )
                                                                      ;         System.out.println
                                                                                 (
                                                                            "Whatever you are, be a good one."
                                                                          )
                                                                      ;
                                                                    }
                                                                               }

Summer 2004                   CS 111                           17   Summer 2004                            CS 111                        18
Java Translation                                                                Java Translation
n   The Java compiler translates Java source                                                  Java source
    code into a special representation called                                                    code                   Java
    bytecode                                                                                                          bytecode
n   Java bytecode is not the machine language
    for any traditional CPU                                                                      Java
                                                                                               compiler
n   Another software tool, called an interpreter,                                                                Java       Bytecode
    translates bytecode into machine language                                                                interpreter    compiler

    and executes it
n   Therefore the Java compiler is not tied to any                                                                          Machine
    particular machine                                                                                                       code

n   Java is considered to be architecture-neutral
Summer 2004                             CS 111                             19   Summer 2004                 CS 111                     20




Using Objects                                                                   Character Strings
n   The System.out object represents a                                          n   Every character string is an object in Java,
    destination to which we can send output                                         defined by the String class
n   In the Lincoln program, we invoked the                                      n   Every string literal, delimited by double
    println method of the System.out object:
                                                                                    quotation marks, represents a String object
    System.out.println ("Whatever you are, be a good one.");                    n   The string concatenation operator (+) is used
                                                                                    to append one string to the end of another
        object       method        information provided to the method
                                              (parameters)                      n   It can also be used to append a number to a
                                                                                    string
n   The System.out object also provides the
    print method that is similar to the println                                 n   A string literal cannot be broken across two
    method, except that it does not advance to                                      lines in a program
    the next line
Summer 2004                             CS 111                             21   Summer 2004                 CS 111                     22




Example                                                                         String Concatenation
                                                                                    The plus operator (+) is also used for
//********************************************************************
// Facts.java        Author: Lewis/Loftus                                       n
                                                                                    arithmetic addition
//
// Demonstrates the use of the string concatenation operator and the
// automatic conversion of an integer to a string.

                                                                                    The function that the + operator performs
//********************************************************************
public class Facts                                                              n
{
   //---------------------------------------------------------------- -             depends on the type of the information on
                                                                                    which it operates
   // Prints various facts.
   //---------------------------------------------------------------- -
   public static void main (String[] args)
   {
      // Strings can be concatenated into one long string                       n   If both operands are strings, or if one is a
                                                                                    string and one is a number, it performs string
      System.out.println ("We present the following facts for your "
                          + "extracurricular edification:" );
        System.out.println ();
                                                                                    concatenation
                                                                                    If both operands are numeric, it adds them
        // A string can contain numeric digits
        System.out.println ("Letters in the Hawaiian alphabet: 12");
                                                                                n

                                                                                    The + operator is evaluated left to right
        // A numeric value can be concatenated to a string
        System.out.println ("Dialing code for Antarctica: " + 672 );
                                                                                n

                                                                                    Parentheses can be used to force the
        System.out.println ("Year in which Leonardo da Vinci invented "
                            + "the parachute: " + 1515);
                                                                                n

}
    }
        System.out.println ("Speed of ketchup: " + 40 + " km per year");
                                                                                    operation order
Summer 2004                             CS 111                             23   Summer 2004                 CS 111                     24
Example                                                                   Escape Sequences
                                                                              What if we wanted to print a double quote character?
//********************************************************************
// Addition.java        Author: Lewis/Loftus                              n
//
// Demonstrates the difference between the addition and string
// concatenation operators.
                                                                          n   The following line would confuse the compiler because
//********************************************************************        it would interpret the second quote as the end of the
public class Addition
{
                                                                              string
   //-----------------------------------------------------------------        System.out.println ("I said "Hello" to you.");
   // Concatenates and adds two numbers and prints the results.
   //-----------------------------------------------------------------
   public static void main (String[] args)                                n   An escape sequence is a series of characters that
   {
      System.out.println ("24 and 45 concatenated: " + 24 + 4 5);             represents a special character
        System.out.println ("24 and 45 added: " + (2 4 + 4 5));           n   An escape sequence begins with a backslash character
}
    }
                                                                              (\), which indicates that the character(s) that follow
                                                                              should be treated in a special way
                                                                              System.out.println ("I said \"Hello\" to you.");



Summer 2004                         CS 111                           25   Summer 2004                   CS 111                       26




Escape Sequences                                                          Variables
n   Some Java escape sequences:                                           n   A variable is a name for a location in
                Escape Sequence              Meaning
                                                                              memory
                                                                          n   A variable must be declared by
                                        backspace
                                                                              specifying the variable's name and the
                        \b
                        \t                 tab
                        \n               newline                              type of information that it will hold
                        \r          carriage return
                        \"            double quote                             data type           variable name
                        \'            single quote
                        \\              backslash                                          int total;
                                                                                           int count, temp, result;

                                                                              Multiple variables can be created in one declaration

Summer 2004                         CS 111                           27   Summer 2004                   CS 111                       28




Variables                                                                 Assignment
n   A variable can be given an initial value                              n   An assignment statement changes the value
    in the declaration                                                        of a variable
                                                                          n   The assignment operator is the = sign
                  int sum = 0;
                  int base = 32, max = 149;                                                     total = 55;


n   When a variable is referenced in a                                    n   The expression on the right is evaluated and
    program, its current value is used                                        the result is stored in the variable on the left
                                                                          n   The value that was in total is overwritten
                                                                          n   You can assign only a value to a variable that
                                                                              is consistent with the variable's declared type
Summer 2004                         CS 111                           29   Summer 2004                   CS 111                       30
Example                                                                         Constants
                                                                                    A constant is an identifier that is similar to a variable
//********************************************************************
// Geometry.java        Author: Lewis/Loftus                                    n
//
// Demonstrates the use of an assignment statement to change the                    except that it holds one value while the program is
// value stored in a variable.
//********************************************************************              active
public class Geometry
{
                                                                                n   The compiler will issue an error if you try to change
   //-----------------------------------------------------------------              the value of a constant during execution
   // Prints the number of sides of several geometric shapes.
   //-----------------------------------------------------------------
   public static void main (String[] args)
                                                                                n   In Java, we use the final modifier to declare a
   {
      int sides = 7; // declaration with initialization
                                                                                    constant
      System.out.println ("A heptagon has " + sides + " sides.");                                final int MIN_HEIGHT = 69;
            sides = 10; // assignment statement
            System.out.println ("A decagon has " + sides + " sides.");          n   Constants:
            sides = 12;                                                             n   give names to otherwise unclear literal values
    }
            System.out.println ("A dodecagon has " + sides + " sides.");
                                                                                    n   facilitate updates of values used throughout a program
}
                                                                                    n   prevent inadvertent attempts to change a value


Summer 2004                            CS 111                              31   Summer 2004                     CS 111                           32




Primitive Data                                                                  Numeric Primitive Data
n   There are exactly eight primitive data types in                             n   The difference between the various
    Java
                                                                                    numeric primitive types is their size,
n   Four of them represent integers:
        n    byte, short, int, long                                                 and therefore the values they can store:
n   Two of them represent floating point                                             Type       Storage     Min Value          Max Value
    numbers:                                                                         byte       8 bits      -128               127
        n    float, double                                                           short      16 bits     -32,768            32,767
n   One of them represents characters:                                               int        32 bits     -2,147,483,648     2,147,483,647
                                                                                     long       64 bits     < -9 x 101 8       > 9 x 101 8
        n    char
n   And one of them represents boolean values:                                       float      32 bits     +/- 3.4 x 103 8 with 7 significant digits
                                                                                     double     64 bits     +/- 1.7 x 10308 with 15 significant digits
        n    boolean
Summer 2004                            CS 111                              33   Summer 2004                     CS 111                           34




Characters                                                                      Characters
    A char variable stores a single character from the
n
    Unicode character set
                                                                                n   The ASCII character set is older and
n   A character set is an ordered list of characters, and                           smaller than Unicode, but is still quite
    each character corresponds to a unique number                                   popular
    The Unicode character set uses sixteen bits per
                                                                                    The ASCII characters are a subset of
n
    character, allowing for 65,536 unique characters                            n

n   It is an international character set, containing                                the Unicode character set, including:
    symbols and characters from many world languages                                    uppercase letters         A, B, C, …
n   Character literals are delimited by single quotes:                                  lowercase letters         a, b, c, …
              'a'      'X'       '7'       '$'       ','       '\n'                     punctuation               period, semi-colon, …
                                                                                        digits                    0, 1, 2, …
                                                                                        special symbols           &, |, \, …
                                                                                        control characters        carriage return, tab, ...
Summer 2004                            CS 111                              35   Summer 2004                     CS 111                           36
Boolean                                              Arithmetic Expressions
n   A boolean value represents a true or             n   An expression is a combination of one
    false condition                                      or more operands and their operators
n   A boolean also can be used to represent          n   Arithmetic expressions use the
    any two states, such as a light bulb                 operators: Addition         +
                                                                          Subtraction            -
    being on or off                                                       Multiplication         *
n   The reserved words true and false                                     Division
                                                                          Remainder
                                                                                                 /
                                                                                                 %     (no ^ operator)
    are the only valid values for a boolean          n   If either or both operands associated
    type                                                 with an arithmetic operator are floating
              boolean done = false;                      point, the result is a floating point
Summer 2004            CS 111                   37   Summer 2004                 CS 111                         38




Division and Remainder                               Operator Precedence
n   If both operands to the division operator        n   Multiplication, division, and remainder
    (/) are integers, the result is an integer           are evaluated prior to addition,
    (the fractional part is discarded)                   subtraction, and string concatenation
              14 / 3   equals?     4                 n   Examples:
              8 / 12   equals?    0
                                                         a + b + c + d + e                a + b * c - d / e
n   The remainder operator (%) returns the                 1   2   3   4                    3   1   4   2
    remainder after dividing the second
    operand into the first                               a / (b + c) - d % e              a / (b * (c + (d - e)))
              14 % 3    equals?                            2    1    4   3                  4    3    2    1
                                   2
              8 % 12    equals?    8
Summer 2004            CS 111                   39   Summer 2004                 CS 111                         40




Data Conversions                                     Data Conversions
n   Sometimes it is convenient to convert data       n   In Java, data conversions can occur in three
    from one type to another                             ways:
n   For example, we may want to treat an integer         n   assignment conversion
    as a floating point value during a computation       n   arithmetic promotion
n   Conversions must be handled carefully to             n   casting
    avoid losing information                         n   Assignment conversion occurs when a value
n   Widening conversions are safest because they         of one type is assigned to a variable of
    tend to go from a small data type to a larger        another
    one (such as a short to an int)                      n   Only widening conversions can happen via
                                                             assignment
n   Narrowing conversions can lose information
    because they tend to go from a large data        n   Arithmetic promotion happens automatically
    type to a smaller one (such as an int to a           when operators in expressions convert their
    short)                                               operands
Summer 2004            CS 111                   41   Summer 2004                 CS 111                         42
Data Conversions                                                Creating Objects
n   Casting is the most powerful, and dangerous,                n   A variable holds either a primitive type or a
    technique for conversion                                        reference to an object
    n   Both widening and narrowing conversions can be          n   A class name can be used as a type to
        accomplished by explicitly casting a value                  declare an object reference variable
    n   To cast, the type is put in parentheses in front of                                String title;
        the value being converted
                                                                n   No object is created with this declaration
n   For example, if total and count are
    integers, but we want a floating point result               n   An object reference variable holds the
    when dividing them, we can cast total:                          address of an object
         result = (float) total / count;                        n   The object itself must be created separately

Summer 2004                  CS 111                        43   Summer 2004                       CS 111                          44




Creating Objects                                                Creating Objects
n   Generally, we use the new operator to                       n   Because strings are so common, we
    create an object                                                don't have to use the new operator to
                                                                    create a String object
    title = new String ("Java Software Solutions");
                                                                         title = "Java Software Solutions";
                                                                n   This is special syntax that works only
                  This calls the String constructor, which is
                    a special method that sets up the object        for strings
n   Creating an object is called instantiation                  n   Once an object has been instantiated,
                                                                    we can use the dot operator to invoke
n   An object is an instance of a particular                        its methods
    class                                                                                   title.length()

Summer 2004                  CS 111                        45   Summer 2004                       CS 111                          46




String Methods                                                  Example
    The String class has several methods
                                                                // Construct different strings
n                                                               String phrase = new String ("Change is inevitable");
                                                                String mutation1, mutation2, mutation3, mutation4;
    that are useful for manipulating strings                    System.out.println ("Original string: \"" + phrase + "\"");
                                                                System.out.println ("Length of string: " + phrase.length());
n   Many of the methods return a value,                         mutation1     =   phrase.concat (", except from vending machines.");

    such as an integer or a new String
                                                                mutation2     =   mutation1.toUpperCase();
                                                                mutation3     =   mutation2.replace ('E', 'X');
                                                                mutation4     =   mutation3.substring (3, 30);
    object                                                      // Print each mutated string
                                                                System.out.println ("Mutation      #1:     "   +   mutation1);
n   See the list of String methods in the                       System.out.println ("Mutation
                                                                System.out.println ("Mutation
                                                                                                   #2:
                                                                                                   #3:
                                                                                                           "
                                                                                                           "
                                                                                                               +
                                                                                                               +
                                                                                                                   mutation2);
                                                                                                                   mutation3);
                                                                System.out.println ("Mutation      #4:     "   +   mutation4);
    Java API                                                    System.out.println ("Mutated length: " + mutation4.length());




Summer 2004                  CS 111                        47   Summer 2004                       CS 111                          48
Class Libraries                                                              Packages
n   A class library is a collection of classes that                          n   The classes of the Java standard class
    we can use when developing programs
                                                                                 library are organized into packages
n   The Java standard class library is part of any
    Java development environment                                             n   Some of the packages in the standard
n   Its classes are not part of the Java language                                class library are:
    per se, but we rely on them heavily                                       Package           Purpose
n   The System class and the String class are                                 java.lang         General support
                                                                              java.applet       Creating applets for the web
    part of the Java standard class library                                   java.awt          Graphics and graphical user interfaces
n   Other class libraries can be obtained through                             javax.swing       Additional graphics capabilities and components
    third party vendors, or you can create them                               java.net          Network communication
                                                                              java.util         Utilities
    yourself                                                                  javax.xml.parsers XML document processing
Summer 2004                             CS 111                          49   Summer 2004                CS 111                         50




The import Declaration                                                       The import Declaration
n   When you want to use a class from a                                      n   All classes of the java.lang package
    package, you could use its fully qualified                                   are imported automatically into all
    name                                                                         programs
                            java.util.Random                                 n   That's why we didn't have to import the
n   Or you can import the class, and then use                                    System or String classes explicitly in
    just the class name                                                          earlier programs
                   import java.util.Random;                                  n   The Random class is part of the
n   To import all classes in a particular package,                               java.util package
    you can use the * wildcard character
                                                                             n   It provides methods that generate
                        import java.util.*;
                                                                                 pseudorandom numbers
Summer 2004                             CS 111                          51   Summer 2004                CS 111                         52




Example                                                                      Class Methods
                                                                                 Some methods can be invoked through the
import java.util.Random ;
public class RandomNumbers                                                   n
{
   public static void main (String[] args)                                       class name, instead of through an object of
                                                                                 the class
   {
      Random generator = new Random();
      int num1;
      float num2;
        num1 = generator.nextInt();                                          n   These methods are called class methods or
                                                                                 static methods
        System.out.println ("A random integer: " + num1);
        num1 = generator.nextInt( 10);
        System.out.println ("From 0 to 9: " + num1);
        num1 = generator.nextInt( 10) + 1;                                   n   The Math class contains many static
                                                                                 methods, providing various mathematical
        System.out.println ("From 1 to 10: " + num1);

        num1 = generator.nextInt( 15) + 20;
        System.out.println ("From 20 to 34: " + num1);
                                                                                 functions, such as absolute value,
                                                                                 trigonometry functions, square root, etc.
        num1 = generator.nextInt( 20) - 10;
        System.out.println ("From -10 to 9: " + num1);
        num2 = generator.nextFloat();
        System.out.println ("A random float [between 0-1]: " + num2);                temp = Math.cos(90) + Math.sqrt(delta);
        num2 = generator.nextFloat() * 6; // 0.0 to 5.999999
        num1 = (int) num2 + 1;
        System.out.println ("From 1 to 6: " + num1);
    }
}
Summer 2004                             CS 111                          53   Summer 2004                CS 111                         54
The Keyboard Class                                  Example
    The Keyboard class is NOT part of the
                                                    import cs1.Keyboard;
n                                                   public class Quadratic

    Java standard class library
                                                    {
                                                       //---------------------------------------------------------------- -
                                                       // Determines the roots of a quadratic equation.
                                                       //---------------------------------------------------------------- -

    It is provided by the authors of the
                                                       public static void main (String[] args)
n                                                      {
                                                          int a, b, c; // ax^2 + bx + c

    textbook to make reading input from                      System.out.print ("Enter the coefficient of x squared: ");
                                                             a = Keyboard.readInt ();

    the keyboard easy                                        System.out.print ("Enter the coefficient of x: ");
                                                             b = Keyboard.readInt ();

n   The Keyboard class is part of a                          System.out.print ("Enter the constant: ");
                                                             c = Keyboard.readInt ();

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


    It contains several static methods for
                                                             double discriminant = Math.pow(b, 2) - (4 * a * c);
                                                             double root1 = (( -1 * b) + Math.sqrt(discriminant )) / ( 2 * a);
n                                                            double root2 = (( -1 * b) - Math.sqrt(discriminant )) / ( 2 * a);

    reading particular types of data                    }
                                                             System.out.println ("Root #1: " + root1);
                                                             System.out.println ("Root #2: " + root2);

                                                    }


Summer 2004            CS 111                  55   Summer 2004                                    CS 111                        56




Formatting Output                                   Example
    The NumberFormat class has static
                                                    import cs1.Keyboard;
                                                    import java.text.NumberFormat;
n                                                   public class Price


    methods that return a formatter object
                                                    {
                                                       //-----------------------------------------------------------------
                                                       // Calculates the final price of a purchased item using values
                                                       // entered by the user.
                                                       //-----------------------------------------------------------------
                                                       public static void main (String[] args)
              getCurrencyInstance()                    {
                                                          final double TAX_RATE = 0.06; // 6% sales tax

                                                            int quantity;
              getPercentInstance()                          double subtotal, tax, totalCost, unitPrice;

                                                            System.out.print ("Enter the quantity: ");
                                                            quantity = Keyboard.readInt();

n   Each formatter object has a method                      System.out.print ("Enter the unit price: ");
                                                            unitPrice = Keyboard.readDouble();


    called format that returns a string with                subtotal = quantity * unitPrice;
                                                            tax = subtotal * TAX_RATE;
                                                            totalCost = subtotal + tax;


    the specified information in the
                                                            // Print output with appropriate formatting
                                                            NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
                                                            NumberFormat fmt2 = NumberFormat.getPercentInstance();


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




Summer 2004            CS 111                  57   Summer 2004                                    CS 111                        58




Formatting Output                                   Example
    The DecimalFormat class can be
                                                    import cs1.Keyboard;
n                                                   import java.text.DecimalFormat;


    used to format a floating point value in
                                                    public class CircleStats
                                                    {
                                                       //---------------------------------------------------------------- -

    generic ways
                                                       // Calculates the area and circumference of a circle given its
                                                       // radius.
                                                       //---------------------------------------------------------------- -
                                                       public static void main (String[] args)

    For example, you can specify that the
                                                       {
n                                                         int radius;
                                                          double area, circumference;

    number should be printed to three                        System.out.print ("Enter the circle's radius: " );
                                                             radius = Keyboard.readInt ();

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


n   The constructor of the                                   // Round the output to three decimal places
                                                             DecimalFormat fmt = new DecimalFormat ("0.###");

    DecimalFormat class takes a string                       System.out.println ("The circle's area: " + fmt.format(area));
                                                             System.out.println ("The circle's circumference: "


    that represents a pattern for the
                                                                                 + fmt.format(circumference));
                                                        }
                                                    }

    formatted number
Summer 2004            CS 111                  59   Summer 2004                                    CS 111                        60

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:6
posted:12/19/2011
language:
pages:10