Welcome to Lesson 10!

Announcements

  • Midterm 1 after a short lesson and the break
  • Don't forget Assignment 9 due Tuesday
  • Don't forget Lab 5 due Friday!


Numbers, Operators and Precision Cont'd

Assignment Operators

  • As we discussed before, we assign values to variables using an equal (=) sign
    int sum = 0;
  • However, the equal sign is really an assignment operator and does not denote equality
  • Thus, unlike math, we can have the same variable on both sides of an equals sign:
    int sum = 25;    // initialize sum to 25
    sum = sum + 10;  // add to sum
    
  • Note that the value of the variable is changed in the second line
  • Reading variables from memory does not change them
  • Values placed into a variable replace (overwrite) previous values:


Shortcut Assignment Operators

  • We can use additional operators to calculate values and assign them to the variable on the left all in one statement
    • Known as shortcut assignment operators
  • The general syntax is:
    variable op= expression;
  • Where op is one of the five arithmetic operators: +-*/%
  • For example, the following two statements create the same result:
    x = x + 3;
    x += 3;
    
  • Shown below are the assignment operators with examples of how they are used:


Summary of Assignment Operators

OperatorDescriptionExampleEquivalent To
=Assigns the value of the expression on the right to the variable on the leftx = 3 
+=Adds the expression on the right to the variable on the leftx += 3x = x + 3
-=Subtracts the expression on the right from the variable on the leftx -= 3x = x - 3
*=Multiplies the expression on the right to the variable on the left and saves the result in the variable on the leftx *= 3x = x * 3
/=Divides the variable on the left by the expression on the right and saves the result in the variable on the leftx /= 3x = x / 3
%=Calculates the remainder from dividing variable on the left by the expression on the right and saves the result in the variable on the leftx %= 3x = x % 3


Increment and Decrement Operators

  • Adding or subtracting one is a common operation in programming
  • Java provides arithmetic shortcuts for these operations with the increment and decrement operators
  • The increment operator (++) adds 1 to a variable's value
  • Pre-increment adds 1 before evaluating an expression
    ++sum;
  • Post-increment evaluates the expression and then adds 1
    sum++;
  • The decrement operator works like the increments operator, except it subtracts 1 from the variable:
    --sum
    sum--
    
  • Pre- and post- increment matters when the operation is part of a larger expression
  • For example, consider the code:
    int x = 5;
    int y = x++;
    System.out.println("x=" + x + " y=" + y);
    
  • We may expect y to be 6 after this code executes
  • Instead, y has the value of 5
  • The reason is that ++ after a variable (post-increment) is equivalent to:
    y = x;
    x = x + 1;
    
  • On the other hand, ++ before a variable (pre-increment) is equivalent to:
    x = x + 1;
    y = x;
    

Casting

  • We often find ourselves converting one data type into another
  • This process is called type conversion or typecasting
  • Java is a strongly-typed language and checks for compatible data types both when compiling and while running
  • To put a value of a different type in a variable, you must convert the type
  • There are two types of conversion: implicit and explicit
  • The term for implicit conversion is sometimes called coercion
  • The most common form of explicit conversion is know as casting

Coercion

  • Type conversion is done automatically (implicitly) when a narrower-type is assigned to a broader-type:
    • Narrower means a smaller number of bytes
    • Broader means a larger number of bytes
  • Data type hierarchy (from narrowest to broadest):
    byte => short => int => long => float => double
                   
    
  • For example:
    double x;
    int n = 5;
    x = n;
    
  • Since n is an integer and x is a double, the value returned by n must be converted to type double before it is assigned to x
  • Note that casting only changes the type of an expression's returned value
    • Not the type of the variable
  • Thus the data type of variable n is unchanged -- it is still an int

Coercion in an Arithmetic Expression

  • Some arithmetic expressions have a mix of data types
  • All values implicitly cast to the highest level before the calculation
  • For example:
    double a;
    int n = 2;
    double y = 1.33;
    a = n / y;
    
  • n is automatically cast to type double before performing the arithmetic

