Java SE basic learning notes 1

Posted by Francoise on Sun, 16 Jan 2022 08:26:16 +0100

The follow-up content is in the notes on basic learning of Java SE 2, which has not been completed
The content is a little messy, there may be errors, and it will be modified frequently
Recommended dark horse Java Tutorial Station B link

Java

characteristic

Interview may ask
Object oriented cross platform is the most important
Three basic characteristics of object-oriented: encapsulation, inheritance and polymorphism

Cross platform principle of Java language

Platform: refers to the operating system
Windows, Mac, Linux
Cross platform: Java programs can run on any operating system
Premise: there is a Java running environment in the program

JRE and JDK

JRE
It is the runtime environment of Java programs, including the JVM and the core class libraries required by the runtime
To run an existing Java program, simply install JRE

JDK
It is a Java program development kit, which contains the tools used by JRE and developers
The development tools include compiling tool (javac.exe) and running tool (java.exe). If we want to develop a new Java program, we must install JDK.

Relationship between JDK, JRE and JVM
JDK: for development, including development tools and JRE
JRE: Java runtime environment for running Java programs, including class loader
JVM: where java programs really run, JVMs with the same functions need to be provided on different operating systems

JDK download and installation

Uninstall JDK , if you do not uninstall, you cannot install a new one
Both need to be uninstalled

Important files in the jdk directory

Directory nameexplain
binVarious JDK tool commands are stored in this path
javac and java are in this directory

Common DOS commands

operationexplain
Drive letter name:Drive letter switch e: press enter to switch to drive E
dirView the contents under the current path
Include sub files and sub folders
cd directoryEnter single level directory
cd itheima
cd ...Fallback to upper level directory
cd directory 1 directory 2Enter multi-level directory
cd itheimaavaSE
cd \Fallback to drive letter directory
clsClear screen
exitExit the command prompt window

Ctrl + C in the command prompt window can end the loop

Configure Path environment variable

To develop Java programs, you need to use the development tools provided by JDK, which are in the bin directory of the JDK installation directory
In order to easily use Java and javac commands when developing Java programs, you need to configure the Path environment variable

  1. JAVA_ HOME new
    ?:\ ...\jdk-11

  2. Path Edit
    %JAVA_HOME%\bin
    Don't forget to move to the top

Java program development and running process

Developing Java programs requires three steps: ① writing programs ② compiling programs ③ running programs

Preparation of HelloWorld case

  1. Create a new text document file and change the name to HelloWorld java
  2. Open HelloWorld with Notepad Java file, write program content
pub1ic c1ass He11oor1d {
	pub1ic static void main(String[]args){
		System out.println("Heiioworid");
	}
)
  1. Compile this file with javac first
    Compiled into bytecode file by compiler class

  2. Then execute the java file

    File names are not case sensitive in the Window operating system

  • Shortcut key
    Press Tab to automatically fill in the file name

What happens to your computer when you run a Java program

During the interview, I often test JVM, Java virtual machine, JDK and JRE

BUG resolution

  1. Have the ability to identify bugs
    Look more and increase the knowledge reserve
  2. Ability to analyze bugs
    Think more and consult more materials
  3. Ability to solve bugs
    Try more and summarize more

Basic grammar

notes

summary

  1. Comments are descriptive information added at a specified location in the program
  2. Comments do not participate in program operation, but only serve as instructions

classification

notesformat
Single-Line Comments //Annotation information
multiline comment / *
*Annotation information
*/
Documentation Comments /**
*Annotation information
*/

Document notes:

  1. Class, method, property
  2. Javadoc can be generated

case

/* 
	Java The most basic component of a program is a class
	
	Class definition format:
		public class Class name{
		)
*/

// This is the Helloworld class I defined
public class Helloworld {

	/* 
		This is the main method
		main Method is the entry method of the program
		The execution of the code starts with the main method
	*/

	public static void main (String[] args){
		System.out.println ("HelloWorld");
	}
}

keyword

summary
A keyword is a word given a specific meaning by the Java language
characteristic

  1. All letters of the keyword are lowercase
  2. Common code editors have special color marks for keywords, which is very intuitive


