Ad Home

Theme images by kelvinjay. Powered by Blogger.

Travel

Header Ads

Java

Selenium

UFT

Framework

General QA Concept

BDD

» » 4 Rules to Remember While Working With Incremental And Decremental Operator in Java

In java the '++' operator is called incremental and '--' operator is called decremental operator. Again Incremental can be divided
  • pre increment (y=++x)
  • Post increment (y=x++)
in pre increment the value of the variable is incremented first and then assign to y.

in post increment the value is assigned first then its value is incremented.
Similarly for decrement we have
  • pre decrement (y=--x)
  • post decrement (y=x--)
Now most importantly the rules are..
Increment and decrement operator can only be applied to variable but not for any constant values..

int x=10;
int y=++x;
System.out.println(y)

This code works fine but...
int x=10;
int y=++10;
System.out.println(y)

this code will throw an compile time error.
Error: Unexpected type
found: value
required:variable

Nesting of increment and decrement operator is not allowed in java
Let me give some piece of code..

int x=10;
int y=++(++x);
System.out.println(y);
This is also not accepted why?

well (++x)will execute perfectly and after that the equation becomes..
y=++11
violating the first rule...hence it will throw the same error.


Increment and decrement operator is not allowed for final variable in java
Check out here for importance of final variable .
for normal variable- this is valid
int x=6;
x++;
++x;
but if that is final variable...these expressions are invalid.
final int x=6;
x++;
++x;
It will throw an compile time error..


Increment and decrement operator can be applied to all primitive data types except Boolean in java
for int::
int x=6;
++x;
System.out.println(x);
output is 7

for char::
char ch ='c';
ch++;
System.out.println(ch);
output is 'd'


for double::
double d=12.5;
d++;
System.out.println(d);
output is 13.5

for Boolean::
Boolean b=true;
b++;
System.out.println(b);
output:
Compile time error
byteTest.java:6: incompatible types
found : boolean
required: java.lang.Boolean

operator ++ cannot be applied to java.lang.Boolean




That's all for today!!

«
Next
Newer Post
»
Previous
Older Post

No comments:

Leave a Reply