COSC 236

Lab 3

The goal of this lab is to get used with the basic elements in Java discussed in Lecture #3 (primitive data types and expressions). Take a look at the examples and the sample programs in the lecture notes and try to apply the same concepts and style when writing your own programs. You will write 3 programs, given below.
NOTE: Before the lab, read and complete the material related to Integer Overflow.


1.  Write a Java program to find the perimeter and area of a rectangular field, given its length and width in yards.

      1. Declare variables for length, width, perimeter and area. Use the naming conventions discussed in class.
      2. Initialize the length and width with some particular values (like 12.25 and 5.82)
      3. For finding the perimeter of the rectangle  use the formula: perimeter = 2 * (length + width)
      4. For finding the area of the rectangle use the formula:   area = length * width
      5. Show the output in the following format:

The perimeter of the rectangle with the length = xx.xx yards and the width = xx.xx yards is xx.xx yards.
The area of the rectangle with the length = xx.xx yards and the width = xx.xx yards is xx.xx square yards.

      1. Test your program for different values of length and width.

2.  Write a Java program that computes the size of a pizza and determines its price per square inch, given its diameter and price.

1.     Declare a class named constant (PI)  for  p= 3.14159265.

2.     Declare variables for diameter, price, size and price per square inch. Use the naming conventions discussed in class.

3.     Initialize the diameter and price with some particular values (like 12 and 6.99)

4.     For finding the size of  the pizza  use the formula:  size = (p * diameter2) / 4

5.     For finding the price per square inch use the formula:   price_sq_inch = price / size

6.     Show the output in the following format:

The size of the pizza with a diameter of xx inches is xx.xx square inches.
The price per square inch for the same pizza is $xx.xx.

7.     Test your program for different values of diameter and price.


3.  Simple math operations: Write a Java program that outputs the result of the modulus and division operations, like in the output sample listed below:

First number is 23. Second number is 5.
23 modulo 5 equals 3
23 divided by 5 using integer division equals 4
23 divided by 5 using floating-point division equals 4.60

NOTE: Use type casting to get different results for the integer and floating-point division. Test your program for different values for first and second numbers.



Integer Overflow - “You can't count that high!”

Background

Summary: Integer values that are too large or too small may fall outside the allowable bounds for their data type, leading to unpredictable problems that can both reduce the robustness of your code and lead to potential security problems.

Description:  The value of each integer variable is stored in a block of memory of a fixed size (typically 4 bytes for an integer).  If a program attempts to assign a value that is either too large or too small to an integer variable, there won't be enough room to hold it.  When this happens, you may not have any idea what the value of that variable might be, but it almost always won't be what you want.

Risk: An integer overflow may be exploited to cause a program crash, lead to incorrect behavior, or present opportunities for malicious software to run code that could do bad things to your computer.

Examples of Occurrences

1. Many UNIX operating systems store time values in 32-bit signed (positive or negative) integers, counting the number of seconds since midnight on January 1, 1970. On Tuesday, January 19, 2038, this value will overflow, becoming a negative number.  Although the impact of this problem in 2038 is not yet known, there are concerns that software that projects out to future dates - including tools for mortgage payment and retirement fund distribution - might face problems long before then. Source: “Year 2038 Problem” http://en.wikipedia.org/wiki/Year_2038_problem
2. On December 25, 2004, Comair halted all operations and grounded 1,100 flights after a crash of its flight crew scheduling software. The number of monthly changes was stored in a 16-bit integer (which had a maximum value of 32,768). A series of storms in early December caused the crew reassignments to exceed this number.

How can you avoid integer overflow?

1) Choose your data types carefully: Choose your data types to be large enough to hold the values you will be working with. If there's any doubt at all as to whether your variable will have values that are too large for a short, use an int. If an int might be too small, use a long.
2) Validate your input for ranges and reasonableness. Check input is valid and reasonable before conducting operations.
3) Check for possible overflows. Always check results of arithmetic operations, to be sure that an overflow has not occurred. The result of multiplying two positive integers should be at least as big as both of those integers, etc. If you find a result that overflows, you can take appropriate action before the result is used. This might mean reporting an exception, stopping the program, or repeating a request for input.

Problem

Run and analyze the following Java program:

public class Lab3_PrintLimits {
    public static void main(String args[]) {
        int x, y, z;
        System.out.println("Min byte value   = " + Byte.MIN_VALUE);
        System.out.println("Max byte value   = " + Byte.MAX_VALUE);
        System.out.println("Min short value  = " + Short.MIN_VALUE);
        System.out.println("Max short value  = " + Short.MAX_VALUE);
        System.out.println("Min int value    = " + Integer.MIN_VALUE);
        System.out.println("Max int value    = " + Integer.MAX_VALUE);
        System.out.println("Min long value   = " + Long.MIN_VALUE);
        System.out.println("Max long value   = " + Long.MAX_VALUE);
        System.out.println("Min float value  = " + Float.MIN_VALUE);
        System.out.println("Max float value  = " + Float.MAX_VALUE);
        System.out.println("Min double value = " + Double.MIN_VALUE);
        System.out.println("Max double value = " + Double.MAX_VALUE);

        System.out.println("\nInteger overflow and integer errors examples: ");
        x = Integer.MAX_VALUE;
        System.out.println("Initialized variable x with MAX_VALUE. x = " + x);
        y = x + 1;
        System.out.println("Assigned to y the value x + 1 and got y = " + y + " --- Is this correct? ---");
        x = Integer.MIN_VALUE;
        System.out.println("Initialized variable x with MIN_VALUE. x = " + x);
        y = x - 1;
        System.out.println("Assigned to y the value x - 1 and got y = " + y + " --- Is this correct? ---");
        z = x * y;
        System.out.println("Initialized variable z with x * y and got z = " + z + " --- Is this correct? ---");
        y = 0;
        z = x / y;
    }
}

Questions:

1. Did integer overflow occur in this program? If yes, how?
2. What happened when an integer overflow occurred?
3. Did integer overflow generate compiling or runtime errors?
4. Why is multiplication particularly a risk for integer overflow?
5. Think about possible problems with the division and modulo operators.
6. Check the error message. Why did you get a runtime error in this program?


Notes:
A.  The lab will NOT be graded, do NOT hand anything in to the instructor.
B.  The lab should be completed by the start of the next scheduled lab class. Save the .java files on your disk and e-mail them (attachments) to Vishal Patel at vpatel12@students.towson.edu

Very important:  Make sure that you have COSC 236, your section, your name, and Lab#3 in the Subject box of your e-mail.
C.  In case you have any problems, contact the TA or the instructor for assistance.