「Java基础」二、Java语言基础

二、Java语言基础

1 - Java中的三种注释

  • 单行注释

    • //注释内容
      
  • 多行注释

    • /*
      注释内容
      */
      
  • 类注释

    • /**
        * 类注释
        */
      

2 - 标识符

由数字,字母和下划线(_),美元符号($)或人民币符号(¥)组成。首位不能是数字

严格区分大小写

Java关键字不能当作Java标识符。但可以包含关键字和保留字,不能包含空格

3 - 关键字

abstract assert boolean break byte continue
case catch char class const
double default do extends else
final float for goto long if
implements import instanceof int interface
native new null return this while
package private protected public
short static strictfp super switch synchronized
throw throws transient try void volatile

4 - 字面量

int i = 1;把整数1赋值给int型变量i,整数1就是Java字面量,
String s = "abc";中的abc也是字面量。

5 - 变量

5 - 1 定义变量

  • 声明变量
    • int x;
  • 给变量赋值
    • x = 1;

5 - 2 常量

常量:java中利用final指示常量,习惯上将常量名大写

final表示这个变量只能被赋值一次,一旦被赋值后就不能更改

类常量:static final修饰,可以在一个类中的多个方法中使用

public class FirstDemo{
public static final int ID = 1;// 类常量

public static void main(String[] args){

  final int ID = 1;// 普通常量
}
}

6 - 运算符

注意:整数 / 0 -----> 异常;浮点数 / 0 ----> 无穷大或NaN

  • 运算符优先级

    优先级 运算符 结合性
    1 ()、[]、{} 从左向右
    2 !、+、-、~、++、-- 从右向左
    3 *、/、% 从左向右
    4 +、- 从左向右
    5 «、»、>>> 从左向右
    6 <、<=、>、>=、instanceof 从左向右
    7 ==、!= 从左向右
    8 & 从左向右
    9 ^ 从左向右
    10 | 从左向右
    11 && 从左向右
    12 || 从左向右
    13 ?: 从右向左
    14 =、+=、-=、*=、/=、&=、|=、^=、~=、«=、»=、>>>= 从右向左

6 - 1 Math类

  • 三角函数
    • Math.sinMath.conMath.tanMath.atanMath.atan2
  • 求平方根
    • Math.sqrt(x) x开根号
  • 幂运算
    • Math.pow(x,a) x的a次幂
  • PI: Math.PI
  • e: Math.E
  • 产生一个0-1的随机数:Math.random()

6 - 2 自增(++)与自减

y = a++; 先对将a的值附给y,在将a的值+1

y = ++a; 先对a进行+1,在将+1后a的值附给y

public class Main {
    public static void main(String[] args) {
        int a = 1;
        int x = 0;
        int y = 0;
        
        x = a++;
        y = ++a;
        
        System.out.println("x = "+ x);  // x = 1  a = 2
        System.out.println("y = "+ y);  // y = 3  a = 3
        System.out.println("a = "+ a);  // a = 3
        
        // 输出结果:x = 1	y = 3	a = 3
    }
}

6 - 3 三元操作符(?:)

x > y ? x : y

x>y为真取x的值;为假取y的值

public class Main {
    public static void main(String[] args) {
        int x = 5;
        int y = 3;

        int outX = x > y ? x : y; // x>y成立,得到x的值,并赋值给outX
        int outY = x < y ? x : y; // x<y不成立,得到y的值,并赋值给outY
        
        System.out.println("outX = " + outX); // outX = 5
        System.out.println("outY = " + outY); // outY = 3

    }

}
posted @ 2021-07-02 23:07  CarryBircks  阅读(57)  评论(0)    收藏  举报