0

Watch out with Java unary operators

Posted by Guillermo GarcĂ­a on 7:15 PM in , ,
Everybody knows how to use arithmetics and logical operators ... It's simple: they are just operators. But what happens with the unary operators? they are easy to use, but if people don't know them, then people don't use it.

In Java, you can find five (5) unary operators:
  • Unary plus operator (+) which indicates a positive value. Example: int a = +1. This is the default behavior for a number in Java. Conclusion: pointless.
  • Unary minus operator (-) which indicates a negative value. Example int a = -1. This is the only way to set a negative value from scratch. Conclusion: naturally useful
  • Increment operator (++) which increases the value of the ''var'' by one (1). Example: ++a or a++. Tricky? not at all!! ... this can be very useful if you know how to use it. Conclusion: later in this post.
  • Decrement operator (--) which decreases the value of the ''var'' by one (1). Example --a or a--. Again? Yes, it has the same benefits. Conclusion: you'll see, trust me.
  • Logical complement operator (!) which inverts the value of a boolean expression. Example: !(true). This is a very important operator in any language. Conclusion: necessary.
So ... we have 5 unary operators, and usually Java newbies only use two. Why? one is pointless (+), but the others are unknown for the most of them.

I will try to fix this, telling you how to use correctly the incremental and decremental operator.

What are the differences between ++a and a++? The key word is "order". When you use the operator BEFORE the var (++a) the jvm (virtual machine) first increments the value of the var, and then returns it. Look this example code:

int a = 1;
System.out.println("Value of var a : "+ (++a));

What will you get on your screen? 1 or 2? The correct answer is 2! because the jvm first increment "a" in one(1) and then returns its value to the println() method.

Ok, and then what happens with a++? Take a look at this change from the previous example:

int a = 1;
System.out.println("Value of var a : "+ (a++));

And now? What will you get? 1 or 2? Obviously, you will get 1! because the jvm first returns the value, and then increments it by one(1)

This difference is very important, because its awareness could simplify yours loops, and many other iterations.

0 Comments

Copyright © 2009 ggarciao.com
- Cup of Java -
All rights reserved.