Elementary Programming: The Basics of Java
Elementary Programming: The Basics of Java
Elementary Programming
                                  1
        Writing a Simple Program
✦ Write a program that will calculate the area of a
  circle.
✦ Remember:
    – Step 1: Problem-solving Phase
    – Step 2: Implementation Phase
                                                 4
           Writing a Simple Program
✦ Write a program that will calculate the area of a
  circle.                                  input
                                                        5
       Writing a Simple Program
✦ Write a program that will calculate the area of a
  circle.
✦ Step 2: Implementation (code the algorithm)
                                i
                            Process
                                                 6
           Writing a Simple Program
✦ Write a program that will calculate the area of a
  circle.
✦ Step 2: Implementation (code the algorithm)
    – In order to store the radius, the program must declare
      a symbol called a variable.
    – A variable represents a value stored in the
      computer s memory
    – You should choose good names for variables with meaning
       ◆ Do not choose x or y …these have no meaning
       ◆ Choose names with meaning… area or radius
                                                        7
           Writing a Simple Program
✦ Write a program that will calculate the area of a
  circle.
✦ Step 2: Implementation (code the algorithm)
    – What value do you want to store in radius?
                                               p          65        6
    – What about area?
                                                44s      Lintor
                                                               as
                                        2
       ◆   Integer? Real number? Something else maybe?    do            2
                                                           9
       Writing a Simple Program
✦ Write a program that will calculate the area of a
  circle.
✦ Step 2: Implementation (code the algorithm)
                                                10
           Writing a Simple Program
✦ Write a program that will calculate the area of a
  circle.
✦ Step 2: Implementation (code the algorithm)
    – Now, we set a value for radius.
       ◆   Later we will learn how to ask the user to input the value
           for radius!
    – We then perform the calculation to get the area.
    – And we print/display the result.
                                                                  11
       Writing a Simple Program
✦ Write a program that will calculate the area of a
  circle.
✦ Step 2: Implementation (code the algorithm)
                                                12
animation
        // Compute area
        area = radius * radius * 3.14159;                            print a message to the
                                                                     console
        // Display results
        System.out.println("The area for the circle of radius " +
          radius + " is " + area);
    }
}
                                                                                          17
a          Writing a Simple Program
✦   Discussion:
    – Variables such as radius and area refer to memory
      locations
    – Each variable has a name, a type, a size, and value
    – Line 3 says that radius can store a double value.
       ◆   But the value is not defined until you assign a value.
    – Line 7 assigns the value 20 into radius.
    – Similarly, line 4 declares the variable area.
    – Line 10 then assigns a value into area.
                                                                    18
        Writing a Simple Program
✦   Discussion:
    – The following table shows the value in memory for
      the variables area and radius as the program is
      executed.
                                                                25
    Reading Input from the Console
✦   Summary:              import
                                                       28
     Program 2: Compute Area with
           Console/User Input
✦   Discussion:
    – There are two types of import statements:
       ◆   Specific import: specifies a single class that should be
           imported
            – Example: import java.util.Scanner;
       ◆   Wildcard import: imports all the classes in a package by
           using the asterisk as the wildcard.
            – Example: import java.util.*;
    – You can use either methods to import classes.
    – The choice is up to you! You are the programmer!
                                                                      29
      Program 3: Compute Average
✦ Write a program to get three values from the user
  and compute their average.
✦ Remember:
    – Step 1: Problem-solving Phase
    – Step 2: Implementation Phase
                                               30
      Program 3: Compute Average
✦ Write a program to get three values from the user
  and compute their average.
✦ Step 1: Design your algorithm
    1. Get three numbers from the user.
       ◆   Use Scanner object
    2. Compute the average of the three numbers:
       ◆   average = (num1 + num2 + num3) / 3
    3. Display the result
                                                   31
    Program 3: Compute Average
✦ Write a program to get three values from the user
  and compute their average.
✦ Step 2: Implementation (code the algorithm)
                                               32
      Program 3: Compute Average
                                   34
                          Identifiers
