For two Days

10 Hours

1060 Lines

Pt (Patrick, my new English name is hey hey 🌝) finally picked up the Java foundation of university Learn and continued to share his notes. Finally being a happy Gopher and going back to the Java pit… T ^ t ^ t tears

Author: Become a good little white

Making: making

CSDN: CSDN_Blog

Hobby: Americano More Ice!

directory

  • directory
    • Java – Docs (official)
      • The data type
        • Basic types of
        • Packing type
        • Buffer pool
      • String
        • The basic concept
        • The benefits of immutability
          • Cacheable hash
          • String Pool need
          • security
          • Thread safety
        • String, StringBuffer and StringBuilder
        • String Pool
        • new String(“aaa”)
      • operation
        • Parameter passing
        • Float and double
        • Implicit type conversion
        • switch
      • The keyword
        • final
          • data
          • methods
          • class
        • static
          • 1 Static variables
          • 2 Static Methods
          • 3 Static statement block
          • Static inner class
          • 5 Static packet guide
          • 6 Initialization sequence
      • Object general method
        • equals()
          • Equivalence relation
          • Equivalence and equality
          • The source code to achieve
        • hashCode()
        • toString()
        • clone()
          • cloneable
          • Shallow copy
          • Deep copy
          • Clone () alternative
      • inheritance
        • Access permissions
        • Abstract classes and interfaces
          • An abstract class
          • interface
          • Difference: Abstract classes and interfaces
          • Used to choose
          • super
        • Overrides and Overload
          • Rewrite (Override)
          • Overloading (phrase)
      • reflection
        • advantages
        • disadvantages
      • abnormal
      • The generic
      • annotations
      • JRE or JDK
      • Reference

Java – Docs (official)

  • Oracle-JavaDocs

The data type

Basic types of

  • byte/8
  • char/16
  • short/16
  • int/32
  • float/32
  • long/64
  • double/64
  • boolean/~

Packing type

Each basic type has a corresponding package type, and the assignment between the basic type and its corresponding package type is done using automatic packing and unpacking

Integer x = 2; / / packing Integer. The valueOf (2)
int y = x;  / / devanning x.i ntValue ()
Copy the code

Buffer pool

Understand the difference between new Integer(123) and integer.valueof (123)

  • new Integer(123)It creates a new object each time
  • Integer.valueOf(123)Objects in the cache pool are used, and multiple calls get references to the same object
Integer x = new Integer(321);
Integer y = new Integer(321);
System.out.println(x == y); // false
Integer z = Integer.valueOf(123);
Integer k = Integer.valueOf(123);
System.out.println(x == y); // true
// same as above
Integer m = 123;
Integer n = 123;
System.out.println(m == n); // true
Copy the code

Take a look at the source code for valueOf()

public static Integer ValueOf(int i) {
  // If in the cache pool
  if (i >= IntegerCache.low && i <= IntegerCache.high)
    // Returns the cache pool contents
    return IntegerCache.cache[i + (-IntegerCache.low)];
  // If not in the cache pool, create a new one
  return new Integer(i)
}
Copy the code

In Java8, the default size of the Integer cache pool is -128 to 127

static final int low = -128;
static final int high;
static final Integer cache[];

static {
    // The maximum value is configurable
    int h = 127;
    String integerCacheHighPropValue =
        sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
    if(integerCacheHighPropValue ! =null) {
        try {
            int i = parseInt(integerCacheHighPropValue);
            i = Math.max(i, 127);
            // Maximum array size integer.max_value
            h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
        } catch( NumberFormatException nfe) {
            // If the attribute cannot be converted to int, ignore it
        }
    }
    high = h;

    cache = new Integer[(high - low) + 1];
    int j = low;
    for(int k = 0; k < cache.length; k++)
        cache[k] = new Integer(j++);

    // range [-128, 127] must be interned (JLS7 5.1.7)
    assert IntegerCache.high >= 127;
}
Copy the code

The buffer pool corresponding to the base type

  • boolean: true and false
  • short: – 128 ~ 127
  • int: – 128 ~ 127
  • char: \u0000 ~ \u007F

