Day01 -- basic knowledge of computer, java development environment, variables, data types, type conversion, operation rules, operators, branch structures, loops, methods, arrays

Cool breeze AAA 2022-02-13 07:39:15 阅读数:401

day01 day basic knowledge java

1 Day01–Java development environment +HelloWorld

1.1 Basic computer knowledge

Information download website : Liu peixia 18600949004
code.tarena.com.cn
tarenacode
code_2017

Notes Download : To download , Reuse world Mode on , At this time, the image copied to the newly created document can be displayed .
qq If it is the other party's mobile phone login , Can't send folder . Only computer login , You can compress the file and send it .( Select the folder and right click ---- Such as : Add to “ Morning talk .rar”)

1.1.1 Computer

Computer (Computer) Full name : electronic computer , Commonly known as computer . It's a program that can run , Automatically 、 Modern intelligent electronic equipment for high speed data processing . from Hardware and software The composition of , A computer without any software installed is called Bare pager . The common form is desktop computers 、 Laptop computer . According to the scale, it is divided into microcomputers 、 minicomputer 、 The mainframe 、 Supercomputers ( supercomputer ) etc. .
The application of computer has penetrated into all fields of society , It's changing people's work 、 The way to learn and live , It promotes the development of society . What aspects ?
 Insert picture description here
Father of computer : The computer structure is based on this structure .
 Insert picture description here

1.1.2 computer hardware

computer hardware (Computer Hardware) It refers to the electronic in the computer system , A general term for various physical devices composed of mechanical and photoelectric elements . These physical devices constitute an organic whole according to the requirements of the system structure, providing the material basis for the operation of computer software .
Computers are usually made of CPU、 a main board 、 Memory 、 Power Supply 、 Main box 、 Hard disk 、 The graphics card 、 keyboard 、 mouse , Display and other components .
One 、 Computer hardware system
So called hardware , It's something you can touch with your hands , A computer usually has :
1、 host : The mainframe is a whole from the outside , But when you open the chassis , You will find that its interior is composed of many independent components .
Here are the components of the main computer
(1) Power Supply : Power supply is an indispensable power supply equipment in computer , Its function is to 220V Communication is converted to the use of computers 5V,12V,3.3V Direct current , The quality of its performance , Directly affect the stability of other equipment .
(2) a main board : The motherboard is the working platform of each part of the computer , It connects all the parts of the computer , Each component transmits data through the motherboard .
(3) CPU:CPU Its function is to perform calculations , Logical operations , Data processing , rounding , Input / The output control computer automatically , Coordinate various operations .
(4) Memory : Memory is also called internal memory , It belongs to electronic storage device , It's made up of circuit boards and chips , It's characterized by its small size , Fast , There is electricity to store , Empty without electricity , Data can be stored when the computer is turned on , All data will be cleared automatically after shutdown .
(5) Hard disk : Hard disk belongs to external memory , Made of metal magnets , The magnetic disc has memory function , So the data stored on the disk , No matter when it's on , Or turn it off , They won't lose .
(6) Sound card : Sound card is an indispensable hardware device for multimedia computer , Its function is when the play command is issued , The sound card converts the sound digital signal in the computer into analog signal and sends it to the speaker to make sound .
(7) The graphics card : The graphics card works with the display to output graphics , written words , Its role is to be responsible for CPU The sent signal is converted into an analog signal recognized by the display , Send it to the monitor to show it .
(8) modems : A modem is one of the essential devices for accessing the Internet through a telephone line . Its function is to convert the digital signal processed by the computer into the analog signal of the telephone line .
(9) network card : The function of network card is to act as a bridge between computer and network cable , It is an important device used to establish Internet access .
(10) floppy disk drive : Floppy disk drive is used to read data from floppy disk . Floppy disk is a read-write external storage device .
(11) CD drive : The optical drive is used to read the data in the optical disc . CD-ROM is a read-only external storage device .
2、 Monitor : The monitor is big and small , There are thin and thick , Its function is to display the results of computer processing . It's an output device .
3、 keyboard : A keyboard is an input device , Used to put words , Input numbers, etc. into the computer .
4、 mouse : When people move to the mouse , There will be an arrow on the computer screen and the pointer will follow it , And it can move to the designated position very accurately , Quickly display on the screen .
5、 Loudspeaker box : It can play the sound in the computer .
6、 The printer : It can be used to print the files in the computer onto paper , It's one of the important output devices .
7、 camera 、 Scanner 、 Digital camera and other equipment 、

1.1.3 Computer software

Computer software (Computer Software) It is an essential thing in the process of using computer , Computer software enables a computer to perform specific functions in a predetermined order , Computer software is divided into system software and application software according to its function
Systems software : DOS(Disk Operating System), Windows, Linux, Unix, Mac, Android, iOS
Application software :office QQ Hero alliance Glory of Kings

Windows System : This operating system is the most widely used operating system in the world , Developed by Microsoft . So far Windows 98 /2000/7/8/10 And many other versions , At present, the largest number of users is WIN7 operating system , The most classic is WINDOWS XP operating system .Win10 Is the latest and most secure operating system , But because of the problem of humility, not many people accept .

Linux System :Linux Is a free and open source class Unix operating system , There are many different Linux edition , But they all use it Linux kernel . This system is mostly used in enterprises , Easy to manage server and other hardware .

1.1.4 software development

Software : A collection of computer data and instructions organized in a specific order .

Development : Software production process .

software development : Make software with the help of development tools and computer language .
 Insert picture description here

1.1.5 Computer language

Language : The various symbols of human communication , Facilitate communication and information exchange between people .
Computer language : A special language for information communication between people and computers , There are also characters in computer languages , Symbols, etc. . Common computer languages such as C,C++,C#,JAVA.
History of computer language development :
 Insert picture description here
 Insert picture description here
 Insert picture description here

1.1.6 Human computer interaction

Concept : The emergence of software enables better interaction between people and computers .
Interactive mode

  1. Graphical interface : This way is simple and intuitive , It's easy for users to accept , Easy to operate .
  2. Command line mode : There needs to be a console , Enter specific instructions , Let the computer do something . More troublesome , You need to record some orders .

1.1.7 Keyboard function key and shortcut key introduction

Keyboard function keys : It is required to master the position on the keyboard .
Tab
Shift Ctrl Alt
Space Enter
Window
The up and down or so
PrtSc(PrintScreen) Screen capture ( Key +ctrl+v To word file , Full screen )

Keyboard shortcuts : It is required to be proficient in the use of .
Ctrl+A Future generations
Ctrl+C Copy
Ctrl+V Paste
Ctrl+X shear
Ctrl+Z revoke
Ctrl+Y Counter cancellation
Ctrl+S preservation …
Alt+F4 close window
ctrl+shift+Esc Open Task Manager , You can view and operate the process .
multi-select : ctrl+ mouse

1.1.8 frequently-used DOS command

Concept :DOS command , Computer terminology , Refer to DOS Operating system commands , It's a disk oriented command , It mainly includes directory operation commands 、 Disk operation class Command 、 File manipulation class commands and other commands .
explain : At present, the commonly used operating systems are windows10,windows 7 etc. , They are all graphical interfaces . The operating system used by people before these systems was DOS System .
( Now it's a graphical interface , Computers used to use dos Command to enter instructions . stay java In development, we will use dos Command window , Such as linux Used in the server-side system of )

open DOS Several ways of the console

  1. Start menu in the lower left corner of the computer +Windows System + Command prompt
     Insert picture description here

  2. Window++cmd ( Recommended )

  3. In any blank space on the desktop , Hold down shift key + Right click , Open here PowerShell window . This window is essentially the same as the command line window .

  4. Enter... In Explorer cmd, You can open the command prompt corresponding to the drive letter position .
     Insert picture description here

Run as an administrator

 Insert picture description here
matters needing attention

  1. stay Dos Right click Properties on the window , You can change the color , Font size, etc .
  2. After input +enter key . After each command is entered, you need enter key
  3. stay DOS Window copy path paste ctrl+v stay windows7 Out-of-service .Windows10 Sure . So you can only use the right mouse button to paste
  4. Dos Symbols in the window , The letters are in English .
  5. You can use the up and down keys of the keyboard to switch the input commands , Do not re-enter the command . A computer can turn on multiple at the same time dos window , But the keyboard up and down can only be used for the same window command .

Commonly used DOS command
cmd Get into DOS window , The default is in c Under the plate , You can switch drive letters .
e: Get into e disc ( Include colon )
dir List the directories and files in the current directory ( Include hidden directories , No colon
mkdir New folder
rmdir Delete folder
cd> + file name create a file
del + file name Delete file
cd java Get into java Catalog ( There's a space in the middle )
cd . . Back to the top directory
cd / Back to the root
E:/>cd /d f: Cross drive switching , Yes E Disk switch to F disc ( Include colon )
exit sign out dos Command line
cls (clear screen) Clear the screen
Ipcongfig View the native ip Address ( Equivalent to the ID card of the computer , A computer has only one
ping www.baidu.com (Ping+ip Address ) Check whether the network connection is normal .

1.2 Java Language Overview

1.2.1 Java History of language development

 Insert picture description here

James · Gauss Lin (James Gosling)1977 Won the Calgary University of Canada Bachelor of Computer Science ,1983 year Received a doctorate in computer science from Carnegie Mellon University in the United States , After graduation to IBM Work , Design IBM First generation workstations NeWS System , But not valued .
Then it turned to Sun company ,1990 year , And Patrick,Naughton and Mike Sheridan And so on “ Green Plan ”, Later a language was developed called “Oak”, Later renamed Java.
JAVA Language is Sun An object-oriented programming language designed by the company .
oracle Acquired sun company

Java Development Kit (kit: Matching components )
1.0 - 1.1 - 1.2 - 1.3 - 1.4 - 1.5
5.0 - 6.0 - 7.0 - 8.0……

Sun The company 1995 Launched in 2013
1991 year sun company James Gosling And others began to develop Oak Language
1994 year , take Oak Language renamed Java
1996 First investment in 1 One hundred million yuan
1998 in jdk1.2, Renamed java2
After that launch jdk1.3 jdk1.4
2005 Renamed as jdk5.0, Significant version improvements have been made
2006 year sun The company announced that it would Java Release as free software
2007 year 3 Month begins , All developers around the world can respond to Java Source code changes
2007 Launched in 2013 jdk6.0
2009 year 4 month Oracle( Oracle ) With 74 $100 million sun company
2011 year 7 Month by month Oracle Official release jdk7
2014 year 3 It was officially released in April java8

java The birth of :
 Insert picture description here
 Insert picture description here

 Insert picture description here
 Insert picture description here

1.2.2 Java Language platform version

J2SE(Java 2 Platform Standard Edition) Standard Edition beginners learn SE)
It's a solution for developing common desktop and business applications , The technology system is the foundation of the other two , Can complete the development of some desktop applications .

J2ME(Java 2 Platform Micro Edition) Small version ( Almost no one learned )
Is for the development of mobile devices and embedded devices ( Electrical appliances 、 robot 、 The set-top box …) Solutions provided .

J2EE(Java 2 Platform Enterprise Edition) Enterprise Edition
It's a set of solutions for developing applications in an enterprise environment , The technologies included in the technical system are as follows Servlet、Jsp etc. , Mainly for Web Application development . You can make websites

Be careful : stay JDK5.0 It was renamed javaSE,javaEE,javaME.SE It's the foundation , Want to learn well EE You have to learn SE.

1.2.3 Java Language features

simplicity High performance
Compilability Explanatory
object-oriented distributed processing
Robustness, Security
Multithreading dynamic
Open source Cross platform
What is cross platform ?
adopt Java Applications written in language can run on different system platforms .
What is the principle ?
As long as it needs to run java On the application's operating system , Install one first Java virtual machine (JVM Java Virtual Machine) that will do . from JVM To be responsible for Java The operation of the program in the system .
Because of the JVM, So the same Java The program can be executed in three different operating systems . That's it Java The cross platform nature of the program . Also known as Java Good portability .
 Insert picture description here

1.3 java Development environment construction

1.3.1 JDK summary

JDK yes Java Language software Development kit , Mainly for mobile devices 、 On embedded devices java Applications .JDK As a whole java The core of development .
It contains :
1、JAVA development tool (jdk\bin)
2、 Basic development library (jdk\jre\lib\rt.jar)
3、 Basic development library source code (jdk\src.zip)

Be careful jdk Don't pursue the latest version , Because the enterprise revolves around java The ecology around the language supports java edition , Use this version that has been stable for several years , Enterprises will use . Because the first element pursued by enterprises is stability . At present, enterprises mainly use jdk8.

1.3.2 jdk The download , Installation and removal

1). download

Download channel

  1. Get it through the official website JDK:http://www.oracle.com
  2. You can also search resources through Baidu .

Download steps : Enter the home page ------ At the bottom, choose java SE14 download------ At the bottom Java Archive----- According to different versions of JavaSE, To select the corresponding of different operating systems jdk . Usually download the last updated version of the same version .
Check your computer version : Computer ---- attribute ---- View the basic information of the computer ( The full name of the computer , Memory, etc. ).

Select the corresponding version : For different operating systems , Download different JDK edition ( Such as :jdk8+Windows +64 position ).
 Insert picture description here
2). install
Install after download , Fool installation , Next step, next step .
Be careful

  1. Install multiple... At the same time jdk You need to use the specified environment variable to confirm which jdk
  2. The installation path should not have Chinese or special symbols such as spaces , It's best to have a unified Directory .( The software used in general software development , Generally follow this 2 A rule )
  3. We also provide a green decompressed version , You don't need to install it. Just unzip it

3). uninstall :

  1. Delete java Installation directory ( If it's a green decompressed version , Just delete the configured environment variables , This step can be omitted .)
  2. Delete JAVA_HOME
  3. Delete path Next about java The catalog of
  4. java_version, stay Dos Window enter this command to check jdk Installation environment .

1.3.3 Configure environment variables JDK

explain : At least 2 Step JAVA_HOME and PATH. The following configuration applies to windows10,windows7 Search Baidu by yourself .
1).JAVA_HOME
This configuration is to configure jdk Installation directory , To determine which version to use jdk.
for example : I put jdk Installed in D:\Java\jdk7. The configuration is as follows :

 Insert picture description here
 Insert picture description here
 Insert picture description here
 Insert picture description here

