Header Ads

What Is The Difference Between ++x And x=x+1 or --x And x=x-1?

This is most interesting question is What Is the difference between ++x and x=x+1 while working with java.

both the statement does the same thing--increment the value of x by 1.
Then the doubts come
  • If both they do same thing why we will have two statements?
  • If they are different then how?
  • Which one is more efficient?
 Let us discuss the concept with some example..
public class operatortest {
 public static void main(String[] Args)
 {
 int x=4;
 ++x;
     System.out.println(x);
 }
 }

output->5
now if we change the statement like--
public class operatortest {
 public static void main(String[] Args)
 {
 int x=4;
 x=x=1;
     System.out.println(x);
 }
 }

output->5 only
Till now no problem if the datatypes are int/long/double
but say the datatype changes now..
instead of int if we use char/byte/short??
lets see...
public class operatortest {
 public static void main(String[] Args)
 {
 byte x=4;
 x=x=1;
     System.out.println(x);
 }
 }

very quickly we will get a compile time error..
if you are running through DOS prompt..
you can see compile error---possible loss of precision
public class operatortest {
 public static void main(String[] Args)
 {
        byte x=4;
 ++x;
     System.out.println(x);
 }
 }

output--5
So no problem with ++ operator.

So the answer of questions are even though we have x++ and x=x+1 statement, they have same pourpose. But in case of ++ or -- operator internal type casting is performed by the compiler,but in case of the normal operators developer need to do type casting explicitly. hence ++,-- operators are most efficient.
Powered by Blogger.