Mend the foundation of Java

JAVA overview:

Java is a high-level computer language. It is a fully object-oriented programming language that can write cross platform application software launched by SUN company (which has been acquired by Oracle company) in May 1995. Java language is easy to use, safe and reliable. It is mainly oriented to Internet programming. Since its inception, its related technologies and applications have developed very fast. Java technology is everywhere in the fields of computers, mobile phones, household appliances and so on.

In order to enable software developers, service providers and equipment manufacturers to develop for specific markets, SUN company divides Java into three technical platforms: JavaSE, JavaEE and JavaME.

Java SE (Java Platform Standard Edition) standard edition is a solution for developing ordinary desktop and business applications. JavaSE is the core part of the three platforms. Both JavaEE and JavaME are developed from JavaSE. JavaSE platform includes the core class libraries of Java, such as collection, IO, database connection and network programming.

Java EE(Java Platform Enterprise Edition) Enterprise Edition is a solution for developing enterprise applications. JavaEE can be regarded as a technical platform for developing, assembling and deploying enterprise applications, including Servlet, JSP, JavaBean, JDBC, EJB, Web Service and other technologies.

Java ME(Java Platform Micro Edition) small edition is a solution for developing consumer electronics products and embedded devices. JavaME is mainly used for the development of software programs on small digital electronic devices. For example, add intelligent control and networking functions for household appliances, and add new game and address book management functions for mobile phones. In addition, Java ME provides advanced Internet protocols such as HTTP, which enables mobile phones to directly access all Internet information in the form of Client/Server, and provides the most efficient wireless communication.

2. JDK and JRE

JDK(Java Development Kit): Java development tool

  • JRE(Java runtime Environment): the running environment of Java programs
    • JVM(Java Virtual Machine): Java virtual machine

Java Chinese website:

3. Java program running mechanism

Java language is not only a compiled language, but also an interpreted language

5. Java keyword

6. Java identifier

  • All components of Java need names. Class names, variable names, and method names are called identifiers.

  • All indicators should be in letters (A-Z or a-z), dollar sign $, or underscore_ Start.

  • Keywords cannot be used as variable or method names

  • Identifiers are case sensitive

7. What are bytes

  • Bit: it is the smallest unit of data storage in the computer. 11001100 is an eight bit binary number

  • byte: it is the basic unit of data processing in the computer. It is customarily expressed in capital B.

  • 1B (byte) = 8bit

  • Characters: letters, numbers, words and symbols used in computers

8. Java data type

Strongly typed language

  • Java stipulates that the use of variables should strictly comply with the regulations. All variables must be defined before they can be used

Java data types fall into two categories:

  • Basic data type

  • Reference data type

Default values for data types

9. Variable

What are variables

  • Java is a strongly typed language. No variable needs to declare its type

  • Java variable is the most basic storage unit in a program. Its elements include variable name, variable type and scope

10. Naming conventions for variable names

11. Operator

12. Package

  • In order to better organize classes, Java provides a package mechanism to distinguish the namespace of class names
  • The syntax format is:

Of which:

In order to use the members of a package, we can import the package "import"


  • The javadoc command is used to generate its own API documents

14. Scanner object

  • Java provides a tool class that can get user input

  • Basic grammar

  • next():

      1. Be sure to read valid characters before you can end the input
      1. The whitespace encountered before a valid character is encountered will be removed by next()
      2. After a space is recognized after a valid character, next () uses the space as a separator or terminator
      3. next cannot get a string with spaces
  • nextLine():

    1. End with Enter (Enter key), that is, the nextLine () method returns all characters before entering carriage return
    2. You can get a blank string

15. Process control statement

  • if

  • if else

  • switch

  • which loop (judge first and execute later)

  • Do... Which loop (execute first, then judge, at least once)

  • for loop

  • Enhanced for loop

    • It is mainly used for array [return without subscript] or collection

  • break

    • The loop flow can be controlled to forcibly exit the loop
  • continue

    • Used to terminate a cycle and then proceed to the next cycle

