java基础复习

Java基础

1.基本语法

1.1注释

单行注释

//单行注释

多行注释

/*多行
注释
*/

文档注释

/**
 * @Description hello
 * @Author w
 */

1.2关键字

1.3标识符

由英文字母,数字,下划线(-),美元符号($)组成,数字不能开头。

1.4数据类型

// 八大基本数据类型
        byte a=10;
        short b=11110;
        int c=11111110;
        long d=14578966555L;
        float e=3.14F;
        double f=3.14478965412;
        char g='中';
        boolean flag=true;
		//String是类,不是关键字
		String j='www'
// 二进制0b 八进制0 十进制 十六进制0x
        //银行业务用BigDecimal
        //最好完全使用float去比较
        float a=2121212121f;
        float b=a+1;
        System.out.println(a==b);

1.5类型转换

//强制转换 会遇到内存溢出或精度问题
int a=1;
byte c=(byte)a;
//自动转换
//byte,short,char->int->long->float->double
//数字之间可用_分割
int d=10_0000_0000;
//sout输出
//psvm main方法

1.6常变量

int a=10;
static final A=10;//常量一般使用大写

命名规范

1.7作用域

类变量,示例变量,局部变量

public class Variable{
    static int allClicks=0;
    String str='lkj';
    public void method(){
        int i=0;
    }
}

1.8运算符

![](C:\Users\王尹愉\Pictures\Screenshots\屏幕截图 2025-03-26 211104.png)

int a=10;
int b=a++;//先使用,再++
int c=++a;//先++,再使用
//&&与 ||或 !非
//短路& |,如果左边可以直接判断结果,则右边不执行
/*
A=0011 1100
B=0000 1101
& 都为1,则为1
| 都为0,则为0
^ 相同为0,否则为1
~ 1为0,0为1
<< 左移 2<<3 16 2* 2*2*2 <<乘2
>> 右移 除2
*/

1.9包机制

一般使用公司域名倒置作为包名

Alt+enter 导包

定义包package

导入包import

1.10JavaDoc

用于生成自己API文档

在文件的文件夹下进入cmd,输出image-20250326215616108

打开index.html,生成文档

2.流程控制

2.1Scanner

new Scanner(System.in);//alt+enter

Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接收");
//判断是否有输入
if(scanner.hasNext()){
    String str=scanner.next();
    System.out.println("输出的内容为:"+str);
}
//属于I/O的类不关闭会一直占用资源
scanner.close();

next语句输入不能有空格,nextline可以有空格,以enter结束。一般使用nextline

//输入n个数字,计算其总和和平均值
Scanner scanner=new Scanner(System.in);
int m=0;
double sum=0;
while(scanner.hasNextDouble()){
    double x=scanner.nextDouble();
    m++;
    sum+=x;
}
System.out.println("sum:"+sum);
System.out.println("平均数"+sum/m);
scanner.close()

2.2顺序结构

从上到下依次执行

2.3选择结构

2.3.1if单选择

if(true){
    System.out.println("true")
}

str.equals(s1) 判断字符串是否相等

2.3.2if双选择

if(true){
    System.out.println("true")
}
else{
     System.out.println("false")
}

2.3.3if多结构

if(score<60){
    System.out.println("不及格")
}
else if(score>60 && score <80){
    System.out.println("及格")
}
else if(score>80 && score<90){
    System.out.println("良好")
}
else{
     System.out.println("优秀")
}

2.3.4嵌套if结构

if(score>90){
    if(score>95){
        System.out.println("恭喜你")
    }
}

2.3.5switch多选择

char grade='C';
switch (grade){
    case 'A':
        System.out.println("优秀");
        break;
    case 'B':
        System.out.println("真好");
        break;
    case 'C':
        System.out.println("及格");
        break;
    case 'D':
        System.out.println("再接再厉");
        break;
    default:
        System.out.println("未知");
}

2.4循环结构

2.4.1while循坏

int a=1;
while(a<10){
    System.out.println(a);
    a++;
}

2.4.2do while循环

int a=1;
do{
    System.out.println(a);
    a++;
}while(a<10);

至少会执行一次

2.4.3for 循环

for(int i=0;i<10;i++)
{
    System.out.println(i);
}

主要用于数组或集合

int[] numbers={10,20,34,50};
for(int i:numbers){
    System.out.println(i);
}

2.4.4break,continue

break强行退出,continue终止某次循环

3.java方法

3.1方法定义

java都是值传递

3.2方法重载