48 keywords
Data types: void, byte, short, int, long, float, double, char,boolean
Permission modifiers: public, protected, private type definitions: class, interface, enum
Class modifiers: static, abstract, final,
Process control: if, else, for, while, do, switch, case, default, break,continue, return, try, catch, finally

3 constant values true false null
2 reserved words const goto

identifier

Identifiers are symbols that give names to classes, methods, variables, etc

Define rules

  1. By numbers, letters, underscores () And dollar sign ($)
  2. Cannot start with a number
  3. Cannot be a keyword
  4. Strictly case sensitive

standard



Naming convention

Small hump nomenclature: methods, variables

  1. When the identifier is a word, the first letter is lowercase
    For example: name
  2. When an identifier consists of multiple words, the first word is lowercase and the other words are uppercase
    For example: firstName

Nomenclature of large humps: Class

  1. When the identifier is a word, the first letter is capitalized
    For example: Student
  2. When an identifier consists of multiple words, the first letter of each word is capitalized
    For example: GoodStudent

constant

summary
A constant is an amount whose value does not change during the running of a program

classification

  • be careful
    Null constant null
    Null constants cannot be output directly
System.out.println (null);		// report errors

data type

Data type, jump in page

Java language is = = strongly typed language = =, which gives explicit data types for each kind of data. Different = = data types = = also allocate different = = memory space = =, so they represent = = data size = =


Memory occupation and value range of data type

Very important

E+38 means that it is multiplied by 10 to the 38th power
E-45 is multiplied by 10 to the minus 45th power

Scientific counting method
156700

If the preceding number exceeds 6 bits, the accuracy will be lost ↓

Accuracy error caused by approximation
This is true for all floating point numbers

Weakly typed languages and strongly typed languages

Strongly typed language is a language that enforces type definition. Once a variable is defined as a type, it will always be the data type without coercion
Strongly typed languages include Java, Python, C + +, etc

Weakly typed language is a language defined by weak types. A variable is defined as a type. The variable can be automatically converted according to environmental changes without explicit coercion
Weakly typed languages include JavaScript, PHP, etc

variable

summary
A variable is an amount whose value can change during the running of a program
In essence, a variable is a small area of memory

Naming of variables

Format: data type variable name = variable value
example:

inta = 10;

// Both of the following are true
int i, j;
int m = 5, n = 10;

i = j = 10;
// i = ( j = 10 )

int x = y = 10;		// Error reported, y not defined
int a, b = a = 10;	// This is OK



Variable constant

Syntax: constant name of final data type;
example:

final f1oat PI = 3.14;

be careful
A constant cannot be assigned after it has been assigned

PI = 3.1415;	// report errors

Use of variables

  1. Value format: variable name
    For example:

    a
    
  2. Modify value format: variable name = variable value;
    For example:

    a = 20;
    

Precautions for use

  1. The name cannot be repeated
  2. The variable is not assigned and cannot be used
  3. Define variables of type long
    long l = 10000000000;		// report errors
    long l = 10000000000L;		// Output 10000000000
    
    System.out.println(l);
    

Integers are of type int by default
When defining a variable of type long, in order to prevent the integer from being too large, add (L) after it

Default value

  1. Define variables of type float
float f = 13.14;		// report errors
float f = 13.14F;		// 13.14

system.out.println(f) ;

Floating point numbers are double by default
When defining variables of float type, in order to prevent type incompatibility, add (F) after them

Type conversion

data type

Type conversion is divided into automatic type conversion and forced type conversion

boolean cannot be converted with other types

Automatic (implicit) type conversion

Default value

Assign a value or variable representing a small data range to another variable representing a large data range
For example:

doubled = 10;

Conversion order
byte => short => int => long => float =>double

short s = 'a';	// It seems that char is automatically converted to short type
char c = 'a';
s = c;			// An error is reported, indicating that char cannot be automatically converted to short type

In fact, the data type of s is int

Case:
correct

	double d = l0 ;				// int → double
	system.out.println (d) ;	// Output 10.0
	
	// Defines a variable of type byte
	byte b = 10 ;
	short s = b ;				// byte → short
	int i = b ;					// byte → int
	
	char c = b ;				// Error byte → char cannot be converted

Automatic conversion pit

Cast type

