3: Arithmetic and Variables

What We Will Cover


Continuations

Homework Questions?

  • A1: Information Please! (9/8/04)
    Exercise 1 and CodeLab Lesson 1 (9/8/04)
    Exercise 2 and CodeLab Lesson 2 (9/13/04)

Viewing WebCT Assignment Results

Questions from last class?

How do comments contribute to good code?
1. They provide hints to the compiler.
2. They provide hints to the interpreter.
3. They provide hints to the user.
4. They provide hints to the programmer.

From Where We Left Off: 2.2.5: Characters

3.1: Arithmetic

Objectives

At the end of the lesson the student will be able to:

  • Use arithmetic operators
  • Perform integer division and use the modulus operator
  • Translate algebraic expressions into Java code

3.1.1: Arithmetic Operators

  • Can perform arithmetic on integers and floating-point numbers
  • Use special symbols to perform the operations:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • For example:
  • 3 + 4
    12 - 7
    12.3 + 4.56
    .065 * 1200
    18 / 2
    17.4 / 3.1
    
  • These combination of numbers and operators are called arithmetic expressions
  • Expressions are parts of a program that return (express) a value
  • We can use these expressions to perform arithmetic and display the results
  • System.out.print(3 + 4); // prints 7

Negation

  • Operators +, -, *, /, % are called binary operators
    • Always need two operands (numbers) to work with
  • Java also provides a unary operator: - (minus sign)
    • Reverses the sign of a number
  • For example:
  • -1    -5.3    - -1
  • Java also provides a plus sign (+) unary operator
    • Generally not used

3.1.2: Mixed-Mode Expressions

  • Recall the different data types are stored in different forms
  • Computer needs both operands in the same form before it can perform an operation
  • If one operand is different than the other, the computer promotes the narrowest
  • Promotion process is also known as casting
  • Data type hierarchy (from narrowest to broadest):
  • byte => short => int => long => float => double
                    /
             char =/
    
  • For example:
  • 2 + 2.2
  • First number (2) is an int
  • Second number (2.2) is a double
  • First number is narrowest, thus gets promoted to a double (i.e. 2.0)
  • Then the arithmetic operation can take place to produce a result of 4.2

3.1.3: Integer Division and Modulus

  • Dividing two integers can produce unexpected results for the unwary
  • For example, what is the result of the following expression?
  • 7 / 2
  • Since both numbers are of type int, one does not get floating-point result
  • Remainder portion is truncated (discarded, thrown away)

Modulus Operator

  • Sometimes want to know the remainder of an integer division
  • Java provides the modulus operator: % (percent sign)
  • Returns the remainder of the division of first number by the second
  • For example:
  • 7 % 2 // returns 1
  • 7 % 2 returns 1 because 1 is the remainder when 7 is divided by 2

Check Ourselves

What is the result of the following arithmetic operations?

  • 9 / 4
  • 17 / 3
  • 14 / 2
  • 9 % 4
  • 17 % 3
  • 14 % 2

3.1.4: Arithmetic Precision and Range

  • There are only a finite set of numbers in arithmetic calculations
  • Can lead to some problems for the unwary

Integer Overflow

  • What happens when an integer is too big for its type?
  • System.out.print("Big number: ");
    System.out.println(2147483647 + 1);
    System.out.print("Small number: ");
    System.out.println(-2147483647 - 2);
    
  • Wraps around from the highest number to the lowest
  • Must be careful that your program will not go beyond the range of its data types

Floating-Point Precision and Range

  • Floating-point numbers are not exact representations of real numbers
  • Rounding errors occur in repeated calculations
  • Type double has about twice the precision of type float
  • However, even type double can have rounding errors
  • System.out.println(.8F + .1F);
    System.out.println(.8 + .1);
    
  • When floating point numbers get too large, they are set to infinity
  • System.out.println(3E38F + 3E38F);
  • Similarly, when too small they are set to 0.0