✦   What is an identifier?
✦   Identifiers are the names that identify elements of your
    program, such as classes, methods, and variables.
    – An identifier is a sequence of characters that consist of letters,
      digits, underscores (_), and dollar signs ($).
    – An identifier must start with a letter, an underscore (_), or a
      dollar sign ($). It cannot start with a digit.
    – An identifier cannot be a reserved word. (See Appendix A,
      “Java Keywords,” for a list of reserved words).
    – An identifier cannot be true, false, or
      null.
    – An identifier can be of any length.
                                                                    35
                         Identifiers
✦   Examples of legal identifiers:
    – area, radius, ComputeArea, $2, average
✦   Examples of illegal identifiers:
    – 2A and d+4
       ◆ These two do not follow the rules
       ◆ Java will report that you have a syntax error!
                                                           36
                            Variables
✦   Variables are used to represent values that may be
    changed in the program.
    – In the previous programs, we used variables to store
      values
       ◆   area, radius, average, etc.
✦   They are called variables because their values can
    be changed!
                                                        37
                         Variables
✦   Discussion:
    –   radius is initially 1.0 (line 2)
    –   then changed to 2.0 (line 7)
    –   area is computer as 3.14159 (line 3)
    –   then changed to 12.56636 (line 8)
                                               38
               Declaring Variables
✦   Syntax for declaring a variable:
    datatype variableName;
✦   Examples:
    int x;                  // Declare x to be
     2  59                  //an integer variable;
    double radius;          // Declare radius to be
                            //a double variable;
    char a;                 //Declare a to be
                            //a character variable;
                                                39
                Declaring Variables
✦   If variables are of the dame data type, they can be
    declared together:
    datatype var1, var2, var3,…, varn;
✦   Example:
    int i, j, k;
✦   Variables often have initial values
✦   You can declare and initialize in one step:
    int count = 1;
    double pi = 3.14159;
                                                          40
                  Declaring Variables
✦ You can also use shorthand form to declare and
  initialize variables of the same type together:
✦ Example:
    int i = 62, j = 78, k = 35;
✦   Tip:
    – A variable must be declared before it can be assigned
      a value, and a value must be assigned to the variable
      before it can be used.
    – Try to declare and initialize in one step.
       ◆   This makes program easier to read and helps to avoid errors
                                                                 41
             Assignment Statements
✦   After a variable has been declared, we can give that
    variable a value.
✦   This is called assigning a value to the variable.
✦   In Java, we do this with the assignment statement.
    – The equal sign (=) is used as the assignment operator.
    – The syntax for assignment statement is as follows:
       variable = value;
        or
        variable = expression;
                                                               42
            Assignment Statements
✦   Sometimes we assign an exact values into variables:
    – Examples:
       int y = 1;               // assign 1 to y
       double w = 3.0;          // assign 3.0 to w
✦   Other times we assign the value of an expression into the
    variable:
    – Examples:
       int x = 5 * (3 / 2);
       double area =radius * radius *3.14159;
                                                          43
             Assignment Statements
✦   If a value is assigned to multiple variables, you can use
    this syntax:
    i = j = k = 5;
✦   This is equivalent to:
    k = 5;
    j = k;
    i = j;
                                                          44
               Assignment Statements
✦ You can also use the same variable on both sides
  of the assignment statement
✦ Example:
       x = x + 1;
    – First, the right side of the assignment is calculated.
    – Then, the new value is assigned into the variable on
      the left (x).
       ◆   So if the value of x was 7 before the statement is executed,
           then x will become 8 after the statement is executed.
                                                           46
                 Named Constants
✦   A named constant is an identifier that represents a
    permanent value.
    – The value of a variable can change during execution
      of a program.
    – However, a named constant, or simply constant,
      represents a permanent data that never changes.
    – Here is the syntax:
       final datatype CONSTANTNAME = value;
    – Example:
       final double PI = 3.14159;
       final int SIZE = 15;
                                                      47
