Online tools

java https://c.runoob.com/compile/10

Write and run Java 8 online https://www.tutorialspoint.com/compile_java8_online.php

SQL online running https://www.bejson.com/runcode/sql/

Java cattle question bank https://www.nowcoder.com/intelligentTest

JDK, JRE, JVM

  • JDK : Java Development Kit
  • JRE : Java Runtime Enviroment
  • JVM : Java Virtual Machine

Output Hello Wolrd

vim Hello.java
public class Hello{
    public static void main(String[] args){
        System.out.print("Hello World!");
    }
}

Compile

javac Hello.java

implement

java Hello

Output

Hello World!

Java program operating mechanism

  • Compiled type:
  • Interpretative:
  • Program operating mechanism:

    Source file (*.java) => Java compiler => bytecode (.class)

    => JVM (Class Loader => Bytecode Verifier => Interpreter)

    => Operating System Platform

IDEA

New Construction

File => New => Project… => Empty Project

File => Project Structure => Project => Project SDK (1.8.0) => Project language level (8) => OK

Basic grammar

1. Comments, identifiers, keywords

Annotation
//单行注释
/* 多行注释 */
/**
  * 文档注释
  * @Author itxiaoma
  */
Identifier
Class names, variable names, and method names are all called identifiers
  • Identifier starts with a letter, dollar ($), underscore (_)
  • The first letter can be a combination of letters, dollar ($), underscore (_), and numbers
  • Cannot use keywords as variable names, method names
  • Case Sensitive
Keywords (50+)

avator

2. Data type

Strongly typed language: Variables must be used strictly in compliance with regulations, and all variables must be defined before they can be used
Java data types
  1. Basic types: (8 basic types)

    1. Numerical value

      1. Integer

        1. byte: 1 byte (-128~127)
        2. short: 2 bytes (-32768~32767)
        3. int: 4 bytes (-2147483648~2147483647) 2.1 billion +
        4. long: 8 bytes (for example: long num=40L;)
      2. floating point

        1. float: 4 bytes (for example: float num=40F;)
        2. double: 8 bytes
      3. String char: 2 bytes
    2. boolean: 1 bit, true/false
  1. Reference type: class, interface, array

Note 1: String is not a data type, but a class

Note 2: 1bit means 1 bit; (bit is the smallest unit of computer internal data storage)

​ 1Byte means 1 byte, 1B=8b;

​ 1KB = 1024B;

​ 1MB = 1024KB;

​ 1GB = 1024MB;

​ 1TB = 1024GB;

Common problems with Java data types
  1. Integer extension

    int a = 10;
    int b = 010;//八进制
    int c = 0x10;//十六进制
  2. Floating point extension

    float f = 0.1f;
    double d = 1.0/10;
    System.out.println(f==d);//false
    
    float d1 = 123123123123f;
    float d2 = d1 + 1;
    System.out.println(d1==d2);//true
    
    //float 有限 离散 舍入误差 接近但不等于
    //不要用浮点数进行比较
    //数学工具类BigDecimal
  3. Character class extension

    char a = 'a';
    System.out.println((int)a);//97
    char a1 = '\u0061';
    System.out.println(a1);//a
    //所有的字符本质还是数字
    
    转义字符:
    \t 制表符
    \n 换行
    ...

3. Type conversion

In operation, different types of data will be converted to the same type first, and then calculated

Priority: low ==> high

byte,short,char => int => long => float => double

Automatic conversion: low => high

Coercion: high => low (type) variable name

Note 1:

  1. Cannot convert boolean values
  2. Cannot convert object type to irrelevant type
  3. High capacity to low capacity, there will be memory overflow or accuracy problems

Note 2: New features of JDK7, numbers can be separated by underscores (1000 = 1_000)

4. Variables, constants, scope

variable
int a = 1;
Constant-final
Constant: can not be changed after initialization, generally uppercase
static final double PI = 3.14;
Scope
  1. Class variable
  2. Instance variable
  3. Local variable