16. Java method

1. What are Java methods

  • Java methods are collections of statements that together perform a function

    • Method is an ordered combination of steps to solve a class of problems
    • Method is contained in a class or object
    • Method is created in the program
  • It is better for a method to complete only one function, which is conducive to later expansion

2. Definition of method

  • Method contains a method header and a method body

    • Modifier: This is optional and tells the compiler how to call the method
    • Return value type: a method may return a value. If there is a return value, define the return value. If not, use void
    • Method name: the actual name of the method
    • Parameter type: a method is like a placeholder. When called, it passes a value to the parameter, which is called an argument or variable. The parameter list refers to the parameter type of the method. Order and number of parameters. Parameters are optional. Methods can contain no parameters
      • Formal parameter: used to receive external input data when the method is called
      • Argument: the calling method is the data actually passed to the method
    • Method body: method body, which contains specific statements and defines the function of the method

3. Method overload

  • 1. What overload?
    • Overloading means that in a class, there are the same function names but different formal parameters
  • Rules:
    • Method names must be the same
    • The parameter list must be different (different number or type, different parameter sorting order, etc.)
    • Returned by the method; Ai Xin can be the same or different
    • Just because the return type is different is not enough to be an overload of a method

17. Method call

  • Calling method: object name. Method name (argument list)

  • Java has two ways to call methods, which are selected according to whether there is a return value

    • When the return value is

    • When the return value is void

      • Executing a statement

18. Variable parameters

  • In the method declaration, add an ellipsis (...) after the specified parameter type

  • A method can only specify one variable parameter, which must be the last parameter of the method. Other common methods should be declared before it.

19. Recursion

What is recursion?

  • ​ Method A calls method B, which is easy for us to understand
  • ​ Recursion is: method A calls method A and calls itself

20. Definition of array

1. What is an array?

  • Arrays are ordered collections of the same type
  • Each data is called an array element. Each element can be accessed through a subscript, and the subscript index starts from 0.

2. Array declaration creation

  • Array variables must be declared before arrays can be used in programs
  • Syntax:

  • The new operator is used in the Java language to create arrays

  • Syntax:

Get array length:

3. Characteristics of array

4. Graphic Array

5. Array creation

  • Static creation

  • Dynamic creation

6. Array bounds

  • Legal range of array subscript: [0, length-1]. If the industry reports an error:

7. Summary

  • An array is an ordered collection of the same data type
  • Arrays are also objects, and array elements are equivalent to member variables of objects
  • The length of the array is fixed and immutable. If it exceeds the limit, an error will be reported

21. Multidimensional array

  • Multidimensional arrays can be regarded as arrays. For example, a two-dimensional array is a special one-dimensional array, in which each element in a two-dimensional array is a one-dimensional array


22. Arrays

  • Array tool class java.util.Arrays
  • The methods in the Arrays class are static methods decorated with static, which can be called directly with the class name

Common functions:

23. Bubble sorting

24. Object oriented (OOP)

  • Before facing, first understand the following process

1. Process oriented thinking:

  • The steps are clear and simple. What to do in the first step and what to do in the second step, from top to bottom
  • Process oriented is suitable for dealing with some simple problems

2. Object oriented thinking:

  • Birds of a feather flock together, the thinking mode of classification. Thinking about problems will first solve the problems, and then think about these classifications separately. Finally, process oriented thinking is carried out on the details under a certain classification.
  • Object oriented is suitable for dealing with complex problems and problems requiring multi person cooperation.

3. What is object-oriented

  • Object oriented programming (OOP)

  • Essence: organize code in the form of classes and organize (encapsulate) data in the form of objects.

4. Three characteristics

  • encapsulation
  • inherit
  • polymorphic

25. Strengthening methods

Definition of method:

