Java基础语法
1、标识符和关键字
标识符
Java 所有的组成部分都需要名字。像类名、方法名、变量名都叫做标识符。
使用标识符规则(重要)⚠️
- 标识符首字母可以用大小写字母、美元符号$、下划线_开始。
- 首字母后面可以用大小写字母、美元符号$、下划线_、数字。($ _很少用)
- 不能用关键字作为方法名和变量名。
- 标识符是区分大小写的
- 正确标识符举例:Age、age、$salary、_value、 _1value
- 错误标识符举例:123abc、-salary、#abc

关键字
在Java中有特殊意义的单词,不能作为变量名或方法名。

2、数据类型【重点难点】
强类型语言
- 要求变量的使用必须符合语法规则,变量必须先定义后使用。比如:C/C++、Java都是强类型语言。
弱类型语言
- 变量的使用没有严格语法限制,比如:JavaScript是弱类型语言。

Java数据类型分为两大类
- 基本类型(primitive type)
- 引用类型(reference type)


什么是字节?
- 位(bit):位是计算机 内部数据 存储的最小单位,例如11001100是一个八位二进制数。
- 字节(byte):字节是计算机 数据处理 的基本单位,一般用大写的 B 来表示。
- 1B=8bit,即一个字节=8个比特。
- 字符:是计算机中使用的字母、数字、文字和符号。
存储容量换算
- 1B = 8bit
- 1KB = 1024B
- 1MB = 1024KB
- 1GB = 1024MB
- 1TB = 1024GB
数据类型拓展
package com.hongcheng.base;
public class IntegerPlus {
    public static void main(String[] args) {
        //整数拓展:进制       二进制  八进制  十进制  十六进制
        int i1 = 0b10;      // 二进制0b,0b10表示2
        int i2 = 010;       // 八进制0,010表示8
        int i3 = 10;        // 十进制10,表示10
        int i4 = 0x10;      // 十六进制0x10,0x10表示16
        //浮点数拓展    银行业务怎么表示钱?
        //银行业务不能用float和double,要用大数BigDecimal,是一个数学工具类
        /*
        为什么???
        浮点数表示出来的数是有限的,但有些数除不尽是离散的!
        浮点数的尾数会四舍五入,这会损失精度。得到的数只是原数据的大概。
        所以最好避免使用浮点数进行比较!!!
        所以最好避免使用浮点数进行比较!!!
        所以最好避免使用浮点数进行比较!!!
         */
        float f = 0.1f;
        double d = 1.0/10;
        System.out.println(f==d);   //false,精度问题
        float f1 = 23323323232323332323f;
        float f2 = f1 + 1;
        System.out.println(f1==f2); //true,其实是错误的
        //字符拓展
        char c1 = 'a';
        char c2 = '国';
        System.out.println(c1);					//a
        System.out.println((int)c1);    //a的ASCII是97,字符强转为数字
        System.out.println(c2);
        System.out.println((int)c2);    //22269,强制类型转换
        //所有字符本质上还是数字
        //ASCII表:(97 = a  65 = A)
        char c3 = '\u0061';     // 十六进制0x61表示十进制数字97,即a
        System.out.println("c3=" + c3);
        //转义字符,在字符串中使用
        // \t 制表符   \n 换行符
        // 还有很多转义字符
        System.out.println("Hello\tWorld");
        System.out.println("Hello\nWorld");
        //对象和值的区别
        String s1 = new String("hello world"); //把对象的地址给了s1
        String s2 = new String("hello world");
        System.out.println(s1 == s2); //false,引用类型比较的是对象地址
        String s3 = "hello world"; //把字符串给了s1
        String s4 = "hello world";
        System.out.println(s3 == s4); //true,比较的是值内容
        //布尔值拓展
        boolean flag = true;
        if (flag) {	//常用
        }
        if (flag == true) { //不用
        }
    }
}
类型转换
强制类型转换
- 因为Java是强类型语言,所以进行运算的时候,需要用到强制类型转换。