Program 4: Compute Area with a
           Constant
                             48
                    Named Constants
✦   So what are the benefits of using constants?
    1. You don t have to repeatedly type the same value if
       it is used multiple times
    2. If you have to change the value, you only need to
       change it in a single location in the code
       ◆   Instead of changing it at all locations
    3. A descriptive name for a constant makes the
       program easier to read
                                                      49
                                   É      k
              Naming Conventions
✦   Choose meaningful and descriptive names.
    – Do not use abbreviations
✦   Variables and method names:
    – Use lowercase. If the name consists of several words,
      concatenate all in one, use lowercase for the first
      word, and capitalize the first letter of each subsequent
      word in the name.
    – For example, the variables radius and area, and the
      method computeArea.
                                                         50
              Naming Conventions
✦   Class names:
    – Capitalize the first letter of each word in the name.
    – For example, the class name ComputeArea.
✦   Constants:
    – Capitalize all letters in constants, and use underscores
      to connect words.
    – For example, the constants PI and MAX_VALUE
✦   Do you have to follow these rules?
    – No. But it makes your program MUCH easier to
      read!!!
                                                          51
          Numerical Data Types
✦ Every data type has a range of possible values
  that it can have/hold
✦ Whenever you make a variable or constant, the
  compiler will allocate (create) memory based on
  the data type requested
✦ Java provides eight primitive data types
✦ The following table lists the six numeric data
  types and their ranges and storage sizes
                                              52
Numerical Data Types
                       I'm   j
                             53
                Numerical Data Types
✦   Example:
    – The largest value you can save into an integer data
      type is 2,147,483,647.
       ◆   This is just over 2billion
    – So what if you try to store a value larger than this in
      to an integer data type?
            int x=2147483648;
    – Answer: you will get an error.
    – This will not work.
    – Solution: use a different data type
       ◆   double, float, long
                                                          54
                Numerical Data Types
✦   Java uses four data types for integers:
    – byte, short, int, long
✦   Which should you use?
    – Choose the type that is most appropriate for your
      variable.
    – Long is usually unnecessary for most int types
       ◆   It is larger than needed.
✦   Normal usage:
    – int is normally used for integers
    – double is normally used for real numbers
                                                          55
               Number Literals
✦ A literal is a constant value that appears directly
  in the program.
✦ For example, 34, 1,000,000, and 5.0 are literals in
  the following statements:
    int i = 34;
    long x = 1000000;
    double d = 5.0;
                                                 56
                     Number Literals
✦ An integer literal can be assigned to an integer
  variable as long as it can fit into the variable.
✦ A compilation error would occur if the literal
  were too large for the variable to hold.
✦ For example, the statement
    byte b=1000;
    – Would cause a compilation error
    – 1000 can not be stored in a variable of the byte type.
    – The range for byte is -128 to 127
       ◆   Anything smaller or larger will result in an error!
                                                                 57
                     Number Literals
✦   An integer literal is assumed to be of the int type
    – The range for int is between -231(-2147483648) to
      231–1 (2147483647).
    – If you want an int, but you need to store a larger
      number, then you should use the type long
    – To denote an integer literal of the long type, append it
      with the letter L or l.
       ◆   L is preferred because l (lowercase L) can easily be
           confused with 1 (the digit one).
                                                                  58
               Floating-Point Literals
✦ Floating-point literals are written with a decimal
  point.
✦ By default, a floating-point literal is treated as a
  double type value.
    – For example, 5.0 is considered a double value, not a
      float value.
    – You can make a number a float by appending the
      letter f or F, and make a number a double by
      appending the letter d or D.
       ◆   For example, you can use 100.2f or 100.2F for a float
           number, and 100.2d or 100.2D for a double number.
                                                                   59
               double vs. float
The double type values are more accurate than the
 float type values. For example,
System.out.println("1.0 / 3.0 is " + 1.0/3.0);
displays 1.0 / 3.0 is 0.3333333333333333
16 digits
7digits
                                               60