public class Hello {
    //类变量:static
    static int a = 1;
    //实例变量:属于对象,不需要初始化(会自动初始化为类型默认值)
    //布尔值默认false,除基本类型以外其他变量都是null
    String b;
    public static void main(String[] args) {
        System.out.println(a);

        int c = 3;//局部变量:必须声明和初始化
        System.out.println(c);

        Hello obj = new Hello();
        System.out.println(obj.b);//null
    }
}
Naming rules:
  1. Class variables, local variables, method names: camel case (the first letter is lowercase)
  2. Constant: uppercase + underscore
  3. Type: Camel case (first letter capitalized)

5. Basic operators

  1. Arithmetic operators: +, -, *, /, %, ++, -
  2. Assignment operator: =
  3. Relational operators: >, <, >=, <=, ==, !=, instanceof
  4. Logical operators: &&,||,!
  5. Bitwise operators: &, |, ^, ~, >>, <<, >>>
  6. Conditional operator:?:
  7. Extended assignment operators: +=, -=, *= ,/=

example:

long a = 123L;
int b = 123;
short c = 10;
byte d = 8;
System.out.println(a+d);//long
System.out.println(b+c);//int
System.out.println(c+d);//int
//结论:有long类型时转long,否则转int

Exponentiation: 2^3

double pow = Math.pow(2, 3);
System.out.println(pow);//8.0

Bit operation

<< 乘2 
>> 除2

6. Package mechanism

The essence of a package is a folder
  1. The package mechanism is to better organize the classes, used to distinguish the namespace of the class name
  2. Generally use the company name inversion as registration pakage com.baidu.www;
  3. Use import to import the package (import package name.* means import all classes under the package)

7. JavaDoc generates documentation

Annotation parameters

/**
 * @author 作者
 * @version 版本
 * @since 需要最早使用的jdk版本
 * @param 参数
 * @return 返回值
 * @throws 异常抛出
 */

Chinese encoding

javadoc -encoding UTF-8 -charset UTF-8 Demo.java

Process control

1. User interaction Scanner (Java5 new feature)

Basic use

import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        //创建扫描器对象,用于接收键盘数据
        Scanner s = new Scanner(System.in);
        //判断用户输入
        if(s.hasNextLine()){
            String str = s.nextLine();
            System.out.println(str);
        }
        //IO流的类会一直占用内存,用完需要关闭
        s.close();
    }
}
//next()以空格为结束符,nextLine()以回车为结束符

Use advanced

Calculate the sum and average of multiple numbers, the non-number ends
Scanner s = new Scanner(System.in);
double sum = 0;
int num = 0;
while(s.hasNextDouble()){
    double x = s.nextDouble();
    sum += x;
    num++;
}
System.out.println("和是:" + sum);
System.out.println("平均值是" + (sum/num));
s.close();

2. Nine-Nine Multiplication Table

/*
1*1=1    
2*1=2    2*2=4    
3*1=3    3*2=6    3*3=9    
4*1=4    4*2=8    4*3=12    4*4=16    
5*1=5    5*2=10    5*3=15    5*4=20    5*5=25    
6*1=6    6*2=12    6*3=18    6*4=24    6*5=30    6*6=36    
7*1=7    7*2=14    7*3=21    7*4=28    7*5=35    7*6=42    7*7=49    
8*1=8    8*2=16    8*3=24    8*4=32    8*5=40    8*6=48    8*7=56    8*8=64    
9*1=9    9*2=18    9*3=27    9*4=36    9*5=45    9*6=54    9*7=63    9*8=72    9*9=81    
*/
for (int m = 1; m <= 9; m++) {
    for (int n = 1; n <= m; n++) {
        System.out.print(m + "*" + n + "=" + (m * n) + "\t");
    }
    System.out.println();
}
//System.out.print 不换行输出

3. Enhance the for loop (new features of JDK1.5)

int[] numbers = {1, 2, 3, 4, 5};
for (int x : numbers) {
     System.out.println(x);
}

4.label