在运算中,不同类型的数据需要先转换成同一种类型,然后再计算。
- 
强制类型转换,大转小 
- 
自动类型转换,小转大 
package com.hongcheng.base;
public class TypeCase {
    public static void main(String[] args) {
        //强制类型转换,大转小
        int i = 128;
        byte b = (byte) i;      //b=-128,内存溢出
        //自动类型转换,小转大
        double d = i;
        /*
        类型转换注意点:
        1. 不能对布尔值进行转换
        2. 不能把对象类型转换成不相干的类型
        3. 从大类型转换成小类型的时候,要用强制类型转换
        4. 转换的时候可能会内存溢出,或者精度丢失!
         */
        //精度丢失
        System.out.println((int)33.8f);     //33,强制类型转换,精度丢失,舍弃小数部分
        System.out.println((int)-54.33);    //-54
        //字符转换
        char c = 'a';   //a在ASCII码中是97
        int i1 = c + 1; //98,c先升级成int的97,再和1相加
        System.out.println(i1);
        System.out.println((char) i1); //b
        //操作比较大的数时,注意类型溢出问题
        //JDK7新特性,数字之间可以用下划线_分隔
        int money = 10_0000_0000;
        int years = 20;
//        int total = money * years;  //-1474836480,内存溢出
//        long total2 = money * years; //还是-1474836480,原因是结果本来就是int的
        long total3 = money * (long)years; //先把一个数转换成long,然后两个变量都转换成long,就不会溢出了
    }
}
变量、常量、作用域【重点】
变量
什么是变量?
- 变量是可以修改的量。
- Java是一种强类型语言,所以每个变量都必须声明它的类型。
- Java变量是程序中最基本的存储单元,包括变量类型、变量名和作用域。
type varName
//变量类型 变量名
使用变量的注意点⚠️
- 每个变量都必须有类型,可以是基本类型,也可以是引用类型。
- 变量名必须是合法的标识符。
- 变量声明是一条完整的语句,末尾必须以分号;结束。
变量的命名规范
- 所有的变量、方法、类名最好见名知意,即看见名字就知道是什么意思。
- 类成员变量:首字母小写和驼峰原则:monthSalary,就是除了第一个单词以外,后面单词首字母都要大写。
- 局部变量:首字母小写和驼峰原则。
- 常量:字母全部大写,可以用下划线分隔单词:MAX_VALUE
- 类名:首字母大写和驼峰原则:Person,SomePerson
- 方法名:首字母小写和驼峰原则:run(),runTime()
总之,只有类名需要首字母大写,其他都是小写,常量比较特殊。
package com.hongcheng.base;
public class Variable {
    //类中可以定义属性和方法
    //属性,即变量;方法,即函数
    //类变量,用static修饰的变量
    static double salary = 2500;    //自动类型转换
    /*
    实例变量:属于对象,如果不自己初始化它,编译器会给一个默认值,
    通常数值的默认值是0或0.0,boolean类型是false,
    除了基本类型,其他类型都是null
     */
    String name;    //默认值是null
    int age;        //默认值是0
    //main方法
    public static void main(String[] args) {
        /*
        局部变量:变量在方法里,必须声明和初始化值,局部变量的作用域是这个方法,
        在其他方法中用不了这个变量,方法结束局部变量也就死亡。
         */
        int i = 10;
        System.out.println(i);
        //创建对象,调用对象属性
        Variable c = new Variable();
        System.out.println(c.name);
        //使用类变量
        System.out.println(salary);
    }
    //其他方法
    public void add() {
//        System.out.println(i);
    }
}
//    public static void main(String[] args) {
//        //声明多个变量,不建议使用,代码可读性差
//        int a,b,c;  //声明三个变量
//        int d = 1, e = 10, f = 100; //初始化三个变量
//
//        int g = 200; //基本类型
//        int h = g;   //引用类型
//    }
常量
什么是常量?
- 常量是初始化之后就不能再改变的量。
- 常量是一种特殊的变量,它的值被设置后在程序运行过程中是不能被改变的。
- 常量名通常字母全部大写。
- 常量使用 final 修饰
final double PI = 3.14;
//final 常量类型 常量名 = 数值;
public class Constant {
    // 修饰符,不区分先后顺序
    public static final double PI = 3.14; //类常量
    public static void main(String[] args) {
        System.out.println(PI);
    }
}
变量作用域
- 类变量,作用域是这个类,跟随类加载就生成类变量。
- 实例变量,作用域是这个对象,创建对象时实例变量也跟着被创建出来。
- 局部变量,作用域是这个方法,在别的方法中无法调用局部变量,方法结束时局部变量也被销毁了。
public class VariableScope {
    public static int allClicks = 0;	//类变量
    public String str = "Hello world"; //实例变量
    
