Programming Tutorials

The Unary Operators example in Java

By: Emiley J in Java Tutorials on 2007-10-13  

The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

+ 	Unary plus operator; indicates positive value (numbers are positive without this, however)
- 	Unary minus operator; negates an expression
++  	Increment operator; increments a value by 1
--    	Decrement operator; decrements a value by 1
!     	Logical complement operator; inverts the value of a boolean

The following program, UnaryDemo, tests the unary operators:

class UnaryDemo {

     public static void main(String[] args){
          int result = +1; // result is now 1
          System.out.println(result);
          result--;  // result is now 0
          System.out.println(result);
          result++; // result is now 1 
          System.out.println(result);
          result = -result; // result is now -1
          System.out.println(result);
          boolean success = false;
          System.out.println(success); // false
          System.out.println(!success); // true
     }
}
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:

class PrePostDemo {
     public static void main(String[] args){
          int i = 3;
	  i++;
	  System.out.println(i);	// "4"
	  ++i;			   
	  System.out.println(i);	// "5"
	  System.out.println(++i);	// "6"
	  System.out.println(i++);	// "6"
	  System.out.println(i);	// "7"
     }
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)