Site icon Narayana Tutorial

Arithmetic Operations

Arithmetic Operations

( +, -, *, /, % )

If we are performing any arithmetic operation between two variables a and b . The result is always type

max ( type of a, type of b, int)

Infinity

 In the case of integral arithmetic, there is no way to represent infinity. Hence division by zero is always Arithmetic Exception. In the case if integral Arithmetic.

s. o. p (10/10)==> int; ( A.E. division by zero)

But in the case of floating point Arithmetic there is always a way to represent infinity. Float and Double classes contain the following constants.

POSITIVE _ INFINITY

NEGATIVE _ INFINITY

Hence in floating point arithmetic division by zero won’t rise Arithmetic Exception.

s. o. p ( 10/ 0.0) ; ==> infinity

s. o. p ( 10/ 0.0 ) ; ==> -infinity

NaN (Not a Number)

If the result is undefined, in the case of integral Arithmetic, there is no way to represent, hence we will get Arithmetic Exception.

( s. o. p (0/0) ;  A.E )

But in the case of floating point Arithmetic, there is a way to represent undefined result for this float to double classes contain a constant NaN. In the case of undefined result, we won’t get any Arithmetic Exception, in the case of floating point Arithmetic.

s. o. p ( 0.0/ 0) Nan

s. o. p ( – 0.0/ 0) Nan

For any x value including NAN, all the below expression returns false

x > NaN

x < NaN

x >= NaN

x<= NaN

x == NaN

For any x value, the following expression return true.

x ! = NaN

Que;- which of the following expressions returns true ?

  1. float. NaN == float. NaN
  2. float. NaN ! == float. NaN
  3. x ! =float. NaN
  4. x> = float. Nan

Ans:- 2, 3.

Arithmetic Exception

It’s always a run time exception, it occurs only in integral, Arithmetic, but not in floating point Arithmetic.

The only operators which cause Arithmetic Exceptions are ‘/’, ‘%’.

String Concatenation Operation [‘+’]

The only over loaded operator in java is ‘+’ operate some times it acts as Arithmetic addition operation & sometimes it acts as String Concatenation Operator.

1). If at least one argument is string type, then ‘+’ operator acts as Concatenation & if both arguments are numbers then ‘+’ operator acts as Arithmetic Operation.

                        int a = 10, b =20, c =30 ;

                        string d = ‘narayanatutorial’ ;

Relational Operators

Relational  operators ‘ >, >=, <, <= ‘

We have to apply these relational operators only for primitive data types except boolean.

Shortcuts

s.o.p –> System.out.println

A.E –>Arithmetic Exception