    public void method() {
        int i = 0;	//局部变量
    }
}
3、基本运算符
运算符
Java有下面这些运算符:
- 算术运算符:+,-,*,/,%,++,--
- 赋值运算符:=
- 关系运算符:>,<,>=,<=,==,!=,instanceof
- 逻辑运算符:&&,||,!
- 位运算符:&,|,^,~,>>,<<,>>>(了解!)
- 条件运算符:? :
- 扩展赋值运算符:+=,-=,*=,/=
使用运算符
package com.hongcheng.operator;
/*
    使用运算符
 */
public class Operator {
    public static void main(String[] args) {
        //二元运算符
        int a = 10;
        int b = 20;
        int c = 46;
        int d = 57;
        System.out.println("a+b=" + (a+b));
        System.out.println("a-b=" + (a-b));
        System.out.println("a*b=" + (a*b));
//        System.out.println("a/b=" + (a/b));    //0,结果是0.5,因为是整数除法,所以小数部分被丢弃
        System.out.println("a/b=" + (a/(double)b));    //0.5
        System.out.println("c%b=" + (c%b)); //46/20 = 2...6,模运算,也叫取余
        long e = 1323213213213L;
        int f = 123;
        short g = 29;
        byte h = 2;
        System.out.println(e+f+g+h);    //long
        System.out.println(f+g+h);  //int
        System.out.println(g+h);    //int,int以下都转换成int类型再计算
        //关系运算符:判断条件,返回结果是布尔值
        int i1 = 10;
        int i2 = 100;
        int i3 = 32;
        System.out.println(i1 > i2);
        System.out.println(i1 < i2);
        System.out.println(i1 == i2);
        System.out.println(i1 != i2);
        //自增、自减运算符:++,--
        int i4 = 3;
        int i5 = i4++;  //先给i5赋值3,然后i4+1,最后i5=3,i4=4
        int i6 = ++i4;  //i4先+1,再给i6赋值,所以i6=5
        System.out.println(i4);
        System.out.println(i5);
        System.out.println(i6);
        //幂运算 2^3 2*2*2 = 8,很多运算,我们会借助一些 数学工具类 来操作!
        double pow = Math.pow(4, 2); //16.0,pow方法返回double类型
        System.out.println((int) pow);   //16,强制类型转换成int
        //与(and) 或(or) 非(取反)
        boolean j = true;
        boolean k = false;
        System.out.println("j&&k: " + (j && k)); //逻辑与运算,两个都为真时,结果才为真
        System.out.println("j||k: " + (j || k)); //逻辑或运算,任何一个为真,结果也为真
        System.out.println("!(j&&k): " + !(j&&k)); //如果是真,就变为假,如果是假,就变为真
        //短路运算
        int i7 = 3;
        boolean b1 = (i7>5) && (i7>2);    // 当第一个条件为false时,后面条件不用再比较,提高性能
        System.out.println(b1);
        System.out.println(i7);
        //位运算(难点)
        /*
        A = 0011 1100
        B = 0000 1101
        A&B = 0000 1100 // 两个位都是1的时候才为1,反之为0
        A|B = 0011 1101 // 任何一个位是1,结果都为1,两个位都是0时才为0
        A^B = 0011 0001 // 两个位相同为0,不同为1(特殊)
        ~B = 1111 0010 //B是1就取0,B是0就取1
        左移<< 乘  右移>> 除
        2*8 = 16    2*2*2*2
        效率极高!!!
        <<      *2      因为是二进制,所以是*或/ 2,如果是8进制就*或/ 8
        >>      /2
        0000 0000   0
        0000 0001   1
        0000 0010   2
        0000 0011   3
        0000 0100   4
        0000 1000   8
        0001 0000   16
         */
        System.out.println(2 << 3); //16
        // += -=
        int l = 10;
        int m = 20;
        l += m; //等于l = l + m
        l -= m; //等于l = l - m
        System.out.println(l);
        //字符串连接符:+
        System.out.println("" + l + m); //1020,只要有一个字符串,就会把其他变量都转换成字符串
        System.out.println(l + m + ""); //30,这30也是字符串,但是运算顺序让l+m先计算得到30,然后30转换成字符串
        //三目运算符
        /*
            x ? y : z
            如果x==true,则结果为y,否则结果为z
         */
        int score = 80;
        String result = score > 60 ? "及格" : "不及格";
        System.out.println(result);
    }
}
4、流程控制【重点难点】
顺序结构
- Java的基本结构就是顺序结构,程序就是按顺序一句一句执行。
- 顺序结构是最简单的算法结构。
- 顺序结构是任何一个算法都离不开的一种基本算法结构。