Explicit Casting

  • Explicit casting changes the data type for a single use of the variable
  • To cast, precede the variable name with the new data type in parentheses:
    (typeName) variableName
    
  • Where:
    • typeName: one of the Java data types
    • variableName: the name of the variable
  • For example:
    int n;
    double x = 2.0;
    n = (int) x;
    
  • The value of x is converted from type double to int before assigning the value to n
  • Note that explicit casting is required to assign a broader type to a narrower type
  • ILLEGAL: Implicit casting to a lower data type:
    int n;
    double x = 2.1;
    n = x; // illegal in Java
    

    Illegal since x is double, n is an int, and double is a higher data type than int

  • LEGAL: Explicit casting to a lower data type:
    int n;
    double x = 2.1;
    n = (int) x; // legal in java
    
  • You can use an explicit cast even when an implicit one will be done automatically

Truncation When Casting double to Integer type

  • Converting (casting) a double to integer type does not round -- it truncates
  • The fractional part is lost (discarded, ignored, thrown away)
  • For example:
    int n;
    double x = 3.99999;
    n = (int) x; // x truncated
    
  • Value of n is 3

Activity 10.1: Prices (10pts)

  • Find a partner for pair programming
  • Open up Eclipse, create a new Java project named Price
  • Copy the following program into a class file named Price.java:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    
    public static void main(String[] args) {
        String name;
        double price = 0;
      Scanner input = new Scanner(System.in);

    System.out.print("Enter the product name: "); name = input.nextLine();
     
    System.out.print("Price of the " + name + ": "); price = input.nextDouble(); // Insert new statements here System.out.println("Total price: $" + price); }
  • Alter the block comments to include your name and section information to the top of the program.
  • Compile and run the starter program to make sure you entered it correctly.

    When you run the program, the output should look like this:

    Enter the product name: iPod Nano
    Price of the iPod Nano: 149.50
    Total price: $149.5
    

    Note the format of the numbers output for the total price. We will address this formatting issue later in the exercise.

  • Run the program again for a product with a very high cost, like a Boeing 777:
    Enter the product name: Boeing 777
    Price of the Boeing 777: 212345678
    Total price: $2.12345678E8
    

    Note the format of the numbers output for the total price. This format is called exponential notation. You may have encountered it in some of your math classes.

  • Let us correct the formatting of the total price. Alter the System.out statement that prints the total price:
    System.out.printf("Total price: $%.2f\n", price);
    
    Compile and run your program again and verify the output looks like:
    Enter the product name: Boeing 777
    Price of the Boeing 777: 212345678
    Total price: $212345678.00
    
  • Let us add a final variable that we will use later in our program. Enter the following code at the top of main where you declare your variables.
    final int percent = 100;
    

    We are declaring this variable rather than using a magic number.

  • Now we will add sales tax to the price of the product. Enter the following code after the percent variable and before the statement that prints the total price:
    double taxRate = 0;
    System.out.print("Enter sales tax rate (%): ");
    taxRate = input.nextDouble();
    double tax = price * taxRate / percent;
    price += tax;
    

    Notice the last statement: price += tax;. This is an alternate way to code the statement: price = price + tax;.

  • Compile and run your modified program and verify the output looks like:
    Enter the product name: iPod nano
    Price of the iPod nano: 89.50
    Enter sales tax rate (%): 9.5
    Total price: $98.00
    
  • Now we will find the whole dollars and cents of the amount to demonstrate casting. Enter the following code after the statement that prints the total price and before the closing curly brace of main:
    int dollars = (int) price;
    System.out.println("In whole dollars: $" + dollars);
    

    Notice the (int) in the first statement. This is known as a type cast or just cast

  • Compile and run your modified program and verify the output looks like:
    Enter the product name: iPod nano
    Price of the iPod nano: 89.50
    Enter sales tax rate (%): 9.5
    Total price: $98.00
    In whole dollars: $98
    



Midterm 1

Upcoming Assignments

~Have a Great Weekend!~