Modifier return value type method name (parameter...){
        Method body
    return Return value;
  • The return value must be of the same type as the return value
  • return ends the method and returns a result
  • Method name: pay attention to the specification and be aware of it
  • Parameter definition: (parameter type, parameter name
  • Exception throw

The difference between break and return

break: jump out of the switch and end the loop

return ends the method and returns a result

Method call:

Non static method:

//    Non static method
    public void student(){
        System.out.println("The students are very happy");

//        Non static method call
//        The Java call needs to instantiate new_ 09_ Fangfa3 class
        Java_09_FangFa3 fa3 = new Java_09_FangFa3();

Static method:

//    Static method
    public static void student1(){
        System.out.println("Big data cow!!!");

//        Static method call
//        Class. Method name

Formal and argument

//                        Formal parameter
    public static int min(int a ,int b){
        return a+b;

Value passing and reference passing

this keyword

26. Create and initialize objects

Create an object using the new keyword

  • When using the new keyword, in addition to allocating memory space, the created object will be initialized by default and the constructor will be called.

  • The constructor in a class can also be called a constructor. It must be called when creating an object, and the constructor has the following characteristics

    • Must be the same as the class name
    • There must be no return type and void cannot be written

Nonparametric Construction:

public class Person {
//    Even if a class doesn't write anything, it will have a method
    String name;

//    Parameterless constructor
//    Instantiation initial value
//    1. Using the new keyword requires a constructor. The essence of new is to call the constructor
    public Person() {

Parametric structure:

public class Person {
//    Even if a class doesn't write anything, it will have a method
    String name;

//    Parametric structure
//    Once there is a parametric structure, there must be a nonparametric structure
    public Person(String name) { = name;
  • Once a parametric construct is generated, a nonparametric construct will fail


//        Use of constructors
        Person person = new Person("xioahe");

Memory analysis:

Pet class

public class Pet {
    String name;
    int age ;

//    There is no parameter structure by default
    public Pet() {

    public void shout(){
        System.out.println( "Let out a cry");

Program entry:

Pet dog = new Pet();

// cat has no assignment
Pet cat = new Pet();


  • 1. Classes and objects
    • Class is a template: an abstract concept
    • Object is a concrete instance
  • 2. Methods: define and call
  • 3. Object reference
    • Reference type: there are eight basic types
    • Objects are operated by reference: stack -- > heap
  • 4. Properties: field member variables
    • ​ Default initialization
      • Number: 0.0
      • char : u0000
      • boolean: false
      • Reference: null
    • Modifier attribute type attribute name = attribute value;
  • 5. Object creation and use
    • You must use the new keyword to create an object. The constructor Person xiaohe = new Person();
    • Object's property
    • Object's method xiaohe.add();
  • 6. Class
    • Static properties -- > Properties
    • Dynamic behavior -- > method

27. Three OOP features

1. Encapsulation


  • The dew that should be exposed, the hide that should be hidden
    • We design programs to pursue "high cohesion and low coupling". High cohesion means that the internal data operation details of the class are completed by themselves, and external interference is not allowed; Low coupling: tightly expose a small amount of methods for external use;
  • Encapsulating data (data hiding)
    • Generally, we should directly access the actual representation of data in an object as soon as possible, and access it through the operation interface, which is called information shadow
  • Property private, get/set


  • Improve program security
  • Shadow code details
  • Unified interface
  • Increased program maintainability

2. Inherit

  • Keywords: Extensions
  • The subclass inherits from the parent class, and the subclass owns all the methods of the parent class
  • Classes in Java only have single inheritance, not multiple inheritance
  • In Java classes, all classes inherit the object class

Parent class

public class Person {



//                    Inherit keywords
public class Student extends Person {
//                    Inherit keywords
public class Teacher  extends  Person{


super keyword vs this keyword


  • super can only be used under inheritance
  • super calling the constructor of the parent class must be placed on the first line of the constructor
  • super can only appear in subclass methods or constructor methods
  • super and this cannot call the constructor at the same time (the constructor called by this must also be placed in the first line of the constructor)


  • 1. Different representative objects

    • This represents the object of this class
    • super represents the object of the parent class
  • 2. Different use premise

    • this can be used without inheritance
    • super: can only be used under inherited conditions
  • Constructor calls are different

    • this(); The method of this class is called
    • super(); The method of the parent class is called

Parent class

//This is a human
public class Person {
    protected String name = "lisi";

    public Person() {
        System.out.println("person No parameter execution");

    //Private things cannot be inherited
    public void print(){
        System.out.println("Java Is a good language 1!");



//This is a student class
//    A subclass inherits from the parent class and owns all the methods of the parent class
//    In Java classes, all classes inherit the Object class by default
//                    Inherit keywords
public class Student extends Person {
        private String name = "myhes";

    public Student() {
        //Hidden code, which calls the parameterless construction of the parent class, must be placed in the first line of the subclass constructor
        System.out.println("student No parameter execution");

    public void print1(){
            System.out.println("Java Is a good language 2!");

        public void test(String name){
            System.out.println(name);//xiaohe name entered by the program
            System.out.println(;//myhes gets the name in this class
            System.out.println(;//lisi gets the name of the parent class


        public void test1(){
            this.print1();  //This points to the method of this class
            super.print();  //super points to the parent class method


Method rewrite

  • Override requires inheritance. Subclasses override the methods of the parent class!
  • Method names must be the same
  • Modifier: the scope can be expanded, but not reduced: public > protected > Default > private
  • Exception thrown: the scope can be reduced, but not expanded

In a word: the methods of the subclass and the parent class must be the same: the method body is different

Why rewrite:

  • The function of the parent class does not meet the needs of the child class

Parent class

public class A {
    public  void add(){



public class B extends A{

//    Static methods are very different from non static methods
    // Static: method calls are only related to the types defined by A and B

    //Non static: non static methods are called rewriting,

//    Override override
    @Override  //Annotation: functional annotation
    public void add() {
        System.out.println("big data");


//        rewrite
        B b = new B();

//        A reference to a parent class points to a child class
        A a = new B();//The child class overrides the method of the parent class

3. Polymorphism


  • One method can adopt many different methods according to different sending objects
  • The actual type of an object is determined, but there can be many types that can be pointed to
    • The types pointed to can be: parent class: related class
Conditions for polymorphism:
  • There is an inheritance relationship
  • Subclasses override methods of the parent class
  • A parent class reference points to a child class object
be careful:

Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes

Person parent class

public class Person {

    public void sun(){
        System.out.println("This is an addition");


student subclass

 public class Student extends Person{
    public void sun() {
        System.out.println("Enhanced addition");

    public void jian(){
        System.out.println("This is a subtraction");


Program class

//        polymorphic
//        The methods that a subclass can call are its own and those of its parent class
        Student student1 = new Student();

//        Point to parent class
//        The parent type can point to a subclass and cannot call methods unique to subclasses
        Person student2 = new Student();
//        grandpa
        Object student3 = new Student();

//        When the method is overridden, the method called by the parent class also goes to the side of the child class

        ((Student) student2).jian();


instanceof (type conversion)

//        instanceof

//        Object > Person >Student
//        Object > String
//        true only if inheritance exists
        Object obj = new Student();
        System.out.println(obj instanceof Student);//true
        System.out.println(obj instanceof Person);//true
        System.out.println(obj instanceof Object);//true
        System.out.println(obj instanceof String);//false

28. static keyword

Student class

public class Student  {

    private static int age;//Static variable
    private double score; //Non static variable

//    Non static method
    public void run(){


//    Static methods, static attributes and static attribute classes are loaded together, so they can be called directly
    public static void add(){


    public static void main(String[] args) {
//        Student s1 = new Student();
//        System.out.println(s1.score); // Access by object

//        age / / static variables can be called directly

//        Student.age / / class variable

        Student s2 = new Student();;// Accessing non static methods through objects

        add();// Static methods can be called directly


Person class

//Static code block
public class Person {
    {   // Anonymous code block, before constructor
        System.out.println("This is an anonymous block of code");

    static { //Static code block, executed only once
        System.out.println("This is a static block of code");

    public Person(){
        System.out.println("Construction method");

    public static void main(String[] args) {
        Person person1 = new Person();
        Person person2 = new Person();

This is a static block of code
        This is an anonymous block of code
    Construction method
    This is an anonymous block of code
            Construction method

  • Static attributes and static methods can be called directly in the class (because static attributes are loaded together with class generation, they can be called directly)
  • However, non static properties and methods need to be called through objects
  • Static code blocks are executed only once

29. abstract class

  • The abstract modifier can also modify a class
  • Ordinary methods can be written in abstract classes, and single abstract methods must be unloaded from abstract classes
  • Abstract classes cannot use the new keyword to create objects
  • Abstract methods have only method declarations and no method implementations. They are implemented using subclasses (constraints)

30. Interface

Common class: only concrete implementation

Abstract classes: concrete implementations and specifications (abstract methods) are available!

Interface: there are only specifications. You cannot write methods yourself

  • The keyword for declaring a class is class, and the keyword for declaring an interface is interface

  • An interface is a specification. It defines a set of rules and implements the idea of "if you are, you must be able to..." in the real world

  • The essence of an interface is a contract. Just like the laws among us, we must abide by them when they are formulated

  • Interface is the essence of OO and the abstraction of objects

  • The interface cannot be instantiated because there is no constructor in the interface

  • Implementations can implement multiple interfaces

  • The method is modified (Abstract) by public abstract by default

  • The attribute is modified by public static final (constant) by default

  • In the implementation class, you must override the methods of the interface

Interface I

//Interface keyword interface
public interface UserService {

//    public void run(){
//    }
    //All definitions in the interface are abstract and use the public abstract modifier
//    public abstract void run();
   void add(String name);
   void delete(String name);
   void update(String name);
   void query(String name);


Interface II

public interface TimeService {
    void time();

Implementation class

//This is an interface implementation class
//    Classes inherit from JAVA through the implements interface, but multiple inheritance can be realized through the interface
public class UserServiceImpl implements UserService,TimeService {

//If you implement the class of the interface, you need to rewrite the methods in the interface
    public void add(String name) {
        System.out.println("Today is Friday");

    public void delete(String name) {


    public void update(String name) {


    public void query(String name) {


    public void time() {


31. Internal class

What is an inner class

  • Internal class is to define a class inside a class. For example, if a class B is defined in class A, then B is called internal class relative to a, and class A is called external class relative to class B

  • 1. Member inner class

  • 2. Static inner class

  • 3. Local inner class

  • 4. Anonymous inner class

Member inner class

public class Outer {
    private int age = 18;
    public void run(){
        System.out.println("This is an external class");

//    Inner class
    public class add{
        public void add(){
            System.out.println("This is an inner class");
            //        The inner class can obtain the private properties / methods of the outer class
        public void e1(){

Static inner class

   //    Static inner class
   public static class add{
        public void add(){
            System.out.println("This is a static inner class");

Local inner class

//    Local inner class
// Write another class in the method
    public void run1(){
        class Inner{

Anonymous Inner Class

public class Test {
    public static void main(String[] args) {
//        There is no name to instantiate the class, so there is no need to save the instance to the variable
//        Anonymous Inner Class 
        new Outer().run();

32. Exception

What is an exception

Exception classification:

Abnormal architecture

Java exception hierarchy:

33. Exception handling mechanism

processing method

  • Throw exception (throw, throws)
  • Catch exception (try, catch, finally)
  • Throwing an exception means not handling the exception, and catching an exception means handling the exception

There are five keywords for exception handling:

  • try ,catch , finally , throw , throws

    Catch exception

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
//     Catch exception
//        If you want to catch multiple exceptions: from small to large according to the exception hierarchy
        try {  //Monitor abnormal areas
        } catch (Exception e) { //Catch catch exception
            System.out.println("Program error"); //Execute code block after catching exception
        }finally { //Deal with the aftermath
//        finally, No


Tags: Java

Posted on Fri, 12 Nov 2021 03:42:33 -0500 by swordske