Summary of the third week of Java learning

Keywords: Java

1. Jump control statement ----- return


Return ------ returns a specific result (end method); It is rarely used alone in methods with specific return value types

return result value;

2. Method

(1) Concept of method

The method is to represent a piece of code for a specific function. Use the function code block {} to package the core content and give it a name (consistent with the identifier)

(2) Definition of method

<1> Methods with specific return values

Definition format: fixed format

Permission modifier static Return value type method name(Formal parameter type 1 variable 1,Formal parameter type 2 variable 2...){
    Function code
    return result;
public static Return value type method name(Formal parameter type 1 variable 1,Formal parameter type 2 variable 2....){
    Function code
    return result;


Permission modifier: the public used now is public. If the permission is large enough, you will learn something else later;

Static: object-oriented learning, static must be added at the current stage;

Return value type: data type;

Method name: see the meaning of the name and comply with the identifier naming specification;

Formal parameter type: data type;

Variable name: must conform to the identifier naming convention

Method call with return value type:

1)Individual call
add(a,b) ; No output results
2)Output call:Can use,Not recommended,Because if you need to further operate the results,Write dead,just so so!
System.out.println("The sum of the two data is:"+add(a,b)) ;
3)Assignment call:recommend
int result = add(a,b) ;
System.out.println("The sum of the two data is:"+result);

grammar:Return value type variable name = Method name(Actual parameter 1,Actual parameter 2...);

Two clear when writing a program:

(1)Explicit return value type
(2)Specify the parameter type and the number of parameters

<2> Method with no specific return value

Definition format: fixed format

Permission modifier static modifier static void Method name(Formal parameter type 1 variable 1,Formal parameter type 2 variable 2...){
    Output statement/Data exchange

be careful:use void Instead of the return value type

Call to method without return value:

1)Individual call:recommend
 Method name(Actual parameter list) ;
2)Output call:no way
3)Assignment call:no way

(3) Considerations for defining and invoking methods in Java

<1> Methods and methods are horizontal relationships. You cannot define another method nested in one method

<2> Java is a strongly typed language. When defining methods, formal parameter types must be carried and cannot be omitted

<3> When calling a method, the actual parameters do not need to carry data types

<4> When defining methods, semicolons are not allowed where there are {open braces;    

No {left curly braces are allowed where there is a; sign, which will show that this method lacks a method body and is meaningless

3. Method overload

(1) Definition

Multiple methods with the same name can be defined in a class. Multiple methods with the same name and different parameter lists are independent of the return value

(2) Precautions

1)Different number of parameters
2)Different parameter types
3)Consider type order

(3) Purpose

The purpose of method overloading is to make this function more extensible

4. Array

(1) Definition of array

A continuous set of storage spaces that store multiple values of the same data type

(2) Array definition format

Data type []     Array name;     eg:     int[] arr ;   Defines an array variable arr of type int

data type     Array name [];     eg:     int arr[] ;   Defines an arr array variable of type int

(3) Initialization of array

<1> Dynamic initialization

Dynamic initialization: given the length of the array, the elements are initialized by the system (Jvm) by default;

data type[] Array name = new data type[length] ; The first one is recommended  eg:   int[] arr = new int[3] ;
Data type array name[] = new data type[length] ;            eg:   int arr[] = new int[3] ;

<2> Static initialization

Static initialization: static initialization refers to giving the specific length content, and the system assigns the length by default


data type[] Array name = new int[]{Element 1,Element 2,Element 3,.....} ; Recommended use
 Data type array name[] = new int[]{Element 1,Element 2,Element 3,.....} ;

Simplified format:Writing code is simple(Note that this format cannot wrap)
			data type[] Array name = {Element 1,Element 2,Element 3,.....} ;
			Data type array name[] = {Element 1,Element 2,Element 3,.....} ;

Note: either dynamic initialization or static initialization cannot be used together

(4) Access to array elements

Array name[Index value];Index value starts at 0
arr[0];//Access the first element of the array
int[] arr = new int[3] ;//The jvm system initializes three by default
 Analytical format:
int:Stored in array int data type
[]:array:One dimensional array(default)
arr:Variable name(The in memory object name of the array)
new:Represents the creation of an object
int:Represents stored data int type
[3]:Three elements stored in the array:(length)

System.out.println(arr) ; //[ I@6d06d69c : address value
[:Represents a one-dimensional array
I:int data type
@:Address value tag
6d...:Hexadecimal data

5. Common exceptions of reference data type

(1) Compile time exception

The jvm failed to check the syntax; there are problems with the syntax format (for example, array and variable formats are written incorrectly, variables are defined multiple times, etc.)

(2) Runtime exception

Problems caused by developers' lax code writing

eg1:java.lang.ArrayIndexOutOfBoundsException: array subscript out of bounds exception
         Cause of occurrence: accessed a corner sign (index value) that does not exist in the array
         How to solve: check the code and change the index value

eg2:java.lang.NullPointerException: null pointer exception
        The default values of reference types are null;
         String s = null ;   String is a special reference type
         Reason: an object is empty and null (there is no heap memory address). At this time, you have to access the element or call
         If the method of this object, a null pointer appears;
         How to solve:
             Use the logical judgment statement to judge the non empty object

6. Classic interview questions

(1) Features of basic data types as formal parameters: basic types are passed as formal parameters. Features: the change of formal parameters will not affect the actual parameters. When the method ends, it disappears (temporary variables - formal parameters);

(2) Features of referencing data types as formal parameters: the change of formal parameters will directly affect the actual parameters. It is the transfer of spatial address value. When the method ends, the object will not be recycled immediately, waiting for garbage collector to recycle (GC)

Note: String is a special reference type, and its effect is the same as that of basic data type

class Demo{
    public static void main(String[] args){
        int a = 10 ;
        int b = 20 ;
        System.out.println("a:"+a+",b:"+b) ; //10,20
        change(a,b) ;
        System.out.println("a:"+a+",b:"+b) ; //10,20
        System.out.println("--------------------------") ; 
        int[] arr = {1,2,3,4,5} ;
        System.out.println(arr[1]) ; //2
        System.out.println("--------------------------")  ;
        change(arr) ;
        System.out.println(arr[1]) ;//4
    public static  void  change(int a,int b){
        a = b ;
        b = a+b ;
        System.out.println("a:"+a+",b:"+b) ; //20,30
    public static void change(int[] arr){
        for(int x = 0 ; x < arr.length;x++){
            if(arr[x] % 2== 0){
                arr[x] = arr[x]*2 ;

7. Advanced array sorting - bubble sorting

(1) Bubble sorting idea: compare two by two, and put the larger value back. After the first round of comparison, the maximum value appears at the maximum index. Carry out the second round and the third round of comparison in turn... To get the final result. For each comparison, the next time will be reduced, and the number of comparisons is - 1;

for(int i = 0;i < arr.length - 1;i++){
			for(int j = 0;j < arr.length -1 - i;j++){
                     Element exchange
				if(arr[j] > arr[j + 1]){
					int temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;

8. Object oriented thinking and characteristics

(1) More in line with our thinking and behavior habits in life

(2) Simplify more complex things

(3) The role has changed from executor to commander

Classic interview question: what is object - oriented: explain the characteristics of object - oriented thought and examples in life

Three characteristics of object-oriented java language: encapsulation, inheritance and polymorphism

9. Category

(1) Class definition: a collection that can describe the properties and behavior of a group of things   Can describe the real things in reality

The most basic unit in java:   Class ------------- things

                                  Member variable ----------- describes the attributes of things

                                  Member method ---------- describes the behavior of things (non static)

(2) Member variable ----------- in class, outside method

    Member method ------------ how to define it before and write it now, but remove the static keyword

public Return value type method name(Formal parameter list){
   Function code block
   return Specific results; 
public void Method name(Formal parameter list){
   Output printing

< note > two clear when defining methods

10. Relationship between class and object

Class: a collection that can describe the attributes and behaviors of a group of things; Class - describes the real "things" in the real world  

Object: describes a specific thing, which is a general term. It describes a specific thing and creates an object of the current class through code

Attention class is a general reference, and the object is the concrete embodiment of the current thing

< code embodiment >

Class name object name = new Class name();

//Assign a value to the attribute of a specific thing
 Object name.Member variable = Assignment by type;

//The act of invoking something specific
 Object name.Member's legal name();

11. Differences between local variables and member variables

(1) Different writing positions in class

Local variable: in a method definition or on a method declaration
Member variable: inside the class, outside the method

(2) Different locations in memory

Local variables: in stack memory
Member variables: in heap memory

(3) Different life cycles

Local variable: exists with the method call and disappears with the end of the method call
Member variable: exists with the creation of the object. It will not disappear immediately after the object is called. It will be collected when the garbage collector is idle

(4) Different initialization time

Local variable: can be defined first and must be initialized before use; Or initialize directly
Member variable: no assignment is allowed. The system initializes the member variable by default;
                     You can also use the object name. Member variable=   value   Complete the assignment

11. Typical examples (formal parameters are class)

If the formal parameter of a method is a class, the actual parameter needs to pass the specific object of the current class

class Student{
	public void study(){
		System.out.println("like to study,Love life!") ;
class StudentDemo{
	public void method(Student s){//Student student = new Student() ; ;  //;
class StudentTest{
	public static void main(String[] args){
		//1) To access the method method method in the StudentDemo class
		//2) How to write the actual parameters when calling?	
		StudentDemo sd = new StudentDemo() ;
		Student  student = new Student() ;
		Student student = new Student() ;

12. Anonymous objects

(1) Definition

Anonymous object: an object with a nominal name

(2) Define format and access format

<1> Definition:       New class name ();     eg:     new Student();

<2> Access:     Accessing member variables of a class            new class name (). Member variable name;
                  Member method of access class: no specific return value type:       new class name (). Member method name ();

(3) Benefits

<1> Anonymous objects can be passed as objects

<2> Save memory space

<3> In development, anonymous objects are generally used as "one-time" and are immediately recycled by the garbage collector

<4> Most of them are used in mobile phones to save memory space

13. Packaging

(1) Encapsulation keyword private: private, which cannot be accessed directly;

(2) Concept of encapsulation: in order to ensure the security of class attributes, all attributes must be added with the private keyword, and public access methods are provided to indirectly assign values to member variables (attributes); setXXX()/getXXX(): both are public: the permission is large enough

(3) Encapsulation features: member variables or member methods modified by private can only be accessed in this class;
                        External classes cannot be accessed directly, but indirectly through public member methods!

14.this keyword

When the local variable name is consistent with the member variable name (the local variable hides the member variable), Java provides a keyword: this;

this: represents the address value reference of the current class object

15. Construction method

(1) Definition of construction method:

Construction method: construction method is a special method with the same name and class name

(2) Characteristics of construction method:

<1> The method name is exactly the same as the class name

<2> Constructor has no return value type

<3> The constructor doesn't even have a void

Note: constructor supports method overloading

(3) Function of construction method

The constructor is to initialize the member properties in the class

(4) Classification of construction methods

<1>Nonparametric construction method:
  public Student(){};
<2>Parametric construction method:
  public Student(String name,int age){};

(5) Precautions for construction method

<1> When developers do not provide parameterless construction methods or parameterless construction methods, the system will always provide us with parameterless construction methods;

<2> If we provide a parametric constructor, the system will not provide a nonparametric constructor by default

16. Several ways to assign values to member variables (private modifier)

(1) Public access method assignment


(2) Assignment with parameter construction method

public Class name(Formal parameters){ = name;
    this.age = age;

17. Content of a standard class

(1) Member variables:     Privatize private

(2) Construction method:     Nonparametric / parametric construction method

(3) Member method:     setxxx(xxx);   getxxx(xxx);     Other methods

Posted by JCF22Lyoko on Wed, 06 Oct 2021 15:55:01 -0700