本篇介绍Java的运算符:算术运算符、关系运算符、逻辑运算符、位运算符、赋值运算符、条件运算符、instanceof运算符。
package com.example.javatest;
/**
* Author:W
* 运算符
* 1.算术运算符
* 2.关系运算符
* 3.位运算符
* 4.逻辑运算符
* 5.赋值运算符
* 6.其他运算符:条件运算符、instanceof运算符
*/
public class OperatorTest {
//算术运算符
public void OperatorByArithmetic()
{
System.out.println("====算术运算符====");
int a = 10;
int b = 3;
System.out.println("a+b = "+(a+b));
System.out.println("a-b = "+(a-b));
System.out.println("a*b = "+(a*b));
System.out.println("a/b = "+(a/b));
System.out.println("a%b = "+(a%b));
System.out.println("a++ :"+a++);
System.out.println("a-- :"+a--);
System.out.println("++b : "+(++b));
System.out.println("--b : "+(--b));
}
//关系运算符
public void OperatorByRelation()
{
System.out.println("====关系运算符====");
int a = 3;
int b = 5;
System.out.println("a==b:"+(a==b));
System.out.println("a!=b:"+(a!=b));
System.out.println("a>b:"+(a>b));
System.out.println("a<b:"+(a<b));
System.out.println("a>=b:"+(a>=b));
System.out.println("a<=b:"+(a<=b));
}
//位运算符
public void OperatorByByte()
{
System.out.println("====位运算符====");
int a = 6;
int b = 5;
System.out.println("a&b="+(a&b));//与
System.out.println("a|b="+(a|b));//或
System.out.println("a^b="+(a^b));//异或
System.out.println("~a="+(~a));//取反
System.out.println("a>>2 ="+(a>>2));//右移
System.out.println("a<<2 ="+(a<<2));//左移
//按位右移补零操作符。左操作数的值按右操作数指定的位数右移,移动得到的空位以零填充。
System.out.println("a>>>2 ="+(a>>>2));
}
//逻辑运算符
public void OperatorByLogic()
{
System.out.println("====逻辑运算符====");
boolean a = true;
boolean b = false;
System.out.println("a&&b="+(a&&b));//与
System.out.println("a||b="+(a||b));//或
System.out.println("!a="+(!a));//非
}
//赋值运算符
public void OperatorByAssign()
{
System.out.println("====赋值运算符====");
int a =15;
int b = 4;
int c = 0;
c = a + b;
System.out.println("= :"+c);
c += b;
System.out.println("+= :"+c);
c -= b;
System.out.println("-= :"+c);
c *= b;
System.out.println("*= :"+c);
c /= b;
System.out.println("/= :"+c);
c %= b;
System.out.println("%= :"+c);
c <<= 2;
System.out.println("<<= :"+c);
c >>= 2;
System.out.println(">>= :"+c);
c &= 2;
System.out.println("&= :"+c);
c ^=2;
System.out.println("^= :"+c);
c |= 2;
System.out.println("|= :"+c);
}
//条件运算符
public void OperatorByCondition()
{
System.out.println("====条件运算符====");
int a = 5;
int b = 3;
int c = (a>b)?a:b;
System.out.println("c="+c);
}
//对象类型检查
public void OperatorByInstance()
{
System.out.println("====instanceof运算符====");
String str = "W";
System.out.println("str is String类型:"+(str instanceof String));
}
}
测试脚本
package com.example.javatest;
/*
*Author:W
* 运算符测试
*/
public class MainTest {
public static void main(String[] args)
{
OperatorTest operatorTest = new OperatorTest();
operatorTest.OperatorByArithmetic();
operatorTest.OperatorByRelation();
operatorTest.OperatorByLogic();
operatorTest.OperatorByByte();
operatorTest.OperatorByCondition();
operatorTest.OperatorByInstance();
operatorTest.OperatorByAssign();
}
}
运行结果如下: