Java Prececedence Operators
Java Prececedence Operators
G IN JAVA
PRECEDENCE RULES AND ASSOCIATIVITY
Precedence Rules and Associativity
Precedence rules are used to determine the order of
evaluation priority in case there are two operators with
different precedence.
Associativity rules are used to determine the order of
evaluation if the precedence of operators is same.
Associativity Types
Associativity is of two types: Left and Right.
Left associativity means operators are evaluated from left to
right and vice versa for right associativity.
Precedence and associativity can be overridden with the help
of parentheses.
Here L-> R indicates associativity from left to right and R->L
indicates associativity from right to left.
Operator Description Precedence Associativity
Multiplication,
*, /,%,+, - 12 Left to Right
Division, Modulus
𝑎𝑛𝑠=𝑥+(−−𝑦)−(++𝑏)
Primitive Type Conversion and Casting
In Java, type conversions are performed automatically when
the type of the expression on the right-hand-side of an
assignment operation can be safely promoted to the type of the
variable on the left-hand-side of the assignment.
Widening conversions
Conversions that are implicit in nature are termed as widening
conversions.
Widening is the conversion of a smaller data type into a larger
one. This type of casting is done automatically by Java and
does not require any explicit syntax.
Example:
byte b = 10; // byte variable
int i = b; // implicit widening byte to int
Widening conversions
Type conversion or promotion also takes place while
evaluating the expressions involving arithmetic operators.
Example:
int i = 10; //int variable
double d = 20; //int literal assigned to a double variable
d = i + d; //automatic conversion int to double
Widening conversions
public static void main(String[] args)
{
byte a=70;
short b=a;
int c=a;
long d=a;
float e=a;
double f=a;
System.out.println(a+" is of byte datatype"); System.out.println(b+"
is of short datatype"); System.out.println(c+" is of int datatype");
System.out.println(d+" is of long datatype"); System.out.println(e+"
is of float datatype"); System.out.println(f+" is of double datatype");
}
Widening conversions
Primitive Type Casting
Type Casting is not implicit in nature.
It has to be explicitly mentioned by preceding it with the
destination type specified in the parentheses.
For instance, int i = (int)(8.0/3.0);
Casting is also known as narrowing conversion
(reverse of widening conversion).
Narrowing conversions
Narrowing is the conversion of a larger data type into
a smaller one.
Unlike widening, this type of casting requires explicit syntax.
Narrowing conversions