User variables : Works for the current user ( Previous work , Computers are not popular , How many people use a computer , One person and one account need to configure their own environment variables . So use user variables .)
System variables : Work for all users .( Now we usually use user variables )
newly build --------JAVA_HOME( Variable name )---------jdk Copy the installation path here ( A variable's value )---- determine

2). PATH
The system will be in path Among the configured values , Look for the executable .
Need to put jdk\bin and jdk\jre\bin Add to path in .

 Insert picture description here
 Insert picture description here
Why use %JAVA_HOME% Instead of jdk The installation directory ?
because : The path starts with jdk Installation directory , The advantage of this is that the later upgraded version only needs to be changed JAVA_HOME The path in , and path There is no need to change the path in . This method is generally recommended .

test jdk Configuration complete :Dos Window type java-version, Show jdk Version Description configuration succeeded .
 Insert picture description here

1.3.4 catalogue

bin Catalog : It's almost full of exe Executable file ,exe The file in windows In the operating system, it means executable files . namely :bin A directory is a binary file , Stored in a series of jdk And java Relevant orders .
db: database , It's not very useful .
Include:jdk And windows Some things that interact with the bottom of the system .
Jre:jdk Included operating environment .
Lib: Class library file , Deposit is jdk Already written file code , We can call .
src.zip:jdk Open source source .
Others are copyright and other documents .

 Insert picture description here

1.4 Eclipse

1.4.1 summary

