|
|
|
1000 Java Tips ebook
|
|
 

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!. |
|
Easy Learn Java: Programming Articles, Examples and Tips - Page 172
Previous
1060 Stories (530 Pages, 2 Per Page)
Next
The Java Lesson 5: Arithmetic operations, conversions, and casts
|
The Java Lesson 5
Arithmetic operations, conversions, and casts
Basic arithmetic operations
-
Involve two "operands" that
must be numeric primitive values (non-boolean). Because char data has a positive integer equivalent, it may be used in
arithmetic operations.
-
Appear in expressions. The
calculated result of the expression is often assigned to a variable according
to the following general syntax:
identifier = expression;
-
Five arithmetic operations are
part of the Java language. Other useful arithmetic operations, such as
exponentiation and trigonometric functions, are provided as packaged code in
the Math class and will
be covered later.
| Operator |
Operation |
| + |
Addition |
| - |
Subtraction |
| * |
Multiplication |
| / |
Division |
| % |
Modulo
(remainder) |
Addition, subtraction, and multiplication
Example: This program reads two
integer values from the user. It then displays the sum, difference, and
product of the two numbers.
public class App { public static void
main(String[] args) {
// Variables for holding two
integer values entered by the user
int
x; int y;
// Prompt for and
read the two integer values
System.out.print("First integer: "); x =
Keyboard.readInt(); System.out.print("Second integer:
"); y = Keyboard.readInt();
// Display the sum, difference, and product of the two
integers
System.out.println("
" + x + " + " + y
+ " = " + (x + y)); System.out.println(" " + x + " -
" + y + " = " + (x - y)); System.out.println(" " + x
+ " * " + y + " = " + (x * y)); } }
Notes:
-
This sample reads data from
the keyboard, which isn't easy in Java. My custom Keyboard class makes it easier. For
information on using the class, click here.
-
The prompt messages use the
print() method
instead of println().
They are virtually the same except that print() leaves the insert point at the end of
the current line so that the user's entry will appear on the same line as
the prompt.
Example: This program results
in an overflow and displays an erroneous sum.
public class App { public static void
main(String[] args) {
// Two extremely large
integer values
int x = 2000000000; // 2
billion. int y = 1000000000; // 1
billion.
// Display an erroneous sum due to
overflow
System.out.println("The erroneous sum is
" + (x + y)); } }
Division
-
When both operands are
integers, the result is the integer quotient obtained by dividing the first
operand (the dividend) by the second operand (the divisor)
-
The sign of the result is
determined by the rules of algebra
-
When both operands are integers
and the second operand is zero, a run time exception occurs
Example: The following program
reads two integer values from the user and displays the result of dividing the
first number by the second number. If the user enters 0 for the second number,
a runtime exception will occur.
public class App { public static void
main(String[] args) {
// Variables for holding two
integer values entered by the user
int
x; int y;
// Prompt for and
read the two integer values
System.out.print("First integer (dividend): "); x =
Keyboard.readInt(); System.out.print("Second integer
(divisor): "); y =
Keyboard.readInt();
// Calculate and display the
integer quotient
System.out.println("
" + x + "
/ " + y + " = " + (x / y)); } }
Note: When testing this code,
be sure to try division by zero.
public class App { public static void
main(String[] args) {
System.out.println(2.1/.7);
} }
Example: This program reads two
floating-point values from the user. It then displays the result of dividing
the first number by the second number. If the user enters 0 for the second
number, a result of + infinity will occur.
public class App { public static void
main(String[] args) {
// Variables for holding two
floating-point values entered by the user
double
x; double y;
// Prompt for
and read the two floating-point values
System.out.print("First floating-point number (dividend):
"); x = Keyboard.readDouble();
System.out.print("Second floating-point number (divisor):
"); y =
Keyboard.readDouble();
// Calculate and display
the result
System.out.println("
" + x + " / " +
y + " = " + (x / y)); } }
Note: When testing this code,
be sure to try division by zero.
Modulo (remainder)
-
When both operands are
integers, the result is the integer remainder obtained by dividing the first
operand by the second operand.
-
The sign of the result is the
same as the sign of the first operand.
-
When both operands are integers
and the second operand is zero, a run time exception occurs
Example: This program reads two
integer values from the user. It then displays the remainder that results from
dividing the first number by the second number. If the user enters 0 for the
second number, a runtime exception will occur.
public class App { public static void
main(String[] args) {
// Variables for holding two
integer values entered by the user
int
x; int y;
// Prompt for and
read the two integer values
System.out.print("First integer (dividend): "); x =
Keyboard.readInt(); System.out.print("Second integer
(divisor): "); y =
Keyboard.readInt();
// Calculate and display the
integer remainder
System.out.println("
" + x +
" modulo " + y + " = " + (x % y)); } }
Note: When testing this code,
try different integer values with different signs. Also try a second operand
of zero.
2.2 % .7 results in 0.10000000000000031
This is obtained by subtracting
.7 from 2.2 until the result is less than .7
-
The sign of the result is
the same as the sign of the first operand
-
When either number is
floating-point, division by zero is allowed. The result will be NaN (meaning Not a Number).
Example: This program reads two
floating-point values from the user. It then displays the remainder that
results from dividing the first number by the second number.
public class App { public static void
main(String[] args) {
// Variables for holding two
floating-point values entered by the user
double
x; double y;
// Prompt for
and read the two floating-point values
System.out.print("First floating-point number (dividend):
"); x = Keyboard.readDouble();
System.out.print("Second floating-point number (divisor):
"); y =
Keyboard.readDouble();
// Calculate and display
the floating-point remainder
System.out.println("
" + x + " modulo " + y + " = " + (x % y));
} }
Note: When testing this code,
try different floating-point values with different signs. Also try a second
operand of zero.
Arithmetic assignment operations
| Operator |
Operation |
| += |
Addition assignment |
| -= |
Subtraction assignment |
| *= |
Multiplication assignment |
| /= |
Division assignment |
| %= |
Modulo (remainder)
assignment |
Example: This program reads a percentage value from the
user (such as 5.5) and converts to the
correct decimal equivalent (such as 0.055) by using the division assignment operator.
public class App
{ public static void main(String[] args)
{
// Variable for holding a percentage entered by
the user
double percent;
// Prompt for and read the percentage
System.out.print("Enter a percentage in n.nn format:
"); percent =
Keyboard.readDouble();
// Convert it to its
decimal equivalent and display the result
percent
/= 100; System.out.println("The decimal equivalent is
" + percent); } }
Note: The arithmetic
assignment operators always result in the first operand (the one on the
left) being modified.
Increment and decrement operations
| Operator |
Operation |
| ++ |
Increment (add one) |
| -- |
Decrement (subtract
one) |
-
Can be placed on the left or right of a numeric variable.
On the left, the increment or decrement occurs before the expression is
evaluated. On the right, the increment or decrement occurs after the
expression has been evaluated.
Example: The following program reads two integer values
from the user. It increments the first value and decrements the second.
public class App
{ public static void main(String[] args)
{
// Variables for holding two integer values to
be entered by the user
int
x; int y;
// Prompt for and
read the two values
System.out.print("Enter an
integer to be incremented: "); x =
Keyboard.readInt(); System.out.print("Enter an integer
to be decremented: "); y =
Keyboard.readInt();
// Perform the increment and
decrement and display the results
x++; System.out.println("The new values are " + x + "
and " + --y); } }
Note: It is best to use a
stand-alone statement when using the ++ or --
operators. It makes your code easier to read.
Conversions
The order of conversion (from
narrowest to widest) is as follows. Memorize this
table!
| byte |
|
|
| | |
|
|
| short |
|
char |
|
|
|
/ |
|
int |
|
|
| |
|
|
long |
|
|
| |
|
|
float |
|
|
| |
|
|
double |
|
- The data type resulting from an expression is that of the largest or most
precise variable or constant appearing in the expression but is never smaller
than int. Programmers
that fail to understand this are constantly plagued by compile errors.
Example: This program to convert a fahrenheit temperature
to celsius will NOT compile.
public class App
{ public static void main(String[] args)
{
// Variables for holding fahrenheit and celsius
temperatures
double tempF;
float tempC;
// Prompt for and read the fahrenheit
temperature
System.out.print("Enter the fahrenheit
temperature (nn.n): "); tempF =
Keyboard.readDouble();
// Convert to celsius and
display the result
tempC = 5 * (tempF - 32) /
9; System.out.println("Celsius equivalent is " +
tempC); } }
Note: To fix the compile
error in this code, tempC must be double or tempF must be float. Alternatively, the result of the expression can be
"cast" as float (the
next topic).
Casts
-
Are a programmer's way of
telling the compiler to ignore possible loss of data or precision that might
result from a conversion
-
Should be used with caution.
Data loss is not to be taken lightly. The general syntax is
identifier = (data-type)
expression;
Example: This is a corrected version of the previous
program that uses a cast to prevent the compile error.
public class App
{ public static void main(String[] args)
{
// Variables for holding fahrenheit and celsius
temperatures
double tempF;
float tempC;
// Prompt for and read the fahrenheit
temperature
System.out.print("Enter the fahrenheit
temperature (nn.n): "); tempF =
Keyboard.readDouble();
// Convert to celsius and
display the result
tempC = (float) (5 * (tempF - 32) / 9); System.out.println("Celsius equivalent is " +
tempC); } }
Note: The result of the
entire expression is double but is cast as float in order to be assigned to the float variable. The additional set of
parenthesis are coded around the entire expression to prevent only the
integer literal 5 from being cast.
Some thoughts on arithmetic
expressions
Arithmetic expressions can be
large and complex with several variables, constants, and operators. The order in
which operations are performed is the same as in mathematics (multiplication and
division first, then addition and subtraction, working from left to right). To
avoid confusion, good programmers keep their expressions as simple as possible
and use parenthesis for clarity.
Review questions
-
Which of the following will
add one to the value of the numeric variable someNumber? (choose four)
-
someNumber += 1;
-
otherNumber = someNumber + 1;
-
someNumber = someNumber + 1;
-
++someNumber;
-
someNumber++;
-
After execution of the code
fragment below, what are the values of variables x, y, and z?
int x, y = 6, z = 7; x = --y * z++;
-
x = 35, y = 5, z = 8
-
x = 42, y = 5, z = 8
-
x = 35, y = 6, z = 7
-
x = 42, y = 6, z = 7
-
x = 48, y = 5, z = 8
-
What will happen if an
attempt is made to compile and execute the following code? You may assume the
statements are within a valid main method of a valid application class and
that the line numbers are for reference purposes only.
1 2 3 4 |
short a =
5; byte b = 2; short c = a - b; System.out.println("The
difference is " + c); |
-
the program will compile
and run to display "The difference is
3"
-
the program will compile
and run to display "The difference is
c"
-
the program will compile
but an error will occur at run time
-
a compile error will occur
at line 3
-
a compile error will occur
at line 4
-
What data type and value
will result from evaluating the following expression?
(5.0 - 20) % 7
-
an int with the value -1
-
a double with the value 1.0
-
a double with the value -1.0
-
a float with the value -0.1428571
-
a float with the value -1.0
31262 bytes more | 21 comments | | Score: 4.25
|
Posted by jalex on Wednesday, February 18, 2004 (00:00:00) (26821 reads)
|
|
|