String

The basic concept

String is declared final(not inheritable, nor is the Integer wrapper class)

# java8 - char[] Array storagepublic final class String
    implements java.io.Serializable.Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
}
# java9 - byte[] Array storagepublic final class String
    implements java.io.Serializable.Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final byte[] value;

    /** The identifier of the encoding used to encode the bytes in {@code value}. */
    private final byte coder;
}
Copy the code

The benefits of immutability

Cacheable hash

Because String hash values are often used, for example String is used as the key of a HashMap. The immutable nature makes the hash value immutable, so it only needs to be evaluated once

String Pool need

If a String has already been created, the reference is taken from the String Pool (taking advantage of immutable properties).

security

String is often used as a parameter, and String immutability ensures that the parameter is immutable

Thread safety

Immutability is inherently thread-safe and can be used safely across multiple threads

String, StringBuffer and StringBuilder

| | | type variability thread-safe | | — – | — – | — – | | String | immutable | String immutable, So is thread-safe | | StringBuilder variable | | not thread-safe | | StringBuffer | | variable is thread-safe, internal use for synchronous | synchronized

String Pool

The String Pool holds all literal strings.

Intern () adds a String to a String Pool, and.intern() implements the same logic as the cache Pool described above

For example

String s1 = new String("aaa");
String s2 = new String("aaa");
System.out.println(s1 == s2);           // false
String s3 = s1.intern();
String s4 = s2.intern();
System.out.println(s3 == s4);           // true
Copy the code

new String(“aaa”)

If the String Pool does not have an “AAA” String, two String objects are eventually created.

  • "aaa"Belonging to a string literal is one
  • newWill be created in the heap is another

Take a look at the String constructor source code

// As you can see, String() does not copy the contents of the value array, but points to the same value array
public String(String original) {
    this.value = original.value;
    this.hash = original.hash;
}
Copy the code

operation

Parameter passing

Java parameters are passed to methods as values, not references

public class Dog {
  String name;

  Dog(String name) {
    this.name = name;
  }

  String getName(a) {
    return this.name;
  }

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

  String getObjectAddress(a) {
    return super.toString(); }}class PassByValueExample {
  public static void main(String[] args) {
    // Point to an object
    Dog dog = new Dog("A");
    // Call an internal method to change the value of the object
    func(dog);
    System.out.Println(dog.getName());
  }

  private static void func(Dog dog) {
    dog.setName("B")}}Copy the code

Let’s look at the scenarios that point to different objects

public class PassByValueExample {
    public static void main(String[] args) {
        Dog dog = new Dog("A");
        System.out.println(dog.getObjectAddress()); // Dog@4554617c
        func(dog);
        System.out.println(dog.getObjectAddress()); // Dog@4554617c
        System.out.println(dog.getName());          // A
    }

