java程序是由许多语句组成的,而语句的基本组成单位是运算符和表达式。
一.运算符
运算符可以分成以下几类:
- 算术运算符
- 关系运算符
- 位运算符
- 逻辑运算符
- 赋值运算符
- 其它运算符
算术运算符
算术运算符在数学中经常用到,有+,-,*,/,%五种,和数学中作用一样,如:
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 10;
int y = 3;
System.out.println("x + y = " + (x + y) );
System.out.println("x - y = " + (x - y) );
System.out.println("x * y = " + (x * y) );
System.out.println("x / y = " + (x / y) );
System.out.println("x % y = " + (x % y) );
}
程序运行结果为:
x + y = 13
x - y = 7
x * y = 30
x / y = 3
x % y = 1
关系运算符
关系运算符在判断语句中常用到,关系运算符如下:
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 10;
int y = 3;
System.out.println("x == y = " + (x == y) );
System.out.println("x != y = " + (x != y) );
System.out.println("x > y = " + (x > y) );
System.out.println("x < y = " + (x < y) );
System.out.println("x >= y = " + (x >= y) );
System.out.println("x <= y = " + (x <= y) );
}
程序运行结果为:
x == y = false
x != y = true
x > y = true
x < y = false
x >= y = true
x <= y = false
上面程序表明用关系运算符是会产生一个布尔值,所以可以用来做判断语句的条件。
位运算符
位运算符可以应用于byte,short,int,long,char等类型。
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 10;
int y = 3;
System.out.println("x & y = " + (x & y) );
System.out.println("x | y = " + (x | y) );
System.out.println("x ^ y = " + (x ^ y) );
System.out.println("~x = " + ( ~x ) );
System.out.println("x << 2 = " + (x << 2) );
System.out.println("x >> 2 = " + (x >> 2 ) );
}
程序运行结果为:
x & y = 2
x | y = 11
x ^ y = 9
~x = -11
x << 2 = 40
x >> 2 = 2
逻辑运算符
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean x = true;
boolean y = false;
System.out.println("x & y = " + (x & y) );
System.out.println("x | y = " + (x | y) );
System.out.println("x && y = " + (x && y) );
System.out.println("x || y = " + ( x || y ) );
}
程序运行结果为:
x & y = false
x | y = true
x && y = false
x || y = true
赋值运算符
赋值运算符主要是 = ,作用就是赋值,其它还有+=,-=,*=,/=等等。
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 10;
int y = 3;
int z = x + y;
System.out.println("z = x + y = " + (z = x + y) );
System.out.println("z += x = " + (z += x) );
System.out.println("z -= x = " + (z -= x) );
System.out.println("z *= x = " + ( z *= x ) );
}
程序运行结果为:
z = x + y = 13
z += x = 23
z -= x = 13
z *= x = 130
其它运算符
有条件运算符(?:)等。
其定义语句为:variable x = (expression) ? value if true : value if false
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 10;
int y ;
y = (x == 1)? 20 : 30;
System.out.println("y = " + y );
y = (x == 10)? 20 : 30;
System.out.println("y = " + y );
}
运行结果为:
y = 30
y = 20