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+)
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
Basic types: (8 basic types)
Numerical value
Integer
- byte: 1 byte (-128~127)
- short: 2 bytes (-32768~32767)
- int: 4 bytes (-2147483648~2147483647) 2.1 billion +
- long: 8 bytes (for example: long num=40L;)
floating point
- float: 4 bytes (for example: float num=40F;)
- double: 8 bytes
- String char: 2 bytes
- boolean: 1 bit, true/false
- 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
Integer extension
int a = 10; int b = 010;//八进制 int c = 0x10;//十六进制
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
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:
- Cannot convert boolean values
- Cannot convert object type to irrelevant type
- 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
- Class variable
- Instance variable
- 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:
- Class variables, local variables, method names: camel case (the first letter is lowercase)
- Constant: uppercase + underscore
- Type: Camel case (first letter capitalized)
5. Basic operators
- Arithmetic operators: +, -, *, /, %, ++, -
- Assignment operator: =
- Relational operators: >, <, >=, <=, ==, !=, instanceof
- Logical operators: &&,||,!
- Bitwise operators: &, |, ^, ~, >>, <<, >>>
- Conditional operator:?:
- 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
- The package mechanism is to better organize the classes, used to distinguish the namespace of the class name
- Generally use the company name inversion as registration pakage com.baidu.www;
- 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:
- Method name must be the same
- The parameter list must be different (number, type, parameter order are different)
- 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
- The length is determined, once created, the length is immutable
- The element types must be the same
- 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
//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 elements | Arrays.toString(a); | |
---|---|---|
Array fill | Arrays.fill(a, 0 , 1, 0); | The elements of the array subscript 0-1 are filled with 0 |
Array sort | Arrays.sort(a); | |
Compare array | equals | |
Find array elements | binarySearch | Binary search on the sorted array |
Bubble Sort
- There are eight sorts
- 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)
- Must be the same as the class name
- Must have no return type (cannot write void)
- 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
- Load Application and Student class information to the method area
- Load the main() method to the stack
- Load xiaoming and xiaohong quoted variable names into the stack
- Load Student xiaoming = new Student(); and Student xiaohong = new Student(); instances to the heap
- 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:
- There is only single inheritance in Java, no multiple inheritance (a child class can only have one parent class)
- All classes in Java inherit the Object class directly or indirectly by default
Super
be careful
- Super calls the constructor of the parent class, which must be in the first line of the constructor
- super can only appear in methods or construction methods of subclasses
- 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
this | super | |
---|---|---|
Representative objects are different | Caller's own object | Reference to the parent object |
Different prerequisites | Can be used without inheritance | Can only be used when there is inheritance |
Call the construction method is different | Call the constructor of this class | Call 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
- Method name, parameter list must be the same
- The range of modifiers can be expanded but not reduced
- 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:
- Inheritance
- Subclass overrides the parent class method
- 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
- static method, belongs to the class, not the instance
- final constants (final modified classes cannot be inherited)
- 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
- Parent class references can point to objects of subclasses, but not vice versa
- The conversion of the subclass to the parent class is called up-casting, which may lose some of its original methods
- 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:
- Abstract classes cannot be new, but can only be implemented by subclasses
- 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:
- The interface cannot be instantiated, there is no constructor in the interface
- All methods in the interface are abstract (public abstract)
- There are only constants in the interface (public static final)
- Classes implement interfaces through implements, and a class can implement multiple interfaces to achieve multiple inheritance
- 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
- Non-runtime exception (IO exception...)
- 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
- try monitoring area (required)
- catch catch exception (necessary)
- finally final processing (release occupied resources)
- throw throws an exception (usually used in methods)
- 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}
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。