Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

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"!.

The Java Lesson 5: Arithmetic operations, conversions, and casts

JavaFAQ Home » Java Lessons by Jon Huhtala Go to all tips in Java Lessons by Jon Huhtala


Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

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

  • Act as you would expect. They calculate the sum, difference, and product of two numeric operands.

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:

  1. 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.

  2. 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.

  • Overflow or underflow will result in an erroneous value if the calculation is mathematically too large or too small to be properly stored in memory

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.

  • When either operand is floating-point, a floating-point value will result that is an approximation. For example, the following program will give you a result other than the expected "3.0"

public class App {
public static void main(String[] args) {
System.out.println(2.1/.7);
}
}

  • When either number is floating-point, division by zero is allowed. The result will be + infinity.

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.

  • When either number is floating-point, the result is a floating-point approximation of the fractional value remaining after an integral number of subtractions. For example,

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

  • Combine arithmetic and assignment into a single operation to save coding time

  • All five basic arithmetic operations have a corresponding arithmetic assignment operator

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

  • Require only one operand. They are said to be "unary" operators.

  • Are the most efficient way to add or subtract one from a numeric variable

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

  • Are performed automatically when mixed numeric types appear within an expression. Variables and constants are not altered, but their values are copied to intermediate areas of larger size or precision to prevent possible data loss during the calculation. This is known as a "widening" conversion.

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

  1. Which of the following will add one to the value of the numeric variable someNumber? (choose four)

  1. someNumber += 1;

  2. otherNumber = someNumber + 1;

  3. someNumber = someNumber + 1;

  4. ++someNumber;

  5. someNumber++;

  1. 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++;

  1. x = 35, y = 5, z = 8

  2. x = 42, y = 5, z = 8

  3. x = 35, y = 6, z = 7

  4. x = 42, y = 6, z = 7

  5. x = 48, y = 5, z = 8

  1. 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);
  1. the program will compile and run to display "The difference is 3"

  2. the program will compile and run to display "The difference is c"

  3. the program will compile but an error will occur at run time

  4. a compile error will occur at line 3

  5. a compile error will occur at line 4

  1. What data type and value will result from evaluating the following expression?

(5.0 - 20) % 7

  1. an int with the value -1

  2. a double with the value 1.0

  3. a double with the value -1.0

  4. a float with the value -0.1428571

  5. a float with the value -1.0


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy