一元运算符只需要一个操作数。它们用于增加,减少或取消一个值。 - :一元减号,用于否定值。
+:一元加号,用于给出正值。仅在故意将负值转换为正值时才使用。
++:增量运算符,用于将值递增1.有两种增量运算符。 后增量:值首先用于计算结果,然后递增。
预增量:首先增加值,然后计算结果。
- :递减运算符,用于将值递减1.有两种增量运算符。 后递减:值首先用于计算结果,然后递减。
预先减量:首先减值,然后计算结果。
!:逻辑非运算符,用于反转布尔值。 // Java program to illustrate
// unary operators
public class operators
{
public static void main(String[] args)
{
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
boolean condition = true;
// pre-increment operator
// a = a+1 and then c = a;
c = ++a;
System.out.println("Value of c (++a) = " + c);
// post increment operator
// c=b then b=b+1
c = b++;
System.out.println("Value of c (b++) = " + c);
// pre-decrement operator
// d=d-1 then c=d
c = --d;
System.out.println("Value of c (--d) = " + c);
// post-decrement operator
// c=e then e=e-1
c = --e;
System.out.println("Value of c (--e) = " + c);
// Logical not operator
System.out.println("Value of !condition =" + !condition);
}
}
输出: Value of c (++a) = 21
Value of c (b++) = 10
Value of c (--d) = 19
Value of c (--e) = 39
Value of !condition =false