day12-变量、常量、作用域、基本运算符

变量作用域

  • 类变量

  • 实例变量

  • 局部变量
    public class Demo05 {

    //类变量 static
    static double salary = 2500;

    //属性:变量

    //实例变量:从属于对象;类的里面,方法(main)的外面,这个类型的默认值 0 0.0
    //布尔值:默认false
    //除了基本类型(8种),其余的默认值都是null
    String name;
    int age;

    public static void main(String[] args) {

      //局部变量;必须声明和初始化值
      int i = 10;
      System.out.println(i);
    
      //变量类型  变量名字 = new Demo05();
      Demo05 demo05 = new Demo05();   //new Demo05  然后alt+回车
      System.out.println(demo05.age);
      System.out.println(demo05.name);
    
      //类变量 static
      System.out.println(salary);
    

    }
    //其他方法
    }

常量

  • 常量(constant):初始化(initialize)后不能再改变值!不会变动的值。
  • 可以把常量理解为一种特殊的变量,它的值被设定后,在程序运行过程中不允许被改变。

final 常量名=值;
final double PI=3.14;
常量一般使用大写字符
public class Demo09 {

//修饰符(变量类型前面的都是修饰符),不存在先后顺序
static final double PI = 3.14;
public static void main(String[] args) {
    System.out.println(PI);

}

}

变量的命名规范

  • 所有变量、方法、类名:见名知意
  • 类成员变量:首字母小写和驼峰原则:moneySalary 驼峰原则:除了第一个单词以外,其余单词首字母大写
  • 局部变量:首字母小写和驼峰原则
  • 常量:大写字母和下划线:MAX_VALUE
  • 类名:首字母大写和驼峰原则:Man,GoodMan
  • 方法名:首字母小写和驼峰原则run(),runRun()

基本运算符

  • 加、减、乘、除

package operator;

public class Demo01 {
public static void main(String[] args) {
//二元运算符
//Ctrl+D :复制当前行到下一行
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((double)a/b);
}

}

package operator;

public class Demo02 {
public static void main(String[] args) {
long a = 123456789L;
int b = 123;
short c = 10;
byte d = 8;
System.out.println(a+b+c+d);//long 如果有一个long类型,结果也是long类型
System.out.println(b+c+d);//int 如果没有long,结果都int
System.out.println(c+d);//int 如果有一个类型为double,结果为double
}
}
关系运算符
package operator;

public class Demo03 {
public static void main(String[] args) {
//关系运算符返回的结果:true false
//if

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

    System.out.println(c%a);//取余(模运算)    c/a   21/10=2......1
    System.out.println(a>b);
    System.out.println(a<b);//= 赋值
    System.out.println(a==b);// ==等于
    System.out.println(a!=b);// != 不等于

}

}

自增自减运算符

package operator;

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

    //++   --    自增   自减   一元运算符
    int a = 3;
    int b = a++;//执行完这行代码后,先给b赋值,再自增
    //a++   a=a+1
    System.out.println(a);
    int c = ++a;//执行完这行代码后,先自增,再给b赋值
    //++a   a=a+1;
    System.out.println(a);
    System.out.println(b);
    System.out.println(c);

    //幂运算2^3   2*2*2=8,很多运算需要使用一些运算来操作
    double pow = Math.pow(2,3);
    Math.pow(2,3);
    System.out.println(pow);
}

}

posted @ 2021-06-28 22:35  shum  阅读(36)  评论(0)    收藏  举报