Summary of this week
1, Application of switch statement
Enter the value of the month (default int) on the keyboard. Please use switch to judge the season
(3, 4, 5 spring, 6, 7, 8 summer, 9, 10, 11 autumn, 12, 1, 2 winter)
code:
//Guide Package import java.util.Scanner ; class SwitchTest2{ public static void main(String[] args){ //Create keyboard entry object Scanner sc = new Scanner(System.in) ; //Prompt and enter data System.out.println("Please enter a value for one month:") ; int month = sc.nextInt() ; //Use the switch statement to accept data switch(month){ case 3: case 4: case 5: System.out.println("spring"); break ; case 6: case 7: case 8: System.out.println("summer"); break ; case 9: case 10: case 11: System.out.println("autumn"); break ; case 12: case 1: case 2: System.out.println("winter"); break ; default: System.out.println("I'm sorry,The month you entered is incorrect."); break ; } } }
2, Circular statement
1. Loop statement ----- for
format
for(Initialization statement; Conditional expression; step/Control body statement){ Loop body statement; }
Execution process
1)Execute initialization statement:Assign values to variables 2)Meet the conditions:establish 3)Execute loop body statement 4)Execution step/Control body statement Perform 2 again)process,Judge whether the conditions are true Sequential cycle ... ... When the conditional expression does not hold,be for End of statement!
give an example
Use the for loop statement to find the sum between 1-10?
class demo{ public static void main(String[] args){ int temp=0; for(int x=1;x<=10;x++){ temp=temp+x; } System.out.println("1-10 The data between and is:"+sum) ; } }
2. Loop statement ----- while
format
while Circular statement format: Basic format while(Judgment conditional statement) { Loop body statement; } Extended format Initialization statement; while(Judgment conditional statement) { Loop body statement; Control condition statement; }
Execution process
1) Initialize discourse sentence for assignment
2) The conditional expression holds,
Execute loop body statement
Execute the control body statement again
3) Again, judge whether the conditional expression is true,
...
...
When the condition does not hold, the while ends
give an example
Calculate the sum of 1-100?
public static void main(String[] args) { //Implementation using a while loop //Define a variable to record the cumulative sum int sum = 0; //Define initialization expression int i = 1; //Use the while loop to change the value of the initialization expression while(i<=100){ //Cumulative summation sum += i ; //A step expression changes the value of a variable i++; } //Print summed variables System.out.println("1‐100 The sum of is:"+sum); }
The difference between for and while
1)In terms of format:Different formats for(Initialization statement;Conditional expression;Control body statement){ Loop body statement; } Initialization statement; while(Conditional expression){ Loop body statement; Control body statement; } for After the cycle ends,Cannot access at for Medium variable,for End of cycle; The variable needs to be released! while Loop can access 2)Memory:for Cycle to save memory space heap,Stack memory(Store local variables:In method definition/Variable on method declaration), Method area..(main()) for End of cycle,Variables are released with,Save memory space;(Can't access this variable.) while End of cycle,You can still access this variable,Compare memory consumption... 3)Usage scenario: for loop:Specify the number of cycles and the number of daffodils used:100-999 (Under development:Priority for) while loop:Ambiguous number of cycles,use
3. Dead cycle
//Two formats: //1) for(;;){ Loop body statement; } //2) while(true){ Loop body statement; }
Example
class DieForWhileDemo{ public static void main(String[] args){ //Dead loop format for: for(;;){ System.out.println("Dead cycle...") ; } //while Loop while(true){//equation holds good under all circumstances System.out.println("Dead cycle...") ; } } }
4. Loop statement - do_while
format
Initialization statement; do{ Loop body statement; Control body statement; }while(Conditional expression) ; Extended format Initialization statement; do { Loop body statement; Control condition statement; } while((Judgment conditional statement);
Characteristics of do... while loop
Execute the loop body unconditionally once. Even if we write the loop condition directly as false, it will still loop once.
give an example
Calculate the sum of 1-100?
class DoWhileDemo{ public static void main(String[] args){ //Sum between 1-100 //Define an end result variable int sum = 0 ; int x = 1 ; do{ sum += x ; x ++ ; }while(x<=100) ; System.out.println("1-100 The sum between is:"+sum) ;
5. for loop nesting
Concept:
A for loop statement is a loop of another for loop statement
format
for(Initialization statement;Conditional expression;Control body statement){ for(Initialization statement;Conditional expression;Control body statement){ } }
give an example
Print "* *" shape (4 rows and 5 columns *)
class ForForDemo{ public static void main(String[] args){ for(int x = 0 ; x < 4 ; x++){ //Outer loop: it is a control line number for(int y = 0 ; y < 5 ; y ++){//Inner loop: control the number of columns System.out.print("*") ; //Output 5 on the same line* } System.out.println() ; } } }
3, Jump control statement
1,break
break: end interrupt, end loop (cannot be used alone)
Usage scenario: terminate switch or loop
In the select structure switch statement
In a loop statement
It is meaningless to leave the existence of the usage scenario
Use demonstration
class BreakDemo{ public static void main(String[] args){ for(int x = 0 ; x < 10 ; x ++){ //judge if(x == 3){ break ; } System.out.println(x) ;//0,1,2 } System.out.println("over") ; } }
2,continue
Continue: continue, use in the loop,
End the current cycle and immediately enter the next cycle
Use demonstration
class ContinueDemo{ public static void main(String[] args) { for (int i = 1; i <= 10; i++) { //Requirement: do not print the third HelloWorld if(i == 3){ continue; } System.out.println("HelloWorld"+i); } }
3,return
The Return keyword is not used to jump out of the loop body. A more common function is to end a method, that is, exit a method. Jump to the caller of the upper layer
Law.
Use demonstration
class ReturnDemo{ public static void main(String[] args){ //Procedure: import return System.out.println("The program begins....") ; for(int x = 0 ; x < 10 ; x ++){ System.out.println("get into for Cycle...") ; if(x==3){ return ; //Used alone, return: the end method } System.out.println(x) ;//0,1,2 } System.out.println("The program is over...") ; } }
return needs to be used related to methods. It is rarely used alone
4, Method
concept
Method: use {} code block to package it and give it a name (see the meaning of name)
Format of method defined in Java:
1) Definition of a method with a specific return value type
Fixed format public static Return value type method name(Parameter type 1 variable name 1,Parameter type 2 variable name 2....){ Business logic code in method... return result; } public: Access permissions are large enough,Public static: Static modifier(Object oriented) return type:Is the data type(Basic data types currently used...) Method name: See the name and know the meaning (Nomenclature of small hump) Parameter type:Data type of the first parameter Variable name:accord with (Nomenclature of small hump) return Ends the method and returns a value of the type specified by the method The return value program is return The returned result is returned to the caller
Calls to methods with specific return value types:
1)Individual call(Don't use it) 2)Output call:Not recommended:Because direct output,If you want to use this result value for operation, you can't 3)Assignment call:recommend
matters needing attention
1)Methods and methods are horizontal relations,Nesting is not allowed: Defining another method in one method is not allowed 2)stay Java in,When defining methods, formal parameters must carry data types! (Java Is a strongly typed language Javascript:Weakly typed language:To define a function,Parameter (without type) 3)When calling a method,The actual parameters passed do not need to carry data types 4)When defining methods: have{Semicolons are not allowed in parentheses;
give an example
class FunctionDemo{ public static void main(String[] args){ int a = 30 ; int b = 20 ; int result = sum(a,b) ; System.out.println(result) ; } public static int sum(int a,int b){//Formal parameters int result = a + b;//30+20 return result ; } }
2) Definition of method without specific return value type:
Code block for a function{} There is no specific return value type,According to the grammar:Must have a value Java A keyword is provided:Instead, there is no specific return value type void Fixed format: public static void Method name(Formal parameter list){ Content in method body; }
give an example
Enter a data a (1 < = a < = 9) on the keyboard and output the corresponding nn multiplication table
import java.util.Scanner; ublic class Homework { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter a Value of"); int a = sc.nextInt(); chengFaBiao(a); } public static void chengFaBiao(int a) { for (int x = 1; x <= a; x++) { for (int z = 1; z <= x; z++) { System.out.print(z + "*" + z + "=" + z * z + "\t"); } System.out.println(); } } }
- method overload
Method overload:
The method name is the same, the parameter list is different, and it has nothing to do with the return value!
The parameter list is different:
1) Different number of parameters
2) Different parameter types
Purpose of method overloading:
Is to improve the scalability of a function
Sometimes: the same method can pass any data type
Characteristics of method overload
The return value has nothing to do with the type, just look at the method name and parameter list
When calling, the virtual machine distinguishes the methods with the same name by different parameter lists
Formal parameter problem of method:
1)If the formal parameter of the method is the basic data type,What are the characteristics? The change of formal parameters will not affect the actual parameters! 2)If the formal parameter of the method is a reference data type(array),What are the characteristics? String type:Special reference types:It is used as a formal parameter,The effect is consistent with the basic data type! The change of formal parameters does not affect the actual parameters(String The essence is constant) If the formal parameter is an array type(except String Out of type), Actual parameter transfer:Pass array object :The change of formal parameters will directly affect the actual parameters
5, Array
Array concept:
It is a container that stores multiple data. You must ensure that the data types in the container are consistent!
Definition format of array:
1) Dynamic initialization
Given the length of the array, the system initializes the elements by default!
Format:
data type[] Array name = new data type[Array length] ; Data type array name[] = new data type[Array length] ;
2) Static initialization
For the specific elements we give, the array length is determined by the system
Format:
data type[] Array name = new data type[]{Element 1,Element 2,Element 3....} ; Data type array name[] = new data type[]{Element 1,Element 2,Element 3....} ; Simplified format: data type[] Array name = {Element 1,Element 2,Element 3....} ; Data type array name[] = {Element 1,Element 2,Element 3....} ;
Program error (understand):
Compile time exception:jvm function java program:Check syntax (The caller must handle!) later stage:IOEXception: When reading and writing data ParseExceptin:Parsing exception take"2021-7-13" Date text format---->java.util.Date Runtime exception:RuntimeException Problems caused by loose code logic or other business judgment ArrayIndexOutOfBoundsException: Array subscript out of bounds exception developer:You need to check whether the angle of the array is correct! NullpointerException:Null pointer exception: describe:An object is currently null,We also use object operations,There will be problems Can be solved through logical judgment Non null judgment for an object
Static initialization application
Set int [] arr = {43, 65, 3, 6, 76}; Traverse
public class work01 { public static void main(String[] args) { int[] arr = { 43, 65, 3, 6, 76 }; System.out.println("After traversal:"); bianLi(arr); } public static void bianLi(int[] arr) { System.out.print("["); for (int i = 0; i < arr.length; i++) { if (i == arr.length - 1) { System.out.println(arr[i] + "]"); } else { System.out.print(arr[i] + ","); } } } }
Array advanced sorting ------ bubbling
Bubble sorting idea:
Compare two by two. Put the larger value back. After the first comparison, the maximum value appears at the maximum index
In this way, you can get the ordered array!
Write a program, known array int[] arr = {43,65,3,6,76},
After sorting the array bubble, traverse and output the result;
public class work01 { public static void main(String[] args) { int[] arr = { 43, 65, 3, 6, 76 }; System.out.println("Before sorting:"); bianLi(arr); System.out.println("After traversal sorting"); paiXu(arr); bianLi(arr); } public static void paiXu(int[] arr) { for (int x = 0; x < arr.length - 1; x++) { for (int y = 0; y < arr.length - 1; y++) { if (arr[y] > arr[y + 1]) { int num = arr[y]; arr[y] = arr[y + 1]; arr[y + 1] = num; } } } } public static void bianLi(int[] arr) { System.out.print("["); for (int i = 0; i < arr.length; i++) { if (i == arr.length - 1) { System.out.println(arr[i] + "]"); } else { System.out.print(arr[i] + ","); } } } }
Memory allocation in Java
Java programs need to allocate space in memory when running. In order to improve the operation efficiency, the space is divided into different regions,
Because each area has a specific data processing method and memory management method.
Stack: storing local variables Heap: storage new What comes out Method area: custom methods/jdk Methods provided Local method area: (system related) Register: (to CPU (use)
6, Object oriented
1. Introduce
Object oriented process based:
Process oriented: (He is the executor) representative:c language 1)requirement analysis 2)Define function code blocks(method) 3)stay main Method call,Display results object-oriented:representative java language You need to find an object to complete an event:such as :Enter a data with the keyboard (jdk provide--->Scanner) Create keyboard entry object Prompt and enter data Show results
2. Object oriented thinking and characteristics:
1) more importantly, our life is a habit of thought and behavior
2) simplify complex things
3) we have changed from executor to commander
3. Three characteristics of object-oriented:
Encapsulation, inheritance, polymorphism
4. Object oriented design concept:
Constantly create objects, use objects, and command objects to do things! (Scanner: keyboard entry)
4. Relationship between class and object
Class: a collection of related properties and behaviors
Object: it is the concrete embodiment of such things
For example, the class leader is an object
Class: it can be understood as a blueprint or template for constructing objects. It is an abstract concept
Object: a concrete instance created with a class as a model. It is a class
A concretization of.
5. Class definition
The properties of things in the real world, people's height, weight and other actors can learn, eat and so on
The same is true for describing things with class in Java. Member variables are the properties of things. Member methods are the behavior of things. Defining classes is actually the composition of defining classes
Member (member variables and member methods)
Examples
Define a calculator class, provide the function of addition, subtraction, multiplication and division, and Test (Test in the Test class, you can enter two data on the keyboard for Test)
Tip: calculator English word: Calculator
Four member methods are provided in this class: addition, subtraction, multiplication and division
import java.util.Scanner; class Caculator { public void add(int a, int b) { int temp = a + b; System.out.println("a+b The values are:" + temp); } public void jian(int a, int b) { int temp = a - b; System.out.println("a-b The values are:" + temp); } public void cheng(int a, int b) { int temp = a * b; System.out.println("a*b The values are:" + temp); } public void chu(int a, int b) { int temp = a / b; System.out.println("a/b The values are:" + temp); } } class CaculatorDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter two numbers in sequence"); int a = sc.nextInt(); int b = sc.nextInt(); Caculator caculator = new Caculator(); caculator.add(a, b); caculator.jian(a, b); caculator.cheng(a, b); caculator.chu(a, b); } }
6. Member variables and local variables
Member variables:
1,Member variables are defined in the class and can be accessed throughout the class. 2,Member variables are created with the creation of the object, disappear with the disappearance of the object, and exist in the heap memory where the object is located. 3,Member variables have default initialization values.
Local variables:
1,Local variables are only defined in the local scope, such as functions, statements, etc., and are only valid in the region to which they belong. 2,Local variables exist in stack memory. When the scope of action ends, the variable space will be automatically released. 3,Local variables have no default initialization value
difference
1) The writing position in the program is different:
Local variable: on a method definition or method declaration Member variables: variables defined outside member methods in a class
2) In memory
Local variables: in stack memory Member variables: in heap memory
3) Different life cycles
Local variable: exists with the method call and disappears after the method call is completed Member variable: exists with the creation of an object. After the object is created, it will not disappear immediately and needs to wait GC(Garbage collector) collects it in idle time 4)Initialization is different Local variable: it can be defined first, but it must be assigned before use, otherwise:Variables may not have been initialized Member variable: can be uninitialized. It has system default initialization (determined by type)
Formal parameter problem
/* Requirement: access the show method in the Demo class? */ //Program class class Programmer{ public void coding(){ System.out.println("Programmers write code according to requirements...") ; } } //Define Demo class class Demo{ //There is a member method public void show(Programmer programmer){//If the formal parameter of the method is a reference type: Class - you need to create the current class object programmer.coding() ; } } class Test{//Test class public static void main(String[] args){ //Create Demo class object Demo d = new Demo() ; //Create an object of the Programmer class Programmer pro = new Programmer() ; d.show(pro) ; } }
7. Anonymous object
concept
An object without a name is a simplified representation of an object
format
new class name ();
Anonymous objects have one feature: they can be passed as parameters
In development, anonymous objects can be used once!
(because no stack memory variable points to the heap memory address,
Directly open up space in the heap memory. After use, it will be recycled immediately!)
8. Encapsulation
Packaging overview
It refers to hiding the properties and implementation details of objects, and only providing public access
Benefits:
Hide implementation details and provide public access
It improves the reusability of the code
Improve security.
Packaging principle:
Hide all contents that do not need to be provided externally.
Hide properties and provide public methods to access them.
Packaging purpose:
In order to ensure the security of your data!
private keyword:
characteristic 1)Member variables can be modified,You can also modify member methods,But they can only be accessed in this class,External classes cannot be accessed 2)These private decorated member variables,Or member method,It can be accessed indirectly through public methods!
In order to hide the member attribute of a class (privatize the attribute (member variable)),
And provide it with public access! (setXXX()/getXXX())
Privatization: the keyword "private" can only be accessed in this class
Example
class Student2{ //Privatization of member variables private String name ;//full name private int age ; //Age private String gender ;//Gender private String hobit ; //hobby //Member method public void study(){ System.out.println("study JavaEE...") ; } //play a game public String playGame(String gameName){ return "Can play"+gameName ; } //function public void sport(){ System.out.println("I like playing football...") ; } //Some public access methods: assign values to name, age, gender and hobbies / also need to obtain these contents //Assign a value to the student's name public void setName(String n){ //"Gao Yuanyuan" name = n ;//name = n = "high circle" } //Get student's name -- > return value: String public String getName(){ return name ; } //Assign a value to the student's age public void setAge(int a){ //41 age = a ; //age = a = 41 } //Get student's age: int type public int getAge(){ return age ; } //Assign gender values to students public void setGender(String g){ //"Female" gender = g ; //gender = g = "female" } //Get the gender of the student: String public String getGender(){ return gender ; } //Assign values to students' hobbies public void setHobit(String h){ //"Run" hobit = h ; //Hobbit = H = "run" } //Get students' hobbies: String public String getHobit(){ return hobit ; } } //Test class class StudentTest2{ public static void main(String[] args){ //Create student class test Student2 s = new Student2() ; //Object name Public member method name () assignment s.setName("Gao Yuanyuan") ; s.setAge(41) ; s.setGender("female") ; s.setHobit("run") ; System.out.println("The current student's name is:"+ s.getName()+",Age is:"+s.getAge()+",Gender is:"+s.getGender()+",Hobbies are:"+s.getHobit()) ; //Other member methods s.study() ;//study String str = s.playGame("lol") ; System.out.println(str) ; s.sport() ; } }
this keyword
this: represents the object reference of the class
this: is the address value reference of the object representing the current class!
When assigning values to attributes:Local variables hide member variables:The names are the same Java The keyword is provided at this time this:Solve the problem that local variables hide member variables
this. Member variable name = local variable;
Use example
Student things
Attributes: name, age, gender
Behavior: study, smoke
Student class to describe student things - add encapsulation ideas and add this keyword
class Student{ private String name ; private int age ; private String gender ; //Provide public setXXX()/getXXX() methods //Assignment name public void setName(String name){ this.name = name ; } public String getName(){ return name ; } //Assign age public void setAge(int age){ this.age = age ; } //Get age public int getAge(){ return age ; } //Assign gender public void setGender(String gender){ this.gender = gender ; } //Get gender public String getGender(){ return gender ; } //Member methods of student learning public void study(String className){ System.out.println("I am learning"+className) ; } //smoking public void smoke(String smokeBrand){ System.out.println("Draw"+smokeBrand) ; } } //Test class class StudentTest{ public static void main(String[] args){ //Create student class object Student s = new Student() ; //Assignment setXXX s.setName("Ma Sanqi") ; s.setAge(20) ; s.setGender("male") ; System.out.println("What is the student's name:"+s.getName()+",Age is:"+s.getAge()+",Gender:"+s.getGender()) ; s.study("JavaSE Object oriented") ; s.smoke("Little orange") ; } }
9. Construction method
Construction method concept:
1)The constructor name is consistent with the class name 2)There is no specific return value type 3)even void none
Purpose of construction method:
To initialize some data for members of a class
Precautions for use of construction method:
1)When we write code in a class,No constructor was provided for this class,The system will provide a parameterless construction method by default 2)If we provide any of the parametric construction methods,Then the system will not provide parameterless construction methods proposal:Always give the parameterless construction method of the class
Using code examples
class Phone{ private String brand ; private int price ;//Price private String color ; public Phone(){ } //The construction method with parameters is provided //("hammer phone", 1299, "black" public Phone(String brand,int price ,String color){//local variable this.brand = brand ; this.price = price ; this.color = color ; } //Provide setXXX()/getXXX() methods public void setBrand(String brand){ this.brand = brand ; } public String getBrand(){ return brand ; } //Assign value to price public void setPrice(int price){ this.price = price ; } public int getPrice(){ return price ; } //Assign color public void setColor(String color){ this.color = color ; } public String getColor(){ return color ; } //Other member methods (behavior of mobile things) } //Test class class ConstructorDemo2{ public static void main(String[] args){ //Creating objects by parameterless construction //Method 1: parameterless construction method + setXXX()/getXXX() Phone p = new Phone();// //setXXX() assignment p.setBrand("Smartisan Mobilephone") ; p.setPrice(1299) ; p.setColor("black") ; System.out.println("brand:"+p.getBrand()+",Price:"+p.getPrice()+",colour:"+p.getColor()) ; System.out.println(p) ; System.out.println("---------------------") ; //Method 2: get the content through parameter construction method assignment + combined with getXXX() Phone p2 = new Phone("Smartisan Mobilephone",1299,"black") ; System.out.println("brand:"+p2.getBrand()+",Price:"+p2.getPrice()+",colour:"+p2.getColor()) ; } }
Member method of class
The member method is actually the method we talked about earlier
Specific division of methods:
The returned values are divided into: There are explicit return value methods and returns void Type method According to the form parameters, it is divided into: Nonparametric method and parametric method
Standard writing of a basic class
class
Member variable
Construction method
Nonparametric construction method Structural method with parameters
Member method
getXxx() setXxx()
How to assign values to member variables
Nonparametric construction method+setXxx() Structural method with parameters