3.1.5: Operator Precedence and Associativity

  • Often need to process expressions of greater complexity than two numbers
    • May need more than one operator
  • Java has certain rules that must be followed

Java Rules

  1. Two binary operators cannot be placed side by side
    • Invalid expression: 5 * % 6
    • Operators * and % cannot be next to each other
  2. Parenthesis can be used to group expressions
    • Anything within parenthesis is evaluated first
  3. Can have parenthesis within parenthesis
    • Innermost parenthesis evaluated first
  4. Parenthesis cannot be used to indicate multiplication
    • Must use the * operator
  5. Programming style: spacing required around operators
  6. Programming style: no spacing after opening or before closing parenthesis

Precedence and Associativity Rules

  • Arithmetic operators processed in algebraic order:
    1. Parenthesis: ( )
    2. Unary operators: +, -
    3. Multiplication, division, modulus: *, /, %
    4. Addition, subtraction: +, -
  • Binary operators of same precedence evaluated left to right

Examples of Expressions

Algebra Expression Java Expression
2(10 + 5)
2 * (10 + 5)
1

12.2 + 3 · 7.3
1 / (12.2 + 3 * 7.3)
10 - 7

3.4 + 9 · 1.6
(10 - 7) / (3.3 + 9 * 1.6)
2 · 42
2 * 4 * 4

3.1.6: Mathematical Methods

  • Only the simplest mathematical operations are provided by operators
  • For more complex operations, you use mathematical methods
  • double myRoot = Math.sqrt(9.0);
  • Java provides the Math class that contains many such methods
  • Name Description Example Result
    abs absolute value Math.abs(-3.9)
    Math.abs(3.9)
    3.1
    3.1
    exp exponent Math.exp(1.0) 2.718...
    log natural log Math.log(10.0) 3.20...
    pow powers Math.pow(2.0, 3.0) 8.0
    sqrt square root Math.sqrt(4.0) 2.0

  • In addition, includes three similar methods: round, floor, and ceil
  • Name Description Example Result
    ceil ceiling: round up Math.ceil(3.3)
    Math.ceil(3.7)
    4.0
    4.0
    floor floor: round down Math.floor(3.3)
    Math.floor(3.7)
    3.0
    3.0
    round round: round off Math.round(3.3)
    Math.round(3.7)
    3.0
    4.0

  • All three return whole numbers, although they are of type double

3.1.7: Summary

  • Java uses the following operators for arithmetic
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • Arithmetic expressions are combinations of numbers and operators
  • Results of integer division are truncated
  • Must use modulus operator (%) to get the remainder value
  • The dash (minus sign) is used for negation
  • Operators have the same precedence as in algebra
    1. Parenthesis: ( )
    2. Unary operators: +, -
    3. Multiplication, division, modulus: *, /, %
    4. Addition, subtraction: +, -
  • Multiplication operator always required, unlike algebra
  • More complex mathematical operations are available using the Math class

Exercise 3.1

  1. Start a text file named exercise3.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 3.1
  4. Submit all exercises for today's lesson in one file unless instructed otherwise
  5. Complete the following and record the answers to any questions in exercise3.txt.

Specifications

    Through the miracles of modern computer technology, we will now convert your $1000 computer into a $10 calculator!

  1. Copy the following program into a text editor; compile and run the program.
  2. public class HelloWorld {
         public static void main(String[] args) {
            System.out.println("Hello, world!");
        }
    }
    
  3. Replace the "Hello, World!" portion of the program with the arithmetic expression 7 + 2 and then recompile and run the program.
  4. Q1: What value was displayed by the computer?

  5. Use the expression 7 / 2 and then recompile and run the program.
  6. Q2: What value was displayed by the computer? Why?

  7. Change the expression to use 7 % 2 and then recompile and run the program.
  8. Q3: What value was displayed by the computer? Why?

  9. The following are algebraic expressions and an incorrect translation to code. Find the errors and write corrected code. Save the corrected expressions in exercise3.txt.
  10. Algebraic Expression Incorrect Conversion
    (2)(3) + (4)(5)
    (2)(3) + (4)(5)
    6 + 18

    2
    6 + 18 / 2
    5

    9
    (100 - 32)
    5 / 9 * (100 - 32)
    2 · 42
    2 * 4 ^ 2

