CS 1401 Homework #4

Date Assigned: Tuesday, February 8, 2005

Due Date: Thursday, February 10, 2005, before the beginning of your lecture section.

Goal: the goal of this assignment is to learn how to deal with numbers in Java.

Assignments:

1. What will be the result of the following expressions:

(a) 2/1/4

Answer: 

Java computations are left to right, so we first compute 2/1=2, then
2/4=0. The result is 0.

(b) 2.0/1.0/4.0

Answer:

First we compute 2.0/1.0=2.0, then 2.0/4.0=0.5.

(c) a++ (if a was originally 2)

Answer: 3

(d) --a (if a was originally 2)

Answer: 1

(e) 2%3%4

Answer:

First, we compute 2%3=2, then 2%4=2. The result is 2.

(f) -2.0%-0.9*-4.0

Answer:

First, we compute -2.0%-0.9=-0.2, then -0.2%-4.0=-0.2. The result is -0.2.

2. Let a be a variable of type int. Use type casting to assign a's value to the following variables:

(a) longA of type long

Answer:

longA = (long)a;
(b) doubleA of type double

Answer:

doubleA = (double)a;
(c) stringA of type string

Answer:

stringA = "" + a;

Comment: The book does not explicitly call this transformation 
type casting, so if you answered that type casting is not possible in
case (c), it is also a correct answer.
Explain in which of these three cases we can use type conversion instead of type casting.
Answer: type conversion is possible in the first two cases but not for 
conversion to a string.

If type conversion is possible, what is the advantage of type casting?
Answer: types casting make type transformation more explicit, 
thus clearer to readers of the code and less error-prone.