Reading Numbers from the Keyboard
Scanner input = new Scanner(System.in);
int value = input.nextInt();
                                          61
Numeric Operators
                    62
             Assignment Statements
✦  Normal division: 7 / 2 = 3.5
✦ In Computer Science, when we say division,
  majority of the time, we mean integer division.
    – When both operands of a division are integers, we
      will use integer division.
✦   What is integer division?
    – Easiest to explain with examples:
       ◆ 5/2=2        12 / 5 = 2
       ◆7/2=3         15 / 4 = 3
       ◆ 15 / 2 = 7   33 / 8 = 4
                                                      63
              Remainder Operator
✦   The % operator is known as the remainder
    operator, or also as the modulo operator
    – This operator will give the remainder after division
    – Examples:
       ◆ 7%3=1            3%7=3
       ◆ 12 % 4 = 0       26 % 8 = 2
       ◆ 20 % 13 = 7
                                                        64
           Remainder Operator
✦ Remainder is very useful in programming.
✦ For example, an even number % 2 is always 0
✦ An odd number % 2 is always 1
✦ So you can use this property to determine
  whether a number is even or odd.
✦ You can also mod by other values to achieve
  valuable results.
                                                65
               Remainder Operator
✦   Example:
    – If today is Saturday, it will be Saturday again in 7
      days. Suppose you and your friends will meet in 10
      days. What day is it in 10 days?
    – Let us assume Sunday is the 1st day of the week.
    – We can find that in 10 days, the day will be Tuesday
      by using the following equation:
    Saturday is the 7th day in a week
                              A week has 7 days
          (7 + 10) % 7 is 3
                                The 3nd day in a week is Tuesday
         After 10 days
                                                              66
         Program 5: Convert Time
✦ Write a program to get an amount of time from
  the user in seconds. Then your program should
  convert this time into minutes and the remaining
  seconds.
✦ Remember:
    – Step 1: Problem-solving Phase
    – Step 2: Implementation Phase
                                               67
           Program 5: Convert Time
✦   Step 1: Problem-solving Phase
    – If you are given seconds, how do you then calculate
      the minutes and remaining seconds?
       ◆   Example:
            – Given 624 seconds, how do we calculate the minutes?
            – We divide by 60!
                • We see how many complete 60s are in 624.
                • Answer: 10 of them. 10x60 = 600.
            – So in 624 seconds, there are a full 10 minutes.
            – After we remove those 10 minutes, how many seconds are
              remaining?
                • 624 –(10x60) = 24 seconds remaining
                • We can use mod! 624%60 = 24 seconds remaining.
                                                                       68
           Program 5: Convert Time
✦   Step 1: Design your algorithm
    1. Get amount of seconds from the user.
       ◆ Use Scanner object
       ◆ Save as an int
                                 70
         Program 5: Convert Time
                                                         74
           Arithmetic Expressions
✦ Java expressions are written the same way as
  normal arithmetic expressions.
✦ Example:
        3 + 4 x 10( y − 5)(a + b + c)     4 9+ x
               −                      + 9( +     )
           5              x               x  y
✦   is translated into
    (3+4*x)/5 –10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
                                                     75
      How to Evaluate an Expression
 ✦   Summary: you can safely apply the arithmetic
     rule for evaluating a Java expression
140 – Operators inside parenthesis are evaluated first
        ◆ Parenthesis can be nested
        ◆ Expression in inner parenthesis is evaluated first
        3 + 4 * 4 + 5 * (4 + 3) - 1
                                (1) inside parentheses first
        3 + 4 * 4 + 5 * 7 – 1
                                (2) multiplication
        3 + 16 + 5 * 7 – 1
                                (3) multiplication
        3 + 16 + 35 – 1
                                (4) addition
        19 + 35 – 1
                                (5) addition
             54 - 1
                                (6) subtraction
            53
                                                               77
    Program 6: Convert Temperature