3.2: Variables and Declarations

Objectives

At the end of the lesson the student will be able to:

  • Use declaration statements to declare variables
  • Assign values to variables

3.2.1: Memory Addresses and Data Storage

  • Computer data is stored in and retrieved from memory
  • Before high-level languages, memory was referred to by its address
  • Storing integers 45 and 12 would allocate memory like the following
  • Quickly becomes cumbersome to write such programs
    • Have to manually keep track of each location
    • Have to make sure locations do not overlap
  • More intuitive to assign each variable a name
    • Let the computer remember the actual memory location
  • Then each memory location can be referred to by name
  • Now our programs can look like the following:
  • num1 = 45;
    num2 = 12;
    total = num1 + num2;
    
  • Each of these statements is called an assignment statement
  • Tells the computer to assign (store) a value into a variable
  • Assignment statements always have a variable name followed by an equal (=) sign
  • To the right of the equals sign is an expression that yields a value

3.2.2: Declaring Variables

  • Declaration statement both names a variable and specifies the data type it can store
  • All Java program variables must be declared before using them
  • General syntax:
  • dataType VariableName1, VariableName2, ...;
    
  • For example:
  • int num1, num2, total;
    long dateNum;
    float firstNum;
    double secNum;
    char letter;
    
  • When variables are declared, computer allocates storage space
  • Amount of storage space depends on the data type
  • Contents of the storage space is undefined until a value is assigned
  • Type Name Kind of Value Memory Size
    byte integer 1 byte
    short integer 2 bytes
    int integer 4 bytes
    long integer 8 bytes
    char single character (Unicode) 2 bytes
    float floating point 4 bytes
    double floating point 8 bytes
    boolean Logical true or false 1 byte

Programming Style: Variable Naming Conventions

  • Start variable names with a lowercase letter
  • Capitalize the first letter in all words after the first word
  • Use meaningful names that are easy to remember as you code

3.2.3: Assigning Values to Variables

  • Use the assignment operator "equals sign" (=)
  • variable = expression;
  • Assigns value of expression (right side) to the variable (left side)
  • The simplest expression is a literal value:
  • length = 25;
    width = 17.5;
    
  • In each statement, value on right is assigned to the variable on the left
  • Can also assign results of more complex expressions to a variable
  • total = num1 + num2;
    slope = (y2 - y1) / (x2 - x1);
    

Assigning Initial Values to Variables

  • Initial values may or may not be assigned when variables are declared:
  • // These may not be initialized when declared
    int sum, number1, number2;
    
    // These are initialized when declared
    int sum = 0;
    int number1 = 5, number2 = 10;
    
  • Good programming practice: initialize variables when declared

Programming Style: Constant Variables

  • The meaning of literal numbers is hard to remember
    • Sometimes called "magic" numbers"
    • Magic because no one has a clue what it means after 3 months, including the author
  • A better approach is to assign the number to a descriptive constant variable
  • Java uses the keyword final to indicate a variable that cannot change
  • public class MyClass {
        public static final int MY_CONSTANT = 10;
    
        public static void main(String[] args) {
            // program statements
        }
    }
    
  • Note that the name is all uppercase letters with an underscore separator
    • This is a common coding convention that you must follow
  • Constants are declared outside any method body but within a class
  • Usually declared along with: public static final

3.2.4: Assignment Variations

  • You 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 changed in the second line
  • Reading variables from memory does not change them
  • Values placed into a variable replace (overwrite) previous values

Abbreviated Assignment Expressions

  • Any statement of form: variable = variable <op> (expression);
  • May be written in an abbreviated form: variable <op>= expression;
  • <op> is one of: +, -, *, /, or %
  • For example:
  • sum = sum + 10;
    
  • Can be written as:
  • sum += 10;
    

Incrementing and Decrementing

  • Adding 1 to a number occurs frequently when programming
  • count = count + 1;
  • You can write this in an abbreviated form like:
  • count += 1;
  • Since it is so common, programmers wanted an even shorter form:
  • count++;
  • This is known as incrementing a variable
  • Similarly, you can decrement a variable
  • count--;

3.2.5: Type Casting

Cast: change the data type of the returned value of an expression

  • Recall that different data types are stored in different forms
  • Sometimes need to change from one form to another
    • Example: arithmetic adding a double and an int value
  • Java will automatically cast some data types to another
  • byte => short => int => long => float => double
                    /
             char =/
    
    • Also known as implicit casting
    • May not know how to convert some values
    • May not cast how the programmer wants
  • Programmers can also explicitly cast data types
  • Recall that casting is done automatically (implicitly) when a narrower-type is assigned to a broader-type
  • Explicit casting changes the data type for a single use of the variable
  • Precede the variable name with the new data type in parentheses:
  • (<dataType>) variableName
    
  • Data type is changed only for the single use of the returned value
  • For example:
  • int n;
    double x = 2.0;
    n = (int) x;
    
  • Value of x is converted from type double to integer before assigning the value to n

Required Casting

  • Explicit casting is required to assign a broader type to a narrower type
  • ILLEGAL: Implicit casting to a narrower 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 broader data type than int

  • Can use an explicit cast even when an implicit one will be done

Casting a char to an int

  • Casting a char value to int produces the ASCII/Unicode value
  • For example, what would the following display?
  • char answer = 'y';
    System.out.println(answer);
    System.out.println((int) answer);
    
  • Answer:
  • >y
    >89
    

Truncation When Casting Floating-Point to Integer type

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

3.2.6: Summary

  • Variables store a value that can change as a program executes.
  • Constants store a value that cannot change.
  • Variables and constants must be declared before use.
  • To initialize a variable or constant, declare a name and assign a value.
  • Simple assignment statements have a variable, equals sign and an expression.
  • variable = expression;
  • The expression is computed before the assignment
  • Java has assignment variations of the form:
  • variable <op>= expression;
  • You can explicitly cast values of an expression to a different type.
  • You must use an explicit cast when assigning a broader type to a narrower type.

Exercise 3.2

Recall the data that we explored in previous exercises:

  1. The average number of four grades
  2. The number of days in a month
  3. The length of the Golden Gate Bridge
  4. The numbers in the state lottery

Write a program for one of these that:

  • Declares one or more variables
  • Initializes the variable(s) with any value you like
  • Prints the variable(s) to the screen

Submit your code along with exercise3.txt as a separate file.

3.3: Working With Strings

Objectives

At the end of the lesson the student will be able to:

  • Identify string types from their literal representation
  • Concatenate strings
  • Convert strings to primitive types

3.3.1: Literal Strings

  • String literals are made by enclosing a sequence of characters in double quotes
  • For example:
  • "abc"   "b"   "3.34159"   "$3.95"   "My name is Ed"
  • Double quotes used to mark the beginning and end of a string are not stored
  • Notice that the string "3.34159" could be expressed as a double by removing the quotes
  • However, a computer stores these two values very differently
  • double type 3.34159 is stored in eight bytes using the IEEE 754-1985 standard
  • String type "3.34159" is stored as Unicode characters
  • Both data types are useful for solving problems

3.3.2: String Assignments

  • String assignments are different than for primitive types
  • Actually a reference type because strings are objects in Java
  • For instance:
String message;
message = new String("Please enter an identification code");
  • First line declares a reference variable of type String
  • Second line creates a String object in memory as assigns the object location to the reference variable
  • Keyword new is an operator that creates storage for an object
  • Because this allocation occurs while the program is running, known as dynamic memory allocation
  • Could combine the two steps into one line:
  • String message = new String("Please enter an ...");
    
  • String literals have a special syntax that does not require the new operator
  • String message = "Please enter an identification code";
    
  • Since this form is shorter, it is preferred by most Java programmers

3.3.3: Joining Strings

  • Most string operations are performed using methods rather than operators
    • Because strings are really a Java class
  • However, there is one string operator: +
  • Same sign as used for numerical addition
  • For strings, performs a concatenation operation
  • Joins two strings into one string
  • For example:
  • "Java" + " rules!"
  • Concatenates the two strings into one string: "Java rules!"
  • Note that the + operator has the same precedence for strings and numbers
  • Can sometimes produce surprising results

3.3.4: String Methods

  • Once you create an object of a class, you use its methods to perform operations on the object.
  • Syntax for calling a method of an object:
  • objectName.method(arguments)

Some Commonly-Used Methods

  • length(): Returns the length of the string
  • String s = "Hello";
    System.out.println(s.length());
    
  • charAt(int): Returns a char at the specified index.
  • toLowerCase(): Returns a new string with all characters in lowercase.
  • toUpperCase(): Returns a new string with all characters in uppercase.
  • trim(): Returns a new string with all whitespace removed from the beginning and end.

3.3.5: Converting Strings

  • Often need to convert String values to numeric types
  • Java provides a very useful set of methods for converting between strings and primitive types
  • These methods are known as wrapper classes
    • Wrap a class structure around a primitive type

  • Each conversion method is a public and static
    • General purpose methods that operate only on their arguments to produce a result

Strings to Primitive Values

Return
Type
Conversion Method Example
int Integer.parseInt(String) Integer.parseInt("1234")
long Long.parseLong(String) Long.parseLong("123456")
float Float.parseFloat(String) Float.parseFloat("123.45")
double Double.parseDouble(String) Double.parseDouble("123.45")

Primitive Values to Strings

Type to
Convert
Conversion Method Example
int Integer.toString(int) Integer.toString(1234)
long Long.toString(long) Long.toString(123456)
float Float.toString(float) Float.toString(123.45)
double Double.toString(double) Double.toString(123.45)

More Information

3.3.6: Summary

  • You make string literals by enclosing characters in double quotes
  • To concatenate two strings, use the "+" operator
  • Strings are an object type in Java and operate differently than primitive types
  • One of the differences is that strings have methods
  • Java has a number of conversion methods to convert strings to primitive types
  • Also has methods to convert primitive types to strings

Exercise 3.3

With a partner, if needed, take 5 minutes to complete the following:

  1. Start a text file named exercise3.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 3.3
  4. Submit all exercises for this lesson in one file unless instructed otherwise
  5. Complete the following and record the answers to any questions in exercise3.txt.

Exercises and Questions

Use the following program for this exercise:

public class NumberApp {
    public static void main(String[] args){
        String stringNumber = "3.14159";
        double parsedDouble = Double.parseDouble(stringNumber);
        String message = "\nString number = " + stringNumber
                       + "\nParsed double = " + parsedDouble;
        System.out.println(message);
    }
}
  1. Save the file as "NumberApp.java".
  2. Q1: Which lines of code declare strings?

  3. Compile and execute the code.
  4. Q2: Which line of code converts (parses) the string to a double?

  5. Use the following line of code to try to convert the string number to an integer:
  6. int parsedInteger = Integer.parseInt(stringNumber);

    Q3: Why do you get an error message?

3.4: Formatted Output

Objectives

At the end of the lesson the student will be able to:

  • Display program output to the console
  • Format numbers during output

3.4.1: Using println Versus print

  • Two useful prewritten methods are print() and println()
  • Their function is to display data
  • The difference between the two methods is that:
    • print() leaves the cursor positioned after the last character
    • println() positions the cursor on a new line
  • Cursor position determines where the next character is displayed
  • System.out.println("Hello, world!");
    
  • In this statement, out is the name of an object in a Java class named System
  • System is automatically created whenever a Java program is executed
  • System.out lets a program know to send data to the standard output stream
    • Usually the video display screen
  • The data to display is passed to the method within parenthesis

