My Java learning notes

matters needing attention

  • Methods cannot be nested
  • void indicates that there is no return value. You can omit return or write return separately without data
  • return the following code will no longer be executed

Method overloading

Method overloading refers to the relationship between multiple methods defined in the same class. Multiple methods that meet the following conditions constitute overloading with each other:

  • Multiple methods in the same class

  • Multiple methods have the same method name

  • The parameters of multiple methods are different, that is, the types or quantities of parameters are different

  • Method overload characteristics

    • Overloading only corresponds to the definition of the method and has nothing to do with the method call. The call method refers to the standard format
    • Overloads only identify the names and parameters of methods in the same class, regardless of the return value. In other words, it is not possible to determine whether two methods constitute overloads with each other through the return value
public class helloworld {
    public static int max(int a,int b) {
        return Math.max(a, b);
    }

    public static int max(int a, int b, int c) {
        int maxnum;
        maxnum = Math.max(a, b);
        maxnum = Math.max(maxnum, c);
        return maxnum;
    }

    public static void main(String[] args) {
        System.out.println(max(10,20));
        System.out.println(max(10,20,30));
    }
}//The above two max methods belong to method refactoring

Parameter passing of method

  • Basic type
public class helloworld {
    public static void change(int number) {
        number = 200;
    }

    public static void main(String[] args) {
        int number = 100;
        System.out.println("call change Before method number: " + number);
        change(number);
        System.out.println("call change After method number: " + number);
    }
}
Console output:
call change Before method number: 100
 call change After method number: 100
//The basic type parameter does not modify the value of the original argument
  • reference type
public class helloworld {
    public static void change(int[] arr) {
        arr[1] = 222;
    }

    public static void main(String[] args) {
        int[] arr = {100, 200, 300};
        System.out.println("call change Before method arr[1]: " + arr[1]);
        change(arr);
        System.out.println("call change After method arr[1]: " + arr[1]);
    }
}
Console output:
call change Before method arr[1]: 200
 call change After method arr[1]: 222
//The reference type modifies the value of the original s number

Object oriented Foundation

11. Classes and objects

1. What is the object

Everything is an object, and everything that exists objectively is an object

2. What is a class

Class is an abstraction of a class of things with common attributes and behaviors in real life

Class features:

  • Class is the data type of an object
  • A class is a collection of objects with the same properties and behavior

3. What are the attributes of an object

Attributes: various characteristics of objects. Each attribute of each object has a specific value

For example, a mobile phone

attributevalue
brandmillet
Price2999
Memory128G
... ...... ...

4. What is the behavior of the object

Behavior: what an object can do

For example, a mobile phone can make calls and send text messages

Phone calls and sour sex can be called his behavior

5. Relationship between class and object

Class: class is the abstraction of a class of things with common attributes and behaviors in real life

Object: a real entity that can be seen and touched

A class is an abstraction of an object, and an object is an entity of a class

6. Definition of class

Importance of class: it is the basic unit of Java program
What is a class: it is an abstraction of a class of things with common attributes and behaviors in real life, and determines the attributes and behaviors that the object will have

Class composition: properties and behavior

  • Attribute: reflected in the class through member variables (variables outside the methods in the class)
  • Behavior: reflected in the class through member methods (compared with the previous methods, just remove the static keyword)

Class definition steps:

① Define class

② Write the member variable of the class

③ Write member methods of classes

public class Class name {
    //Member variable
    Data type of variable 1;
    Data type of variable 2;
    ...
    //Member method
    Method 1;
    Method 2;
    ...
}
public class Phone {
    //Member variable
    String brand;//brand
    int price;//Price

    //Member method

    public void call() {
        System.out.println("phone");
    }
    public void  sendMessage() {
        System.out.println("send message");
    }
}

7. Use of objects

create object

  • Format: class name object name = new class name ();
  • Example: Phone p = new Phone();

Use object

1: Using member variables

  • Format: object name. Variable name

  • Example: p.brand

2: Using member methods

  • Format: object name. Method name ();
  • Example: p.call();
public class PhoneDemo {
    public static void main(String[] args) {
        //create object
        Phone p = new Phone();

        //Using member variables
        System.out.println(p.brand);
        System.out.println(p.price);

        p.brand = "millet";
        p.price = 2999;

        System.out.println(p.brand);
        System.out.println(p.price);

        //Using member methods
        p.call();
        p.sendMessage();
    }
}

8. Multiple objects point to the same

When one object is equal to another, Student s2 = s1; Two object names will point to the same block address. In this case, the value of one object will be modified, and the value of the other object will also be modified

12. Member variables and local variables

1. What are member variables and local variables

Member variable: a variable outside a method in a class

Local variables: variables in methods

public class Student {
    String name;//Member variable
    
    public void study() {
        int i = 0;//local variable
        System.out.println("study hard");
    }
    
    public void doHomework() {
        System.out.println("Do more exercises");
        int j = 0;//local variable
    }
    
    int age;//Member variable
    
}

2. Differences between member variables and local variables

differenceMember variablelocal variable
Different positions in classOutside method in classWithin a method or on a method declaration
Different locations in memoryHeap memoryStack memory
Different life cyclesExist with the existence of the object and disappear with the disappearance of the objectIt exists as the method is called and disappears as the method is called
Different initialization valuesThere are default initialization valuesThere is no default initialization value. It must be defined and assigned before it can be used

13. Packaging

1. private keyword

  • Is a permission modifier
  • Members (member variables and member methods) can be decorated
  • The function is to protect members from being used by other classes. Members modified by private can only be accessed in this class

If the private modified member variable needs to be used by other classes, provide corresponding operations

  • The "get variable name ()" method is provided to obtain the value of the member variable. The method is decorated with public
  • The set variable name (parameter) method is provided to set the value of the member variable. The method is decorated with public

2. Use of private keyword

A standard class is written:

  • Modify member variables with private
  • Provide the corresponding getXxx()/setXxx() methods

3. this keyword

① The variable modified by this refers to the member variable

  • If the formal parameter of the method has the same name as the member variable, the variable without this modifier refers to the formal parameter, not the member variable
  • The formal parameter of the method does not have the same name as the member variable. The variable without this modifier refers to the member variable

② When to use this? Local variables hide member variables when solving the problem with the same name

③ this: represents the object reference of the class

  • Remember: this represents the object to which the method is called

example:

package com.jihua;

public class Phone {
    
    //Member variable
    private String brand;//brand
    private int price;//Price

    
    //Member method
    public void call() {
        System.out.println("phone");
    }
    public void  sendMessage() {
        System.out.println("send message");
    }
    
    
    // get, set methods
    public void setBrand(String brand) {
        this.brand = brand;
    }

    public void setPrice(int price) {
        if (price>0 && price<9999){
            this.price = price;
        }else {
            System.out.println("The price you set is wrong");
        }
    }
    
    public int getPrice() {
        return price;
    }

    public String getBrand() {
        return brand;
    }
}

package com.jihua;

public class PhoneDemo {
    public static void main(String[] args) {
        //create object
        Phone p = new Phone();

        //Using member variables
        System.out.println(p.getBrand());
        System.out.println(p.getPrice());

        p.setBrand("millet");
        p.setPrice(2999);

        System.out.println(p.getBrand());
        System.out.println(p.getPrice());

        //Using member methods
        p.call();
        p.sendMessage();
    }
}

4. Packaging

1. Package overview

Is one of the three characteristics of object-oriented (encapsulation, inheritance, polymorphism)

It is the simulation of the objective world by object-oriented programming language. In the objective world, the member variables are hidden inside the object, and the outside world can not be operated directly

2. Packaging principle

Some information of the class is hidden inside the class, and external programs are not allowed to access it directly. Instead, the operation of hidden information and access to member variable private are realized through the methods provided by the class, and the corresponding getXxx()/setXxx() methods are provided

3. Packaging benefits

Methods are used to control the operation of member variables, which improves the security of the code

The code is encapsulated by method, which improves the reusability of the code

14. Construction method

1. Overview of construction method

Construction method is a special method

Role: creating objects

Format:

public class Class name{
    Modifier class name(parameter) {
    }
}

