Java notes (basic sorting)

Posted by jomama on Sat, 05 Mar 2022 15:06:58 +0100

Java notes (basic sorting)

In the rookie tutorial, the foundation of java is very comprehensive and thorough data type

java is a strongly typed language. Variables must be declared to indicate their data types before use.

  • Basic data types: byte, short, int, long, float, double, boolean, char
  • Reference data types: array, class, interface, enumeration, annotation, String class

Conversion between data types: automatic type conversion and forced type conversion

Automatic: from small to large

Strong turn: from big to small

int a = (int)10.9

2. Operator

Arithmetic operators: +, -, *, /,%

String concatenation operator: + (it is basically not used in normal production. String concat method is used to realize string splicing)

Relational / comparison operators: >, > =, <, < =, = =,! =, Relational operator returns boolean type

Self increasing and decreasing operators: + +, –, which can only be used for variables to make the value of the current variable add (subtract) 1

Logical operators: & &, |!, Returns a boolean expression

Ternary operator (often used as a simple maximization): conditional expression? Expression 1: expression 2

int a = 2;
int c = 3;
int b = (a > c) ? a : c;

Assignment operators: =, + =, - =, * =, / =,%=

Shift operators (not commonly used): <, > >, > > >

Bitwise operators (not commonly used): &, |, ~^

3. Process control statement

Branch structure: if branch, Switch branch

if branch structure:

if(a>0){"Start execution a>0 Branch of");

If else branch structure:

if(a>0){"Start execution a>0 Branch of");
}esle{"implement else branch")

If else branch structure:

if(a<1000){"Start execution a<1000 Branch of");
}else if(a<2000){
    // The interval value involved in the production environment is generally based on the principle of left closing and right opening"Start execution 1000<=a<2000 Branch of");
}esle if(a<3000){"Start 2000<=a<3000 Branch of");
}esle{"Start execution a>=3000 of else branch");

switch case branch structure:

// Example: test score judgment
switch(score / 10){
	case 0;
    case 1;
    case 2;
    case 3;
    case 4;
    case 5;
    case 6;
    case 7;
    case 8;
    case 9;
    case 10;
        System.out.println("Full mark");

Note: the branch will jump out only when it encounters a break. If there is no break after the literal value of the case, the statement block of the next case will be executed until it encounters a break.

Loop structure: for loop, double for loop, while loop, do while loop

4. Array

• you can directly access the elements at the specified location through subscript (or index), which is very fast.
• arrays require all elements to be of the same type.
• the array requires continuous memory space and cannot be modified once the length is determined.
• when adding and deleting elements, a large number of elements may be moved, which is inefficient.

// Declare an array and traverse the array
int[] intArray = {1,2,3,4,5};
for(int i : intArray){

// Two dimensional array, traversal
int[][] intDoubleArray = {{1,2,3},{4,5,6},{7,8,9}};
for(int i=0;i < intDoubleArray.length;i++){
        for(int j=0;j < intDoubleArray[i].length;j++){

Array tool class: Java util. Arrays

        // Declare an array
        int[] intArray = {1,9,9,4,12,88,320,768};
        // Positive ordering api
        // Output array contents
        // Until the element is found
        int findSet = Arrays.binarySearch(intArray,320);

5. Method and packaging

  • The member method body is mainly used to write statement blocks that describe the function of the method.
  • Member methods can realize code reuse and simplify code.

Construction method

The constructor name is exactly the same as the class name, and there is no return value type, not even void.

When using the new keyword to create an object, the constructor will be called automatically to initialize the member variable.

heavy load

Overload is in a class. The method names are the same, but the parameters are different. The return type can be the same or different.

Each overloaded method (or constructor) must have a unique list of parameter types.

The most common place is the overloading of constructors.

Example: three construction methods of ArrayList, specifying length, no parameters and converting ArrayList directly from Collection

	public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+

     * Constructs an empty list with an initial capacity of ten.
    public ArrayList() {

     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
    public ArrayList(Collection<? extends E> c) {
        Object[] a = c.toArray();
        if ((size = a.length) != 0) {
            if (c.getClass() == ArrayList.class) {
                elementData = a;
            } else {
                elementData = Arrays.copyOf(a, size, Object[].class);
        } else {
            // replace with empty array.
            elementData = EMPTY_ELEMENTDATA;

this keyword

  • If this keyword appears in the construction method, it represents the object currently being constructed.
  • If this keyword appears in the member method, it represents the object currently being called.
  • this keyword is essentially a reference variable of the current class type.

this is equivalent to "mine",

When different objects call the same method, the this keyword is different due to different objects calling the method, so this The results of access will be different.

Recursion (dolls)

The essence of recursion is to call the current method itself directly or indirectly inside the method body


  • The use of recursion must have the law of recursion and exit conditions.
  • Using recursion must simplify the problem rather than complicate it.
  • If recursion affects the execution performance of the program, it is replaced by recursion.
// Factorial n!
int recursive(int n) {
    if (0 == n) {
        return (1);
    else {
        return n * recursive(n - 1);












  • Privatize member variables and use the private keyword to modify them.
  • Provide public get and set methods, and judge the reasonable value in the method body.
  • In the construction method, we call the set method to determine the reasonable value.

Property private

get and set methods are public

6.static keyword

Static means "global" or "static". It means that the memory allocated after compilation will exist until the program exits, and the memory will not release this space

Modified member variable: static modified members can add "." to the class name Direct access

Modify member methods: static modified methods can add "." to the class name For direct access, it is often used for the API of configuration information or tool classes, as well as the main method

Building blocks and static code blocks

  • Building blocks: code blocks directly enclosed by {} in the class body.
  • The building block is executed once for each object created.
  • Static code block: a building block decorated with the static keyword.
  • Static code blocks are executed once as the class loads

Execution sequence:

Static code block, static, its action level is class,

Construct code blocks and constructors, whose action level is object.

Therefore, the execution order must be: static code block > construction code block > construction method

Single case design mode

**Intent: * * ensure that a class has only one instance and provide a global access point to access it.

**Main solutions: * * a globally used class is frequently created and destroyed.

**When to use: * * when you want to control the number of instances and save system resources.

**How to solve: * * judge whether the system already has this single instance. If so, return it. If not, create it.

**Key code: * * constructor is private.

public class SingleObject {
   //Create an object of SingleObject
   private static SingleObject instance = new SingleObject();
   //Make the constructor private so that the class will not be instantiated
   private SingleObject(){}
   //Get the only available objects
   public static SingleObject getInstance(){
      return instance;
   public void showMessage(){
      System.out.println("Hello World!");

public class SingletonPatternDemo {
   public static void main(String[] args) {
      //Illegal constructor
      //Compile time error: constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();
      //Gets the only available object
      SingleObject object = SingleObject.getInstance();
      //display messages

The starving Han style is used in the production. As for the above type, the class loading mechanism avoids the synchronization problem of multiple threads

7. Succession

In the Java language, the extensions keyword is used to represent the inheritance relationship

Public class Worker extensions Person {} - indicates that the Worker class inherits from the Person class

Using inheritance improves the reusability, maintainability and expansibility of code, which is the prerequisite of polymorphism


  • Subclasses have non private properties and methods of the parent class.

  • Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.

  • Subclasses can implement the methods of their parent classes in their own way.

  • Java does not support multiple inheritance, but supports multiple inheritance, a extensions B, B extensions C


Rewriting is a subclass's rewriting of the implementation process of the accessible methods of the parent class, and the return value and formal parameters cannot be changed. That is, the shell remains unchanged and the core is rewritten!

Inherited building blocks and static code blocks

  • First execute the static code block of the parent class, and then execute the static code block of the child class. (static decoration is executed when the class is loaded)
  • Execute the building block of the parent class and the constructor body of the parent class.
  • Execute the construction block of the subclass and the constructor body of the subclass.

access control

public (all accessible)

protected (other classes cannot be accessed and subclasses can)

Default (subclasses cannot be accessed)

private (only this class can access)

Member methods are decorated with public keyword, and member variables are decorated with private keyword

final keyword

Final modification class: the final class cannot be inherited. The method in it will automatically become final modification, but the variable is not final modification

Final modification method: the final method, which cannot be overridden by subclasses

final modification variable: this variable cannot be modified

8. Polymorphism

Polymorphism mainly refers to the multiple forms of the same thing.

Advantages of polymorphism:

  1. Eliminate coupling between types
  2. Replaceability
  3. Extensibility
  4. Interface
  5. flexibility
  6. Simplification

Three necessary conditions for polymorphism:

  • inherit
  • rewrite
  • The parent class reference points to the child class object: Parent p = new Child();


public class Test {
    public static void main(String[] args) {
      show(new Cat());  // Call the show method with a Cat object
      show(new Dog());  // Call the show method with a Dog object
      Animal a = new Cat();  // Upward transformation;               // Cat eat is called
      Cat c = (Cat)a;        // Downward transformation;        // Cat work is called
    public static void show(Animal a)  {;  
        // Type judgment
        if (a instanceof Cat)  {  // What cats do 
            Cat c = (Cat)a;  
        } else if (a instanceof Dog) { // What dogs do 
            Dog c = (Dog)a;  
abstract class Animal {  
    abstract void eat();  
class Cat extends Animal {  
    public void eat() {  
        System.out.println("Eat fish");  
    public void work() {  
        System.out.println("Catch a mouse");  
class Dog extends Animal {  
    public void eat() {  
        System.out.println("Eat bones");  
    public void work() {  

9. Abstract classes and abstract methods

Related concepts:

  • Abstract methods are not realizable and have no method body

  • A class with abstract methods must be an abstract class

  • Therefore, the real abstract class should be a class with abstract methods and decorated with abstract keyword


  1. The practical significance of abstract classes is not to create objects, but to be inherited
  2. When a class inherits an abstract class, it must override the abstract method, otherwise the class will also become an abstract class
  3. Abstract classes are mandatory and normative to subclasses, which is called template design pattern

10. Interface

Related concepts:

An interface is a class more abstract than an abstract class, which is reflected in that all methods are abstract methods.

The keyword that defines a class is class, and the keyword that defines an interface is interface.

Relationship between classes and interfaces:

The relationship between classes -- extensions -- supports single inheritance

The relationship between classes and interfaces -- implements -- supports multiple implementations

Interfaces and the relationship between interfaces -- extensions -- support multiple inheritance

11. Special category

Inner class: another class can be nested in one class

class OuterClass {   // External class
    // ...
    class NestedClass { // Nested classes, or inner classes
        // ...

Anonymous Inner Class

Anonymous inner classes are the only classes without constructors. Because it has no constructor, the scope of use of anonymous inner classes is very limited. Most anonymous inner classes are used for interface callback. The anonymous inner class is automatically named outer $1 by the system when compiling class. Generally speaking, anonymous inner classes are used to inherit other classes or implement interfaces. There is no need to add additional methods, but to implement or rewrite the inherited methods.


interface Person {
     public void eat();
public  class Demo {
     public static void main(String[] args) {
         // Format: Interface / parent type reference variable name = new interface / parent type () {override of method};
         Person p = new Person() {
             public void eat() {
                 System.out.println( "eat something" );


  • The description of constants represented by public static final is cumbersome. enum keyword is used to define enumeration type instead of constants
  • Java 5 starts with enumeration
  • Enumeration class common APIs


  • Annotation, reference data type
  • Annotations are essentially special tags in code that allow you to perform specified processing at compile, class load, and run time
  • Custom annotation automatically inherits Java lang.annotation. Annotation interface.
  • You can modify the declaration of packages, classes, member methods, member variables, construction methods, parameters and local variables by @ annotation names.
  • Annotation is an auxiliary class, which is widely used in Junit, Struts, Spring and other tool frameworks.


  • Compilation check: @ SuppressWarnings, @Deprecated and @ Override have the function of compilation check
  • Use Annotation in reflections:
import java.lang.annotation.Annotation;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Inherited;
import java.lang.reflect.Method;

 * Annotation Examples of use in reflection functions
@interface MyAnnotation {
    String[] value() default "unknown";

 * Person Class. MyAnnotation uses it.
class Person {
     * empty()The method is marked by both "@ Deprecated" and "@ MyAnnotation(value={"a","b "})"
     * (01) @Deprecated´╝îMeans that the empty() method is no longer recommended
     * (02) @MyAnnotation, This means that the value value of MyAnnotation corresponding to empty() method is the default value "unknown"
    public void empty(){
     * sombody() Marked by @ MyAnnotation(value={"girl","boy"}),
     * @MyAnnotation(value={"girl","boy"}), It means that the value value of MyAnnotation is {"girl","boy"}
    public void somebody(String name, int age){
        System.out.println("\nsomebody: "+name+", "+age);

public class AnnotationTest {

    public static void main(String[] args) throws Exception {
        // New Person
        Person person = new Person();
        // Get the Class instance of Person
        Class<Person> c = Person.class;
        // Gets the Method instance of the somebody() Method
        Method mSomebody = c.getMethod("somebody", new Class[]{String.class, int.class});
        // Execute the method
        mSomebody.invoke(person, new Object[]{"lily", 18});

        // Gets the Method instance of the somebody() Method
        Method mEmpty = c.getMethod("empty", new Class[]{});
        // Execute the method
        mEmpty.invoke(person, new Object[]{});        
    public static void iteratorAnnotations(Method method) {

        // Judge whether the somebody() method contains MyAnnotation annotation
            // Gets the MyAnnotation annotation instance of the method
            MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
            // Get the value of myAnnotation and print it out
            String[] values = myAnnotation.value();
            for (String str:values)
                System.out.printf(str+", ");
        // Get all annotations on the method and print them out
        Annotation[] annotations = method.getAnnotations();
        for(Annotation annotation : annotations){
  • Generate help documents according to the Annotation: by adding @ Documented tag to the Annotation annotation, the Annotation tag can appear in javadoc

//Gets the MyAnnotation annotation instance of the method
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
//Get the value of myAnnotation and print it out
String[] values = myAnnotation.value();
for (String str:values)
System.out.printf(str+", ");

    // Get all annotations on the method and print them out
    Annotation[] annotations = method.getAnnotations();
    for(Annotation annotation : annotations){


- according to Annotation Generate help document: by giving Annotation Annotation plus @Documented Label that enables the Annotation Label appears in javadoc in

Topics: Java