选择结构
- if单选择结构
- if-else双选择结构
- if-else if-else多选择结构
- 嵌套的if结构
- switch多选择结构
if单选择结构
判断一个条件是否正确,正确的话就去执行,我们需要一个 if语句实现。
- 语法
if (判断条件) {    // 如果条件为true就执行结构体语句}
 
package com.hongcheng.struct.struct;import java.util.Scanner;/*    选择结构-if单选择结构    判断条件,如果为true就执行循环体语句,否则就跳过循环体执行后面的语句    思路:读取用户输入的字符串,判断字符串是否等于给出的字符串,如果相等就输出字符串,然后结束程序 */public class If1 {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        System.out.println("请输入内容:");        String s = scanner.nextLine();        //equals()方法判断字符串是否相等        if (s.equals("hello")) {            System.out.println(s);        }        System.out.println("End");        scanner.close();    }}
if双选择结构 if-else
示例场景:奶茶店有两款饮品,蜜桃四季春6元,高山四季春3元,现在我微信上有5元,我想喝蜜桃四季春,如果不行就要高山四季春。
这时候我们就需要一个双选择结构 if else,单if选择结构已经不能满足我们的需求了。
语法:
if (判断条件) {    // 如果条件为true,执行这些语句} else {    // 如果条件为false,执行这些语句}
 
package com.hongcheng.struct.struct;/*    选择结构-if else双选择结构        场景:奶茶店有两款饮品,蜜桃四季春6元,高山四季春3元,    1、假设现在我微信上有5元,我想喝蜜桃四季春,如果不行就要高山四季春。    2、假设现在我微信上有10元,我想喝蜜桃四季春,如果不行就要高山四季春。    思路:判断钱包的余额够不够买蜜桃四季春,不够就买高山四季春 */public class If2 {    public static void main(String[] args) {        final double Uid1 = 6; //蜜桃四季春        final double Uid2 = 3; //高山四季春        double money = 5; //微信余额        if ((money-Uid1) >= 0) {            System.out.println("成功购买<蜜桃四季春>");        } else {            money -= Uid2;            System.out.println("成功购买<高山四季春>");        }    }}
if多选择结构 if-else if-else
有时候我们不只要买自己的饮料,还要帮哥哥姐姐买。
这时,双选择结构无法满足我们需求,我们就需要使用多选择结构!
- 语法
if (判断条件1) {    // 如果条件1为true,执行这些语句} else if (判断条件2) {    // 如果条件2为true,执行这些语句} else if (判断条件3) {    // 如果条件3为true,执行这些语句} else {    // 如果条件3为false,执行这些语句}

package com.hongcheng.struct.struct;/*    选择结构-多选择结构    场景:奶茶店有两款饮品,蜜桃四季春6元,雪王大圣代5元,柠檬水4元,高山四季春3元,冰水0元    现在我微信上有5元,我想喝蜜桃四季春,如果不行就要雪王大圣代,再不行就要柠檬水,    再不行就要高山四季春。    思路:判断微信余额够不够买蜜桃四季春,如果不够就依次买更便宜的饮品 */public class If3 {    public static void main(String[] args) {        final double uid1 = 6; //蜜桃四季春        final double uid2 = 5; //雪王大圣代        final double uid3 = 4; //柠檬水        final double uid4 = 3; //高山四季春        final double uid5 = 0; //冰水        double money = 5; //微信余额                /*            if语句最多有1个 else语句,else语句必须在最后!            if语句可以有多个 else if 语句,他们必须在 else语句之前            一旦其中一个 else if语句为真,其他的 else if和 else语句都会跳过         */        if ((money - uid1) >= 0) {            System.out.println("成功购买<蜜桃四季春>");        } else if ((money - uid2) >= 0) {            System.out.println("成功购买<雪王大圣代>");        } else if ((money - uid3) >= 0) {            System.out.println("成功购买<柠檬水>");        } else if ((money - uid4) >= 0){            System.out.println("成功购买<高山四季春>");        } else {            System.out.println("成功购买<冰水>");        }    }}
嵌套的if结构
可以使用嵌套的if...else 语句,一个 if else语句里面可以再嵌套多个if else。
- 语法
if (判断条件1) {    //如果条件1为true,再执行一个if判断    if (判断条件2) {        //如果条件2为true    }} //如果条件1为false,直接跳过
switch多选择结构
多选择结构也可以使用 switch语句实现。
- 
switch case语句判断一个变量和一些值中的某个值是否相等,每个值叫做一个分支。 
- 
switch语句的变量类型可以是:byte、short、int、char 
- 
从JDK7开始,switch可以用字符串String类型作为变量类型 
- 
case标签必须是字符串常量或字面量 
注意⚠️:case穿透,如果匹配到那个分支没有写break,就会一直执行后面的分支,直到遇到break为止。
语法格式:
switch本质是条件和value比较,其实是比较hashcode,相同就执行所在的语句!
switch (expression) {    case value:        //语句        break;	//可选,但最好使用    case value:        //语句        break;    default:        //语句}
package com.hongcheng.struct.struct;/*    选择结构-Switch    场景:奶茶店有多款饮品,蜜桃四季春,雪王大圣代,柠檬水,高山四季春,冰水    现在我下单购买一杯饮品    思路:从菜单中选择一款饮品,不买也可以免费获得一杯冰水 */public class Switch1 {    public static void main(String[] args) {        final char uid1 = 1; //蜜桃四季春        final char uid2 = 2; //雪王大圣代        final char uid3 = 3; //柠檬水        final char uid4 = 4; //高山四季春        final char uid5 = 9; //冰水        char selected = 3; //选中饮品        switch (selected) {            case 1:                System.out.println("成功购买<蜜桃四季春>");                break;            case 2:                System.out.println("成功购买<雪王大圣代>");                break;            case 3:                System.out.println("成功购买<柠檬水>");                break;            case 4:                System.out.println("成功购买<高山四季春>");                break;            default:                System.out.println("成功购买<冰水>");        }    }}
反编译
从.class字节码反编译回.java文件,通过IDEA可以实现这种操作。
- 具体步骤
- 找到字节码输出文件夹
- 把字节码文件复制到.java文件夹
- 使用IDEA打开工程目录下的字节码文件即可
发现Switch通过比较对象的 hashCode 来匹配标签,可以认为 hashCode 是唯一的。

package com.hongcheng.struct;public class Switch2 {    public static void main(String[] args) {        String name = "布鲁斯韦恩";        /*        JDK7的新特性,可以用String类型作为 switch变量类型        字符的本质还是数字         */        //反编译   (编译)java--->class(字节码文件)--->java(反编译IDEA)        switch (name) {            case "迪丽热巴":                System.out.println("迪丽热巴");                break;            case "古力娜扎":                System.out.println("古力娜扎");                break;            case "布鲁斯韦恩":                System.out.println("布鲁斯韦恩");                break;            default:                System.out.println("杨超越");        }    }}
循环
while循环
while循环是最基本的循环。
语法:
while (conditon) {    //循环语句}
- 只要判断条件为true,循环就会一直进行下去。
- 我们一般情况是想让循环停下来,所以需要一个让判断条件失效的情况结束循环。
- 只有少部分情况才需要循环一直执行,比如服务器监听客户端请求等......
- 判断条件一直为true就会无限循环,也叫死循环,我们编程的时候应该尽量避免写死循环,死循环会影响程序性能或造成程序崩溃。
package com.hongcheng.struct;public class While1 {    public static void main(String[] args) {        //输出1~100        int i = 0;        while (i < 100) {            i++;            System.out.println(i);        }        //死循环        while (true) {            //等待客户端连接            //......        }    }    }
计算1+2+3+...+100=?如下:
package com.hongcheng.struct;public class While2 {    public static void main(String[] args) {        // 计算1+2+3+...+100=?        int i = 0;        int sum = 0;        while (i < 100) {            i++;            sum += i;        }        System.out.println(sum);    }}
do while循环
- 在while循环中,如果判断条件为false,那么循环体不会执行。有时我们需要先执行再判断,do while循环保证至少执行一次。
do while语法:
do {    //循环语句} while (判断条件);
- while和 do while的区别
- while是先判断后执行,do while是先执行后判断。
- do while保证循环体最少执行一次,while有可能一次都不执行。
 
package com.hongcheng.struct;public class DoWhile {    public static void main(String[] args) {        int a = 1;        while (a < 0) { //循环体一次都不执行            System.out.println(a);            a++;        }        System.out.println("===============");        do {            ////循环体至少执行一次            System.out.println(a);            a++;        } while (a < 0);    }}
for循环
for循环是一种可以迭代的循环结构,是最有效、最灵活的循环结构。
- for循环执行的次数在开始前就确定。
for循环语法:
for (初始化; 判断条件; 更新) {    //循环语句}
for循环执行流程
- 先执行初始化条件,初始化条件可以声明一个或多个变量,也可以为空。
- 然后执行判断条件,如果为true就执行循环体,如果为false就跳过循环体执行后面的语句,判断条件也可以为空,即是true。
- 执行一次循环后更新迭代部分。
- 然后判断条件,重复上面的2,3步骤。
package com.hongcheng.struct;public class For1 {    public static void main(String[] args) {        int i = 1;  //初始化条件        while (i <= 100) {  //条件判断            System.out.println(i);  //循环体            i += 2; //迭代        }        System.out.println("while循环结束");        //初始化条件、判断条件、迭代        for (int a = 1; a <= 100; a++) {            System.out.println(a);        }        System.out.println("for循环结束");    }}
增强for循环
- 增强for循环主要用在数组和集合中遍历元素。
forEach语法:
for (变量类型 变量名 : 数组名) {    //循环语句}
package com.hongcheng.struct;public class ForEach {    public static void main(String[] args) {        int[] numbers = {10, 20, 30, 40, 50};   //静态初始化一个数组        //普通for循环,遍历数组        for (int a = 0; a < numbers.length; a++) {            System.out.println(numbers[a]);        }        System.out.println("==============");        //增强for循环,遍历数组        for (int i : numbers) {            System.out.println(i);        }    }}
break和continue
- 
break可以用在任何循环和switch中,break的作用是强制退出循环,不再执行循环的剩余语句,转而执行循环后的语句。 
- 
continue只能用在循环中,continue的作用是中止本次循环,回到判断条件看是否继续循环。 
package com.hongcheng.struct;
public class Break {
    public static void main(String[] args) {
        int i = 0;
        while (i < 100) {
            i++;
            System.out.println(i);
            if (i == 40) {
                break;      //退出循环,执行循环后的语句
            }
        }
        System.out.println("最后的i是:" + i);
    }
}
package com.hongcheng.struct;
public class Continue {
    public static void main(String[] args) {
        int i = 0;
        while (i < 100) {
            i++;
            if (i % 10 == 0) {
                System.out.println();
                continue;       //中止这次循环,回到开头重新判断条件
            }
            System.out.print(i + " ");
        }
    }
}
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号