Arithmetic Operators Core Java

The usual arithmetic operators + – * / are used in Java for addition, subtraction, multiplication,and division. The / operator denotes integer division if both arguments areintegers, and floating -point division otherwise. Integer remainder (sometimes calledmodulus) is denoted by %. For example, 15 / 2 is 7, 15 % 2 is 1, and 15.0 / 2 is 7.5.

Note that integer division by 0 raises an exception, whereas floating-point divisionby 0 yields an infinite or NaN result.

There is a convenient shortcut for using binary arithmetic operators in an assignment.
For example,
x += 4;
is equivalent to
x = x + 4;
(In general, place the operator to the left of the = sign, such as *= or %=.)

NOTE: One of the stated goals of the Java programming language is portability. A computationshould yield the same results no matter which virtual machine executes it. For arithmeticcomputations with floating -point numbers, it is surprisingly difficult to achieve this portability. The double type uses 64 bits to store a numeric value, but some processors use80-bit floating-point registers. These registers yield added precision in intermediate steps of a computation. For example, consider the following computation:

Many Intel processors compute x * y and leave the result in an 80-bit register, then divide byz, and finally truncate the result back to 64 bits. That can yield a more accurate result, and itcan avoid exponent overflow. But the result may be different than a computation that uses64 bits throughout. For that reason, the initial specification of the Java virtual machine mandatedthat all intermediate computations must be truncated. The numeric community hatedit. Not only can the truncated computations cause overflow, they are actually slower than themore precise computations because the truncation operations take time. For that reason,the Java programming language was updated to recognize the conflicting demands for optimumperformance and perfect reproducibility. By default, virtual machine designers are nowpermitted to use extended precision for intermediate computations. However, methodstagged with the strictfp keyword must use strict floating-point operations that yield reproducible results. For example, you can tag main as
public static strictfp void main(String[] args)

Then all instructions inside the main method use strict floating-point computations. If you taga class as strictfp, then all of its methods use strict floating -point computations.

The gory details are very much tied to the behavior of the Intel processors. In default mode,intermediate results are allowed to use an extended exponent, but not an extended mantissa.(The Intel chips support truncation of the mantissa without loss of performance.) Therefore,the only difference between default and strict mode is that strict computations may overflowwhen default computations don’t.

If your eyes glazed over when reading this note, don’t worry. Floating-point overflow isn’t aproblem that one encounters for most common programs.

Increment and Decrement Operators

Programmers, of course, know that one of the most common operations with a numericvariable is to add or subtract 1. Java, following in the footsteps of C and C++, has bothincrement and decrement operators: n++ adds 1 to the current value of the variable n, andn-- subtracts 1 from it. For example, the code

changes n to 13. Because these operators change the value of a variable, they cannot beapplied to numbers themselves. For example, 4++ is not a legal statement.

There are actually two forms of these operators; you have seen the “postfix” form of theoperator that is placed after the operand. There is also a prefix form, ++n. Both change thevalue of the variable by 1. The difference between the two only appears when they areused inside expressions. The prefix form does the addition first; the postfix form evaluatesto the old value of the variable.

We recommend against using ++ inside other expressions because this often leads to confusingcode and annoying bugs.

(Of course, while it is true that the ++ operator gives the C++ language its name, it alsoled to the first joke about the language. C++ haters point out that even the name of thelanguage contains a bug: “After all, it should really be called ++C, because we onlywant to use a language after it has been improved.”)

Relational and boolean Operators

Java has the full complement of relational operators. To test for equality you use a doubleequal sign, ==. For example, the value of
3 == 7
is false.
Use a != for inequality. For example, the value of
3 != 7
is true.

Finally, you have the usual <(less than), >(greater than), <= (less than or equal), and >=(greater than or equal) operators.

Java, following C++, uses &&for the logical “and” operator and || for the logical “or”operator. As you can easily remember from the != operator, the exclamation point ! is thelogical negation operator. The &&and || operators are evaluated in “short circuit” fashion.The second argument is not evaluated if the first argument already determines the value. If you combine two expressions with the &&operator,
expression1 &&expression2
and the truth value of the first expression has been determined to be false, then it isimpossible for the result to be true. Thus, the value for the second expression is notcalculated. This behavior can be exploited to avoid errors. For example, in thee xpressionx != 0 && 1 / x > x + y // no division by 0the second part is never evaluated if x equals zero. Thus, 1 / x is not computed if x iszero, and no divide-by-zero error can occur.

Similarly, the value of expression1 || expression2 is automatically true if the first expressionis true, without evaluation of the second expression.

Finally, Java supports the ternary ?: operator that is occasionally useful. The expression
condition ? expression1 : expression2
evaluates to the first expression if the condition is true, to the second expression otherwise. For example,
x < y ? x : y
gives the smaller of x and y.

Bitwise Operators

When working with any of the integer types, you have operators that can workdirectly with the bits that make up the integers. This means that you can use masking techniques to get at individual bits in a number. The bitwise operators are
&(“and”) | (“or”) ^ (“xor”) ~ (“not”)
These operators work on bit patterns. For example, if n is an integer variable, then
int fourthBitFromRight = (n & 8)/ 8;

gives you a 1 if the fourth bit from the right in the binary representation of n is 1, and 0 ifnot. Using &with the appropriate power of 2 lets you mask out all but a single bit.

NOTE: When applied to boolean values, the &and | operators yield a boolean value. These operators are similar to the &&and || operators, except that the &and | operators are notevaluated in “short circuit” fashion. That is, both arguments are first evaluated before theresult is computed.

