java变量常量及运算符

本文详细介绍了Java编程中的变量类型,包括实例变量、类变量、局部变量和常量的使用规则。同时,文章讲解了各种运算符,如算术运算符、关系运算符、逻辑运算符和三元运算符的用法,并通过实例展示了它们在代码中的应用。此外,还提到了自增自减运算符和数学类的方法。
摘要由CSDN通过智能技术生成

变量

//实例变量:从属于对象;作用范围更大;如果不自动初始化,这个类型的默认值  0 0.0 u0000
//布尔值:默认是false
//除了基本类型其余都是null;

类变量需要在前面加static

局部变量定义后一定要赋值

常量

public class Demo07 {
    //变量之前的都是修饰符,不存在先后顺序
    //常量用final来定义
    static final double PI = 3.14;

    public static void main(String[] args) {
        System.out.println(PI);
    }
}

运算符

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HRB18eeK-1646583874518)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20220306162732678.png)]

package operator;

public class Demo01 {
    public static void main(String[] args) {
        //二元运算符
        int a = 10;
        int b = 20;
        int c = 30;
        int d = 40;

        System.out.println(a+b);
        System.out.println(a-b);
        System.out.println(a*b);
        System.out.println(a/(float)b);
    }
}
package operator;

public class Demo03 {
    public static void main(String[] args) {
        //关系运算符的返回结果:正确,错误   用布尔值来表示

        int a = 10;
        int b = 20;
        int c = 21;

        System.out.println(a>b);
        System.out.println(a<b);
        System.out.println(a==b);

        //取余,模运算
        System.out.println(a%c);
    }
}
package operator;

public class Demo04 {
    public static void main(String[] args) {
        //++  ——  自增自减(一元运算符)
        int a = 10;
        int b = a++;//先把a的值赋给b,执行完这条指令后a执行+1指令变为11
        int c = ++a;//先加一再赋值

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);

        //幂运算;2^3;会使用一些工具来进行运算
        //数学类方法
        double pow = Math.pow(2, 3);
        System.out.println(pow);
    }
}
package operator;
//逻辑运算符
public class Demo05 {
    public static void main(String[] args) {
        // 与,或,非
        boolean a = true;
        boolean b = false;

        System.out.println(a && b);
        System.out.println(a || b);
        System.out.println(!(a && b));

        //短路运算
        int x = 5;
        boolean t = (x<4)&&(x++<4);
        System.out.println(x);
        System.out.println(t);
    }
}
package operator;
//三元运算符
public class Demo08 {
    public static void main(String[] args) {
        //x?y:z如果x为真则结果为Y否则为z
        int score = 80;
        String type = score<60?"不及格":"及格";
        System.out.println(type);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值