Eclipse(IBM company , Open source 、 Free of charge 、 You don't need to install it, just unzip it ) Is an open source 、 be based on Java The extensible development platform . In terms of itself , It's just a framework and a set of services , Used to build development environment through plug-in components .

Java development tool

  1. Text compiler ( Generally do not use ): Notepad , EditPlus , Notepad++…
  2. Integrated development environment tools ( This kind of enterprise development tool is generally used ): Eclipse,STS( Installed Spring The plug-in Eclipse),IDEA ,NetBeans…
     Insert picture description here

1.4.2 Download and install

1、 Download and install on the official website
2、 Download the complete package file (java ee Enterprise Edition ), You can use it by decompressing it directly

1.4.3 working space workspace

Used to save all development files and code, etc , You can also switch workspaces , In the future, you can find your own code in this location .
 Insert picture description here

 Insert picture description here

1.5 HelloWorld Case study

1.5.1 establish / Delete day01 engineering

 Insert picture description here

 Insert picture description here

 Insert picture description here
 Insert picture description here
Delete project : Select the project , Right click —delete ----ok( Check to delete all , Include worksplse In space )

1.5.2 Create a package

The package name is all lowercase .
 Insert picture description here

 Insert picture description here

 Insert picture description here
 Insert picture description here

1.5.3 establish HelloWorld class

Be careful

  1. The class name should conform to the hump nomenclature .
  2. You don't have to create a package first , Create classes while directly creating packages .
     Insert picture description here
     Insert picture description here
     Insert picture description here

1.5.4 Create method

class HelloWorld{

public static void main(String [] args){

System.out.println(Hello World);// What is output without double quotation marks is what it represents . Add double quotation marks to directly output the contents in quotation marks .
}
} // Mouse over the braces will automatically display the corresponding braces 

1.5.5 explain

// Single-line comments 
/* Multiline comment */
/** Text Annotation */
/* * Used to define a package * package The effect of bold and red , It's called keyword . Specifically used to define packages . * cn.tedu.hello Package name -- Full lowercase + The company's domain name is written upside down * ; yes Java The terminator of a statement , amount to . */
package cn.tedu.hello;
/* * Used to define a class * public Is the key word , Specifically used to modify the access rights of a class . Public * class Is the key word , Specifically used to define a class * HelloWorld Class name -- PASCAL nomenclature ( Use... When creating classes : All initials are capitalized ) * { java Code } */
public class HelloWorld {

/* * Define a main function / Main method /main Method ( Shortcut key main +alt+/) * public Is the key word , Used especially to decorate main Access to method . Public * static Is the key word , modification main Methods are static methods * void empty / nothing ,main Method return value is null * main Method name * () It's the sign of the method * String[] args Method parameters * { Java Code / Method body } */
public static void main(String[] args) {

/* * Used to output the specified data to the console * System To issue system instructions * out The act of issuing an output * println Line feed after printing . Print Do not wrap after printing * () It's the sign of the method * "hello java" Method parameters -- Data to output * ; Java The terminator of a statement */
System.out.println("hello java");// Output shortcut key , syso +alt+/
}
}

1.5.6 Operation and working principle

 Insert picture description here

1、 compile : adopt javac The order will java The source file of is .java File compiled into .class file .
2、 perform ( The run-time ): Start... First java virtual machine , Different operating systems have different jvm, therefore java Cross platform . Re pass JVM load HelloWorld.class Bytecode file . And load main Method execution program .

1.6 expand :

1.6.1 Download the latest version eclipse

Download and use by yourself

1.6.2 JDK JRE JVM The relationship between

1、JDK–Java Development Kit( Development kit ): Is aimed at Java Developer's products , As a whole Java At the heart of , It includes Java Running environment JRE、Java Tools and Java Base class library .
2、JRE–Java Runtime Environment( Running environment ): Is to run JAVA The runtime environment for , contain JVM and Java The core library .
3、JVM–Java Virtual Machine(JVM virtual machine ):Java Abbreviation of virtual machine , As a whole java The core part of cross-platform implementation , Able to run to Java The software program of language writing .

 Insert picture description here

1.6.3 Java Of ” Write once , Run everywhere ” How is it realized ?

Java The program will be compiled into bytecode class file , These bytecodes can run on any platform , therefore Java It's platform independent .

1.6.4 Packet mechanism

package : It's like a folder .
Such as :www.baidu.com—>com.baidu.www
 Insert picture description here

1.6.5 Java The order in which the program is executed

Go ahead main Method inside , In accordance with the program object method call execution, etc .
standard : A project should have only one main startup class

1.6.6 Java Naming conventions in development

project : All lowercase
package : Full lowercase ( Company domain name write back , Use... For each word . separate )
class : All words are capitalized ( Pascoe nomenclature )
Interface : Pascoe nomenclature
abstract class : Pascoe nomenclature
Variable :( Hump nomenclature )
Method : Hump nomenclature
Constant :1. All words must be capitalized 2. Use... For each word _ separate . for example : PI MAX_VALUE

2 Day02– Variable + data type + Type conversion

2.1 Preface

2.1.1 identifier

It can be simply understood as a name . stay Java in , We need to identify many elements of the code , Include Class name 、 Method 、 Field 、 Variable 、 Package name etc. . The name we choose is called an identifier , also Follow these rules

  • A. Identifiers can be made up of letters 、 Numbers 、 Underline (_)、 Dollar symbol ($) form , But it can't contain @、%、 Space and other special characters .
  • B. Cannot start with a number .
  • C. Identifiers are strictly case sensitive .
  • D. The naming of an identifier should best reflect its function , Be aware of your name and meaning in English .
  • E. It can be named in Chinese , But it is generally not recommended to use , Pinyin is not recommended , very low.

2.1.2 keyword

stay java Some words in a language that have been given a specific meaning . Altogether 53 Key words . There are two reserved words :const( constant , constant ) and goto( go to ). Keywords cannot be used as identifiers !!
Reserved words : It doesn't work for the time being. It may work in the future .
Java There are many keywords in , There's no need to force memory , Because in the compiler, if you use keywords as identifiers, the compiler will remind you of errors .

 Insert picture description here

2.1.3 notes

explain :Java Explanation of the code . Does not affect the operation of the program , For auxiliary reading program .

// Single-line comments ( Shortcut key :ctrl+/)
/* Multiline comment */ ( Shortcut key :ctrl+shift+/), Uncomment :ctrl+shift+\
/** Documentation Comments */ ( Shortcut key :/**+enter) 

2.1.4 eclipse Shortcut key in

View source code , ctrl+ Mouse click .
syso+alt+/: Output statement shortcut key
ctrl +/ : Select multiple lines of code , Quickly add a single line comment .( Cancel it , Press the shortcut key again )
Ctrl+shift+o: Package guide shortcut key
Ctrl +d: Shortcut keys to delete one line at a time ( In the code block to be deleted , After that, use the shortcut key to delete a line )
ctrl +n Shortcut keys are equivalent to new Use the up and down keys ( Create project , package , Class does not use a mouse )
Alt+ Up and down arrow ( Move the code up and down )

2.1.5 eclipse Escape characters in

Escape character : Used to express a special symbol or meaning .
\b : Means to go back one character
\t : Represents a tab stop
\n : Change to the next line
\r: enter

\” : Double quotation marks
\’ : For single quotes
\ : Represents a backslash character \

2.1.6 eclipse The output statement in

System,out.print(); // Output does not wrap 
System,out.println(); // Line break 
System,out.println(“ ”);// Output a space 
System,out.println(“\t”); // alignment : The number of outputs plus spaces is a total of 8 position . It can also be changed to (“ “) In the form of .

2.1.7 Variable

give an example
room --------- Variable
Room name --------- Variable name
Room type -------- Variable type
Check in guests ------- A variable's value

Concept : stay JAVA in , Some data values are not fixed , It's always changing , We also need to record these values , We can think of these values as variables .

The nature of variables : It's actually a part of memory , When creating variables , It means to request some memory space from the operating system , Declaring different types of variables essentially means that the amount of memory space applied is different ;( The first step in the execution of the program , Are loaded into memory , Technology is based on the relationship between program execution and hardware )

The principle of using variables : Nearby principle , Try to keep it to a minimum .

Declaration of variables Variable type Variable name = A variable's value .
= : Assignment number , The data on the right , Given to the variable on the left .

int num=18; // The simultaneous assignment of declarations 
Equivalent to :
int num; // Antecedent variable 
num = 20;// I'm doing an assignment 

Be careful

  1. The variable name must be a valid identifier .
  2. Variable name cannot be used java keyword .
  3. Variable names cannot be duplicate .
  4. java The punctuation marks in are in English .
  5. Variables end every sentence with a semicolon .

Java Rules for using variables in

  1. java The variables in need to be declared before using .( Local variables have no default value , If you want to output, use , Must be declared and assigned to use . Member variables have default values , If you want to output, use , Output without assignment )
  2. When variables are used , Variables can be declared and initialized at the same time ( initialization : First assignment ), It can also be declared first and then assigned .
  3. Only one value can be attached to a variable at a time , But it can be modified many times .
  4. Main The variables defined in the method must be assigned first , Then we can output .
  5. Although there are no errors in the grammar , But it's actually being developed , Chinese is not recommended for variable names , It is prone to potential safety hazards , For example, there is garbled code during cross platform operation in the later stage .
  6. The use of variables must match the data type .
  7. Variable Scope Range : From the declaration of variables to Include its most recent { } Of Program end .
  8. Variable naming rule : Hump nomenclature "score,myScore,myJavaScore( The second word is capitalized ).

Classification of variables

  1. Divided by the declared location : Member variables ( Inside the class, outside the method ) and local variable ( Methods the internal ). Member variables are divided into : Instance variables and Static variables ( add to Static keyword )
  2. According to the data type : Basic data type and Reference data type .

local variable

  1. Defined in method ( Include method parameters ), Or in a local code block .
  2. Must be initialized manually ( Assign initial value to ), To allocate memory . Such as :int i=5;
  3. Scope is in a method or in a local code block , After the method runs, the memory is released .
    Defined in a class .

Member variables

  1. Defined in a class and out of a method .
  2. No initialization , It will also be automatically initialized to the default value .
  3. The scope is in the whole class , Class disappeared , Variables are released .

Default value of member variable

1). Reference type ( except 8 The big basic type ): The default value is null
2). Basic types
among char: /u0000 ( The default value is , Generally, it does not display . Whitespace code yes 0x20,0x20 Here are the invisible control characters . Some systems will output a box when they encounter invisible characters, indicating that they encounter invisible characters )

Basic types The default value is
byte 0
shot 0
int 0
long 0L
float 0.0f
double 0.0d
boolean false

2.1.8 Constant

stay day02 – 3.3 --final Constants learned in .

summary : During the running of the program, the amount that will not change consistently becomes a constant .

The definition form of constant final data type Constant names = value ;, Generally, in order to facilitate external calls , Will be static modification , Can be directly by class name . visit . The final form is :public final data type Constant names = value ;.

Constant naming conventions It is recommended that all letters of constant names be capitalized , Underline multiple words ("_") separate ( Recommendation is not mandatory ) Such as :MAX_VALUE
Constant considerations :

  1. Must declare and initialize at the same time ( The initial value must be assigned directly , Do not modify ),( Assignment in static blocks can also , But it is not recommended. )
  2. Accessed by the class name point , And can't change

Advantages of constants : Constants are directly replaced with specific values at compile time - - Efficient

When constants are used ? Data is always constant and often used .

2.1.9 Variable test case

package cn.tedu.variable;
import org.junit.Test;
// test Use of variables 
public class Test6_Variable {

//TODO Test other types The default value of 
//2, Member variables : The location is outside the method in the class + Have default values + The scope is in the whole class 
double count ;
//3, Nearby principle --- Premise is --- When a member variable and When a local variable has the same name , You must be using local variables 
int sum = 20 ;
// unit testing junit : The method shall be marked @Test + The method must be public Of + Method return value is void, No parameter list 
@Test // Need to guide package (1 2 Fine )
public void show() {

//1, local variable : The position is in the method + Must be initialized + The scope of action is in the method 
int sum = 10;
System.out.println(sum);//10, Nearby principle 
System.out.println(count);//0.0
}
}
package cn.tedu.arrays;
public class Test2_Variable {

//1、 Member variables : Inside the class, outside the method is 
// The scope is in the whole class 
// It can be uninitialized , There will also be default values 
int age = 20;
int sum = 30;
public static void main(String[] args) {

//2 local variable : In the method is 
// The scope of action is in the method , Out of this method, I don't know 
// Must be initialized 
int sum = 10;
System.out.println(sum);//10
//3、 The proximity principle of variables , Someone with the same name nearby will perform the latest 
System.out.println(sum);//10
}
}

2.2 data type

Strong type language : It is required that the use of variables should strictly comply with the regulations , All variables must be defined before they are used . Such as :Java、.net 、Python、C++ Other languages .

Weak type language : Languages in which data types can be ignored . It's the opposite of a strongly typed definition language , A variable can assign values of different data types . Such as :vb 、PHP、javascript Other languages .

Java The data types of are 2 Categories:

  1. Basic data type : Variables store the data itself .( Equivalent to what's in the drawer )
  2. Reference data type :( Except for the basic types, they are all reference types , Such as : class , Interface , Array ) Variables store the spatial address of the data .( The key to the drawer )

2.2.1 Basic types ( Eight kinds )

Sort from small to large :byte short (char) int long float double
explain : Boolean types do not participate in sorting ,char Will automatically convert to int.
A term is used to explain : What are bytes .
 Insert picture description here

 Insert picture description here

2.2.2 practice 1: Max min

package day0102;
// summary 
//1, Basic types :byte short int long float double char boolean
//2, Tool class :Byte Short Integer Long Float Double Character Boolean 
//3, Tool classes provide many functions , It contains the size value 
// The wrapper class corresponding to the basic type provides some functions , Maximum , minimum value Not having parentheses is not a method 
Pay attention to the initial capital of packaging class , especially 2 It's special
public class Test1 {

public static void main(String[] args){

//=====1、 The integer test begins 
// Variable type Variable name = A variable's value 
byte a=-128; Print the value of the variable , Unwanted " "
byte b=127;
short c=Short.MIN_VALUE;
short d=Short.MAX_VALUE;
int e=Integer.MIN_VALUE;
int f=Integer.MAX_VALUE;
long g=Long.MIN_VALUE;
long h=Long.MAX_VALUE;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
System.out.println(f);
System.out.println(g);
System.out.println(h);
//===== The integer test is over 
//=====2、 Floating point test start 
/** *float It's single precision , Imprecise calculation of decimals .double Double precision , Accurate calculation of decimals . * For programmers ,double and float Is the difference between the double High precision , but double Memory consumption is float Twice as many . * And double The operation speed is faster than float Slightly slower . */
float i=Float.MIN_VALUE; //1.4E-45( representative 10 Negative 45 Power )
float j=Float.MAX_VALUE; //3.4028235E38( representative 10 Of 38 Power )
double k=Double.MIN_VALUE; //4.9E-324
double l=Double.MAX_VALUE; //1.7976931348623157E308
System.out.println(i);
System.out.println(j);
System.out.println(k);
System.out.println(l);
//===== Floating point test end 
//=====3、 Character test starts 
/** * character char Single quotation marks * character string String(S Capitalization ) Double quotes */
char c = 'a'; // You can save a letter or number or symbol, but not without , It can be a space 
char c4 ='1'; // Only one number can be saved .
char c2 = 97; // You can save numbers directly ( You can write multiple numbers )
char c3 = ' in ';// You can save a Chinese character 
//char Type can store a number , But in use , It's not the numbers themselves , Instead, look up the character corresponding to the number , Then use the characters .
//ascii clock , Specifies the correspondence between numbers and characters . And the numbers 97 It corresponds to the character a. 9 7----a 65---A 48---0
//ascii In the code table , Specifies the 0~127 The character corresponding to the number ,char Value of type 
// The scope is 0~65535. So from 128~65535 The default character is ?.
System.out.println(c);
System.out.println(c2);//a
System.out.println(c3);
//=====4、 Boolean 
boolean b = true;
boolean b2 = false;
}
}
//System.currentTimeMillis() Used to get information from 1970.1.1 The number of milliseconds from zero o'clock to this moment 

2.2.3 practice 2: Enter personal information

Wang Haitao this year 20 year , a monthly salary 20000, I advise you to study hard java, To reach the peak of life as soon as possible .
package day0201_ The rules ;

import java.util.Scanner;
public class Test1_ Personal information {

public static void main(String[] args) {

System.out.println(" full name :");
String name= new Scanner(System.in).nextLine();
// Be careful :String The corresponding is Line
System.out.println(" Gender :");
String gender= new Scanner(System.in).nextLine();
System.out.println(" Age :");
// Everything else is capitalized 
int age= new Scanner(System.in).nextInt();
System.out.println(" The personal information you entered is :");
System.out.println(" full name :"+name);
System.out.println(" Gender :"+gender);
System.out.println(" Age :"+age);
}
}

2.2.4 practice 3: String splicing process .

Hello everyone , My name is Zha Hui , This year, 28.

package cn.tedu.basic;
// This class is used to test string splicing 
public class Test2_Info {

public static void main(String[] args) {

// Value is a string of ,Java It represents a string of data , Namely String type .
String name = " Cai Xukun: A boy devoted to music in "More than Forever" ";
byte age = 28;
// adopt + String concatenation , "+?+"
System.out.println(" Hello everyone , My name is "+name+", This year, "+age+".");
}
}

2.2.5 practice 4: Circular area

Area of circle :πrr
The circumference of a circle :2πr

package day0104;
import java.util.Scanner;
public class Test1 {

public static void main(String[] args) {

// Defining variables , Record the radius r
// double r = 10.1;// Not good. , It's worth writing .
// Dynamically accept the value entered by the keyboard 
// When testing :console Try to keep the small red dot on , Indicates waiting for user input , Press enter after input , End of input .
double r = new Scanner(System.in).nextDouble();
double result = 3.14*r*r;// Bring in the formula 
System.out.println(result);
// perhaps System.out.println(3.14*r*r);
}
}

2.2.6 practice 5: Variable exchange

 Insert picture description here

Receive the value entered by the user : hypothesis a=1,b=2 take a and b Exchange the value of .

package day0103;
import java.util.Scanner;
public class Test1 {

public static void main(String[] args) {

/ /1, Accept keyboard input integer a And integer b
System.out.print(" Input integer a:");
int a=new Scanner(System.in).nextInt();
// Before and after comparison 
System.out.print(" Input integer b:");
int b=new Scanner(System.in).nextInt();
//2. Start swapping 
int t=a; // hold a The value of t end to end 
a=b; // hold b The value of a
b=t; // hold t The value of b 
System.out.println(a);
System.out.println(b);
}
// The second way :a=a+b; b=a-b;a=a-b Another kind 2 Exchange numbers 
}