Assign a value or variable representing a large data range to another variable representing a small data range
Format: target data type variable name = (target data type) value or variable;
The data range of this value or variable must be larger than that of the target data type

Note: data may be lost / overflowed

long l = 2200000000L;
Float f1 = 1.5f;

byte b1 = 10;
char c1 = (char)b1;
System.out.println(c1);		

short s1 = 128;
//How to convert decimal to two
byte b2 = (byte)s1;		// -128
	

System.out.println(compare(1,2));

compare(1,2)					// int
compare((byte)1,(byte)2)		// byte
compare((short)1,(short)2)		// short
compare(1L,2L)					// long

exceptional case:

	int k = (int)88.88;		// 88.88 is a floating point number
	System.out.println(k); // 88
  • It can be seen from the above case that forced type conversion can be done, but there is data loss, so it is not recommended

Scope

Location is important

operator

Interview questions

When complex operations are encountered, they can be enclosed in parentheses

int a = 1;
int b = 1;

--a++;		// report errors
a +++ b;	// a++ + b
a ++++ b;	// report errors
a ++-++ b;	// a++ - ++b

// The + - in the middle can hold an infinite number
a ++-+-+-+-++ b;
// (a++) - (+ - + - + - (++b))
// 1 - (- - - 2) = 3

Operators and expressions

  • Operator: a symbol that operates on constants or variables
  • Expression: an expression that connects constants or variables with operators and conforms to java syntax can be called an expression

Expressions connected by different operators represent different types of expressions

  • case
	int a = 10;
	int b = 20;
	int c = a + b;

+: is an operator and is an arithmetic operator
a + b: is an expression. Since + is an arithmetic operator, this expression is called an arithmetic expression

Arithmetic operator

Arithmetic operators and data types

data type
Low data type to high data type during operation

1. In operation, char, byte and short types will be automatically converted to int calculation

short s1 = b1 +10;	// An error is reported. s1 is of type int

byte b1 = 10;
byte b2 = 20;

short s1 = b1;			// No error is reported, and s1 is not calculated, so it is short
short s2 = b1 + b2;		// An error is reported. s2 is of type int

2. When there are two constant value operations in the expression, the two values will be operated directly during compilation

short s4 = 'a' + 'b';	// √
//          97 +  98 = 195
// short s4 = 195 syntax compliant

char c1 = 'a';
char c2 = 'b';
short s5 = c1 + c2;		// report errors

If you want to divide integers by (%), you can only get floating-point numbers

System.out.println (6 / 4);		// 1
System.out.println (6.0 / 4);	// 1.5

System.out.println( 10.5 % 3.3 );
// 10.5/ 3.3 = 3 ..... 0.6
// In fact, it is 0.6000000000000000 5
// Converted to double

System.out.println(-11 % 3);	// -2
System.out.println(11 % -3);	// 2
System.out.println(-11 % -3);	// -2

Different data types

When an arithmetic expression contains values of multiple basic data types, the type of the entire arithmetic expression will be promoted automatically

Promotion rules

  1. byte type, short type and char type will be promoted to int type
  2. The type of the entire expression is automatically promoted to the same type level order as the highest level operands in the expression ↓
    byte,short,char → int → long → float → double

case

//Define two variables
int i = 10;
char c ='A'; 			// The value of 'A' is 65

char ch= i + c;			// If an error is reported, the char type will be automatically promoted to int type
int j = i + c;
System.out.println(i) ;	// 75

int k = 10 + 13.14;		// report errors
double d = l0 + 13.l4;	// √

"+" operation of string

  1. When a string appears in the "+" operation, the "+" is a string connector, not an arithmetic operation
    "abc"+ 123			// abc123
    
  2. In the "+" operation, if a string appears, it is a connection operator, otherwise it is an arithmetic operation. When the "+" operation is performed continuously, it is performed one by one from left to right
    "abc"+ 12 + 3		// abc123
    1 + 2 +"abc"		// 3abc
    

Compound operator



+=Precautions
(+ - * /%) = operation implies cast

short s = 10;
	
1
s += 20;		// thirty 	 It is suggested to write like this
	
2
s = s + 20;		// Type mismatch: cannot convert from int to short
	
3
s = (short)(s + 20);	// Strong to short type
	
System.out.println(s);

Self increasing and self decreasing operator

++ –
Location is critical

  1. When used alone, + + and - whether placed before or after variables, the result is the same
  2. Participate in the operation. If it is placed behind the variable, take the variable to participate in the operation first, and then take the variable as + + or –
  3. Participate in the operation. If it is placed in front of the variable, take the variable as + + or –, and then take the variable to participate in the operation

case

1
int a = 10;
int b = a++;	// First assign a to b, and then a to b++
System.out.println(a);	// 11
System.out.println(b);	// 10

2
int b = ++a;	// 11

Relational operator

The value must be Boolean true false

Logical operator

// ^The same is false, but the different is true
System.out.println(i > j ^ i > k );  // false ^ false = false
System.out.println(i < j ^ i > k );  // true  ^ false = true
System.out.println(i > j ^ i < k );  // false ^ true  = true
System.out.println(i < j ^ i < k );  // true  ^ true  = false

! You can put more than one, that is, take the reverse, take the reverse, and then take the reverse

Short circuit logic operator

Logic and&Short circuit and&&
Whether the left is true or false, the right should be executedIf the left is true, execute on the right
If the left is false, the right is not executed
Logical or lShort circuit or ll
Whether the left is true or false, the right should be executedIf the left is false, execute on the right
If the left is true, the right is not executed

Bitwise Operators







Interview questions

How to achieve num * 2^n at the fastest speed
-Shift left





Binary:
0 000000
-1 111111
-2 111110
-3 111101

The binary of a negative number equals the binary of a positive number minus + 1

Ternary operator

formatexample
Relational expression? Expression 1: expression 2;a > b ? a : b
  1. First, evaluate the value of the relationship expression
  2. If the value is true, the value of expression 1 is the result of the operation
    If the value is false, the value of expression 2 is the result of the operation
//Gets the larger of the two data
int max = a > b ? a : b;	// Don't forget to define the data type (int) first

Ternary operators are right to left

associativity of operator

Interview questions

Output System

Enter Scanner


The message will be scanned after pressing enter