There are also >>and <<operators, which shift a bit pattern to the right or left. These operators are often convenient when you need to build up bit patterns to do bitmasking:
int fourthBitFromRight = (n & (1 << 3)) >> 3;

Finally, a >>>operator fills the top bits with zero, whereas >>extends the sign bit into thetop bits. There is no <<<operator.

CAUTION: The right-hand side argument of the shift operators is reduced modulo 32(unless the left-hand side is a long, in which case the right-hand side is reduced modulo 64).For example, the value of 1 << 35 is the same as 1 << 3 or 8.

C++ NOTE: In C/C++, there is no guarantee as to whether >> performs an arithmetic shift(extending the sign bit) or a logical shift (filling in with zeroes). Implementors are free tochoose whatever is more efficient. That means the C/C++ >> operator is really only defined for non -negative numbers. Java removes that ambiguity.

Mathematical Functions and Constants

The Math class contains an assortment of mathematical functions that you may occasionallyneed, depending on the kind of programming that you do.

To take the square root of a number, you use the sqrt method:

NOTE: There is a subtle difference between the println method and the sqrt method. Theprintln method operates on an object, System.out, defined in the System class. But the sqrt method in the Math class does not operate on any object. Such a method is called a static method.

The Java programming language has no operator for raising a quantity to a power: Youmust use the pow method in the Math class. The statement
double y = Math.pow(x, a);

sets y to be x raised to the power a (xa). The pow method has parameters that are both oftype double, and it returns a double as well.

The Math class supplies the usual trigonometric functions
and the exponential function and its inverse, the natural log:
Finally, two constants denote the closest possible approximations to the mathematical constants ð and e:

TIP: Starting with Java SE 5.0, you can avoid the Math prefix for the mathematical methodsand constants by adding the following line to the top of your source file:
import static java.lang.Math.*;
For example:

NOTE: The functions in the Math class use the routines in the computer’s floating -pointunit for fastest performance. If completely predictable results are more important thanfast performance, use the StrictMath class instead. It implements the algorithms from the“Freely Distributable Math Library” fdlibm, guaranteeing identical results on all platforms.

Conversions between Numeric Types

It is often necessary to convert from one numeric type to another.

Legal conversions between numeric types

Legal conversions between numeric types

The six solid arrows in figure below denote conversions without information loss. Thethree dotted arrows denote conversions that may lose precision. For example, a largeinteger such as 123456789 has more digits than the float type can represent. When the integer is converted to a float, the resulting value has the correct magnitude but it loses some precision.
int n = 123456789;
float f = n; // f is 1.23456792E8

When two values with a binary operator (such as n + f where n is an integer and f is a floating-point value) are combined, both operands are converted to a common type before the operation is carried out.

  • If either of the operands is of type double, the other one will be converted to a double.
  • Otherwise, if either of the operands is of type float, the other one will be converted to a float.
  • Otherwise, if either of the operands is of type long, the other one will be converted to a long.
  • Otherwise, both operands will be converted to an int.


In the preceding section, you saw that int values are automatically converted to double values when necessary. On the other hand, there are obviously times when you want toconsider a double as an integer. Numeric conversions are possible in Java, but of course information may be lost. Conversions in which loss of information is possible are doneby means of casts. The syntax for casting is to give the target type in parentheses, followedby the variable name. For example
double x = 9.997;
int nx = (int) x;
Then, the variable nx has the value 9 because casting a floating-point value to an integer discards the fractional part.

If you want to round a floating-point number to the nearest integer (which is the more useful operation in most cases), use the Math.round method:
double x = 9.997;
int nx = (int) Math.round(x);

Now the variable nx has the value 10. You still need to use the cast (int) when you call round. The reason is that the return value of the round method is a long, and a longcan only be assigned to an int with an explicit cast because there is the possibility of information loss.

CAUTION: If you try to cast a number of one type to another that is out of the range for the target type, the result will be a truncated number that has a different value. For example, (byte) 300 is actually 44.

C++ NOTE: You cannot cast between boolean values and any numeric type. This convention prevents common errors. In the rare case that you want to convert a boolean value to a number, you can use a conditional expression such as b ? 1 : 0.

Parentheses and Operator Hierarchy

Table below shows the precedence of operators. If no parenthesesare used, operations are performed in the hierarchical order indicated. Operators on thesame level are processed from left to right, except for those that are right associative, asindicated in the table. For example, because &&has a higher precedence than ||, the
a && b || c
(a && b) || c
Because += associates right to left, the expression
a += b += c
a += (b += c)
That is, the value of b += c (which is the value of b after the addition) is added to a.

Operator Precedence

Operator Precedence

C++ NOTE: Unlike C or C++, Java does not have a comma operator. However, you can usea comma-separated list of expressions in the first and third slot of a for statement.

Enumerated Types

Sometimes, a variable should only hold a restricted set of values. For example, you maysell clothes or pizza in four sizes: small, medium, large, and extra large. Of course, youcould encode these sizes as integers 1, 2, 3, 4, or characters S, M, L, and X. But that is anerror -prone setup. It is too easy for a variable to hold a wrong value (such as 0 or m).

Starting with Java SE 5.0, you can define your own enumerated type whenever such a situationarises. An enumerated type has a finite number of named values. For example:
Now you can declare variables of this type:
Size s = Size.MEDIUM;

A variable of type Size can hold only one of the values listed in the type declaration orthe special value null that indicates that the variable is not set to any value at all.

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Topics