    private static void func(Dog dog) {
        System.out.println(dog.getObjectAddress()); // Dog@4554617c
        dog = new Dog("B");
        System.out.println(dog.getObjectAddress()); // Dog@74a14482
        System.out.println(dog.getName());          // B}}Copy the code

Float and double

Java cannot implicitly perform a downward transformation because it would reduce accuracy.

Downward transformation: that is, high precision to low precision to transform

Implicit type conversion

For example, an int >short precision cannot be implicitly cast downward, but the += or ++ operators perform implicit type conversions

short s1 = 1;
/ / equivalent to the
s1 = s1 + 1
s1 += 1;
s1++;
/ / equivalent to the
s1 = (short) (s1+1);
Copy the code

switch

As of Java 7, the equivalence judgment in switch supports String object, but does not support long, float, double, if too complex or fix

String s = "a";
switch (s) {
    case "a":
        System.out.println("aaa");
        break;
    case "b":
        System.out.println("bbb");
        break;
}
Copy the code

The keyword

final

data

Declare data as constants, which can be compile-time constants and cannot be changed after initialization

  • For base types,finalKeep the value constant
  • For reference types,finalMakes the reference immutable, but the reference object itself mutable
final int x = 1;
final A y = new A();
y.a = 1;
Copy the code
methods

Declare methods cannot be overridden by subclasses, and private methods are implicitly specified as final

If a method defined in a subclass has the same signature as a private method in the base class, the subclass method does not override the base class method, but defines a new method in the subclass

In general, subclasses that define the same methods as their parent are not overridden

class

Final states that a class cannot be inherited

static

1 Static variables
  • Static variable: Also known as a class variable, that is, the variable belongs to the class. All instances of the class share a static variable and can access it directly through the class name. There is only one static variable in memory.
  • Instance variables: An instance variable is created for each instance that is created, and it lives and dies with that instance
public class A {
  private int x;
  private static int y;

  public static void main(String[] args) {
    A a = new A();
    int x = a.x;
    inty = A.y; }}Copy the code
2 Static Methods

Static methods exist when the class is loaded and do not depend on any instance. A static method must have an implementation, so it cannot be abstract.

Only the static fields and methods of the owning class can be accessed. The methods cannot have the this and super keywords because they are associated with specific objects.

public class A {
  private static int x;
  private int y;

  public static void func1(a) {
    int a = x;
    // int b = y; Not static variable error
    // int b = this.y; Cannot have the this and super keywords}}Copy the code
3 Static statement block

A static statement block is run once during class initialization

public class A {
  static {
    System.out.println("123");
  }

  public static void main(String[] args) {
    A a1 = new A();
    A a2 = newA(); }}// output: 123
Copy the code
Static inner class

A non-static inner class depends on an instance of an external class (that is, an instance of an external class is created before a non-static inner class is available). A static inner class does not

A static inner class cannot access the non-static variables and methods of an external class

public class OuterClass {
  // Non-static inner class
  class InnerClass {}

  static class StaticInnerClass {}

  public static void main(String[] args) {
    // Create a class instance
    OuterClass outClass = new OuterClass();
    // Rely on external class instances
    InnerClass innerClass = outerClass.new InnerClass(a);
    StaticInnerClass staticInnerClass = newStaticInnerClass(); }}Copy the code
5 Static packet guide

You no longer need to specify ClassName when using static variables and methods

Advantages: Simplified code Disadvantages: Greatly reduced readability

import static com.xxx.ClassName.*

6 Initialization sequence

The default scenario

// The order of the following depends on the order in the code
public static String staticField = "Static variable";
static {
  System.out.println("Static statement block");
}

public String field = "Instance variable";

public String field = "Instance variable";

{
  System.out.println("Plain block");
}

public InitialOrderTest(a) {
  System.out.println("Constructor");
}
Copy the code

There are inheritance scenarios

Parent class (static variable, static statement block) Subclass (static variable, static statement block) Parent class (instance variable, ordinary statement block) Parent class (constructor) subclass (instance variable, ordinary statement block) Subclass (constructorCopy the code

Object general method

equals()

Equivalence relation

Two objects are equivalent, five conditions

/ / reflexivity
x.equals(x); // true
/ / symmetry
x.equals(y) == y.equals(x); // true
/ / deliverables
if (x.equals(y) && y.equals(z))
    x.equals(z); // true;
// consistency (the result of multiple calls does not change)
x.equals(y) == x.equals(y); // true
// Compare with null
x.equals(null); // false;
Copy the code
Equivalence and equality

For primitive types, == determines whether two values are equal. Primitive types have no equals() method. For reference types, == determines whether two variables refer to the same object, and equals() determines whether the referenced objects are equivalent

Integer x = new Integer(1);
Integer y = new Integer(1);
System.out.println(x.equals(y)); // true
System.out.println(x == y); // false
Copy the code
The source code to achieve
public class EqualExample {
  private int x;
  private int y;
  private int z;

  public EqualExample(int x, int y, int z) {
    this.x = x;
    this.y = y;
    this.z = z;
  }

  @Override
  public boolean equals(Object o) {
    // A reference to the same object
    if (this == o) return true;
    // If not the same type
    if (o == null|| getClass() ! = o.getClass())return false;

    // Object transforms the Object
    EqualExample that = (EqualExample) o;

    // If the key fields are not equal
    if(x ! = that.x)return false;
    if(y ! = that.y)return false;
    // If the key fields are equal
    returnz == that.z; }}Copy the code

hashCode()

HashCode () returns the hash value, and equals() is used to determine whether two objects are equivalent

EqualExample e1 = new EqualExample(1.1.1);
EqualExample e2 = new EqualExample(1.1.1);
System.out.println(e1.equals(e2)); //true
HashSet<EqualExample> set = new HashSet<>();
set.add(e1);
set.add(e2);
System.out.println(set.size()); / / 2
Copy the code

The ideal hash function should be uniform, that is, unequal objects should be evenly distributed over all possible hashed values. R is generally 31, because it’s an odd prime, and if it’s even, when you have a multiplication overflow, the information is lost because multiplying by 2 is the same thing as moving one bit to the left, losing the leftmost bit. And a number multiplied by 31 can be converted to shifts and subtraction: 31*x == (x<<5)-x, which the compiler automatically optimizes

@Override
public int hashCode(a) {
  int result = 17;
    result = 31 * result + x;
    result = 31 * result + y;
    result = 31 * result + z;
    return result;
}
Copy the code

toString()

public class ToStringExample {

  private int number;

  public ToStringExample(int number) {
    this.number = number;
  }
}

ToStringExample example = new ToStringExample(123);
System.out.println(example.toString())
// This form is returned by default. The value after @ is an unsigned hexadecimal representation of the hash code
// ToStringExample@4554617c
Copy the code

clone()

cloneable

Clone () is the protected method of Object. To call other classes, explicitly override clone().

public class CloneExample {
  private int a;
  private int b;
}

CloneExample e1 = new CloneExample();
// CloneExample e2 = e1.clone(); 'clone()' has protected access in 'java.lang.object'
Copy the code

Rewrite the clone() implementation

public class CloneExample {
  private int a;
  private int b;

  @Override
  public CloneExample clone(a) throws CloneNotSupportedException {
    return (CloneExample)super.clone();
  }
}

CloneExample e1 = new CloneExample();
try {
  CloneExample e2 = e1.clone();
} catch (CloneNotSupportedException e) {
  e.printStackTrace();
}
/ / an error, throw CloneNotSupportedException because there is no implement Cloneable interface
Copy the code

Let’s change that

// Implementing the Cloneable interface is required
public class CloneExample implements Cloneable {
    private int a;
    private int b;

    @Override
    public Object clone(a) throws CloneNotSupportedException {
        return super.clone(); }}Copy the code
Shallow copy

The reference type of the copy object and the original object refer to the same object

public class ShallowCloneExample implements Cloneable {
  private int[] arr;

  public ShallowCloneExample(a) {
    arr = new int[10];
    for(int i = 0; i < arr.length; i++) { arr[i] = i; }}public void set(int index, int value) {
    arr[index] = value;
  }

  public int get(int index) {
    return arr[index];
  }

  @Override
  protected ShallowCloneExample clone(a) throws CloneNotSupportedException {
    return (ShallowCloneExample) super.clone();
  }
}

ShallowCloneExample e1 = new ShallowCloneExample();
ShallowCloneExample e2 = null;
try {
  e2 = e1.clone();
} catch (CloneNotSupportedException e) {
  e.printStackTrace();
}
e1.set(2.222);
System.out.println(e2.get(2)); / / 222
Copy the code
Deep copy

The reference types of the copy object and the original object refer to different objects

public class DeepCloneExample implements Cloneable {
  private int[] arr;

  public DeepCloneExample(a) {
    arr = new int[10];
    for(int i = 0; i < arr.length; i++) { arr[i] = i; }}public void set(int index, int value) {
    arr[index] = value;
  }

  public int get(int index) {
    return arr[index];
  }

  @Override
  protected DeepCloneExample clone(a) throws CloneNotSupportedException {
    DeepCloneExample result = (DeepCloneExample) super.clone();
    result.arr = new int[arr.length];
    for(int i = 0; i < arr.length; i++) {
      result.arr[i] = arr[i];
    }
    return result;
  }
}

DeepCloneExample e1 = new DeepCloneExample();
DeepCloneExample e2 = null;
try {
  e2 = e1.clone();
} catch (CloneNotSupportedException e) {
  e.printStack();
}
e1.set(2.222)
System.out.println(e2.get(2)); / / 2
Copy the code
Clone () alternative

Copy objects by copy constructors or copy factories (Effective Java)

public class CloneConstructorExample {
  private int[] arr;

  public CloneConstructorExample(a) {
    arr = new int[10];
    for(int i = 0; i < arr.length; i++) { arr[i] = i; }}public CloneConstructorExample(CloneConstructorExample original) {
    arr = new int[original.arr.length];
    for(int i = 0; i < original.arr.length; i++) { arr[i] = original.arr[i]; }}public void set(int index, int value) {
    arr[index] = value;
  }

  public int get(int index) {
    return arr[index];
  }
}

CloneConstructorExample e1 = new CloneConstructorExample();
CloneConstructorExample e2 = new CloneConstructorExample(e1);
e1.set(2.222);
System.out.println(e2.get(2)); / / 2
Copy the code

inheritance

Access permissions

Three modifiers

  • private
  • protected
  • public

Abstract classes and interfaces

An abstract class

If a class contains abstract methods, the class must be declared abstract

The biggest difference between abstract classes and ordinary classes is that abstract classes cannot be instantiated, only inherited

public abstract class AbstractClassExample {
  protected int x;
  private int y;

  public abstract void func1(a);

  public void func2 {
    System.out.println("func2"); }}public class AbstractExtendClassExample extends AbstractClassExample {
  @Override
  public void func1(a) {
    System.out.println("func1"); }}// An abstract class instantiation error was reported
// AbstractClassExample ac1 = new AbstractClassExample();
AbstractClassExample ac2 = new AbstractClassExample();
ac2.func1();
Copy the code
interface

Interface members (fields + methods) are public by default and are not allowed to be private or protected. Since Java 9, it has been possible to define methods as private so that some reusable code can be defined without exposing methods

Interface fields are static and final by default

public interface InterfaceExample {
  void func1(a);

  default void func2(a) {
    System.out.println("func2");
  }

  int x = 123;
  public int z = 0;
}

public class InterfaceImplementExample implements InterfaceExample {
    @Override
    public void func1(a) {
        System.out.println("func1"); }}// InterfaceExample ie1 = new InterfaceExample();
// Output: 'InterfaceExample' is abstract; cannot be instantiated
InterfaceExample ie2 = new InterfaceImplementExample();
ie2.func1();
System.out.println(InterfaceExample.x);
Copy the code
Difference: Abstract classes and interfaces
An abstract class interface
The design level Abstract classes provide an IS-A relationship that satisfies the Li substitution principle, which states that subclass objects must be able to replace all superclass objects A like-a relationship that simply provides A way to implement the contract and does not require the interface and the class implementing the interface to have an IS-A relationship
Use level A class cannot inherit from more than one abstract class A class can implement multiple interfaces
field There is no limit to Can only be static or final
Members of the Multiple access rights public
Used to choose
  • Interface:

    • All unrelated classes need to implement a method, for example, all unrelated classes can implement itComparableThe interfacecompareTo()Methods;
    • Multiple inheritance is required.
  • An abstract class:

    • The code needs to be shared among several related classes.
    • You need to be able to control the access of inherited members, not all of thempublic
    • Need to inherit non-static and nonstatic fields
super
  • Access the constructor of the parent class
  • Access a member of the parent class
public class SuperExample {
  protected int x;
  protected int y;

  public SuperExample(int x, int y) {
    this.x = x;
    this.y = y;
  }

  public void func(a) {
    System.out.println("superExample.func()"); }}Copy the code
public class SuperExtendExample extends SuperExample {
  private int z;

  public SuperExtendExample(int x, int y, int z) {
    super(x, y);
    this.z = z;
  }

  @Override
  public void func(a) {
    super.func();
    System.out.println("superExtendExample.func()"); }}Copy the code

call

SuperExample e = new SuperExtendExample(1.2.3);
e.func();
// output
// superExample.func()
// superExtendExample.func()
Copy the code

Overrides and Overload

Rewrite (Override)

In order to satisfy the li substitution principle, rewriting has the following three limitations:

1. A subclass method must have access rights greater than or equal to the parent method

2. The return type of a subclass method must be the parent method return type or a subtype

3. The exception type thrown by a subclass method must be the type thrown by its parent or its child

The @override annotation uses the compiler to check that the above three restrictions are met

For example

/ / parent class
class SuperClass {
  protected List<Integer> func(a) throws Throwable {
    return newArrayList<>(); }}/ / subclass
class SubClass extends SuperClass {
  // The compiler automatically checks to see if the constraint is met
  @Override
  // Public is greater than protected
  // Change the return type to ArrayList
      
  // The Exception type is Exception
  public ArrayList<Integer> func(a) throws Exception {
    return newArrayList<>(); }}Copy the code

Call method logic: first look in this class to see if there is a corresponding method, if not in the parent class to see if it is inherited from the parent class, otherwise it is necessary to transform the parameter, into the parent class to see if there is a corresponding method

Priority: this.func(this) => super.func(this) => this.func(super) => super.func(super)

Overloading (phrase)

If a method exists in the same class, it has the same name as an existing method, but has at least one different parameter type, number, and order

class OverloadingExample {
  public void show(int x) {
    System.out.println(x);
  }

  public void show(int x, String y) {
    System.out.println(x + ""+ y); }}public static void main(String[] args) {
  OverloadingExample example = new OverloadingExample();
  example.show(1);
  example.show(1."2");
}
Copy the code

reflection

Class provides support for reflection along with java.lang.reflect. The Java.lang. Reflect library consists of three classes:

  • FieldUse:get()set()Method read and modifyFieldObject associated with the field
  • MethodUse:invoke()Method calls andMethodMethods for associating objects
  • Constructor:ConstructornewInstance()Creating a new object

advantages

  • scalability
  • Class browser and visual development environment
  • Debuggers and test tools

disadvantages

Although reflexes are very powerful, they should not be abused. If a function can be done without reflection, it’s best not to.

  • Performance overhead: Designed for dynamic type resolution, the JVM cannot optimize the code, which is inefficient. Avoid using it frequently or when performance is required
  • Security restrictions: Must operate in an environment with no security restrictions
  • Internal exposure: Because reflection allows code to perform operations that it would not normally allow, resulting in dysfunction and breaking portability. Reflecting code breaks abstractness, so when the platform changes, it is possible for the code to behave as well.

abnormal

Throwable represents any class that can be thrown as an Exception, divided into Error and Exception

  • Error
    • Represents an error that the JVM cannot handle
  • Exception
    • 1.B. abnormalTo:try... catch...Statement is captured and processed, and can be recovered from exceptions
    • 2.No abnormality under examination: is a program runtime error, such as division by 0Arithmetic ExceptionThe program crashes and cannot be recovered

The generic

// T indicates Type
public class Box<T> {
  private T t;
  public void set(T t) { this.t = t; }
  public T get(a) { returnt; }}Copy the code

annotations

Understood as => auxiliary

Java annotations are meta-information attached to code that is parsed and used by tools during compilation, runtime, and configuration. Annotations do not and cannot affect the actual logic of the code.

JRE or JDK

  • JRE:Java Runtime Environment(Short for runtime environment, which provides the required environment) it is aJVMProgram, mainly includesJVMThe standard implementation and someJavaBase class libraries.
  • JDK: Java Development Kit.JavaThe development kit is providedJavaDevelopment and operation environment.JDKJavaThe core of development, integratedJREAnd some other tools, such as compilationJavaSource code compilerjavacAnd so on.

Reference

  • Java Programming Ideas [M](Eckel B)
  • Effective java(Bloch J.)

Conclusion: if encounter what question or suggestion, can leave a message comment directly! The author will reply immediately

If you feel small white this article is good or helpful to you, look forward to your one key three even 💫! ❤ ️ ni ~