2.3 Literal type of basic type (5 strip )

2.3.1 Integer literal type ( The default value is ) yes int type

int a = 9999999999;// wrong , The right side is int type , But out of range 

2.3.2 byte,short,char Three ratios int Small integers can be assigned directly with values in the range

byte b=127;// Yes 
byte b=128;// wrong , On the right, it's over byte The scope is int Data of type 
Add out of range Add 2 The next maximum is equal to itself ( All the basic types )

2.3.3 The literal value of a floating-point number is double type

double a=3.14;// Yes 
float a=3.14;// wrong , On the right double,float It's four bytes double It's the eight character festival that can't be saved 

2.3.4 Literal suffix l f d

// Because it defaults to int Although the type can be automatically transferred to , But it's beyond its scope . So add one L Express long type .
// This integer defaults to int type , But beyond int Range , What else do you want to use ?
// suffix L, Used to put the literal value int Data of type , Ascend to long type 
Llong Such as :long a = 99999999999;// wrong , Out of range , Solution plus L
// suffix f, Used to put the default double Type of decimal , Turn into float type 
Ffloat Such as :float a = 3.14;// wrong , On the right double type , Solution plus F
// suffix d, Used to put the literal value int Type of 3, Turn into double type 
Ddouble Such as :double a=3;// wrong , On the right int, Solution plus D Or change it into 3.0
// The suffix is generally capitalized by default , Because lowercase sometimes think of numbers 1 It's hard to distinguish .
Be careful not to add or report errors , because 3 stay double The value range of type .

2.3.5 Base prefix

0x - 16 Base number
0 -8 Base number
\u -char type ,16 Base number
0b -2 Base number 0b0011

2.4 Type conversion of basic types

matters needing attention
1. Cannot convert Boolean values .
2. You cannot convert an object type to an unrelated type .
3. When converting high capacity to low capacity, you need to cast .
4. Small type to large type will be converted automatically .
5. Memory overflow or precision problems may occur during conversion .

2.4.1 Small to large ( Implicit conversion )

There is no need to cast

// Automatic type conversion 
Byte a =120;
Int b=a;// Go straight to 
The integer can be converted to a floating point type
char It can be directly transformed into int type

 Insert picture description here

2.4.2 Big to small ( Explicit conversion )

A cast is required

// Cast 
int xx = 356;
byte y=(byte) xx;
// Memory overflow problem 
int i=128;
byte b=(byte)i;// out of memory ,byte The scope is -128~127
// Precision problem : Convert decimals to integers , Decimals are discarded directly .
double y = 9.1;
int x = (int)y;// On the right side of the y It's a big type , For small types x assignment , A strong turn is needed 、
System.out.println(x);//9, Discard the fraction 
// No matter 0.1 still 0.9 Give up all 
//char Conversion of type 
char c='a'; //97
int d=c+1;
System.out.println(d);//98
System.out.println((char)d);//b

2.5 Operational rules (5 strip )

2.5.1 The data type of the calculation result , Consistent with the largest type

3/2 have to 1 , instead of 1.5, The result is int type
3d/2 have to 1.5, amount to double/int, The result is double type

2.5.2 byte,short,char Three ratios int Small integers , It will be automatically converted to int

byte a=3;
byte b=4;
byte c=a+b;// wrong , Runtime ,byte It will automatically change to int Re operation ,int+int still int
byte c = (byte)(a+b);
// On the right side of the a+b Operation time , It will automatically become int type , It's a big type . To the left c Small type assignment ??-- Cannot be assigned directly. Strong conversion is required 

2.5.3 Integer operation overflow

Integer operation , It's like a clock , When it comes to maximum , Then transfer back to the smallest .
Be careful : When operating on a large number , Pay attention to overflow problem .
Solution : Expand the range of variable values in advance , hold int Literal value plus L Suffix expansion , become long type 、 Usually the first number is followed by L.


//jdk1.7 New characteristics : Numbers can be separated by underscores , Output will not affect .
int money=10_0000_0000;
int years=20;
int total=money*years; // out of memory -1474836480
long total2=money*years; // out of memory , After calculation, the default is int type , Convert to long There was a problem before . -1474836480 
long total3=(long)money*years;//20000000000
System.out.println(total);
System.out.println(total2);
System.out.println(total3);
// Calculation : What's the length of a year at the speed of light 
System.out.println(300000000*60*60*24*365);
System.out.println(300000000l*60*60*24*365);
// Calculation results , The literal value is int type . however , It's over int Value range , Integer operation overflow will occur 
// Solution : hold int Literal value plus L Suffix expansion , become long type 、 Usually the first number is followed by L.

2.5.4 Floating point operations are not accurate

reason : Floating point numbers are characterized by Co., LTD. , discrete , There will be rounding errors , The result can only be a divisor , Close to but not equal to .
solve :java Provides a solution , I'll talk about it later ,BigDecimal.

System.out.println(1-0.8);//0.19999999999999996
System.out.println(4.35*100);//434.99999999999994
// It's best to avoid floating-point comparisons entirely 
float f= 0.1f;//0.1
double d=1.0/10;//0.1
System.out.println(f==d);//false

2.5.5 The special value of a floating-point number

Infinity infinity 3.14/0
Nan not a number 0/0.0
// This cannot happen to the output result , Once the check code appears ( The denominator is 0 Or both numerator and denominator are 0)

2.6 expand

2.6.1 char Can a Chinese character be stored in the type variable , Why? ?

char Type can store a Chinese character , because Java The code used in is Unicode( Do not select any specific encoding , Use the number of characters in the character set directly , This is the only way to unify ), One char Type account 2 Bytes (16 The bit ), So it's OK to put a Chinese .

2.6.2 javaDoc

 Insert picture description here
jdkApi Online documentation for : Baidu search ,jdk Help document .
Generate one's own API file : From the command line, you can also use development tools such as idea, Specific Baidu .
 Insert picture description here
 Insert picture description here
 Insert picture description here
command javadoc Parameters file
 Insert picture description here
 Insert picture description here
 Insert picture description here

2.6.3 User interaction Scanner

Be careful :String The corresponding is Line, Everything else is capitalized .

import java.util.Scanner;
public class Test1_ Personal information {

public static void main(String[] args) {

System.out.println(" full name :");
String name= new Scanner(System.in).nextLine();
// Be careful :String The corresponding is Line
System.out.println(" Gender :");
String gender= new Scanner(System.in).nextLine();
System.out.println(" Age :");
// Everything else is capitalized 
int age= new Scanner(System.in).nextInt();
System.out.println(" The personal information you entered is :");
System.out.println(" full name :"+name);
System.out.println(" Gender :"+gender);
System.out.println(" Age :"+age);
}
}

 Insert picture description here
The output is :hello
 Insert picture description here
Output :hello world
 Insert picture description here
reason
 Insert picture description here
If it is a number, use the corresponding nextxxx() Method to judge :

package lianxi;
import java.util.Scanner;
public class Ta {

public static void main(String[] args) {

Scanner scanner =new Scanner(System.in);
// Receive data from keyboard 
int i=0;
float f=0.0f;
System.out.println(" please enter an integer :");
if(scanner.hasNextInt()) {

/* * If you don't write anything, the default is true( Old hand writing ) * if(scanner.hasNextInt()==true) { New way to write */
i= scanner.nextInt();
System.out.println(" Integer data "+i);
}else {

System.out.println(" The input is not integer data ");
}
scanner.close();
}
}

3 Day03– Operator + Branching structure + loop

3.1 Operator

3.1.1 summary

Be careful : Logical operators :&&,||,! ( And or Not ) yes ( The result is boolean type true or false) Based on relational operators

 Insert picture description here
Logical operators :& and &&,| And || The relationship between .
When one & When an expression is evaluated , Both operands are evaluated ,&& More like Is a shortcut to an operator . When one && When an expression is evaluated , First calculate the first operand , If it returns true Will calculate the second operand . If the first operand The value is fale, The second operand is not evaluated .

 In general, you want to express true perhaps false, It can be used 1 Express true, use 0 Express false
Shan Yu :& -- And the relationship between
1 & 2 -- 1 and 2 All for true, The result is true
Single or :| -- To express or express the relationship between
1 | 2 -- 1 and 2 There is one for true, The result is true
Double and / Short circuit and :&& -- And the relationship between , Efficient
1 && 2 -- 2 Will be short circuited , Premise is 1 by false
Double or / Short circuit or :|| -- To express or express the relationship between , Efficient
1 || 2 -- 2 Will be short circuited , Premise is 1 by true
really & really -》 really
really & false -》 false
false & really -》 false
false & false -》 false
false | false -》 false
false | really -》 really
really | false -》 really
really | really -》 really

An operator &,|,^,~,>>,<<,>>>

/* A = 0011 1100 B = 0000 1101 ------------------ A&B = 0000 1100 Up and down 2 All of them are 1 Only then 1, Otherwise 0 A/B = 0011 1101 Up and down 2 All of them are 0 Only then 0, Otherwise 1 A^b = 0011 0001 Up and down 2 The same position is 0, Otherwise it would be 1. ~B = 1111 0010 Take the opposite 2*8 = 16 2*2*2*2 Very efficient !!! << *2 Move left and expand >> /2 Move right and zoom out 0000 0000 0 0000 0001 1 0000 0010 2 0000 0011 3 0000 0100 4 0000 1000 8 0001 0000 16 */
System.out.println(2<<3);//16

Operator priority : Single item multiplication and division are relations , After the logical three items, the assignment .

 Monocular operator : An operator that acts on one variable at a time , Also called unary operator
Monocular : Monocular operator +( Positive and negative ) ,++ –,!( Logic is not ),~( According to the not )
Multiplication and division : Arithmetic operator :* / % + -* / % The priority must be greater than +- Of )
by : An operator :~( According to the not )<<( Move left ) >>( Move right ),^( You can also perform bit operations , Binary XOR )
Relationship : Relational operator :> < >= <= == !=
Logic : Logical operators ( except !)&& || & | ^
Three orders : Conditional operator A > B ? X : Y
after : meaningless , Just to make up the words
assignment := += -= *= /= %= |= &= ^=
explain : The front priority is greater than the rear priority , For example, monocular operator ~ It's also a bitwise operator ,~ The priority of is at the monocular level . As for the self-test not seen in the assignment operator

 Insert picture description here
PS: You don't have to memorize the priority order of operators , In development , Generally, parentheses are used to assist in priority management . Such as :
 Insert picture description here

3.1.2 practice 1: A normal year, a leap year

 Enter the year , Determine if it's a leap year . Two conditions :
1、 Can be 4 to be divisible by , And can't be 100 to be divisible by
2、 Or can be 400 to be divisible by
package day0203_ A normal year, a leap year ;
import java.util.Scanner;
public class Test1 {

public static void main(String[] args) {

System.out.println(" Year number :");
int y = new Scanner(System.in).nextInt(); //1, Accept the year entered by the user 
String r=" Ordinary year "; // The default is weekday 
//2, Judge , Is this year a normal year or a leap year 
if(y%4==0){

if(y%100!=0){

r=" Leap year ";
}
}
if(y%400==0){

r=" Leap year ";
}
perhaps
// explain :
// The relationship between the two conditions is or , For efficiency , Double or 
// General conditions 1 There are two small conditions , The relationship between two small conditions is and , For efficiency , Use double and 
// Whether it can be divided , To take the remainder , Remainder is 0 It can divide . The remainder is not 0 It's just not divisible .
if( ( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0){

// If the year , Can meet the judgment conditions , Will come in and modify r The default value of is leap year . If not satisfied , It has always been the default value, weekdays 
r = " Leap year ";// modify r The value of is leap year 
if((y%4==0&&y%100!=0)||y%400==0){

r=" Leap year ";
}
System.out.println(y+" Year is "+r);
}
}

3.1.3 practice 2: Increase and decrease

package cn.tedu.basic;
// This class is used to test self increasing and self decreasing 
public class Test1_Zizeng {

public static void main(String[] args) {

//++,-- Represents itself plus one and minus one , The result of the operation is related to the order of symbols .
int a = 1;
// The sign is after , Use first and then change 
System.out.println(a++);//1
int b = 1;
// The sign is in front of , Change before use 
System.out.println(++b);//2
// The operations are in order :b=1, Change first ++b=2, In use 2 Assign a value to b=2. Notice that after the change here is ++b=2
System.out.println(++a+b+a++);//3+2+3
// Pay attention to the last one 3 It's the front ++a Of 3, Not the one above 3
int c = 1;
System.out.println(c--);//1
int d = 1;
System.out.println(--d);//0
System.out.println(--c-d-d--);//-1-0-0
}
}

3.1.4 practice 3: Find the large value in two numbers

package cn.tedu.basic;
import java.util.Scanner;
// This class is used to test the large value in two numbers 
public class Test3_Max {

public static void main(String[] args) {

//1, Accept two integers entered by the keyboard 
// Be careful :scanner You can write directly , Then the trinocular operator boolean Is his return value , Other types can be written in front to accept 
int a = new Scanner(System.in).nextInt();
int b = new Scanner(System.in).nextInt();
//2, Than the size 1 ? 2 :3 ,1 After judgment, if true , The result is 2
//a > b If it's true , hold a hand max Record , otherwise , hold b hand max Record 
int max = a > b ? a : b ;
System.out.println(max);
}
}

3.1.5 practice 4: Find the maximum of three numbers

package day0203_ A normal year, a leap year ;
import java.util.Scanner;
public class Test1_ The maximum of three numbers {

public static void main(String[] args) {

System.out.println(" Integers a:");
int a = new Scanner(System.in).nextInt();
System.out.println(" Integers b:");
int b = new Scanner(System.in).nextInt();
System.out.println(" Integers c:");
int c = new Scanner(System.in).nextInt();
int max = a>b?a:b;
max=max>c?max:c; // Write separately 
perhaps
int max = a>b?(a>c?a:c):(b>c?b:c); // Write together 
System.out.println(max);
}
}

3.1.6 practice 5: Power operation

//2^3 2*2*2=8 Many operations we will use some tool classes to operate .
double pow=Math.pow(3,2);
System.out.println(pow);

3.1.7 practice 6: Compound assignment operator

Lazy writing , With strong rotation function .

 example 1int a=10;
int b=20;
a+=b; //a=a+b;
a-=b; //a=a-b
System.out.println(a);//30
example 2byte a = 1;
// a=(byte) (a+4);// On the right side int, left byte, Big to small , Strong go .
// a=(byte) (a+4);// On the right side int, left byte, Big to small , Strong go .
a+=4;// The data type conversion will be completed automatically 
// Be careful :a=a+4 and a+=4 There is a difference !!
System.out.println(a);

3.1.8 practice 7: String connector

// String connector : if + One end is a string , Will be converted to Sring Type of splicing and .
int a=10;
int b=20;
System.out.println(" "+a+b);//1020
System.out.println(a+b+" ");//30

3.2 Branching structure 1:if

3.2.1 summary

 Insert picture description here

problem Sequential structure Although the program can solve the calculation 、 Output and so on , But you can't make a choice . For questions that need to be judged first and then selected, the branching structure should be used .
summary
Any complex program logic can be realized through three structures :
1) Sequential structure : Line by line from top to bottom , Every sentence must go
2) Branching structure : Execute a statement conditionally once , Not every sentence has to go
3) Loop structure : Conditionally execute a statement multiple times , Not every sentence has to go

3.2.2 form

 Single branch : Meet the judgment conditions , Then execute the contents in braces .
if( Judge the condition ){

Code ...
}
Double branch :
if( Judge the condition ){

Code 1...
}else{

Code 2...
}
Multiple branches :
if( Judge the condition 1){

Code 1...
}else if( Conditions 2){

Code 2...
} else if( Judge the condition 3){

Code 3...
}else{

Code 4...
}
Nesting branches :
if( Judge the condition ){

if( Judge the condition ){

Code
}
}

matters needing attention

  1. if There is at most one statement else sentence ,else Statement in all of else if After statement .
  2. if A statement can have several else if sentence , They have to be in else The statement before .
  3. Once one of them else The statement is detected as true, Others else if Statements and else Statements are not executing .
  4. For conditional structures , If braces are omitted , It will only take effect for the first sentence of the code ( And : If there are no braces, end with the first semicolon ) let me put it another way : If there is only one sentence of code in the conditional structure , Then braces can be omitted .

3.2.3 practice 1: Goods on sale

Receive the original price entered by the user . full 1000 hit 9 fold . full 2000 hit 8 fold . full 5000 hit 5 fold .

package day999;
import java.util.Scanner;
public class ttt {

public static void main(String[] args) {

System.out.println(" Enter the total original price ");
//1, Accept the original price entered by the user 
double price = new Scanner(System.in).nextDouble();
//2, Calculate the discounted price , And the output 
double now = price;// Record the discount price 
// Be careful java The conditions in cannot be written as :a>b>c Instead, use logical operators a>b&&b>c To output .
if( price >= 5000 ) {
// full 5000
now = price * 0.5 ;//now Record 5 Discount price 
}else if( price >= 2000 ) {
// full 2000
now = price * 0.8 ;//now Record 8 Discount price 
}else if( price >= 1000 ) {
// full 1000
now = price * 0.9 ;//now Record 9 Discount price 
}
perhaps
if( price >= 1000 && price < 2000) {
// full 5000
now = price * 0.9 ;//now Record 9 Discount price 
}else if( price >= 2000 && price < 5000 ) {
// full 2000
now = price * 0.8 ;//now Record 8 Discount price 
}else if( price >= 5000 ) {
// full 1000
now = price * 0.5 ;//now Record 5 Discount price 
}
System.out.println(" The original price is :"+price+", The discount is :"+now);
}
}

3.2.4 practice 2: Count student scores

90 More than good
80~89 good
70~79 secondary
60~69 pass
60 Below fail,

package game;
import java.util.Scanner;
public class aa {

public static void main(String[] args) {

double score = new Scanner(System.in).nextDouble();
//!!! Used to enhance the robustness of code 
if (score >= 100 || score <= 0) {

System.out.println(" Please enter 0~100 The value within ");
return; // End procedure 
}
if (score > 90 && score <= 100) {

System.out.println(" good ");
} else if (score >= 80 && score <= 90) {

System.out.println(" good ");
} else if (score >= 70 && score <= 79) {

System.out.println(" secondary ");
} else if (score >= 60 && score <= 69) {

System.out.println(" pass ");
}else if (score < 60) {

System.out.println(" fail, ");
}
}
}
// Optimize 
String desc = " good ";
if(score >= 90) {
//90 More than good 
desc = " good ";
}else if(score >= 80 && score < 90 ) {
//80~89 good 
desc = " good ";
}else if(score >= 70 && score < 80 ) {
//70~79 secondary 
desc = " secondary ";
}else if(score >= 60 && score < 70 ) {
//60~69 pass 
desc = " pass ";
}else if(score < 60) {
//60 Below fail, 
desc = " fail, ";
}
System.out.println(" The score is :"+score+", Belong to :"+desc);

3.3 [ understand ] Branching structure 2:switch

3.3.1 summary

When one case establish , From this match to case Back through everything case, Include default, Until the program ends or encounters break It's the end of the program .
advantage : Efficient 、 The structure is clear
shortcoming : Only applicable to Integers 、 equal

3.3.2 form

switch(expr1) in ,expr1 It's an integer expression , An integer expression can be int Basic type or Integer Packaging type , because byte,short,char Can be implicitly converted to int, So I support .
Be careful

  1. jdk1.7 In the future String type .
  2. case Label must be a string constant or literal .
switch( Variables or expressions ){

case 1: break;
case 2: break; //break: Jump out of switch loop , Optional .
case 3: break;
case 4: break;
default: //default You can add insurance without writing , When there is no match in the front, it is equivalent to adding an insurance to take the default .
}

3.3.3 practice 1: Number matching

package cn.tedu.ifdemo;
// test switch grammar 
public class Test7_Switch {

public static void main(String[] args) {

int i = 2;
// i The type of That is, the type indicated in parentheses -- byte short int char jdk1.7 Added String
switch( i ) {

case 1 : System.out.println(1);break;
case '1' : System.out.println('1');break;
/*1, When matching to case when , The program will continue to penetrate back through all case Include default, namely * Meet a case When conditions are met, all remaining case Include default The contents will * For the output , Until the program ends or encounters break It's the end of the program . */
case 2 : System.out.println(2);break;
//2, break To end the program 
case 3 : System.out.println(3);break;
case 4 : System.out.println(4);break;
case 5 : System.out.println(5);break;
case 6 : System.out.println(6);break;
default: System.out.println(0);//default There's no need to write... Later break
}
}
}
// If the output conditions are the same, it can be abbreviated as :
case 0:
case 1:
case 2:
case 3:
System.out.println(" Xiao Ming ");
break;

3.4 Loop structure 1:for

3.4.1 summary

Loop structure refers to the need for Repeat A program structure set up for a function . It is by the conditions in the circulatory body , Determine whether to continue a function or exit the loop . According to the judgment condition , The loop structure can be subdivided into the loop structure of judgment before execution and the loop structure of execution before judgment .

for Advantages of circulation :for Loop statement is a general structure supporting iteration , yes Most effective , Most flexible The cycle structure of .

There are three elements of circulation :

  1. Initialization of loop variables
  2. Condition of circulation ( Based on cyclic variables )
  3. Changes in loop variables ( Towards the end of the cycle )

Loop variable : The number changed repeatedly throughout the cycle .

3.4.2 form