✦   Write a program that converts a temperature in
    Fahrenheit into Celsius.
    – You will need the following formula:
✦   Remember:
    – Step 1: Problem-solving Phase
    – Step 2: Implementation Phase
                                                 78
    Program 6: Convert Temperature
✦   Step 1: Design your algorithm
    1. Get temperature in Fahrenheitfrom the user.
       ◆ Use Scanner object
       ◆ Save temperature as an int
                                                     79
    Program 6: Convert Temperature
✦   Step 2: Implementation
                                 80
    Program 6: Convert Temperature
✦   Discussion: be careful when dividing integers
    – Notice the formula has 5 divided by 9
               celsius = ( 95 )( fahrenheit − 32)
    – What happens if we write this formula as:
       celsius= (5 / 9) * (fahrenheit–32);
    – (5 / 9) evaluates to zero!
       ◆   Integer division!
    – So we use (5.0 / 9) instead, which gives a number
✦   Remember:
    – Step 1: Problem-solving Phase
    – Step 2: Implementation Phase
                                               82
     Program 7: Show Current Time
✦   Step 1: Problem-solving Phase
    – Remember how you print to the screen?
       ◆ You use the method println
       ◆ This method is inside the System class
          System.out.println
    – Well, there are many beneficial methods inside this
      System class.
    – Java provides a method to return the current time
       System.currentTimeMillis()
       ◆ This method returns the current time, in milliseconds, in
         milliseconds since midnight, January 1, 1970 GMT.
                                                                83
     Program 7: Show Current Time
✦   Step 1: Problem-solving Phase
    System.currentTimeMillis()
      ◆ This method returns the current time, in milliseconds, in
        milliseconds since midnight, January 1, 1970 GMT.
      ◆ Why this specific date?
                                                                    84
     Program 7: Show Current Time
✦   Step 1: Problem-solving Phase
    System.currentTimeMillis()
      ◆ So this method returns the number of milliseconds since
        1970.
      ◆ That s a LOT of milliseconds
                                                                        87
     Program 7: Show Current Time
✦   Step 1: Problem-solving Phase
    6. Obtain the total hours, totalHours, by dividing
      totalMinutesby 60
       ◆   totalHours= totalMinutes/ 60;
            – Example: 20053051 minutes / 60 = 334217 hours
    7. Compute the current hour from totalHours% 24
       ◆   currentHour= totalHours% 24;
            – Example: 334217 hours % 24 = 17, which is the current hour
                                                                       88
     Program 7: Show Current Time
✦   Step 1: Problem-solving Phase
    – All these numbers are HUGE
    – The int data type is not large enough
    – All variables should be declared as the long data
      type for this program
                                                          89
     Program 7: Show Current Time
✦   Step 2: Implementation
                                    90
     Program 7: Show Current Time
✦   Step 2: Implementation
                                    91
    Augmented Assignment Operators
✦   Very often, we use the current value of a
    variable, we modify it, and then save it back to
    the same variable.
    – Example:
       count = count + 1;
    – Java allows you to combine this addition and
      assignment into one operator, which is called the
      augmented assignment operator.
                               j
    – Example:
       count += 1;
                                                          92
Augmented Assignment Operators
                             93
    Augmented Assignment Operators
✦   The augmented assignment operator is
    performed last after all the other operators in the
    expression are evaluate
    – Example:
       x /= 4 + 5.5 * 1.5;
       is same as
       x = x / (4 + 5.5 * 1.5);
           then
    – Caution: there are no spaces in the augmented
      operators
       ◆   For example, + = should be += (with no space)
                                                           94
Increment and Decrement Operators
✦   Another common expression is to simply
    increment (increase) a variable by one
    – Such as x = x + 1;
    – Because this is so common, Java gives you special
      increment and decrement operators
       ◆ Increment operator: ++     I
       ◆ Decrement operator: --
                                  That
    – Examples:
       int i = 3, j = 3;
       i++;           // i becomes 4
       j--;           // j becomes 2
                                                      95
