03day
1. Cyclic structure
1). While statement
while (conditional expression) { execute statement;} The while statement runs when the condition is met, until the judging condition is not established or a break jumps out of the loop
2). Do While statement
do{ executes the statement;} while (conditional expression)//do While statement runs unconditionally before starting to determine whether the condition is satisfied. If the condition is not satisfied, jump out of circulation
3). For statement
for (initialize expression; loop condition expression; post-loop action expression) { execute statement;} For and while can be interchanged. If you need to define a loop increment, use for is more appropriate. Wireless loop representation for (;;) {} while (1) {}
4). For loop Practice
Class d3printxing //Print shape star type {public static void Main (string[] args) {for (int i=6; i>0;i--) { for (int j=i; j>0;j--) { System.out.print ("*"); } System.out.println ("");}} Class D3chengfabiao //print multiplication table {public static void Main (string[] args) {for (int i=1; i<10;i++) { c15/>for (int j=i; j>0;j--) { System.out.print (i + "*" + j + "="); if (i*j<10) { System.out.print ("0" +i*j); } else{ System.out.print (i*j); } System.out.print (""); } System.out.println ("");}}
2.break and Continue
Break this statement causes the program to terminate the loop that contains it and to proceed to the next stage of the program (the statement following the entire loop), that is, not jumping to the next cycle cycle but exiting the loop. If the break statement is contained within a nested loop, it only jumps out of the innermost loop.
Continue: When the program runs to this statement, it does not execute the following continue in the loop body, but jumps to the next loop to perform the next loop. If the continue statement is contained within a nested loop statement, it affects only the innermost loop that contains it.
3. Functions
A function is a small program of independent pairs that defines a specific function in a class.
The format of the function:
Modifier returns the class value type function name (parameter type parameter 1)
{
Execute the statement;
return value;
}
Return value type: is the data type of the result after the function is run.
Parameter type: is the data type of the formal parameter.
Formal parameters: A variable that is used to store the actual arguments that are passed to the function when the function is called.
Actual parameter: is the specific value of the passed form parameter.
return: Used to end the function.
Return value: The value is returned to the caller.
The main function is a typical function
static void main (string[] args) { System.out.println ("Hello World"); return;}
Overloaded overload of functions
In the same class, it is permissible to have more than one function with the same name, as long as the number of arguments or different types of arguments can have a function overloading relationship.
Features of overloading:
function overloading is independent of the return value type and is related to the parameter list.
4. Arrays
An array is a collection of the same data type.
Defining arrays
element type [] Array name = new element type [element number or array length];
int [] arr = new INT[5];
element type [] Array name = new element type []{element 1, Element 2, ..., element n};
int [] arr = new int[] {21,31,43,52,12,312,431};
Memory structure
When a Java program is running, you need to allocate space in memory. In order to improve the computational efficiency, Java divides the memory space into different regions, because each region has a specific way of handling data and memory management.
Stack memory
For storing local variables, the space occupied by the variable is automatically freed when the data is used.
Heap Memory
Arrays and objects, which are created by means of new, are stored in heap memory. Each instance has a memory address value, the variables in the instance have default initialization values, the instance is no longer used, the space occupied is not automatically freed immediately, but is reclaimed by the Java garbage collector at an indeterminate time.
Method area
Local Method Area
Register
04day
Class D4arraysort//select sort{public static voidMain (string[] args) {int[] array = new int[] {43,656,754,887,112,2,41,512,1131,213,232,323,32,22,3,212,361}; Before sortingPrintArray (array); Selectsort (array,true); After sortingPrintArray (array); Array = new int[] {43,656,754,887,112,2,41,512,1131,213,232,323,32,22,3,212,361}; Before sortingPrintArray (array); Bubblesort (array,true); After sortingPrintArray (array); }//Select sort/* Each trip selects the smallest (or largest) element from the data element to be sorted, placing the order at the end of the ordered sequence until all the data elements to be sorted are exhausted. *///desc sort from large to small, public static int[] Selectsort (int[] Arr,boolean Desc) {System.out.println ("******************* selectsort *********************"); if (arr = = NULL) {returnArr } if(DESC) {for (int i=0;i<arr.length-1;i++) {for (int j=i+1;j<arr.length; j + +) {if (arr[i]<Arr[j]) {swap (ARR,I,J);}} System.out.print ("I ' =" +i+ ""); PrintArray (arr); }} else{for (int i=0;i<arr.length-1;i++) {for (int j=i+1;j<arr.length; j + +) {if (arr[i]>Arr[j]) {swap (ARR,I,J);}} }} returnArr }//Bubble sort/* The bubbling Sort algorithm works as follows: (from backward to forward) compare adjacent elements. If the first one is bigger than the second one, swap them both. Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number. Repeat the above steps for all elements, except for the last one. Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare. */public static int[] Bubblesort (int[] Arr,boolean Desc) {System.out.println ("******************* bubblesort *********************"); if (arr = = NULL) {returnArr } if(DESC) {for (int i=0;i<arr.length-1;i++) {for (int j=0;j<arr.length-i-1; j + +) {if (arr[j]<arr[j+1]) {Swap (arr,j,j+1); }} System.out.print ("I ' =" +i+ ""); PrintArray (arr); }} else{for (int i=0;i<arr.length-1; i++) {for (int j=0;j<arr.length-i-1; j + +) {if (arr[j]>arr[j+1]) {Swap (arr,j,j+1); }}}} returnArr } public static void PrintArray (int[] arr) {for (int i=0;i<arr.length; i++) {if (I < arr.length-1) {System.out.print (arr[i]+ ","); } else{System.out.print (arr[i]);} } System.out.println (""); }//Interchange location public static void swap (int [] arr, int x, inty) {int temp =ARR[X]; ARR[X] =Arr[y]; Arr[y] =Temp }}classd4getarrayindex{public static voidMain (string[] args) {int [] arr =new int[] {1,3,4,6,8,12,15,16,35,67,69,70,92}; int index =-1 ; index = HALFSEARCH2 (arr,16 ); System.out.println ("index=" + index);} Two-point lookup public static int Halfsearch (int[] arr,int key) {int min,mid,max; min = 0 ; max = ARR.LENGTH-1
; Mid = (Min+max)/2
, while (arr[mid]!= key) {if (arr[mid]> key) max = Mid-1 ; else if (arr[mid]<< Span>key) min = mid+1 ; if (min> max) return-1 ; mid= (Min+max)/2 ;} return mid;}//Two points find pub Lic static int halfSearch2 (int[] arr, int key) {int min = 0, max = arr.length-1, mid = 0 ; while (min <=
max) {mid = (Min+max) >> 1
, if (arr[mid]< key) min = mid + 1 ; else if (arr[mid]> key) max = Mid-1 ; else return mid;} return-1 ;}
05day
1. Object-oriented
Object-Oriented is a method of understanding and abstraction of the real world. By object-oriented approach, the real world is abstracted into objects, and the relationship in the real world is abstracted into classes and inheritance, which helps people to realize the abstraction and digital modeling of the real world.
2. The real world and the abstract world
Defining a class is defining the properties and behavior of the class in the process of describing things in the real world.
1) class is the description of things in the real world.
2) The object is this kind of thing, the actual existence of the individual
3) The attribute corresponds to the variable in the class
4) behavior corresponds to a function in a class
3. Relationship and difference between member variables and local variables
1) Scope of action:
Member variables act on the entire class.
A local variable acts in a function, or in a statement.
2) in the memory location:
Member variable: In heap memory, it exists in memory because the object exists.
Local variable: exists in the stack memory.
4. Anonymous objects
An anonymous object is a simplified form of an object.
Anonymous objects Two use cases:
1). When only one tune is made to an object method
2). Anonymous objects can be passed as actual parameters
5. Encapsulation
Encapsulation refers to the properties and implementation details of hidden objects, and provides public access only externally.
Principles of Encapsulation:
Hide content that you don't need to provide externally.
Hides properties, providing public methods for accessing them.
Benefits of Encapsulation:
Isolate changes, ease of use, improve reusability, and improve security.
Class person{ private int age;//private: Private, permission modifier, used to decorate a member of a class. Private is only valid in this class. //The Age attribute is privatized here in order to encapsulate age, only the age property in this class can be modified by the Setage () method. void setage (int age ) { if (age>0 && age<150) { this.age = age ; } } void speak () { System.out.println ("age=" + Age);}} Class persondemo{public static void main (string[] args) {person p = new Person (); P.setage;//p. Setage (-10)//Age error, p.speak ();}}
6. Constructors
Constructor, is a special method. It is used primarily to initialize an object when it is created, to assign an initial value to an object member variable, and to always use the new operator in the statement that creates the object.
Features of the constructor:
1. The function name is the same as the class name.
2. Do not define the return type and do not return.
3. When a constructor is not defined in a class, the system defaults to a constructor that adds an empty argument to the class.
Class person{ private int age ; Private String name; Person () {} default constructor person () { speak (); } Person (String Name,int age ) { this.name = name, Setage (age), speak ();} void Setage (int age ) {if (age>0 && age<150) {this.age = Age ;}} void speak () {System.out.println ("name =" +name+ ", Age = ' + age ';}} Class persondemo{public static void main (string[] args) {person p = new Person (); person P1 = new person ("ha", +);}} /* The difference between a constructor and a general function is run, when the constructor is run as soon as the object is established, and is used to initialize the object and the general method is to execute on the object invocation, which is the function of adding objects to the object. An object is established, and the constructor runs only once. The general method can be invoked by the object any time it is run. */
7. Building Code Blocks
Function: Initializes an object,
The object runs as soon as it is established, and takes precedence over the constructor execution. The initialization content of different object commonalities is defined in the Construction code block.
Differences from constructors:
Constructing a code block is a unified initialization of all objects, and the constructor initializes the corresponding object.
Class person{ private int age ; Private String name; Person () {} default constructor person () { speak (); } Person (String Name,int age ) { this.name = name, Setage (age), speak ();} void Setage (int age ) {if (age>0 && age<150) {this.age = Age ;}} void speak () {System.out.println ("name =" +name+ ", Age = ' + age ';} {SYSTEM.OUT.PRINTLN ("This constructs a block of code, all pairs are run once, and takes precedence over the constructor function!) "); } } Class persondemo{public static void main (string[] args) {person p = new Person (); person P1 = new person ("ha", +);}}
8.this keywords
This is mainly to emphasize the object itself. The popular point is that this represents the current object.
Another usage of this: Call the constructor with this
Class person{ String name; private int age ; Public Person () { System.out.println ("1. Public person () "); Public person (String Name,int- age) {this ();//Call this class without a parameter construction method this.name = name;//this indicates that the current object is This.age = is A;//this Represents the current object System.out.println ("2. Public person (String Name,int age) "); }}
9.static keywords
Usage: is a modifier. Used to decorate members (member variables and member functions).
When a member variable is statically decorated, it can be called directly by the class name, in addition to being called by the object. (class name. Static member)
The characteristics of static:
1. As the class loads, the declaration period is the longest as the class disappears.
2. Precedence over object existence
3. Shared by all objects
4. Can be called directly by the class name
The difference between an instance variable and a class variable
1. Storage location
Class variables exist in the method area as the class is loaded
Instance variables exist in heap memory as objects are established
2. Life cycle
The class variable life cycle is the longest.
Instance variables disappear as the object disappears
Considerations for static use
1. Static methods can only access static members
Non-static and static methods can be accessed
2. This, super and other keywords cannot be used in a static method
Because static takes precedence over the existence of an object, the This keyword does not appear in a static method
Static has pros and cons
Benefit: Save space by storing the shared data of an object in a separate space. There is no need to have a copy of an object. Can be called directly by the class name
Cons: The life cycle is too long and access is limited.
Classperson{private intAge PrivateString name; private static String country = "the World"; Person () {} default constructorPerson () {speak (); } person (String Name,intAge ) {this.name = name; Setage (age), speak ();} void Setage (int age ) {if (age>0 && age<150) {THIS.A GE = Age ;}} void speak () {System.out.println ("My Name is" +name+ ", I ' m" +age+ ".") ); } {this.country = "CN";} static void SayHello () {System.out.println ("hi,i am from" +country); System.out.println ("My Name is" +name+ ", I ' m" +age+ "."); The error static method cannot call a non-static member }}class persondemo{public static void main (string[] args) {Person.sayhello ();//class name. static Method (), because the static code block runs over the code block, so nationality is still the world. Person p = new Person (); P.sayhello (); person P1 = new Person ("Li", +);}} /* Run result F:\java\code>java persondemohi,i am from the worldmy name IsNull, I ' m 0.hi,i am from cnmy name Isli, I ' M 30. When does the Use static variables? When shared data appears in an object, the data uses static adornments. When to use static functions The function can be defined as static when no non-static data is accessed inside the function. */
10 main function
public static void Main (string[] args)
Main function: is a special function, is the entry of the program, can be called by the JVM.
The meaning of the main function:
Public: Represents the largest of the function's access rights.
Static: Represents the main function that already exists as the class loads.
void: Indicates that the main function has no return value.
Main: Not a keyword, but a special word that can be used to identify the JVM
(string[] args): The parameter of the main function, which is an array of strings.
The JVM is calling the main function, which is the new string[0];
11. The privatization of the constructor can prevent the class from being instantiated
public class A{private A () {};} Class Ademo{a a = new A ();//Compile Failed}
12. Format the description document (public class only)
javadoc-d Generate directory-author-version class name. java
eg. javadoc-d c:\-author-version D1.java
13. Static code block
Format:
Static
{
Execution prediction in a static code block
}
Feature: Executes as the class is loaded and executes only once for initialization of the class. A non-static member cannot be called within a method.
Classperson{private intAge PrivateString name; private static String country = "the World"; Person () {} default constructor//private person () {}//Privatization constructor prevents objects of this class from being establishedPerson () {speak (); } person (String Name,intAge ) {this.name = name; Setage (age), speak ();} void Setage (int age ) {if (age>0 && age<150) {THIS.A GE = Age ;}} void speak () {System.out.println ("My Name is" +name+ ", I ' m" +age+ ".") ); } static void SayHello () {System.out.println ("hi,i am from" +country); Speak (); The error static method cannot call a non-static member } {this.country = "CN";} static {country = "China";//Static code block takes precedence over code block execution//speak ();/error code block does not Can call non-static member }}class persondemo{public static void main (string[] args) {Person.sayhello ();//class name. static method (), because precedence To the code block, so nationality is "China". Person p = new Person (); P.sayhello (); person P1 = new Person ("Li", +);}} /* Run result F:\java\code>java persondemohi,i am from Chinamy name IsNull, I ' m 0.hi,i am from cnmy name Isli, I ' M 30.*/ /c16>
14. Single-Case mode
Steps:
1. Privatize the constructor
2. Create an object of this class in a class
3. Provides a way to get to the object
/* A hungry man recommend using */classd6single{PrivateD6single () {}; private static D6single s = newD6single (); public staticD6single getinstance () {returnS } private int num =0; public intGetnum () {returnNum } public void Setnum (intnum) {this.num =Num }}classd6singledemo{public static voidMain (string[] args) {D6single s =d6single.getinstance (); S.setnum (+); D6single S1 = d6single.getinstance (); System.out.println (S1.getnum ()); }}/* lazy Try inefficient */class d6single2{private static D6single2 single2 = null; private D6single2 () {};//Synchronize public STA Tic d6single2 GetInstance2 () {if (Single2 = = null) {//double-judge synchronized (D6single2.class) {if (Single2 = = Nu ll) Single2 = new d6single2 ();}} return Single2;} private int num =0, publicint Getnum () {return num,} public void Setnum (int num) {this.num = num;}} Class d6singledemo2{public static void main (string[] args) {d6single2 S1 = d6single2.getinstance2 (); s1.s Etnum (+); D6single2 s2 = d6single2.getinstance2 (); System.out.println (S2.getnum ()); }}
Java Learning-Next day