Print all prime numbers between 101 and 150
outer:for (int i = 101; i <= 150; i++) {
    for (int j = 2; j < i / 2; j++) {
        if (i % j == 0) {
            continue outer;
        }
    }
    System.out.println(i);
}

Java method

A method is a code fragment used to complete a specific function, composed of a method name and a method body

Method name: Modifier return value type method name (parameter type parameter name) {}

Method body: return return value;

Parameter type: actual parameter, formal parameter

Note: Java is all passed by value, not passed by reference

1. Method overload

Overloading is a function with the same function name but different formal parameters in a class

Method overloading rules:

  1. Method name must be the same
  2. The parameter list must be different (number, type, parameter order are different)
  3. The return type can be the same or different

2. Command line parameter transfer

Pass parameters when the program is running, you can pass through the main method
public static void main(String[] args) {
    for (int i = 0; i < args.length; i++) {
        System.out.println(args[i]);
    }
}

3. Variable parameters (new features of JDK1.5)

public static void main(String[] args) {
    test(1,2,3);
}
public static void test(int... i){
    System.out.println(i[0]);
    System.out.println(i[1]);
    System.out.println(i[2]);
}

4. Recursion

Recursive header: when not to call its own method. If there is no head, it will fall into an endless loop.

Recursive body: When do you need to call your own method.

Java array

An array is an ordered collection of data of the same type
dataType[] arrayRefVar = new dataType[size];

int nums[] = new int[10];
//二维数组
int[][] n = new int[2][2];
int[][] n = {{1,2},{3,4}} 

Basic Features

  1. The length is determined, once created, the length is immutable
  2. The element types must be the same
  3. The array object itself is in the heap (array is a reference type and can be regarded as an object, array elements are equivalent to the member variables of the object, and Java objects are in the heap)

Memory analysis

graph LR
A(java内存)
A --> B(堆)
      B -->B1[存放new的对象和数组]
      B -->B2[可以被所有线程共享,不会存放别的对象引用] 
A --> C(栈)
      C -->C1[存放基本变量类型,包含具体数值]
      C -->C2[引用对象的变量,存放引用在堆中的地址] 
A --> D(方法区)
      D -->D1[可以被所有线程共享]
      D -->D2[包含所有calss和static变量] 
//1.声明数组
int[] nums;//在栈中
//2.创建数组
nums = new int[10];//在堆中

Three initialization states

//静态初始化
int[] a = {1, 2, 3};
Man[] mans = {new Man(1),new Man(2)}

//动态初始化(包含默认初始化)
int[] b = new int[10];//默认分配10个0
b[0] = 10;

Note: The array is a reference type, and the array elements are equivalent to the instance variables of the class. Space is allocated when the array is created, and the array elements are also initialized with default values.

Array utility class java.util.Arrays

Print array elementsArrays.toString(a);
Array fillArrays.fill(a, 0 , 1, 0);The elements of the array subscript 0-1 are filled with 0
Array sortArrays.sort(a);
Compare arrayequals
Find array elementsbinarySearchBinary search on the sorted array

Bubble Sort

  1. There are eight sorts
  2. Time complexity is O(n2)

Sparse array

When most of the elements in an array are 0 or the same value, you can use a sparse array to save

Processing method:

1. Record the number of rows and columns of the array, and the number of different values

2. Record the element row and column information of different values ​​and the element value in a small-scale array

/*
稀疏数组
1    2    1
2    3    2
还原数组
0    0    0    0    0    0    0    0    0    0    0    
0    0    1    0    0    0    0    0    0    0    0    
0    0    0    2    0    0    0    0    0    0    0    
0    0    0    0    0    0    0    0    0    0    0    
0    0    0    0    0    0    0    0    0    0    0    
0    0    0    0    0    0    0    0    0    0    0    
0    0    0    0    0    0    0    0    0    0    0    
0    0    0    0    0    0    0    0    0    0    0    
0    0    0    0    0    0    0    0    0    0    0    
0    0    0    0    0    0    0    0    0    0    0    
0    0    0    0    0    0    0    0    0    0    0    
*/
public class Demo {
    public static void main(String[] args) {
        int[][] array1 = new int[11][11];
        array1[1][2] = 1;
        array1[2][3] = 2;
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (array1[i][j] != 0) {
                    sum++;
                }
            }
        }
        int[][] array2 = new int[sum + 1][3];
        array2[0][0] = 11;
        array2[0][1] = 11;
        array2[0][2] = sum;
        int count = 0;
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array1[i].length; j++) {
                if (array1[i][j] != 0) {
                    count++;
                    array2[count][0] = i;
                    array2[count][1] = j;
                    array2[count][2] = array1[i][j];
                }
            }
        }
        System.out.println("稀疏数组");
        for (int j = 1; j < array2.length; j++) {
            System.out.println(array2[j][0] + "\t" + array2[j][1] + "\t" + array2[j][2]);
        }
        System.out.println("还原数组");
        int[][] array3 = new int[array2[0][0]][array2[0][1]];
        for (int j = 1; j < array2.length; j++) {
            array3[array2[j][0]][array2[j][1]] = array2[j][2];
        }
        for (int[] ints : array3) {
            for (int num : ints) {
                System.out.print(num + "\t");
            }
            System.out.println();
        }
    }
}

Object-oriented

Organize code in classes. Organize (encapsulate) data by objects

Three characteristics: encapsulation, inheritance, polymorphism

1. Create classes and objects

There should only be one main method in a project
Create an object
When using new to create an object, in addition to allocating memory space, the created object will also be initialized by default, and the constructor in the class will be called.

com/oop/demo/Application.java

package com.oop.demo;
public class Application {
    public static void main(String[] args) {
        //类:抽象的,实例化后会返回一个自己的对象
        Student xiaoming = new Student();
        Student xiaohong = new Student();
        xiaoming.name = "小明";
        xiaoming.age = 20;
        xiaohong.name = "小红";
        xiaohong.age = 21;
        System.out.println("姓名:" + xiaoming.name + "\t年龄:" + xiaoming.age);
        xiaoming.study();
        System.out.println("姓名:" + xiaohong.name + "\t年龄:" + xiaohong.age);
        xiaohong.study();
    }
}

com/oop/demo/Student.java

package com.oop.demo;
public class Student {
    //属性
    String name;
    int age;
    //方法
    public void study() {
        System.out.println(this.name + "在学习");
    }
}
Constructor (construction method)
  1. Must be the same as the class name
  2. Must have no return type (cannot write void)
  3. Once a parameterized constructor is defined, you must write a parameterless constructor if you don’t want to pass parameters when you new object
public class Student {
    //属性
    String name;
    int age;
    //无参(默认)构造器
    public Student(){
        
    }
    //有参
    public Student(String name){
        this.name = name;
    }
    public Student(String name,int age){
        this.name = name;
        this.age = age;
    } 
}

Create object memory analysis

public class Application {
    public static void main(String[] args) {
        //类:抽象的,实例化后会返回一个自己的对象
        Student xiaoming = new Student();
        Student xiaohong = new Student();
        xiaoming.name = "小明";
        xiaoming.age = 20;
        xiaohong.name = "小红";
        xiaohong.age = 21;
        System.out.println("姓名:" + xiaoming.name + "\t年龄:" + xiaoming.age);
        xiaoming.study();
        System.out.println("姓名:" + xiaohong.name + "\t年龄:" + xiaohong.age);
        xiaohong.study();
    }
}

The method area is also in the heap;

The static method area is loaded with the class, so the static method can be called directly without instantiation

  1. Load Application and Student class information to the method area
  2. Load the main() method to the stack
  3. Load xiaoming and xiaohong quoted variable names into the stack
  4. Load Student xiaoming = new Student(); and Student xiaohong = new Student(); instances to the heap
  5. xiaoming and xiaohong call the study method in the method area

Note: The variables outside the basic types are all reference types, which are operated by reference; the reference name is in the stack and points to the address of the object entity in the heap.

Encapsulation

It is forbidden to directly access the actual representation of the data in an object, and should be accessed through interface operations.

Property private (private), get/set

public class Student {
    private String name;
    private int age;
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getAge() {
        return age;
    }
}

Inherits

The essence of inheritance is the abstraction of a certain batch of classes, so as to achieve better modeling;

Inheritance is the relationship between classes, subclasses extend all public methods of the parent class;

Private properties and methods cannot be inherited

Note:

  1. There is only single inheritance in Java, no multiple inheritance (a child class can only have one parent class)
  2. All classes in Java inherit the Object class directly or indirectly by default

Super

be careful
  1. Super calls the constructor of the parent class, which must be in the first line of the constructor
  2. super can only appear in methods or construction methods of subclasses
  3. super and this cannot be called in the constructor at the same time (both need to be in the first line)
The difference between super and this
thissuper
Representative objects are differentCaller's own objectReference to the parent object
Different prerequisitesCan be used without inheritanceCan only be used when there is inheritance
Call the construction method is differentCall the constructor of this classCall the constructor of the parent class

com/oop/demo/Application.java

package com.oop.demo;

public class Application {
    public static void main(String[] args) {
        Student xiaoming = new Student();
        xiaoming.test1();
        //Person无参构造
        //Student无参构造
        //Student
        //Student
        //Person
    }
}

com/oop/demo/Person.java

package com.oop.demo;

public class Person {
    public Person() {
        System.out.println("Person无参构造");
    }
    public void print(){
        System.out.println("Person");
    }
}

com/oop/demo/Student.java

package com.oop.demo;

public class Student extends Person{
    public Student() {
        //隐藏代码:调用了父类的无参构造super();
        //super();
        System.out.println("Student无参构造");
    }
    public void print(){
        System.out.println("Student");
    }
    public void test1(){
        print();
        this.print();
        super.print();
    }
}

Method override @Override

The method of the subclass and the parent class must be consistent, and the method body is different

Rewriting is the rewriting of methods, and has nothing to do with attributes

Static methods cannot be overridden!

be careful
  1. Method name, parameter list must be the same
  2. The range of modifiers can be expanded but not reduced
  3. The scope of throwing exceptions can be reduced but not expanded
Code example

Static method

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();//A=>test()
        //父类的引用指向了子类
        B b = new A();
        b.test();//B=>test()
    }
}

Method rewriting

public class B {
    public void test(){
        System.out.println("B=>test()");
    }
}
public class A extends B{
    @Override
    public void test() {
        System.out.println("A=>test()");
    }
}
public class Application {
    public static void main(String[] args) {
        A a = new A();
        a.test();//A=>test()
        B b = new A();
        b.test();//A=>test()
    }
}

Polymorphism

The same method adopts a variety of different behaviors according to different sending objects;

The type of an object is determined, but there are many reference types that can point to the object (subclass, parent class, Object)

Conditions for the existence of polymorphism:

  1. Inheritance
  2. Subclass overrides the parent class method
  3. The parent class reference points to the child class object

Note: Polymorphism is the polymorphism of the method, there is no polymorphism in the attribute.

Methods that cannot be overridden
  1. static method, belongs to the class, not the instance
  2. final constants (final modified classes cannot be inherited)
  3. private method
//子类能调用的方法都是自己的或继承父类的
A a = new A();
B b = new B();
//对象能执行哪些方法看左边的引用类型
//父类引用可以指向子类,但不能调用子类独有的方法
B c = new A();
a.test();//A=>test()
b.test();//B=>test()
//子类重写了父类方法,会执行子类的方法
c.test();//A=>test()

instanceof and type conversion

  1. Parent class references can point to objects of subclasses, but not vice versa
  2. The conversion of the subclass to the parent class is called up-casting, which may lose some of its original methods
  3. The conversion of the parent class to the subclass is called downcasting, and requires a forced conversion
public class Application {
    public static void main(String[] args) {
        //子类特有方法go
        Student s = new Student();
        s.go();
        //向上转型,转型后无法再调用go方法
        Person p = s;
        //向下转型
        ((Student) p).go();
    }
}

static keyword

Static variable
private static int age;
Static method
public class Application {
    private static void test(){
        System.out.println("Static Function");
    }
    public static void main(String[] args) {
        test();
    }
}
Static code block
public class Person {
    {
        System.out.println("匿名代码块");
    }
    static {
        System.out.println("静态代码块");//只会在类加载时执行一次
    }
    public Person() {
        System.out.println("构造方法");
    }
    public static void main(String[] args) {
        Person p = new Person();
        //静态代码块
        //匿名代码块
        //构造方法
    }
}
Static import package
import static java.lang.Math.random;
public class Person {
    public static void main(String[] args) {
        System.out.println(random());
    }
}

Abstract class abstract

//抽象类 (接口可以多继承)
abstract class Person {
    public abstract void doSomething();//抽象方法:只有方法名,没有方法体
}

Note:

  1. Abstract classes cannot be new, but can only be implemented by subclasses
  2. Abstract methods must be in abstract classes, but abstract classes can contain ordinary methods

Interface

Abstraction of objects, separation of constraints and realization: interface-oriented programming

Note:

  1. The interface cannot be instantiated, there is no constructor in the interface
  2. All methods in the interface are abstract (public abstract)
  3. There are only constants in the interface (public static final)
  4. Classes implement interfaces through implements, and a class can implement multiple interfaces to achieve multiple inheritance
  5. The class that implements the interface must rewrite all methods in the interface
public interface UserService {
    void userTest1();
    void userTest2();
}
public interface TimeService {
    void time1();
    void time2();
}
public class UserTime implements UserService,TimeService{
    @Override
    public void userTest1() {
    }
    @Override
    public void userTest2() {
    }
    @Override
    public void time1() {
    }
    @Override
    public void time2() {
    }
}

Inner class

Anonymous object: do not save the instance to the variable (stack), only use the object in the heap memory

public class Application {
    public static void main(String[] args) {
        new Apple().eat();
    }
}
class Apple{
    public void eat(){
        System.out.println("吃苹果");
    }
}

Anonymous inner class

public interface UserService {
    void userTest1();
    void userTest2();
}
public class Application {
    UserService u = new UserService() {
        @Override
        public void userTest1() {
        }
        @Override
        public void userTest2() {
        }
    };
}

Error Exception

Error

The Error class object is generated and thrown by the JVM. Most errors have nothing to do with the operation. When an error occurs, the JVM generally terminates the thread;

Such as memory overflow (OutOfMemeryError), stack overflow, class definition error (NoClassDefFoundError), link error (LinkageError)

Exception

Exceptions are usually caused by logic errors and should be avoided as much as possible
  1. Non-runtime exception (IO exception...)
  2. RuntimeException (RuntimeException)

Note: Errors are usually fatal errors that cannot be handled by the program; Exceptions can and should usually be handled as much as possible.

Exception handling mechanism

  1. try monitoring area (required)
  2. catch catch exception (necessary)
  3. finally final processing (release occupied resources)
  4. throw throws an exception (usually used in methods)
  5. throws

Note: Catching multiple exceptions requires starting from small to large XXXException <XXXException <Throwable

public class Application {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try{
            if(b == 0){
                throw new ArithmeticException();
            }
            System.out.println(a/b);
        }catch (ArithmeticException e){
            e.printStackTrace();//打印错误的栈信息
        }catch (Exception e){
            
        }catch (Throwable e){
            
        }finally {
            
        }
    }
}

Custom exception

User-defined exception class, only need to inherit Exception class
public class MyException extends Exception {
    String msg;

    public MyException(String msg) {
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "MyException{" + msg + "}";
    }
}
public class Application {
    static void test(String msg) throws MyException{
        throw new MyException(msg);
    }
    public static void main(String[] args) {
        try{
            test("test");
        }catch (MyException e){
            System.out.println(e);//MyException{test}
        }
    }
}

IT小马
1.2k 声望166 粉丝

Php - Go - Vue - 云原生