Increment and Decrement Operators
✦   More details:
       ◆ i++ is pronounced as i plus plus
       ◆ i-- is pronounced as i minus minus
                                                                    96
Increment and Decrement Operators
✦   More details:
    – The operators can also be placed before the variable
       int i = 3, j = 3;
       ++i;           // i becomes 4
       --j;           // j becomes 2
    – Again, ++i increments i, and --j decrements j
    – In this small example, result is the same
       ◆ Meaning i++ and ++i both increase i from 3 to 4.
       ◆ And both --j and j–decrease j from 3 to 2.
                                                            97
Increment and Decrement Operators
✦   More details:
    – If the statement is ONLY doing increment or
      decrement, the effect of j++and ++j is the same.
    – However, the effect changes when these operators
      are used in other types of statements.
       ◆   Specifically:
              – ++i: the increment is done before evaluating an expression
              – i++: the increment is done aftere valuated an expression
      a I                                                                    98
Increment and Decrement Operators
Pk
                               99
Increment and Decrement Operators
✦   Consider the following code:
    – Details:
       ◆ Here, we first get the value of i (which is 10)and calculate
                                        To
         newNum.
       ◆ Then, we increment i.
           – i is not incremented until AFTER the expression is evaluated.
                                                                        100
Increment and Decrement Operators
✦   Consider the following code:
    – Details:
       ◆ Here, we first increment i
                       t
       ◆ Then, after i is incremented, we calculate newNum.
                                                              101
Increment and Decrement Operators
✦   Another example:
    – Consider the following code:
       double x = 1.0;         2 7
                              1  6
       double y = 5.0;        X O
                         6
                         It
       double z = x--+ (++y);
    – What is the value of x, y, and z after are three lines
      are executed?
       ◆ x becomes 0.0
       ◆ y becomes 6.0
◆ z becomes 7.0
                                                         102
Increment and Decrement Operators
✦   More details:
    – Using increment and decrement operators makes
      expressions short
       ◆   but it also makes them complex and difficult to read
    – Avoid using these operators in expressions that
      modify multiple variables, or the same variable for
      multiple times such as this:
       int k = ++i + i; if  i 3
                           K 8
                         andIT
       ◆ Is this legal?
            – Yes. But it is confusing!
            – Message: don t use increment/decrement like this.
                                                                  103
           Numeric Type Conversion
✦   Can you perform binary operations with
    operands of different types?
    – Meaning, can we add an integer literal with a double
      literal?
    – Answer: YES.
       ◆   If you add an integer with a floating-point number, Java
           automatically coverts the int to a floating point value.
    – Example:
       ◆ 3 * 4.5 is the same as
       ◆ 3.0 * 4.5
                                                                104
           Numeric Type Conversion
✦   Details:
    – You can always assign a value to a numeric variable
      just so long as the value is within the limits/range of
      the data type.
    – Example:
       ◆ You can save an int into a double, because the double is
         much wider (larger) than the int
          int x = 4;
          double y;
          y = x;
       ◆ This is allowed, because x can easily fit into y.
                                                              105
           Numeric Type Conversion
✦   Details:
    – However, you cannot assign a value to a variable of
      a data type with a smaller range of values.
       ◆   Unless you use type casting
    – Casting is an operation that coverts a value of one
      data type into a value of another data type
       ◆ Casting a type with a small range to a type with a larger
         range is known as widening a type
                                                   Large  small       É
                                                                    casting
                                                                   106
           Numeric Type Conversion
✦   Casting:
    – Java will automatically widen a type, but you must
      request a narrowing explicitly
    – Syntax:
       ◆   specify the target type in parentheses, followed by the
           variable s name or the value to be cast
    – Example:                          int x     int 8.5
           System.out.println((int)1.7); x 8
       ◆ 1 gets printed.
                                                                 107
         Numeric Type Conversion
✦   Casting:
    – Example:
       System.out.println((double)1/2);
       ◆ 0.5 gets printed.
    – Example:
       System.out.println(1 / 2);
       ◆ Be careful!
                                                               108
                     Type Casting