3.4.2: Using Predefined Number Formats

  • Important to display program results attractively
  • Java allows formatting numbers for different locales
  • Java provides some prefefined formats using the NumberFormat class

Currency Format

  • First we format numbers with the currency format
  • We use NumberFormat to get a currency instance
  • We then use the currency to format the output
import java.text.NumberFormat;

public class Currency {
    public static void main(String[] args) {
        double price = 11.575;
        NumberFormat currency =
            NumberFormat.getCurrencyInstance();
        String formattedCurrency = currency.format(price);
        System.out.println(formattedCurrency);
    }
}

Percent Format

  • Next we format numbers with the percent format
  • We use NumberFormat to get a percent instance
  • We then use the percent to format the output
import java.text.NumberFormat;

public class Percent {
    public static void main(String[] args) {
        double majority = .512;
        NumberFormat percent =
            NumberFormat.getPercentInstance();
        percent.setMinimumFractionDigits(1);
        String formattedPercent = percent.format(majority);

        System.out.println(formattedPercent);
    }
}

Number Format

  • Finally we format numbers with the number format
  • We use NumberFormat to get a number instance
  • We then use the number to format the output
import java.text.NumberFormat;

public class Number {
    public static void main(String[] args) {
        double miles = 15341.256;
        NumberFormat number =
            NumberFormat.getNumberInstance();
        number.setMaximumFractionDigits(1);
        String milesString = number.format(miles);

        System.out.println(milesString);
    }
}

Setting the Decimal Place

  • NumberFormat provides two methods to control the number of digits to the right of the decimal
  • setMaximumIntegerDigits(int num): Sets the maximum number of digits allowed to the right of the decimal place
  • number.setMaximumFractionDigits(3);
  • setMinimumFractionDigits(int num): Sets the minimum number of digits allowed to the right of the decimal place
  • number.setMinimumFractionDigits(2);
  • The minimum must be less than the maximum

3.4.3: Formatting with Patterns

  • We can get more control by using patterns in our number formatting
  • The DecimalFormat class provides the capability to specify the format of each number
  • To do this, we use special symbols to specify the output
  • For example:
  • import java.text.*;
    
    public class FormattingDecimals {
        public static void main(String[] args) {
            // next statement creates the default format
            DecimalFormat num = new DecimalFormat("#.00");
    
            System.out.println(num.format(6.35));
            System.out.println(num.format(-18.4));
            System.out.println(num.format(124));
            System.out.println("------");
            System.out.println(num.format(6.35-18.4+124));
        }
    }
    
  • Output of program:
  • 6.35
    -18.40
    124.00
    ------
    111.95
    
  • Notice the string literal in the DecimalFormat statement
  • Used to specify the formatting of the numbers
  • Following table shows some of the symbols used in a format string
  • Symbol Meaning
    0 Digit
    # Digit, zero shows as absent
    . Decimal point
    - Minus sign
    , Grouping separator
    ; Separates positive and negative formats in the format string
    % Multiply by 100 and show as percentage

3.4.4: Summary

  • You can use the System.out object to print to the console
    • System.out.print() leaves the cursor positioned after the last character
    • System.out.println() positions the cursor on a new line
  • It is important to display program results attractively
  • Java provides some prefefined formats using the NumberFormat class
    • currency
    • percent
    • number
  • NumberFormat provides also two methods to control the number of digits to the right of the decimal
    • setMaximumFractionDigits
    • setMinimumFractionDigits
  • We can get more control over number formats using DecimalFormat
  • To do this, we use special symbols to specify the output

Exercise 3.4

Modify your code from the previous exercise to display exactly 2 decimal places on output.

Save your program along with this weeks exercises.

Wrap Up

Home | WebCT | Announcements | Schedule | Expectations | Course info
Help | FAQ's | HowTo's | Links

Last Updated: September 20 2004 @13:52:06