Function: it mainly completes the initialization of object data

2. Construction method and precautions

① Creation of construction method

  • If no construction method is defined, the system will give a default parameterless construction method
  • If a construction method is defined, the system will no longer provide the default construction method

② Overloading of construction methods

  • If you customize the construction method with parameters and use the nonparametric construction method, you must write another nonparametric construction method (because it is no longer given by the system)

③ Recommended usage
Whether used or not, the parameterless construction method is written manually

example:

package com.jihua;

public class Student {

    //Member variable
    private String name;//brand
    private int age;//Price

    //Construction method
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //Member method
    public void show() {
        System.out.println(this.name + ": " + this.age);
    }

    // get, set methods
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

    public void setAge(int age) {
        this.age = age;
    }
}
package com.jihua;

public class StudentDemo {
    public static void main(String[] args) {
        //create object
        Student s1 = new Student("Zhang San",19);

        //Using member methods
        s1.show();
    }
}

3. Production of standards

① Member variable

  • Use private decoration

② Construction method

  • Provides a parameterless construction method
  • Provides a construction method with multiple parameters

③ Member method

  • Provide setXxx()/getXxx() corresponding to each member variable
  • Provides a show() that displays object information

④ There are two ways to create an object and assign values to its member variables

  • After the object is created by the parameterless constructor, setXxx() is used for assignment
  • Use the construction method with parameters to directly create objects with attribute values

character string

1. API

  • API(Application Programming Interface): application programming interface
  • Write a robot program to control the robot to play football. The program needs to send various commands to the robot, such as running forward, running backward, shooting, grabbing the ball and so on. Robot manufacturers will certainly provide some interface classes for controlling robots, which define the methods for operating various actions of robots. In fact, these interface classes are the interfaces provided by robot manufacturers for application programming. We call these classes API

Java API: refers to Java classes with various functions provided in JDK

These classes encapsulate the underlying implementation. We don't need to care about how these classes are implemented. We just need to learn how to use these classes. We can learn how to use these API s through help documents

2. String

1. General

The String class is under the java.lang package, so you don't need to import the package when using it

The String class represents a String. All String literals (such as "abc") in the Java program are implemented as instances of this class, that is, all double quoted strings in the Java program are objects of the String class

Characteristics of string

  • Strings are immutable, and their values cannot be changed after creation
  • Although String values are immutable, they can be shared
  • String effect is equivalent to character array (char []), but the underlying principle is byte array (byte[])//JDK8 used to be character array and JDK9 used to be byte array

2. Construction method

Method nameexplain
public String()Create a blank string object that contains nothing
public String(char[] chs)Create a string object based on the contents of the character array
public String(byte[] bys)Create a string object based on the contents of the byte array
String s = "abc" (recommended)Create a string object by direct assignment. The content is abc

3. Characteristics of string object

① For string objects created through new, each new will apply for a memory space. Although the contents are the same, the address values are different

char[ ] chs = { 'a' , 'b ','c' };
string s1 = new string(chs) ;
string s2 = new string(chs) ;

In the above code, the JVM will first create a character array, and then each time it creates a new address, but the string contents referenced by s1 and s2 are the same

② As long as the character sequence is the same (order and case), no matter how many times it appears in the program code, the JVM will only create a String object and maintain it in the String pool

string s3 = "abc" ;
string s4 = "abc" ;

In the above code, for the first line of code, the JVM will create a String object and put it in the String pool for s3 reference;

The second line makes s4 directly refer to the String objects in the String pool, that is, they are essentially the same object

4. String comparison

Use = = for comparison

  • Basic type: compares whether the data values are the same
  • Reference type: compares whether the address values are the same

A string is an object that compares whether the contents are the same. It is implemented through a method called: equals()

  • public boolean equals(Object anObject): compares this string with the specified object. Since we are comparing string objects, the parameter passes a string directly
package com.jihua;

public class helloworld {

    public static void main(String[] args) {
        //Get the object by constructing the method
        char[] chs = {'a', 'b', 'c'};
        String s1 = new String(chs);
        String s2 = new String(chs);

        //Get the object by direct assignment
        String s3 = "abc";
        String s4 = "abc";

        //Compare whether the address values of string objects are the same
        System.out.println(s1 == s2);
        System.out.println(s1 == s3);
        System.out.println(s3 == s4);
        System.out.println("--------");

        //Compare whether the string contents are the same
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));
        System.out.println(s3.equals(s4));

    }
}

Output:

false
false
true
--------
true
true
true

The process has ended with exit code 0

5. Traversal string

public char charAt(int index): returns the char value at the specified index. The index of the string also starts from 0

public int length(): returns the length of this string

length of array: array name. length

Length of string: String object. length()

3. StringBuilder

1. Overview of StringBuilder

public static void main(String[] arges) {
    String s = "hello";
    s += "world";
    System.out.println(s);
}

Output:

helloworld

If the String is spliced, a new String object will be constructed each time, which is time-consuming and a waste of memory space, and this operation is inevitable. So is there a better way to solve this problem? The answer is yes. We can solve this problem through the StringBuilder class provided by Java.

StringBuilder is a variable string class. We can regard it as a container. The variable here means that the content in the StringBuilder object is variable

  • The difference between String and StringBuilder
    • String: the content is immutable
    • StringBuilder: the content is mutable

2. SrtingBuilder construction method

Method nameexplain
public StringBuilder()Create a blank variable string object that contains nothing
public StringBuilder(String str)Creates a variable string object based on the contents of the string
public static void main(String[] args) {
        StringBuffer sb1 = new StringBuffer();
        System.out.println("sb1:" + sb1);
        System.out.println("sb1.length():" + sb1.length());

        StringBuffer sb2 = new StringBuffer("hello");
        System.out.println("sb2:" + sb2);
        System.out.println("sb2.length():" + sb2.length());
    }

Output:

sb1:
sb1.length():0
sb2:hello
sb2.length():5

The process has ended with exit code 0

3. Adding and reversing methods of StringBuilder

Method nameexplain
Public StringBuilder append (any type)Add data and return the object itself
public StringBuilder reverse()Returns the opposite sequence of characters
public static void main(String[] args) {
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = sb1.append("hello");
        System.out.println("sb1:" + sb1);
        System.out.println("sb2:" + sb2);
        System.out.println(sb1 == sb2);
    }

Output:

sb1:hello
sb2:hello
true

The process has ended with exit code 0
public static void main(String[] args) {
        StringBuilder sb1 = new StringBuilder();
        sb1.append("hello");
        sb1.append("world");
        System.out.println(sb1);
    }
public static void main(String[] args) {
        StringBuilder sb1 = new StringBuilder();
        sb1.append("hello").append("world");
        System.out.println(sb1);
    }

The above two are written in the same way, and the output is:

helloworld

The process has ended with exit code 0

4. Conversion between StringBuilder and String

  • Convert StringBuilder to String
    • public String toString(): you can convert StringBuilder to String through toString()
  • Convert String to StringBuilder
    • public StringBuilder(String s): you can convert a String into a StringBuilder by constructing a method

Set basis

1. Collection basis

1. Set description

When programming, if you want to store multiple data, using a fixed length array storage format does not necessarily meet our needs, but can not adapt to changing needs.

Characteristics of collection class: it provides a storage model with variable storage space, and the stored data capacity can be changed.

2. ArrayList<E>

  • Resizable array implementation

  • <E> : is a special data type, generic.

    Where E appears, we can replace it with the application data type

    Example: ArrayList < string >, ArrayList < student >

3. ArrayList construction method and addition method

Method nameexplain
public ArrayList()Create an empty collection object
public boolean add(E e)Appends the specified element to the end of this collection
public void addd(int index,E element)Inserts the specified element at the specified location in this collection
public static void main(String[] args) {
        ArrayList<String> arr = new ArrayList<>();
        arr.add("hello");
        arr.add("world");
        arr.add("java");
        arr.add(1,"javase");
        System.out.println(arr);
    }

Output:

[hello, javase, world, java]

The process has ended with exit code 0

Tags: Java

Posted on Tue, 30 Nov 2021 14:57:03 -0500 by croakingtoad