Java包机制和运算符

包机制

  • 为了更好的组织类,Java提供了包机制,用于区别类名的命令空间
  • 包语句的语法格式为:
package pkg1[.pkg2[.pkg3...]]
  • 一般用公司域名倒置作为包名
  • 为能使用某一个包的成员,我们需要在Jave程序中明确导入该包,使用”import“语句可以完成
import pkg1[.pkg2[.pkg3...]].(classname|*)

运算符

  • 算术运算符 +,-,*,/,%,++,--
int a=10;
        int c=30;

        int b=a++;//a++ 先赋值,再自增
        //a=a+1
        //=================================================================

        //a=a+1
        int b1=++a; //先自增,再赋值
        System.out.println(b);
        System.out.println(b1);
  • 赋值运算符 =

  • 关系运算符>,<,==,instanceof

  • 逻辑运算符 &&,||,| 与或非

package com.scx.java.operator;
//逻辑运算符
public class Demo05 {
    public static void main(String[] args) {
        // &&(与) ||(或) !(非)
        boolean a = false;
        boolean b = true;
        System.out.println("a && b  "+(a&&b));//交,当第一个是false时,不会执行第二个,比如短路运算
        System.out.println("a || b  "+(a||b));//并
        System.out.println("!(a && b) "+(!(a&&b)));//反

        // 短路运算
        int c = 5;
        boolean  d = (c<5) && (++c>3);//错了之后后面就不执行了 
        System.out.println(d);
        System.out.println(c);//5
    }
}

  • 位运算符 &,|,^,~,>>,<<,>>>

  • 条件运算符?:

  • 拓展赋值运算符 += -+ *= /=

//幂运算 2^3
        // 很多运算会使用工具类
        double pow = Math.pow(2, 3);//alt + enter +enter
        System.out.println(pow);

优先级

可以多加括号给予

运算过程中的注意事项

public class Demo02 {
    public static void main(String[] args) {
        long a = 123456789076L;
        int b = 123;
        short c = 10;
        byte d = 8;
        double f =123;
        //输出结果默认是int,除非有更高级的类型
        System.out.println(a+b+c+d);//long
        System.out.println(b+c+d);//int
        System.out.println((double) (d+c));//double
    }
}

字符与运算的关系

package com.scx.java.operator;

public class Demo07 {
    public static void main(String[] args) {
        //拓展赋值运算符
        int a=10;
        int b=10;
        a+=b;
        System.out.println(a);
        //字符串连接符 + ,String
        System.out.println(a+b+" ");//先计算,再变字符
        System.out.println(""+a+b);//有字符,直接都是字符


    }
}

三元运算符

package com.scx.java.operator;
import com.scx.java.*;
//全部导入
import com.scx.java.operator.Demo07;
//三元运算符
public class Demo08 {
    public static void main(String[] args) {
        // x?y:z
        //如果x成立 则输出y,否则为z
        int score = 99;
        String type = score < 60 ?"不及格":"及格";

        System.out.println(type);
    }

}
posted @ 2025-06-06 23:35  单星星  阅读(13)  评论(0)    收藏  举报