在一个类中,函数名相同,形参不同的函数

3.3可变参数(不定项)

一个方法只能存在一个可变参数,必须是方法的最后一个参数

public static void main(String[] args) {
        test(10,5,20,30);
    }
    public static void test(int... i){
        for(int j:i){
            System.out.println(j);
        }
    }

3.4递归

自己调用自己

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

    public static int f(int i) {
        if (i == 1) {
            return 1;
        } else {
            return i*f(i-1);
        }
    }

4.数组

4.1数组定义

相同数据类型的有序集合

 int[] num=new int[10];

数组通过下标访问

4.2内存分析

java内存分为堆,栈,方法区,堆存放new的对象和数组,栈存放基本类型包括其数值,方法去包含class和static变量

4.3三种初始化

静态初始化

int[] num={1,2,3,4,5};

动态初始化

int[] b=new int[10];
b[0]=10;

隐式初始化

数组分配空间后值默认为0;

4.4多维数组

int[][] a=new int[2][5];
int[][] array={{1,2,},{3,4},{5,6},{7,8}};
 System.out.println(array[1][0]);

4.5Arrays类

查看JDK帮助文档

int[] num={1,2,3,6,5};
//打印数组元素
 System.out.println(Arrays.toString(num));
 //给数组排序
 Arrays.sort(num);
 System.out.println(Arrays.toString(num));
//给数组填充
Arrays.fill(num,0);
System.out.println(Arrays.toString(num));
Arrays.fill(num,0,3,2);//左闭右开
System.out.println(Arrays.toString(num));

4.6稀疏数组

当一个数组大部分元素为0,或者为同一值的数组时,可以使用稀疏数组来保存该数组

处理方式:

记录数组几列几行,有多少个不同值;记录不同值在的行列以及值

![](C:\Users\王尹愉\Pictures\Screenshots\屏幕截图 2025-03-27 195820.png)

int[][] arrays = new int[11][11];
arrays[1][2] = 1;
arrays[2][3] = 2;
for (int[] ints : arrays) {//arrays.for
    for (int anInt : ints) {//ints.for
        System.out.print(anInt+"\t");
    }
    System.out.println();
}


//转换成稀疏数组保存
//获取有效值个数
int sum=0;
for (int i = 0; i < 11; i++) {//fori
    for (int j = 0; j < 11; j++) {//fori
        if (arrays[i][j]!=0){
            sum++;
        }
    }
}
System.out.println(sum);
//创建稀疏数组
int[][] array1=new int[sum+1][3];
array1[0][0]=11;
array1[0][1]=11;
array1[0][2]=sum;
//遍历数组,将非零的数存到稀疏数组中

int count=0;
for (int i = 0; i < arrays.length; i++) {
    for (int j = 0; j < arrays[i].length; j++) {
        if(arrays[i][j]!=0){
            count++;
            array1[count][0]=i;
            array1[count][1]=j;
            array1[count][2]=arrays[i][j];
        }

    }

}
for (int[] ints1 : array1) {
    for (int anInt : ints1) {
        System.out.print(anInt + "\t");
    }
    System.out.println();
}
//还原稀疏数组
    int[][] array2=new int[array1[0][0]][array1[0][1]];
for (int i = 1; i < array1.length; i++) {
    array2[array1[i][0]][array1[i][1]]=array1[i][2];
}
for (int[] ints : array2) {
    for (int anInt : ints) {
        System.out.print(anInt+"\t");
    }
    System.out.println();
}

5.面向对象

5.1基础

image-20250401201554020

类只包含属性和方法

public class Demo1 {
    public static void main(String[] args) {
        Student xiaoming=new Student();
        Student xh=new Student();
        xiaoming.name="小明";
        xiaoming.age=10;
        System.out.println(xiaoming.name+xiaoming.age);
        System.out.println(xh.name+xh.age);
    }

}
class Student{
    String name;
    int age;
}

5.2构造器

类会默认存在一个无参构造方法,构造器具有以下特点,必须和类的名字相同,必须没有返回类型,也不能写void

一旦自己定义了构造方法,默认的就会失效,需要自己重新定义

public class Person {
    String name;
    //实例化初始值
    //使用new关键字,必须要有构造器
    public Person(){
        this.name="xiaoming";
    }
    //有参传递
    //有参传递
    public Person(String name){
        this.name=name;
    }

    public static void main(String[] args) {
        Person person=new Person("xh");
        System.out.println(person.name);
    }
}

5.3创建对象内存分析

