Home » Data Structures using Java »
Sample Code that use Unary Operators in Java
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
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
}
}
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"
}
}
Related posts:
If you enjoyed this article, subscribe to receive more great content just like it.
Disclaimer
Labels
- Computer Tips and Tricks (8)
- Content Management System (1)
- Data Structures using Java (15)
- Database Management Systems (2)
- File Formats (7)
- Gadgets Reviews (2)
- Games Reviews (2)
- hardware (16)
- Internet Terms (7)
- Management Information System (5)
- networking (8)
- Programming (15)
- sofware (17)
- Tech News (4)
- Web Design (4)
0 comments for this post
Leave a reply