for( Starting conditions ; The loop condition ; Change conditions ){

Loop body code …
}
For Special use of loop :
1. Dead cycle
For(; ;){
 // Dead cycle 
}
2. You can open it and write
int i=1;
for(;i<10;i++){
 // Remove... Upwards 
}
for(int i=1;i<10;){
 // Remove... Downwards 
i++; // Notice that this place has a semicolon (;)}
3. You can also declare 2 Number :
for(int i=1,j=6;i<6;i+2,j--){

} //for In expression 1 and expression 3, commas can be used , More than two expressions can only use &&, || ,!( And , or , Not )

3.4.3 practice 1: Print 0 To 10

 Insert picture description here

package cn.tedu.fordemo;
// test for loop 
public class Test8_For {

public static void main(String[] args) {

//for( Starting conditions ; Judge the condition ; Change conditions ){ The loop body }
// Print 0 To 10
//i Used to record the value obtained each time , The default is 0 Start 
for( int i = 0 ; i <= 10 ; i++){

System.out.println(i);
}
}
}

3.4.4 practice 2: Print 10 To 0

// from 10 Start , as long as >=0, Just print , The printed data decreases in turn 
for( int i = 10 ; i >= 0 ; i-- ){

System.out.println(i);
}

3.4.5 practice 3: Print 8,88,888,8888

for( int i = 8 ; i <= 8888 ; i=i*10+8 ){

System.out.print(i+",");// Peer presentation data . Such as 8,88,....
}

3.4.6 practice 4: seek 【1,100】 in , An odd number , Number of even Numbers

int count = 0, Why not int count And assign more values to 0 Well ?? stay day01 When it's abnormal .

 int count = 0;// Defining variables , Record the number of odd numbers 
int oucount = 0;// Defining variables , Record the number of even numbers ,( Defined as 0, The following assignment will not affect the program )
for(int i = 1 ; i <= 100 ; i++) {

// Judge , If it's odd 
if( i % 2 == 1 ) {
 // Can also write !=0
count++;// Every time you encounter an odd number +1
}
// Judge , If it's even 
if( i % 2 == 0 ) {

oucount++;// Every time you encounter an even number +1
}
}
System.out.println(" The number of odd numbers is :"+count+", The number of even numbers is :"+oucount);

3.4.7 practice 5: seek 【1,100】 in , Even and odd

 int sum = 0;// Defining variables , Record even numbers and 
int jisum = 0;// Defining variables , Record odd numbers and 
for(int i = 1 ; i <= 100 ; i++) {

// Judge , If it's even 
if(i % 2 == 0) {

// Sum every even number obtained 
sum = sum + i;
}
// Judge , If it's odd 
if(i % 2 == 1) {
 // Or i%2!=0 It's OK 
jisum = jisum + i;// Sum every odd number 
}
}
System.out.println(" Even sum is :"+sum+", Odd sum is :"+jisum);

4 Day04– loop

4.1 nesting for loop

4.1.1 summary

According to the conditions of the outer layer , Judge whether the inner layer can execute , If it can be carried out , After looping through the inner code , Then continue the execution , Continue to judge ..

4.1.2 form

for(){

for(){

}
}

4.1.3 Introductory cases

package day0000;
public class T {

public static void main(String[] args) {

// f1();
f2();
}
// summary 1: When i=1 when ,j Get all the data that meet the conditions ,1,2,3,4,5.
// That is, the outer loop executes 1 Time , The inner loop is executed many times 
private static void f1() {

for(int i=1;i<=3;i++){
// Outer loop 
System.out.println("i="+i);//1,2,3
for(int j=1;j<=5;j++){
// Inner loop 
System.out.println("j="+j);//1,2,3,4,5
}
}
}
// summary 2: Outer loop control line , Inner loop control column 
private static void f2() {

for(int i=1;i<=3;i++){

for(int j=1;j<=5;j++){

System.out.print("*");
}
System.out.println();
}
}
}

4.1.4 practice 1: Print a square

****
****
****
****
for(int i=1;i<5;i++){

for(int j=1;j<5;j++){

System.out.print("*");
}
System.out.println();
}

4.1.5 practice 2: Print left right triangle

*
**
***
****
*****
// Right triangle 
private static void f4() {

for (int i = 0; i < 5; i++) {
// Outer loop , The control line , It must be 
for (int j = 0; j <= i; j++) {
// Inner loop , Columns are not fixed , Is increasing 
System.out.print("*");// Make sure the first line prints out a *, Attention condition 
}
System.out.println();
}
}

4.1.6 practice 3: Print 99 Multiplication table

//99 Multiplication table positive sequence 
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
private static void f4() {

for (int i = 1; i < 9; i++) {
// Outer loop , The control line , It must be 
for (int j = 1; j <= i; j++) {
// Inner loop , Columns are not fixed , Is increasing 
System.out.print(i+"*"+j+"="+i*j+" ");// Make sure the first line prints out a *, Attention condition 
}
System.out.println();
}
}
// The multiplication table is in reverse order 
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*4=4 2*4=8 3*4=12 4*4=16
1*3=3 2*3=6 3*3=9
1*2=2 2*2=4
1*1=1
for(int i=9;i>=1;i--) {

for(int j=1;j<=i;j++) {

System.out.print(j+"*"+i+"="+i*j+"\t");
}
System.out.println();
}

4.1.7 practice 4: Print right triangle

Print right angle

 *
**
***
****
*****
package day999;
public class a {

public static void main(String[] args) {

// Output 5 That's ok 
for(int i=1;i<=5;i++){

// Space triangle 
for(int x=5;x>i;x--){
// It can also be changed to :for(int x=1;j<=5-i;x++) 
System.out.print(" ");
}
//* Triangle number 
for(int j=1;j<=i;j++){

System.out.print("*");
}
System.out.println();
}
}
}

4.1.8 practice 5: Print full triangle

Print full triangle

 *
***
*****
*******
*********
package day999;
public class a {

public static void main(String[] args) {

// Print 5 That's ok 
for(int i=1;i<=5;i++){

// Print the inverted triangle of the space ( The principle is : One space per round )
for(int j=5;j>=i;j--){
 // Exchangeable :for(int j=1;j<=5-i;j++)
System.out.print(" ");
}
// Print * The triangle of the number 
for(int k=1;k<=i*2-1;k++){

System.out.print("*");
}
System.out.println();
}
}
}

4.2 enhance for loop

 Insert picture description here

package lianxi;
import java.util.Random;
import java.util.Scanner;
public class Ta {

public static void main(String[] args) {

int [] numbers = {
10,20,50,7,0,9,22,11};// Define an array 
for (int aa: numbers) {

System.out.println(aa);
}
}
}

4.3 break and continue

To terminate the cycle , You can use these two ways .
 Insert picture description here

4.3.1 form

break: Interrupt the current loop , Simple and crude
for(){

Code 1
if( Conditions ){

Code 3break;// If set up , Just jump out of this for loop 
}
Code 2}
continue: Jump out of this cycle , Go to the next round
for(){

Code 1
if( Conditions ){

Code 3continue;// If set up , Jump out of this time for loop , Go to the next round 
}
Code 2}

4.3.2 practice 1: Look for the numbers 88

Receive input from the user 100 Subnumeral , If not 88 Continue to input , find 88 Just go back to

package cn.tedu.breakdemo;
import java.util.Scanner;
// test break and continue
// summary :break and continue Can end the cycle .
//1,break It can end the cycle immediately, simple and rough .continue Is to end the current cycle and continue the next cycle .
//2,break and continue No code can appear after that , There is also unreachable code 
public class Test3_Break {

public static void main(String[] args) {

for(int i = 1 ; i <= 100 ; i++) {

//1, Accept the number entered by the user 
int input = new Scanner(System.in).nextInt();
//2, Judgment is not 88
if(input == 88) {
// yes 88
System.out.println(" It's in ");
break;// Program end 
}else if(input != 88) {
// No 88
continue;// Continue to input 
}
}
}
}

4.4 Loop structure 2:while

First judge , Re execution
 Insert picture description here

4.4.1 Format

while( conditions for execution ){

Code …
}

4.4.2 practice 1: Guess the number

To produce a random number , Compare with the number the user has been typing .

package cn.tedu.whiledemo;
import java.util.Random;
import java.util.Scanner;
/** * test while loop * summary : * 1.while It is also a circular structure :while( The loop condition ){ The loop body } * 2.while(true) It simply realizes the form of dead cycle ,for You can also realize that the code is more complex . * 3. This structure -- First judge , Re execution */
public class Test4_While {

public static void main(String[] args) {

/** * That produces random numbers 2 Methods : * The first 1 Kind of :int num=(int)(Math.random()*1000+1); Generate random number 1~1000 * explain :Math.random() The return is 0( contain ) To 1( It doesn't contain ) Between double value , Need to convert to strong integer . * The first 2 Kind of :int random = new Random().nextInt(100) +1; Generate random number 1~100 * explain : To produce m Random number within , The default from the 0 Start , barring m Such as :0~100 barring 100(0~99) You can add 1 Turn into (1~100) */
//1, Let the program generate random numbers 
int random = new Random().nextInt(100) +1;
System.out.println(random);
//2, Start guessing -- Repeat a b Things about , Put it in the loop structure 
//while(random > 50) {

//for The dead cycle of form : Let the cycle condition always be true Just go 
//for(int i = 1; i >= 1 ; i++ ) {

while(true) {
 // Dead cycle -- The exit of the program must be set !!
//a, Accept the value entered by the keyboard 
int input = new Scanner(System.in).nextInt();
//b, Get the entered value , and ,random Debbie 
if(input > random) {

System.out.println(" big ");
}else if(input < random) {

System.out.println(" The small ");
}else if(input == random) {

System.out.println(" It's in ");
break;// Program end -- The outlet of the dead cycle !!!
}
}
}
}

4.5 Loop structure 3:do-while

Execute first , To determine
 Insert picture description here

4.5.1 Format

do{

Code …
}while( conditions for execution ); // Notice that there's a semicolon here 

4.5.2 practice 1: Guess the number

To produce a random number , Compare with the number the user has been typing .

package cn.tedu.whiledemo;
import java.util.Random;
import java.util.Scanner;
// test do...while loop 
// summary :
//do...while structure , Guaranteed loop code , least , Do it once 
// Can you continue the cycle , It depends on whether the cycle conditions can be met 
public class Test5_Dowhile {

public static void main(String[] args) {

int random = new Random().nextInt(100) + 1;
System.out.println(random);
do {

// a, Accept the value entered by the keyboard 
int input = new Scanner(System.in).nextInt();
// b, Get the entered value , and ,random Debbie 
if (input > random) {

System.out.println(" big ");
} else if (input < random) {

System.out.println(" The small ");
} else if (input == random) {

System.out.println(" It's in ");
break;// Program end -- The outlet of the dead cycle !!!
}
}while (random > 50);// Clear cycle conditions 
}
}

4.6 summary : The difference between the three cycles

All three cycles can replace each other
1、for: Know the number of cycles ( The application rate is the highest )
2、while/do while: When the number of cycles is uncertain
3、while: First judge , Not in line with the rules , No code execution ( It's possible not to do it once )
4、do while: Code is executed at least once , Then judge , Conform to the rules , Execute the code again .

How to determine which cycle to use ?
1. If it is related to the number of times, use for loop
2. In judging conditions 1 And conditions 3 Are they the same? : If the same, use do while The difference is while ( Variable initialization , Conditions , Change quantity )

5 Day05– Method + Array

5.1 Method

5.1.1 summary : Method ( function , The process )

1. Method : Encapsulate a specific business logic function .
2. The method should be as independent as possible , One method only does one thing .
3. Method can be called repeatedly with .
4. Reduce code duplication , Good for code maintenance , Conducive to team collaboration .
5. Methods can have parameters , You can also have no participation , Multiple parameters separated by commas ( See the demand ).
6. Methods and methods are peer-to-peer .
7. Method name naming rules : Hump naming hair .

5.1.2 form

 Modifier return type Method name ( parameter list ){

Method body ;
return Return value ;// void( No return value ) int,double,String… There is a return value 
}

5.1.3 practice 1: Method call

Method call Call... Based on the signature of the method .

Method signature : Method name + parameter list

grammar

  1. No return value type (void): Method name ( There is reference to pass reference );
  2. There are return value types : data type Variable = Method name ( There is reference to pass reference );

Be careful

  1. stay In a class , There can be no 2 The signatures of the two methods are exactly the same .
  2. As long as the return value type is not void, There must be a return value retuen, When receiving, you need to declare a data type to receive .
  3. Actual parameters : Parameters passed when calling the method ( It can be a definite number It can also be an uncertain number )
  4. Shape parameter : When defining a method , Parameters defined in the parameter list of the method .
  5. When the method is called , The actual parameter value will be passed to the parameter variable of the method . Delivery must be guaranteed Type of parameter and Number Declaration of conformity with the method .

 Insert picture description here
explain The following calls are all method calls in the same class , And you need to modify the method to static Static resources , Because static methods can call each other .

package cn.tedu.method;
// The package name can be modified directly in the code , The mouse will prompt you to create a package without .
// Empathy : Class is the same 
// Use of test methods +-------------------------------
public class Test6_Method {

public static void main(String[] args) {

System.out.println(1);
function();// The specified function()
System.out.println(2);
}
// establish function() If not in main Method invocation method , Then the program will not actively execute this method .
// Modifier Return value Method name ( parameter list ){ Method body }
public static void function() {

System.out.println(3);
System.out.println(4);
System.out.println(5);
}
}

5.1.4 practice 2: Method dissemination

package cn.tedu.method;
// Use of test methods 
public class Test6_Method {

public static void main(String[] args) {

System.out.println(1);
// function();// The specified function()
// param(10);// Method dissemination 
// param2("jack",10);// Pass two parameters -- It's called the actual parameter 
// Be careful : The parameters passed when calling a method are called arguments , Whether it's a number or a variable, it's an argument 
// param3(5,10,"jack"); The number and type of parameters are the same , But different order also means different parameter list , The method is different .
param4("jack",5,10);
System.out.println(2);
// The assignment is outside the parentheses , Just like direct assignment in method .
int m=10;
String n=”rose”;
Param5(m,n);
}
// establish param5 Methods 
public static void param5(inta,String b) {

System.out.println(a+b+);
}
//TODO establish param4("jack",5,10) -- Method dissemination : Parameter type must match 
public static void param4(String a,int b,int c) {

System.out.println(a+b+c);//jack510
}
//TODO establish param3(5,10,"jack") -- Method dissemination : Parameter type must match 
// Use... Between multiple parameters ”,” separate .
public static void param3(int a,int b,String c) {

//+ Between numbers is an addition operation , And string + It's a concatenated string 
System.out.println(a+b+c);//15jack
}
// establish param2("jack",10) -- Method dissemination : Parameter type must match 
//String n,int a -- It's called a formal parameter : The parameters in the method are called formal parameters 
public static void param2(String n,int a) {

System.out.println(n);
System.out.println(a);
}
// establish param() -- Method dissemination : Parameter type must match 
// Modifier Return value Method name ( parameter list ){ Method body }
// public static void param( Parameter type Parameter name ) {

public static void param(int num) {

System.out.println(num);
}
// establish function()
// Modifier Return value Method name ( parameter list ){ Method body }
public static void function() {

System.out.println(3);
System.out.println(4);
System.out.println(5);
}
}

5.1.5 practice 3: Method return value

return Return value ;: After the method ends, you can return a data , Called return value , Method must specify the type of return value when declaring .

Be careful : Methods can have return values , There can be no return value (void).
When there is a return value ? When there is no return value ?
When method execution ends

  1. If you still need to use a certain data in the method ---- There is a return value ( The return value type cannot be void, and return Continuous use , If there is a return value, you need to define a variable or array to accept it .)
  2. If you no longer need to use a certain data in the method ---- no return value ( The return value type is void, No need to write return.)

Return Two forms of action ?
The first one is :return value ;
1. End method execution
2. Return to caller .( Be careful : As long as there is a return value type, there must be return The number )

The second kind :return ;
4. End method execution ( Be careful : No return value type, no need to write return, Because the program still ends after execution , It doesn't make sense to write directly . Sometimes you can talk to if Branch structures are used in conjunction with , Used to jump out of the program .)

package cn.tedu.method;
// The return value of the test method 
public class Test7_Method2 {

public static void main(String[] args) {

//result Record method() The results of the implementation of a b And 
int result = method(10,5);
System.out.println(result);
//TODO 
String name = method2("jack","rose","jerry");
System.out.println(name);
}
//TODO establish method2("jack","rose","jerry")
public static String method2(String a,String b,String c){

return a+b+c;// The return value is not just a variable , Count . You can also return a formula 
}
// establish method(10,5)
// Be careful : The return value of the method should be the same as result The variables are of the same type 
public static int method(int a,int b) {

// adopt return The result of method execution can be , Return to , The position !!
return a+b;
}
}
// Be careful : Example , Different types are returned to see whether it is string splicing , use String
String sum2=method("jack",10,5);
System.out.println(sum2);
public static String method(String c,int a,int b) {

return c+a+b; // Here is a string splicing, so use String type . The return value type is the same as return The types after are the same .
}

5.2 Method overloading Overload

5.2.1 Concept

1. Method overloading refers to In a class , Same method name , Different parameter list , Different methods , The same doesn't make sense .
2. The compiler will automatically bind and call different methods according to the signature of the method during compilation .( We can think of overloaded methods as completely different methods , It's just that good methods have the same name .
3. Overloading is for methods .

Meaning of overloading : For programmers , The method name that needs to be remembered is very simple. It only needs to remember one name , Method parameters can be passed in flexibly .

Different parameter list : Include parameter types , The order , Number .

5.2.2 practice 1: Sum the numbers

package cn.tedu.overload;
// Test method overload :
// requirement : Same method name + Different parameter list 
// significance : Because when users use , We don't know the parameters passed in , In order to show that my program is very flexible 
// Try to provide as many different parameters as possible , The same way 
public class Test8_Overload {

public static void main(String[] args) {

add(5);
add(10,5);
add("jack",5);
add(10,"rose");
//TODO
print(10);
print("jerry");
print(' in ');
}
// establish add(10,"rose")
public static void add(int a,String b) {

System.out.println(a+b);//10rose
}
// establish add("jack",5)
public static void add(String a,int b) {

System.out.println(a+b);//jack5
}
// establish add(10,5)
public static void add(int a,int b) {

System.out.println(a+b);
}
// establish add(5)
public static void add(int a) {

System.out.println(a*a);
}
}
// summary : Method , The ginseng , The data type is consistent with the parameter list ,( namely : Number , type , In the same order ).
// Return value : If there is a return value, it should be the same as the return value type , The return value is consistent with the accepted type .
// Such as :
public static void main(String[] args) {

// Method practice 
method(2,3," Xiao Ming ");
String aa=method2(2,3," Xiaohong ");
System.out.println(aa);
}
public static void method(int a,int b,String c) {

System.out.println(a+b+c);
}
public static String method2(int a,int b,String c) {

return a+b+c;// Yes String type ,int type . It splices string types , So we should use String As its return value type , Its acceptance value is also String type .
}

5.2.3 practice 2: Data printing

package day004;
public class Test07 {

public static void main(String[] args) {

// TODO Auto-generated method stub
print(10);
print(2.2);
print(true);
print("jack");
}
public static void print(int a) {

System.out.println(a);
}
public static void print(double a) {

System.out.println(a);
}
public static void print(boolean a) {

System.out.println(a);
}
public static void print(String name) {

System.out.println(name);
}
}

5.3 Variable parameters

Variable parameters are essentially arrays .
 Insert picture description here

5.4 recursive

 Insert picture description here
Be careful

  1. Recursion levels cannot be too many , If too much, it will greatly reduce the efficiency of the computer .
  2. If you don't need recursion, you don't have to , It can be realized by some other algorithms .
package lianxi;
import java.util.Random;
import java.util.Scanner;
public class Ta {

public static void main(String[] args) {

// recursive thinking 5*4*3*2*1
System.out.println(f(5)); // You can't have too many levels 
}
public static int f(int n) {

if (n==1) {

return 1;
}else {

return n*f(n-1);
}
}
}

 Insert picture description here

5.5 Array

5.5.1 Concept

explain : Is used to store Multiple of the same type A collection of data .

Array Array The sign of is :[ ]

Get the element value in the array : You can get it from the subscript of the element , The subscript is from 0 At the beginning , The maximum value of the subscript is its length -1.

The type of array : Array Array Is a reference type , Stored is the address , Addresses take up very little memory in space ( It's a string of numbers ).
 Insert picture description here

5.5.2 Create array

It is generally divided into dynamic initialization and static initialization .

grammar

 An array type [ ] Array name = Array objects ;// Recommended 
perhaps
An array type Array name [ ] = Array objects ;// It is not recommended to use , This is a c++ Language habits , Early for c++ Programmers learn java Created .

Case study

 dynamic initialization : Declare before assign , You need to specify the number of elements stored .
int[] a = new int[4];// The type of array should be consistent with each data type stored 
a[0] =1;
a[1] =4;
a[2] =7;
a[3] =5;
initiate static : Assign values while declaring an array
int[] b = new int[]{
1,2,3,4,5};// The elements between arrays are separated by commas .
int[] c = {
1,2,3,4,5};

Default initialization of arrays : An array is a reference type , Its elements are equivalent to the instantiation variables of the class , therefore The array has allocated space , Each of these elements is also initialized in the same way as the instance variable .

int[] aa = new int[5];
At this time, space has been allocated in memory , The default value for each element is int Type value 0.

 Insert picture description here

5.5.3 practice 1: Store... In the array hello

package cn.tedu.array;
import java.util.Scanner;
// This class is used to test the creation of arrays 
public class Test1_Array {

public static void main(String[] args) {

//1, Create array . Deposit in hello
// Determine the array type , The length of the array 
// static state 
// Because each grid has one character , So use char type .
char[] a = new char[] {
'h','e','l','l','o'};
char[] b = {
'h','e','l','l','o'};
System.out.println(a);
System.out.println(b);
// 2, dynamic Create array , need , Specify the length of the array !!
char[] c = new char[5];
// Be careful : Save string is used char Array . No string
//3, All elements in the array have subscripts , The default from the 0 Start 
c[0]='h';// Give it to 1 Elements , That is, the subscript is 0 The elements of , assignment 
c[1]='e';// Give it to 2 Elements , That is, the subscript is 1 The elements of , assignment 
c[2]='l';// Give it to 3 Elements , That is, the subscript is 2 The elements of , assignment 
c[3]='l';// Give it to 4 Elements , That is, the subscript is 3 The elements of , assignment 
c[4]='o';// Give it to 5 Elements , That is, the subscript is 4 The elements of , assignment 
//4,java.lang.ArrayIndexOutOfBoundsException Array subscript out of bounds exception 
// The reason is that if the length of the array is 5, The maximum subscript is 4, There is no such thing as... Subscript 5 The situation of , Subscript 5 Out of range 
//c[5]='o';// Give it to 6 Elements , That is, the subscript is 5 The elements of , assignment --- Report errors !!
System.out.println(c);
}
}

5.5.4 Length of array

  • length Property to get the array length .
  • Once the array is created , The length is immutable , namely : The array is a fixed length .
  • allow 0 An array of lengths .

5.5.5 Characteristics of array

 Insert picture description here

5.5.6 Bounds of an array

 Insert picture description here

5.6 Traversal of array

From a to Z , Access the position of the array in turn .

5.6.1 form

1. Ordinary for loop
for( From the subscript for 0 The position begins ; To array length -1 end ; Subscript ++){

Loop body code
}
2. compete for supremacy for loop , But I can't get the subscript .
for( Statement statement : expression ){

Loop body code
}

5.6.2 practice 1: enhance for Loop traversal

package lianxi;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Ta {

public static void main(String[] args) {

int[] arrays = {
1,3,6,3,8,9,0};
for(int aa:arrays) {

System.out.println(aa);
}
}
}

5.6.3 practice 2: Output the number of days per month

package cn.tedu.array;
// Array exercise 
public class Test2_Array2 {

public static void main(String[] args) {

method();// Output the number of days per month 
}
// establish method()
public static void method() {

// 1, Create arrays statically 
int[] days = {
 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 2, Traverse the array with subscripts 
// i Represents the subscript 
// int i = 0 , From the subscript 0 Start 
// i <= days.length-1, To the maximum value of the subscript 
// i++, Traverse backward one by one 
for (int i = 0; i <= days.length - 1; i++) {

// days[i] finger days Array , The value stored in each subscript 
System.out.println((i + 1) + " Monthly " + days[i] + " God ");
}
}
}// If you output an array directly, you output the address , The output corresponding subscript is the element it represents 

Output the elements represented by each subscript in the array in turn .
 Insert picture description here

5.6.4 practice 3: Traversal array , Deposit in 1 To 10

package lianxi;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Ta {

public static void main(String[] args) {

//1, dynamic Create array 
int[] a = new int[10];
System.out.println(Arrays.toString(a));//[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
//2, Traversal array , Save the data 
for(int i = 0 ; i <= a.length-1 ; i++ ) {

// Get each element a[i]
a[i] = i+1;
}
//3, Look at the elements in the array 
System.out.println(a);//[[email protected]
/** * except char Array can directly output the elements inside , Other arrays are addresses . * Want to see not char[] What are the elements in the array --Arrays Tool class toString() Display the specified data as an array */
System.out.println(Arrays.toString(a));//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
}

Direct output array :
 Insert picture description here

5.6.5 practice 4: Create random arrays

obtain 100 An array of random values within

// establish method3()
public static void method3() {

//1, dynamic Create array 
int a[] = new int[10];
//2. Traversal array , Reassign 
for(int i = 0 ; i <= a.length-1 ; i++) {

//a[i] Get elements 
a[i]=new Random().nextInt(100);
}
//3. Look at the elements in the array 
System.out.println(Arrays.toString(a));
}

5.7 Array utility class Arrays

5.7.1 Arrays.toString( Array )

Put the data in the array , Concatenate a string with commas .( The return value is String)
Format :[10, 14, 20, 46, 51]

package day006;
import java.util.Arrays;
public class Test02 {

public static void main(String[] args) {

// to String
method();
}
public static void method() {

int[] aa= {
1,2,3,4,5,6};
// Directly output the entire array without traversal , The previous traversal is to insert . 
// for(int i=0;i<aa.length-1;i++) {

// }
// Direct printing is the address value, such as :[[email protected] After using the tool class is :[1, 2, 3, 4, 5, 6] 
System.out.println(Arrays.toString(aa));
}
}

5.7.2 Arrays.sort( Array )

Sort arrays in ascending order : For arrays of basic types, use the optimized quick sorting algorithm , Efficient . Array of reference types , Using the optimized merge sort algorithm .

No return value .
Example :

package lianxi;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Ta {

public static void main(String[] args) {

int[] as = {
4,9,4,1,2,5,9,6,4,5,2};
Arrays.sort(as);
System.out.println(Arrays.toString(as));
}
}

 Insert picture description here

5.7.3 Arrays.copyOf( Array , New length )

Copy the array into a new array of specified length .( What's changed is the new array , The original array has not changed )
The length of the new array is larger than that of the original array , Equivalent to replication , And add positions .-- Expansion of array
The length of the new array is smaller than that of the original array , It is equivalent to intercepting the previous part of the data .-- Reduction of array size
There is a return value .

5.7.4 test

package cn.tedu.array;
import java.util.Arrays;
// Array test tool class 
// Why? sort() No return value is ,void
// Why? copyOf() There is a return value , Such as :int[]
// as a result of :sort() On the basis of the original array , Adjust the position of the array 
//copyOf(): Once the array is created , The length is immutable !!! So we must return the generated new array / And here you change the length .
public class Test4_Arrays {

public static void main(String[] args) {

int[] a = {
97, 7, 41, 37, 55, 3, 3, 34, 34, 83};
// sortArray(a);//a Is the argument , Sort unordered arrays 
int[] newA = copyArray(a);// Array copy a It's the original array 
// [97, 7, 41, 37, 55, 3, 3, 34, 34, 83, 0, 0, 0, 0, 0]
// [97, 7, 41, 37, 55]
System.out.println(Arrays.toString(newA));
}
// establish copyArray The first way , Capacity expansion , Shrinkage capacity ( And the length of the new array is greater than or less than the length of the new array )
public static int[] copyArray(int[] from) {

//copyOf(from,num)--from Is the original array name ,num Is the length of the new array -- New array length > Original array length -- Capacity expansion 
int[] to = Arrays.copyOf(from, 15);
// [97, 7, 41, 37, 55, 3, 3, 34, 34, 83, 0, 0, 0, 0, 0]
//from Is the original array name ,5 Is the length of the new array -- New array length < Original array length -- Shrinkage capacity -- Equivalent to intercepting data .
int[] to2 = Arrays.copyOf(from, 5);
// [97, 7, 41, 37, 55]
return to2;
}
// establish sortArray
public static void sortArray(int[] a) {
// Shape parameter 
//sort() Used to sort unordered arrays 
Arrays.sort(a);// Bottom source 
// [3, 3, 7, 34, 34, 37, 41, 55, 83, 97]
//toString() For the specified array contents , Display as a string 
System.out.println(Arrays.toString(a));
}
}
Example :
// Copy of array The first 2 Kind of arraycopy It's all changed on the new array , Pay attention to the difference between the two writing methods .
int [] we= {
4,8,5,8,9}; // The new array is small, automatic interception , When it is big, it will automatically fill .
int[] we1=Arrays.copyOf(we, 4);
System.out.println(Arrays.toString(we));
System.out.println(Arrays.toString(we1));
System.out.println("11111111111");// Pile driving 
int[] we2=new int[5];// This is a new array. If the length is small, there will be an array subscript out of bounds exception . That won't . The advantage is that it is more flexible .
System.arraycopy(we,0,we2,0,5);
System.out.println(Arrays.toString(we2));
// Expansion of array 
int we3[]=Arrays.copyOf(we, we.length+1);
System.out.println(Arrays.toString(we3));

5.8 expand :

5.8.1 Understand two-dimensional arrays

An array that holds arrays , In other words, the data stored in the array is still in the form of array .
 Insert picture description here

public class Test06 {

//ctrl +n Shortcut keys are equivalent to new Use the up and down keys ( Create project , package , Class does not use a mouse )
public static void main(String[] args) {

// Two dimensional array : Array set array 
// Format : location : Such as ,c[0][1] Traverse 2 Time .
int [][] c={
{
1,2},{
3,4},{
5,6}};// The form of the statement 
for(int i=0;i<=c.length-1;i++) {
// Traverse the outer array 
for(int j=0;j<=c[i].length-1;j++) {
 // Traverse inner array 
System.out.println(c[i][j]);// Output form 
}
}

5.8.2 Understand bubble sorting

Bubble sort (Bubble Sort), It's a simpler sort algorithm in the field of computer science .
It repeatedly visits the element columns to be sorted , Compare two adjacent elements in turn , If they are in order ( : from large to small 、 First letter from A To Z) Mistakes are exchanged . The job of visiting an element is to do it repeatedly until no adjacent elements need to be exchanged , That is, the element is sorted .
The algorithm got its name because larger elements are exchanged slowly “ floating ” Go to the top of the list ( Ascending or descending order ), Just as the bubbles of carbon dioxide in carbonated drinks eventually rise to the top , So the name “ Bubble sort ”.

 Insert picture description here
Bubble sort explanation

  1. Compare array 2 Two adjacent elements , If the first number is larger than the second , We'll exchange his position .
  2. Each comparison produces a maximum or minimum number .
  3. The next round can reduce one sorting .
  4. Cycle in turn until the end .

 Insert picture description here
Optimization of bubble sort : There's a lot of , The most basic can be judged by variable identification , If the order is correct, then , There is no need to compare

5.8.3 Bubble sort code

package cn.tedu.bubble;
// The first one is 20 The number ratio is 20 round Ratio per round -i-1 Time 
// The second kind 20 The number ratio is 19 round Ratio per round -i Time 
import java.util.Arrays;
// This class is used to test bubble sorting algorithm 
public class Test3_Bubble {

public static void main(String[] args) {

//1, Define unordered arrays 
int[] a = {
21, 94, 21, 58, 47, 16, 10, 9, 50, 44};
//2, Sort 
//5 Number , Than 4 round . Number of external circulation control wheels , Let the outer loop execute 4 Time 
//i < a.length-1 a.length yes 5,-1 Namely 4,i<4, Outer loop execution 4 Time 
for(int i = 0 ; i < a.length-1 ; i++ ) {

// Internal circulation controls how many times each round needs to be compared with each other 
//-i : The first 1 round , Need to be compared with 4 Time , Five numbers participate in the comparison -0,
// The first 2 round , Need to be compared with 3 Time , Four numbers participate in the comparison -1,( Because a large value is sunk in the first round, it does not participate in the comparison )
// The first 3 round , Need to be compared with 2 Time , Four numbers participate in the comparison -2,( Because the two large values from the first two rounds are not involved in the comparison )
// The first 4 round , Need to be compared with 1 Time , Four numbers participate in the comparison -3,( Because the three big values from the first three rounds do not participate in the comparison )
for(int j = 0 ; j < a.length-1 - i; j++ ) {

//1, Comparison of adjacent elements 
// Previous value a[j] Greater than the following value a[j+1]
if(a[j]>a[j+1]) {

//2, Exchange order s
int t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
System.out.println(Arrays.toString(a));
}
}

5.8.4 Bubble sorting code optimization writing method

package lianxi;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Ta {

public static void main(String[] args) {

//1, Define unordered arrays 
int[] a = {
21, 94, 21, 58, 47, 16, 10, 9, 50, 44};
//2, Sort 
//5 Number , Than 4 round . Number of external circulation control wheels , Let the outer loop execute 4 Time 
//i < a.length-1 a.length yes 5,-1 Namely 4,i<4, Outer loop execution 4 Time 
for(int i = 0 ; i < a.length-1 ; i++ ) {

boolean flag=false;// adopt flag Identification reduction meaningless comparison 
// Internal circulation controls how many times each round needs to be compared with each other 
//-i : The first 1 round , Need to be compared with 4 Time , Five numbers participate in the comparison -0,
// The first 2 round , Need to be compared with 3 Time , Four numbers participate in the comparison -1,( Because a large value is sunk in the first round, it does not participate in the comparison )
// The first 3 round , Need to be compared with 2 Time , Four numbers participate in the comparison -2,( Because the two large values from the first two rounds are not involved in the comparison )
// The first 4 round , Need to be compared with 1 Time , Four numbers participate in the comparison -3,( Because the three big values from the first three rounds do not participate in the comparison )
for(int j = 0 ; j < a.length-1 - i; j++ ) {

//1, Comparison of adjacent elements 
// Previous value a[j] Greater than the following value a[j+1]
if(a[j]>a[j+1]) {

//2, Exchange order s
int t = a[j];
a[j] = a[j+1];
a[j+1] = t;
flag=true;
}
}
if(flag==false) {

break;
}
}
System.out.println(Arrays.toString(a));
}
}

 Insert picture description here

5.8.5 Learn about other algorithms

Such as : Merge algorithm , Bisection algorithm , Fast algorithm, etc , Bubbling is the most common , It is also the one with the highest occurrence rate in the interview

5.8.6 Sparse array

B Sparse video connection station :https://www.bilibili.com/video/BV12J41137hu?p=59&spm_id_from=pageDriver

copyright:author[Cool breeze AAA],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130738490024.html