java内存分为堆,栈,方法区,堆存放new的对象和数组,栈存放基本类型包括其数值,方法去包含class和static变量

image-20250402195008581

public class Application {
    public static void main(String[] args) {
        Pet dog = new Pet();
        dog.name="旺财";
        dog.age=3;
        dog.shout();
        Pet cat = new Pet();

    }
}
public class Pet {
    String name;
    int age;
    public void shout(){
        System.out.println("正在叫");
    }
}

初始化:数字:0;char:u0000;boolean:false;引用:null;

5.4封装

属性私有,使用get和set方法查看和修改属性

public class Students {
    private String name;
    private int age;
    private char sex;
    //alt+insert 自动生成get和set方法
	//shift可以多选
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age>120||age<0)
        {
            this.age=3;
        }else {
            this.age = age;
        }
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }
}

封装的意义:1.提高程序的安全性,保护数据

2.隐藏代码的实现细节

3.统一接口

4.系统的可维护性增加了

5.5继承

所有的类都默认继承object类

ctrl+h看类的继承情况

类只有单继承,没有多继承

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Student extends Person{
}
public class Application {
    public static void main(String[] args) {
        Student student = new Student();
        student.setName("xiaoming");
        System.out.println(student.getName());
    }
}

image-20250402212315050

5.6super

调用除父类私有属性及方法以外的所有方法和属性

public class Person {
    public void print(){
        System.out.println("person");
    }
}
public class Student extends Person{
    //隐藏语句super();调用父类构造方法,必须放在子类的第一行
    //先调用父类的无参构造,再调用子类的无参构造;
    public void print(){
        System.out.println("student");
    }
    public void test(){
        print();
        this.print();
        super.print();
    }
}
public class Application {
    public static void main(String[] args) {
        Student student = new Student();
        student.test();
    }
}

image-20250402214015350

5.7方法重写

重写指方法重写,没有属性重写

public class B {
    public static void test(){
        System.out.println("B test");
    }
}
public class A extends B{
    public static void test(){
        System.out.println("A test");
    }
}
public class Application {
    public static void main(String[] args) {
        //静态方法:方法的调用只和左边的类型有关
        //非静态方法:重写
        A a = new A();
        a.test();
        //父类的引用指向子类
        B b =new A();
        b.test();
    }
}

image-20250402220121153

5.8多态

同一方法可以根据发送对象的不同而采用多种不同的行为方式

public class Person {
    public void run(){
        System.out.println("run");
    }
}
public class Student extends Person{
    @Override//alt+enter
    public void run() {
        System.out.println("son");
    }
    public void test(){
        System.out.println("son test");
    }
}
public class Application {
    public static void main(String[] args) {
        //对象类型可以确定
        //new Student();
        //new Person();
        //可引用的类型不确定
        //子类可以调用子类和父类的方法
        Student student = new Student();
        //父类的引用指向子类
        //父类型:可以指向子类,但不能调用子类独有的方法
        Person person=new Student();
        Object object=new Student();
        student.run();
        person.run();
        student.test();
        ((Student)person).test();
    }
}

image-20250402221819134

5.9instance of 和类型转换

instance of判断一个对象是什么类型的

Object object = new Student();
//Object>String
//Object>Person>Student
//Object>Person>Teacher
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof String);//false

Person person = new Student();
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Teacher);//false
//System.out.println(person instanceof String);//编译错误

Student student = new Student();
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
System.out.println(student instanceof Student);//true
//System.out.println(student instanceof Teacher);//编译错误
//System.out.println(student instanceof String);//编译错误

类型转换:将父类转换为子类,从高到低,需要强制转换;将子类转换为父类,可以自动转换

Person person = new Student();
((Student)person).test();
//子类转换为父类,可能会丢失一些方法
Student student = new Student();
Person person1=student;

5.10static

public class Person {
    {
        System.out.println("匿名代码块");
    }
    static {//只会执行一次
        System.out.println("静态代码块");
    }
    public Person(){
        System.out.println("构造方法");
    }

    public static void main(String[] args) {
        System.out.println("111111111");
        Person person = new Person();
        System.out.println("===========");
        Person person1 = new Person();
    }
}
/*
静态代码块
111111111
匿名代码块
构造方法
===========
匿名代码块
构造方法
*/

5.11抽象类

抽象类不可以通过new实例化对象,子类继承抽象类,一定要重写抽象方法,抽象类中可以有正常方法