Use steps

  1. Guide Package: introduce Scanner class

    import java.uti1.Scanner ;
    

    The action of importing packages must appear above the public class definition

  2. Define (create) objects

    Scanner sc = new Scanner (System.in);
    

    In the above format, sc is the variable name

  3. receive data
    sc.nextXxx(); Xxx data type

    //full name
    string name;
    System.out.println("Please enter your name:");
    name = sc.next();			// Returns the input of a string
    
    //Age
    int age;
    System.out.println("Please enter your age:");
    age = sc.nextInt();
    
    //Gender
    System.out.println("Please enter your gender:");
    String sex = sc.next(); 	// The next method has no char type
    
    //Telephone number
    System.out.println("Please enter your mobile number:");
    String phone = sc.next(;
    

Completion shortcut Ctrl + Alt + V

sc.nextInt();

next() and nextLine()

The methods next() and nextLine() in the Scanner class absorb the characters input by the input console

difference:
next() will not absorb the space before / after the character / Tab key, only absorb the character, and start to absorb the character (not before and after the character) until it meets the space / Tab key / enter
nextLine() absorbs the space before and after the character / Tab key, and the Enter key ends
Explain in detail

Branch statement

Process control statement classification:

  1. Sequential structure: execute according to the sequence of codes
  2. Branch structure (if, switch)
  3. Loop structure (for, while, do... While)

if

Execution process

  1. First, evaluate the value of relationship expression 1
  2. If the value is true, the statement body 1 will be executed, and if the value is false, the value of relationship expression 2 will be calculated
  3. If no relational expression is true, the statement body n+1 is executed

switch

  • case: followed by the value to be compared with the expression
  • default: indicates that the content will be executed when all conditions do not match

case penetration

In the switch statement, if break is not written behind the case controlled statement body, penetration will occur. Without judging the next case value, run down until break is encountered or the whole switch statement ends

switch (month) {
	case l:
	case 2:
	case 12:
		System.out.println("winter");
		break ;
	case 3:
	case 4:
	case 5:
		System.out.println("spring");
		break ;
	case 6:
	case 7:
	case 8:
		System.out.println("summer");
		break;
	case 9:
	case 10:
	case ll:
		System.out.println("autumn");
		break;
	default:
		System.out.println("The month you entered is incorrect");
}

Circular statement

sentenceexplain
Initialization statementUsed to indicate the starting state when the cycle is on
That is, what does the cycle look like at the beginning
Conditional judgment statementA condition used to represent repeated execution of a loop
That is, judge whether the loop can be executed all the time
Loop body statementUsed to represent the content of repeated execution of a loop
That is, things that are executed repeatedly
Conditional control statementUsed to represent the contents of each change in the execution of the loop
That is, whether the control loop can be executed + + –

The top-down order of the table is also the order of circular execution. The initialization statement is executed only once

for

Multiple initialization variables can't be put on it

for (int start = 0,end = 5;...;...)

Scope of variable

  1. The for conditional control statement controls the self increasing variable
    Because in the syntax structure of the for loop, it cannot be accessed again after the for loop ends

  2. The while condition controls the self increasing variable controlled by the statement
    For the while loop, it does not belong to its syntax structure. After the while loop ends, the variable can continue to be used

    for(int i = l; i<3; i++){
    	System.out.println ("abc") ;
    }
    
    System.out.println(i) ;		// report errors
    

Narcissistic number

int a;
int b;
int c;
int j = 0;
		
for (int i = 100;i < 1000; i++) {
			
a = i / 100;
b = i / 10 % 10;
c = i % 10;
			
	if (i == a * a * a + b * b * b + c * c * c) {
		j++;
		System.out.println(i);
	}
}	

System.out.println(j);
j = 0;

Rabbit born rabbit

A pair of rabbits give birth to a pair of rabbits every month from the third month after birth. The little rabbit grows to another pair of rabbits every month after the third month. If the rabbits don't die, what are the logarithm of rabbits in the twentieth month?

while

Everest & Origami

Everest: 8844430mm, paper: 0.1mm, how many times do you fold

int a = 8844430;
double b = 0.1;
int i = 0;
		
while (b < a) {
	b *= 2;
	i++;
}
		
System.out.println(i + "second");	// 27

do...while

Because it is executed before judgment, it will be executed once anyway

int k = 3;
do {
	System.out.println("abc");	// Output abc once
	k++;
}while (k<3) ;

Jump control statement

continue and break Use in JavaScript

exit in Java

System.exit(0);

0 means normal program shutdown, non-0 means abnormal shutdown, and can also be placed in the loop body, similar to break

Generate a Random number Random

Use the same steps as Scanner

  1. Guide Package

    import java.util.Random;
    

    The action of importing packages must appear above the public class definition

  2. create object

    Random r = new Random();
    

    r is the variable name, which can be changed, and nothing else can be changed

  3. Get random number

    int a = r.nextInt(10);
    // Range of data obtained: [0,10) including 0 but excluding 10
    

    a is 10 of the variable name and value range, which can be changed, and others cannot be changed

Gets a random number between 1 and 100

Scheme: [0100) → [1101)

int a = r.nextInt(100) + 1;

IDEA and eclipse

IDEA

Is an integrated environment for Java language development
Integrated environment: a development tool that integrates code writing, compilation, execution, debugging and other functions

Fool installation

30 day trial unlimited refresh

eclipse

Fool Chinese and English

Basic operations for creating a project

Coding format:

Shortcut key
ctrl + + zoom in
ctrl + - zoom out

HelloWorld

It can be divided into two parts
Part I

  1. Create a project (Project0109)
  2. Create a module (idea_test)

Part II

  1. Create a package (com.practice) under src under the module
    It can't be called com Package, unable to create
  2. Create a new class (HelloWorld) under the package
  3. Writing code in a class
  4. Execution procedure

Video tutorial

Project structure

Module → package → class → method

Content assist key

  1. Fast generation
    effectKey
    Quick generate main() methodpsvm + ENTER
    Quickly generate output statementsSouth + ENTER
  2. Content assist key
    effectKey
    Content prompt, code completion, etcAlt + /

Shortcut key

effectKey
Single-Line Comments Ctrl + /
multiline comment Ctrl + Shift + /
formatting code Ctrl+Alt+L

Shortcut keys are not responding

Module operation in IDEA

1. Create a new module




2. Delete module

effectoperation
Remove from programRight click the corresponding module
Click Remove Module
Completely delete in fileShow in Explorer
Open file delete ↓


3. Key points of import module
Import modules from elsewhere into the project



If an error is reported, install the SDK

array

Array: a storage model used to store multiple data of the same type
Purpose: declare a large number of variables used to store data at one time
For example: student number, grade

Define format

First kindSecond
formatData type [] variable nameData type variable name []
exampleint[ ] arrint arr[ ]
Reading methodDefines an array of type int
The array name is arr
Defines a variable of type int
The variable name is an arr array

The first one is recommended

Array initialization

Arrays in Java must be initialized before they can be used
Initialization: allocate memory space for array elements in the array and assign values to each array element

Array initialization methods: dynamic initialization and static initialization

dynamic initializationinitiate static
effectOnly the array length is specified during initialization
Initial values are assigned by the system to the array
Specifies the initial value of each array element during initialization
The length of the array is determined by the system
formatData type [] variable name = new data type [array length];Data type [] variable name = new data type [] {data 1, data 2,...};
Simplified format: data type [] variable name = {data 1, data 2,...};
standardint[ ] arr = new int[3];int[ ] arr = new int[ ]{1,2,3};
int[ ]arr = { 1,2,3};

Structure description

int[] arr = new int[3];
  • Left:
    key wordexplain
    intDescription the element type in the array is int type
    [ ]This is an array
    arrThe name of the array
  • right:
    key wordexplain
    newRequest memory space for array
    intDescription the element type in the array is int
    [ ]This is an array
    3Array length, that is, the number of elements in the array

Array element access

visitformat
Array variable accessArray name
Access to data stored inside the arrayArray name [index]

Index: how data in an array is numbered

Function: the index is used to access the data in the array. The array name [index] is equivalent to the variable name, which is a special variable name

Note: in actual development, if the corresponding index does not exist, it usually returns a negative number, usually represented by - 1

memory allocation

Space nameeffectEnd of use
Stack memoryStore local variables
That is, the variables defined in the method, for example: arr
Disappear immediately
Heap memoryStored new content (entity, object)
Every new thing has an address value, such as 001
Will be collected when the garbage collector is idle


video
Memory allocation in javaScript

Default value

When the array is initialized, a default value is added to the storage space

data typeDefault value
integer0
Floating point number0.0
booleanfalse
Character charNull character
Reference data typenull

Multiple arrays point to the same

Assign the address of the first array to the second array

int[] arr2 = arr;		// The two array addresses will be the same


Output ↓

Array summary



Debug

Debug debugging, also known as breakpoint debugging, is a program debugging tool for programmers
A breakpoint is actually a marker that tells us where to start looking

Functions of Debug:

  1. View the execution process of the program
  2. Trace program execution to debug the program

Debug operation flow

  1. How to add breakpoints

  2. How to run a program with breakpoints

  3. Look where

    1. Look at the Debugger window
    2. Look at the console
  4. Where

    1. Continue running

      Note: if the data comes from keyboard input, be sure to remember to input the data, otherwise you can't continue to view it

    2. end

  5. How to delete a breakpoint
    There are multiple breakpoints, which can be deleted one by one or all at once

method

Method: it is a code set that organizes code blocks with independent functions into a whole and makes them have special functions

Method can improve the reusability of code

Method definition

Methods must be created before they can be used. This process is called method definition

Format:

public static void Method name(){
	//Method body
}

example:

public static void method() {
	//Method body
}

I may be a fool to write other methods in the main method

Method call

Methods do not run directly after they are created, and they need to be executed manually. This process is called method call

Format:

Method name();

example:

method();
public static void main(String[] args) {
	method();	// 1
}
	
public static void method() {
	int a = 1;
	if (a > 0) {
		System.out.println(a);
	}
}

matters needing attention

  1. The statement of method call should be written in the main method, because the main method is the entry method of the program
  2. The method must first be defined after the call, otherwise the program will report wrong, but don't forget to call it at last.
    However, the program executes the statement of method call first, and then the statement of method definition

Method with parameters

Definition method

Single parameterMultiple parameters
formatpublic static void method name (data type variable name) {...}public static void method name (data type variable name 1,...) {...}
standardpublic static void method(int number) {...}public static void getMax(int a,int b,...) {...}

Call method

Single parameterMultiple parameters
formatMethod name (parameter);Method name (variable name 1 / constant value 1, variable name 2 / constant value 2);
standardmethod(3);getMax (a,5,...) ;
  • When calling a method, the number and type of parameters must match the settings in the method definition, otherwise the program will report an error

case

Basic data type

public static void main(String[] args) {
	int a = 2;
	// There is no need to write data type here
	method(a);		// 2
}

// int b here has nothing to do with the above, so does int a
// Note that this is not JavaScript. Don't forget your data type, int!
public static void method(int a) {
	if (a > 0) {
		System.out.println(a);
	}
}

array

public static void main(String[]args) {
		
	// Define an array and initialize the array elements with static initialization
	int[] arr = {1,2,3};
		
	// Call method
	printArray(arr);
}

	// Define a method to traverse the array in the general format of array traversal/*
	/* 
	   Two clear:
	 	 Return value type: void
		 Parameter: int[] arr
	*/
	
public static void printArray(int[] arr) {
	for(int x = 0;x<arr.length;x++) {
		System.out.println(arr[x]);
	}
}

Formal and argument


Method with return value

Format:

public static Data type method name(parameter){
	return data;
}

example:

// boolean
public static boolean method(int number){
	return true;
}
// int
public static int getMax(int a,int b) {
	return 100;
}

matters needing attention

  1. The return value of a method is usually received using a variable, otherwise the return value will be meaningless
  2. return can be written with or without void

    Case:
public static void main(String[] args) {
	int a = 2;
	boolean b = method(a);
	System.out.println(b);
}

public static boolean method(int a) {
	if (a > 0) {
		return true;
	} else {
		return false;
	}
}

General format of method

Format:

public static Return value type method name(parameter){
	Method body;
	return data;
}
key wordexplain
public staticModifier
return typeThe data type of the data returned after the method operation is completed
If the method operation is completed and no data is returned, void is written here, and return is generally not written in the method body
Method nameThe identifier used when calling the method
parameterIt consists of data type and variable name, and multiple parameters are separated by commas
Method bodyCode block to complete the function
returnIf the method operation is completed, there is a data return, which is used to return the data to the caller

matters needing attention

When defining a method, two things should be clear

  1. Explicit return value type
    It mainly specifies whether there is data return after the method operation
    1. No, write void
    2. Yes, write the corresponding data type
  2. Explicit parameters
    It mainly specifies the type and quantity of parameters

When calling a method

  1. Method of void type can be called directly
  2. A method of non void type that receives calls with variables

Method overloading

Method overloading: the relationship between multiple methods defined in the same class, which satisfies

① Multiple methods in the same class
② Multiple methods have the same method name
③ Multiple methods have different parameters, different types or different quantities. These three points are different

Multiple methods of each other constitute overloads

Method overload characteristics

  1. 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
  2. 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

The parameter int a is the same
Independent of return value
Different number of parameters
Same parameter typeMethodDemo01 and MethodDemo02 are two classes

Case:

When calling, the Java virtual opportunity distinguishes the methods with the same name through different parameters

public static void main(String[] args) {
	//Call method
	int result = sum(1,2);
	System.out. println(result);		// 3

	double result2 = sum(1.0,2.0);
	System.out.println(result2);		// 3.0
		
	int result3 = sum(1,2,3);
	System.out.println(result3);		// 6
}

//Requirement 1: method for finding the sum of two int type data
public static int sum(int a,int b) {
	return a + b;
}
	
// Requirement 2: method for finding the sum of two double type data
public static double sum(double a,double b) {
	return a + b;
}

// Requirement 3: method for finding the sum of three int type data
public static int sum(int a,int b,int c) {
	return a + b + c;
}

Method parameter transfer

Basic type

For parameters of basic data type, the change of formal parameters does not affect the value of the arguments

reference type

For the parameter of reference type, the change of formal parameter will affect the value of actual parameter

Debris pile

report errors

Syntax errors display red wavy lines

Guide Package

There are three ways to guide the package

  1. Manual guide bag
    Scanner example
  2. Shortcut key guide package Alt + Enter
  3. Automatic package Guide (recommended)

Topics: Java Back-end