0
点赞
收藏
分享

微信扫一扫

java运算符注意项总结


1、算术运算符

package test;

public class test1 {
public static void main(String[] args) {

int a, b, c, d, e, h1, h2, g, f;
a = (+3);//正号
b = (-3);//负号
c = 1 + 2;//加
d = 3 - 1;//减
e = 2 * 4;//乘
f = 6 / 3;//除
g = 7 % 3;//求余
h1 = (++a);//自增(前)或a-- --a是自减
h2 = (a++);//自增(后)

{
System.out.println(f);//整数运算,商是整数,f=2
double F = 2.4 / 2;//如果有小数参与时,结果会是小数
System.out.println(F);//F=1.2
}


{
System.out.println("g=" + g);//g=1
int G = (-7) % 3;
System.out.println("G=" + G);//G=-1,运算结果的正负取决于被模数(%左边的数) 的符号,
// 与模数(%右边的数)的符号无关
double G1 = 7.2 % 3;
System.out.println("G1=" + G1);//G1=1.2000000000000002
}


{
int r = 2;
int plus = d + (++r);//放前面时是先自加1,然后再和d做运算
System.out.println(plus);//plus=5
System.out.println(r);//r=3
}


{
int r = 2;
int reduce = d + (r++);//放后面是先和d做运算,然后再自加1
System.out.println(reduce);//reduce=4
System.out.println(r);//r=3
}


{
int r = 2;
int reduce1 = -(d + r) + r++;
System.out.println("reduce1=" + reduce1);//随意写一个式子,结果-2
//先算d+r,再算前面的负,再与r相加,最后r自加
int r1 = 2;
int d1 = 2;
int reduce2 = -d1 + r1 + (++r1);
System.out.println("reduce2=" + reduce2);//reduce2=2

}


}


}

2、赋值运算符

package test;

public class test1 {
public static void main(String[] args) {

int a, b;
a = 5;
b = 3;//赋值运算
int e;
a += b;//加等于,相当于a=a+b
e = a;
System.out.println(e);
//+=,-+,*=,/=,%= 一样如此
}

{
int a1, b1, c1;
a1 = b1 = c1 = 5;//正确

}

{
int a1, b1, c1 = 5;//错误
}

{

short a1 = 6;
int a2 = 9;
a1 += a2;//发现short可以转向int,说明在此类运算符中,强制类型转换可以自动完成的
System.out.println(a1);
}
}

3、比较运算符

package test;

public class test1 {
public static void main(String[] args) {

int a, b;
a = 7;
b = 4;
System.out.println(a == b);//判断真假的
System.out.println(a != b);
System.out.println(a < b);
System.out.println(a > b);
System.out.println(a <= b);
System.out.println(a >= b);


}
}

4、逻辑运算符

& 与

真&真=真

真&假=假

假&真=假

假&假=假

java运算符注意项总结_java

| 或

一真全真,全假才假

java运算符注意项总结_java_02

^ 异或

除了两真变假,其余和 或 (|) 一样

!非

非真及假,非假及真

&& 短路与

和 与(&)一样

|| 短路或

和 或(|)一样

java运算符注意项总结_自增_03

package test;

public class test1 {
public static void main(String[] args) {

int a, b;
boolean c;
a = 1;
b = 3;
c = a == 3 && b == -1;
System.out.println(c);//结果c为假,注意==和=,是不同的运算符
}

}

5、优先级

java运算符注意项总结_算术运算符_04



举报

相关推荐

0 条评论