Implicit casting
double d = 3; // (type widening)
Explicit casting
int i = (int)3.0; // (type narrowing)
int i = (int)3.9; // (Fraction part is truncated)
What is wrong? int     x = 5 / 2.0;
                          range increases
                 I
           byte, short, int, long, float, double
              HE
✦   See sample program: JavaBasics.java
                                                    109
               Conversion Rules
     When performing a binary operation involving two
     operands of different types, Java automatically
     converts the operand based on the following rules:
                                                       110
            Program 8: Sales Tax
✦   Write a program that reads a purchase amount
    from the user, calculates the sales tax, and then
    displays the result.
    – But we want to print the tax with only two decimal
      places
✦   Remember:
    – Step 1: Problem-solving Phase
    – Step 2: Implementation Phase
                                                      111
               Program 8: Sales Tax
✦   Step 1: Design your algorithm
    1. Get purchase amount from user.
       ◆ Use Scanner object
       ◆ Save purchaseAmount as a double
                                                                112
                 Program 8: Sales Tax
✦   Example:
    – If purchaseAmount is entered as 197.55
    – Then the sales tax is evaluated as 197.55 * 0.06
       ◆    This equals 11.853
    – So how do we display this with only two decimals?
       1.    Multiply 11.853 by 100
             •   11.853 * 100 = 1185.3
       2.    Cast the result as an integer
             •   Now 1185.3 becomes 1185 (the .3 is removed)
       3.    Now, divide by 100.0, which is a double
             •   And we get 11.85
                                                               113
           Program 8: Sales Tax
✦   Step 2: Implementation
6
  –This is equivalent to
      ◆sum   = (int)(sum + 4.5);
                                                                  115
     Common Errors and Pitfalls ion
✦   Common Error # 1: Undeclared/Uninitialized
    Variables and Unused Variables
    – a variable must be declared and a value assigned to it
      before you use it.
    – Common errors include not declaring or not
      initializing a variable
    – Example:
       double interestRate= 0.05;
       double interest = interestrate * 45;
          – Java is case sensitive. In the 2nd line, interestrate is not
            defined, because the R is not capitalized
                                                                      128
     Common Errors and Pitfalls ion
✦   Common Error #2: Integer Overflow wedigits                          II
                                                                             129
    Common Errors and Pitfalls ion
                                                    EE      6
✦ Common Error #3: Round-off Errors IT
  – a round-off error, also called a rounding error, is the
    difference between the exact mathematical value of
    a number and the approximated value that was
    calculated.
  – Example:
      ◆ 1/3 is approximately 0.333 if you use three decimals
      ◆ and it is 0.3333333 if you use seven decimal places
                                                              130
     Common Errors and Pitfalls ion
✦   Common Error #3: Round-off Errors
    – Calculations with floating-point numbers are also
      approximated
       ◆ Because they are not stored with complete accuracy
    – Example:
       ◆   System.out.println(1.0 -0.1 -0.1 -0.1 -0.1
           -0.1);
            – The output should be 0.5, but the output is really
              0.5000000000000001
       ◆   System.out.println(1.0 -0.9);
            – The output should be 0.1, but the output is really
              0.09999999999999998
    – Message: use integers for exact/precise results!
                                                                   131
     Common Errors and Pitfalls ion
✦   Common Error #4: Unintended Integer Division
    – Perhaps you want normal division Ew double   ints tilt
                                             µ I 405 I
       ◆   Example: 3 / 2 = 1.5              100     05 4.4
    – However, if both operands are integers, Java will
      automatically use integer division
    – If you do not want integer division, you should make
      one of the operands a floating-point number
K
HE
g
                                                     133
     Common Errors and Pitfalls ion
✦   Common Pitfall #1: Repeated Input Objects
    – The code is not wrong, but it is inefficient (slow)
    – It creates two input objects, which is a waste
    – The correct code is below:
134