Decrement Operator
In java, there are two types of decrements operators
- Pre-Decrements b = --a;
- Post-Derement b = a--;
int a=10;
int b;
Expression initial value of a value of b after the completing expression final value of a
b = ++a 10 11 11
b = a++ 10 10 11
b = -- a 10 9 9
b = a-- 10 10 9
Rule 1.
We can apply increment & decrement operators only for variables but not for constant value.
If we are trying to apply for constant value then we will get Compile Time Error.
int a=10;
int b=++a;
System.out.println(y); output is 11
example 2:-
int x=10;
int y = ++ 10;
Compile Time Error : Unexpected Type
found: value
expected: variable
Rule 2.
For final variables, we can't apply increment & decrement operators.
If we are trying to apply for constant value then we will get Compile Time Error.
example:-
final int w=10;
w++;
System.out.println(w);
Compile Time Error :can not assign to final variable x
Rule 3.
Nesting (looping) fo increment and decrement operators not allowed .
If we are trying to apply for constant value then we will get Compile Time Error.
example:-
int c=10;
int d=++ (++c);
System.out.println(d);
Compile Time Error : Unexpected Type
found: value
expected: variable
Rule 4.
We can apply increment & decrement operator for every primitive type except boolean.
int w=10
w++;
System.out.println(w); Output 11
char ch='a';
ch++;
System.out.println(ch); Output b
System.out.println(ch); Output b
double d=10.5;
d++;
System.out.println(d); Output 11.5
System.out.println(d); Output 11.5
boolean b=true;
b++;
System.out.println(b);
Compile Time Error :can not apply to boolean
Rule5.
If we apply any arithmetic operator between two variables a & b then the result will be always
maximum(int ,type of a, type of b).
Arithmetic operators minimum value return is int type.
let's understand this with an example.
example 1.
byte a=10;
byte b=20;
byte c=a+b;
System.out.println(c);
Output is:-
Compile time error :possible loss of precision
found: int
required: byte
Explanation : Because arithmetic operators minimum type is int .The type of variable a is the byte, the type of variable b is byte but the minimum return type is int. now we are getting 10+20=30 which is int type and we are assigning the int value to byte (lower type) that's why we are getting Compile time error.
Now how to solve this problem?
We can Solve this problem by using type casting.
example 2:-
byte a=10;
byte b=20;
byte c=(byte) (a+b);
System.out.println(c);