public abstract class Action {
    public abstract void run();
    public void test(){
        System.out.println("test");
    }
}
public  class A extends Action{

    @Override
    public void run() {

    }
}

5.12接口

只有抽象方法,实现约束和实现分离

public interface UserService {
    //默认为public abstract
    void add();
    void delete();
    void update();
    void query();
    //常量:默认为public static final
    int PI=99;
}
public interface TestService {
    void test();
}
public class UserServiceImpl implements UserService,TestService{
    @Override
    public void add() {

    }

    @Override
    public void delete() {

    }

    @Override
    public void update() {

    }

    @Override
    public void query() {

    }

    @Override
    public void test() {

    }
}

image-20250403192242143

5.13内部类

内部类就是在一个类的内部定义一个类

1.成员内部类2.静态内部类3.局部内部类4.匿名内部类

//成员内部类
public class Outer {
    private int ID=10;
    public void on(){
        System.out.println("这是一个外部类");
    }
    public class Inter{
        public void in(){
            System.out.println("这是一个内部类");
        }
        //可以获得外部类的私有属性
        public void getID(){
            System.out.println(ID);
        }
    }
}
public class Application {
    public static void main(String[] args) {
        Outer outer = new Outer();
        Outer.Inter inter = outer.new Inter();
        inter.in();
        inter.getID();
    }
}
//静态内部类
public class Outer {
    private int ID=10;
    public void on(){
        System.out.println("这是一个外部类");
    }
    public static class Inter{
        public void in(){
            System.out.println("这是一个内部类");
        }

    }
}
public class Application {
    public static void main(String[] args) {
        Outer.Inter inter = new Outer.Inter();
        inter.in();

    }
}

一个Java类中可以有多个class类,但是只能有一个public class类

//局部内部类
public class Outer {
    private int ID=10;
    public void math(){
        class Inter{
            
        }
        Inter inter = new Inter();
    }
}
//匿名内部类
public class Application {
    public static void main(String[] args) {
        new Apple().math();
        new UserService(){

            @Override
            public void test() {
                
            }
        };
    }
}
class Apple{
    public void math(){
        System.out.println("test");
    }
}
interface UserService{
    void test();
}

6.异常

6.1Error和Exception

image-20250403203353704image-20250403203750319

6.2捕获和抛出异常

异常处理关键字:try,catch,finally,throw,throws

public class Test {
    public static void main(String[] args) {
        int a=10;
        int b=0;
        //选中这行代码,ctrl+alt+t可以包裹代码
        //捕获异常
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            System.exit(1);
            e.printStackTrace();//打印错误的栈信息
        } finally {
            System.out.println("finally");
        }
    }
}
public class Test {
    public static void main(String[] args) {
        int a=10;
        int b=0;
       //假设捕获多个异常:从小到大
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            System.out.println("exception");
        } catch (Error e){
            System.out.println("Error");
        } catch (Throwable t){
            System.out.println("throwable");
        } finally {
            System.out.println("finally");
        }
    }
}
/*
exception
finally*/
public class Test {
    public static void main(String[] args) {
        try {
            new Test().test(1,0);
        } catch (ArithmeticException e) {
            throw new RuntimeException(e);
        }
    }
    //假设这方法中,处理不了这个异常。方法上抛出异常
    public void test(int a,int b)throws ArithmeticException{
       if(b==0){
           throw new ArithmeticException();
           //主动的抛出异常,一般在方法中使用
       }
    }
}
/*
Exception in thread "main" java.lang.ArithmeticException
	at Demo5.Test.test(Test.java:9)
	at Demo5.Test.main(Test.java:5)
*/

6.3自定义异常

image-20250403222513860

public class MyException extends Exception{
    //传递数字>10
    private int detail;

    //alt+insert选constructor
    public MyException(int detail) {
        this.detail = detail;
    }
    //alt+insert选toString
    @Override
    public String toString() {
        return "MyException{" + detail + '}';
    }
}
public class Test {
    static void test(int a) throws MyException {
        System.out.println("传递的参数为"+a);
        if(a>10){
            throw new MyException(a);//alt+enter选择抛出异常
        }
        System.out.println("ok");
    }

    public static void main(String[] args) {
        //alt+enter 捕获
        try {
            test(1);
        } catch (MyException e) {
            System.out.println(e);
        }

    }
}
/*
传递的参数为1
ok
*/
/*如果a=11,输出
传递的参数为11
MyException{11}
*/

posted @ 2025-04-04 21:22  wyy61  阅读(78)  评论(0)    收藏  举报