Basic arithmetic

From Wikibooks, open books for an open world
Jump to: navigation, search

Arrays Java Programming
Basic arithmetic
Mathematical functions
Navigate Language Fundamentals topic: v  d  e )

[edit] Using arithmetic within Java

In order to do arithmetic in Java, one must first declare at least one variable. Typically one declares a variable and assigns it a value before any arithmetic is done. Here's an example of declaring an integer variable:


Computer code
int x = 5;


After creating a variable, one can manipulate its value by using Java's operators (the examples use our previously declared x variable):

Operator Function Value of
x before
Example
input
Example
output
Value of
x after
+ Addition 5 x + 2 7 5
- Subtraction 5 x - 4 1 5
* Multiplication 5 x*3 15 5
/ (Integer) Division 5 x/2 2 5
 % Modulo (Remainder) 5 x%2 1 5
++ Pre- & postincrement by one 5 ++x 6 6
-- Pre- & postdecrement by one 5 --x 4 4

The division operator rounds towards zero: 5/2 is 2, and -5/2 is -2. The remainder operator has the same sign as the left operand; it is defined such that ((a/b)*b) + (a%b) is always equal to a. The preincrement, predecrement, postincrement, and postdecrement operators are special: they also change the value of the variable, by adding or subtracting one. The only difference is that preincrement/decrement returns the new value of the variable; postincrement returns the original value of the variable. So if we executed


Computer code
int x1 = 7;
int y1 = 2*++x1;

int x2 = 7;
int y2 = 2*x2++;


both x1 and x2 would be 8, but y1 would be 16 and y2 would be 14. y1 was calculated using the incremented value of x1, and y2 was calculated using the original value of x2. All increment/decrement operators can be used alone to add or subtract 1 from a variable. For example one can write just x++; or ++x; to add 1 to x.

Note that by inserting these example statements into Java source code, no output would be produced. To print the results of a math operation, you would use:


Computer code
System.out.println(x + 2);


When using several operators in the same expression, one must consider Java's order of precedence. Java uses the standard PEMDAS (Parenthesis, Exponents, Multiplication and Division, Addition and Subtraction) order. When there are multiple instances of the same precedence, Java reads from left to right. Consider what the output of the following code would be:


Computer code
System.out.println(10*5 + 100/10 - 5 + 7%2);


The following chart shows how Java would compute this expression:


Figure 1: Computation of an arithmetic expression in the Java programming language
Java Computation of Arithmetic Expression.svg


The output would be "56".

Besides performing mathematical functions, there are also operators to assign numbers to variables (each example again uses the variable initialized as x = 5):

Operator Function Example
input
Example
output
= Assignment x = 3 3
+= Assign x plus another integer to itself x += 5 10
-= Assign x minus another integer to itself x -= 4 1
*= Assign x multiplied by another integer to itself x *= 6 30
/= Assign x divided by another integer to itself x /= 5 1

A third kind of operator does not return or assign numbers. The following are Java's evaluation operators, which either return "true" or "false.":

Operator Function Example
input
Example
output
< Less than x < 7 true
> Greater than x > 5 false
<= Less than or equal to x <= 5 true
>= Greater than or equal to x >= 1 true
== Equal to x == 5 true
 != Not equal to x != 5 false

These statements come in handy when using if-else, statements and for and while loops. What would the output of the following code be?


Computer code
public class Test {
   public static void main(String[] args) {
     int x = 4;
     int y = 4;
     int z = 6;
     x++;
     y *= 2;
     z += x;
     if (x <= y) {
       System.out.println("x is less than or equal to y.");
     }
     if (z <= y) {
       System.out.println("z is less than y.");
     }
     if (x != z) {
       System.out.println("x is not equal to z.");
     }
   }
 }


This code would print:

x is less than or equal to y.
x is not equal to z

[edit] Using bitwise operators within Java

Java has besides arithmetic operators a set of bit operators to manipulate the bits in a number, and a set of logical operators. The bitwise logical operators are

Operator Function Value of
x before
Example
input
Example
output
Value of
x after
& Bitwise AND 7 x&27 3 7
| Bitwise OR 7 x|27 31 7
^ Bitwise XOR 7 x^27 28 7
~ Bitwise inversion 7 ~x -8 7

Besides these logical bitwise functions, there are also operators to assign numbers to variables (x = -5):

Operator Function Example
input
Example output
&= Assign x bitwisely ANDed with another value to itself x &= 3 3
|= Assign x bitwisely ORed with another value to itself x |= 3 -5
^= Assign x bitwisely XORed with another value to itself x ^= 3 -8
<<= Assign x divided by another integer to itself x <<= 1 -10
>>= Assign x bitwisely negated with another value to itself x >>= 1 -3
>>>= Assign x bitwisely negated with another value to itself x >>>= 1 2,305,843,009,213,693,949 (64 bit)

The shift operators are used to shift the bits to the left or right, which is also a quick way to multiply/divide by two:

Operator Function Value of
x before
Example
input
Example output Value of
x after
<< Logical shift left -15 x << 2 -120 -15
>> Arithmetic shift right -15 x >> 3 -2 -15
>>> Logical shift right -15 x >>> 3 2,305,843,009,213,693,937 (64 bit) -15


Arrays Java Programming
Basic arithmetic
Mathematical functions
Personal tools
Namespaces

Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export