Java learning notes 1

1, What is a computer

  1. It is widely used in scientific computing, data processing, automatic control, computer aided design, artificial intelligence and network fields
  2. It consists of hardware and software

2, Computer hardware

Composition of computer hardware: CPU, memory, motherboard, IO device and graphics card

3, Von Neumann architecture

  • Von Neumann
  • Turing

4, Computer software

1. System software: DOS, Linux, Windows, Android, iOS

2. Application software: WPS, QQ, wechat, hero alliance, Jedi survival

5, The history of computer language

Easier and stronger

First generation language

  • machine language

Second generation language

  • assembly language
    • Instruction instead of binary
    • Solve the problem that human beings cannot understand machine language
  • Current application
    • reverse engineering
    • robot
    • virus

Third generation language

  • Moore's law
  • When the price remains unchanged, the number of transistors that can be accommodated on the integrated circuit will double every 18 months, and the performance will also double. In other words, the computer performance that can be bought for every dollar will more than double every 18 months
  • high-level language
  • Generally, it can be divided into two categories: process oriented and object-oriented
  • C language is a typical process oriented language. Java and C + + are typical object-oriented languages
  • Various programming languages
    • C language: the ancestor of high-level language
    • C + + language
    • Java language: server development
    • C# language
    • Python
    • PHP

6, First acquaintance with Java

The birth of the Java Empire

C & C++

  • C language was born in 1972
    • Close to hardware, running very fast and selling very high
    • Operating system, compiler, database, network system
    • Pointer and memory management
  • C + + was born in 1982
    • object-oriented
    • Compatible with C
    • Graphics, games, etc

Java born

  • Java 2 Standard Edition (J2SE): to occupy the desktop
  • Java 2 Mobile (J2ME): to occupy the mobile phone
  • Java 2 Enterprise Edition (J2EE): to occupy the server

Java development

  • They have developed a huge number of platform systems and tools based on Java
    • Build tools: Ant, maven, Jekins
    • Application servers: Tomcat, Jetty, Jboos, Websphere, weblogic
    • Web development: Struts, Sprig, myBatis
    • Development tools: Eclipse, IDEA
  • 2006: Hadoop (big data field)
  • 2008: Android (mobile)
  • A great empire was born

java features and advantages

  • Simplicity
  • object-oriented
  • Portability
  • High performance
  • Distributed
  • Dynamics: reflection mechanism
  • Multithreading: interactivity and real-time
  • Security
  • Robustness

7, Three versions of Java

  • JavaSE Standard Edition: desktop applications
  • JavaME embedded development: mobile phones and small household appliances
  • Java EE Enterprise Edition: server, web

8, JDK, JRE, JVM

  • JDK: Java Development Kit Java developer tool, including JRE and JVM
  • JRE: Java runtime environment, which contains the JVM
  • JVM: Java virtual machine

Detailed introduction of JDK, JRE and JVM

9, Construction of Java development environment

  • JDK download and installation
  • Configure environment variables
  • JDK directory introduction
  • Helloworld and simple grammar rules
  • Notepad + + installation and use

JDK installation and environment variable configuration

10, java program running mechanism

  • Compiled: develop operating systems such as C or C++
  • Interpretive: Web pages and servers interpret while executing, which does not require high speed

Understanding: if Americans read books written by Chinese, the first way can be translated into an English version, and the second way can find a translator to translate and read them over and over again. The compiled version is equivalent to the first method, which is to translate this book directly into English. It will have a program responsible for translation, which is called the compiler; Interpretive is equivalent to the second way.

  • Operation mechanism of program

11, Installation of IDEA

Installation and rotation steps of idea

What is IDE?

IDEA is an IDE, known as one of the best Java development tools.

12, Java basic syntax

  1. Comments, identifiers, keywords
  2. data type
  3. Type conversion
  4. Variable, constant
  5. operator
  6. Package mechanism, JavaDoc

1. Notes

Comments are not executed. They are read by the person who writes the code

  • There are three types of Java annotations:

    • Single line note://
    • Multiline comment:
    • Document notes:
    public class HelloWorld {
        public static void main(String[] args) {
            //Single line annotation: only one line of text can be annotated
            //Output a hello
            System.out.println("hello");
            /*
            multiline comment 
            I am a multiline annotation, which can annotate a paragraph of text
             */
            /**
             * Document comments, you can add something
             * @Author Chao Yongzheng
             */
        }
    }
    
    

2. Identifier

  • keyword

Note: String is not a keyword, it is a class.

Keyword details

  • All components of Java need names. Class names, variable names, and method names are all called identifiers.

Considerations for identifiers

  • All identifiers should be in letters (A-Z or a-z), dollar sign ($), or underscore () You cannot start with a number
  • The initial letter can be followed by a letter (A-Z or a-z), dollar sign ($), or underscore () Or any combination of characters
  • Keywords cannot be used as variable or method names
  • Identifiers are case sensitive
  • It can be named in Chinese, but it is generally not recommended to do so or use pinyin. It is very low
String Glory of Kings="Hundred star king";//There's nothing wrong. It's right

3. Data type

  • Strongly typed language
    • It is required that the use of variables should strictly comply with the regulations, and all variables must be defined before they can be used
  • Weakly typed language
  • Java data types fall into two categories
    • Basic type
    • Reference type: except for the eight basic types, they are all reference types, such as class, interface and array

Eight data types of Java

 //Integer extension: binary 0b decimal octal 0 hexadecimal 0x 0~9 A~F
        int i = 10;//Decimal 1 * 10 power + 0 * 10 power
        int i2 = 010;//Octal 1 * 8 power + 0 * 8 power
        int i3 = 0x10;//Hexadecimal 1 * 16 power + 0 * 16 power
        System.out.println(i);
        System.out.println(i2);
        System.out.println(i3);
        System.out.println("================================================");
        //How to express floating point extended banking business? Cannot compare with float
        // BigDecimal math tool class
        //float finite discrete rounding error is approximately close to but not equal to
        //double
        //It is best not to use floating point numbers for comparison
        float f = 0.1f;//Float type
        double d = 1.0/10;//double type
        System.out.println(f);
        System.out.println(d);
        System.out.println(f==d);//false
        float d1=231121316f;
        float d2 = d1+1;
        System.out.println(d1==d2);//true

Output results:

4. What are bytes

  • Bit: it is the smallest unit of data storage in the computer. 11001100 is an eight bit binary number.
  • Byte: it is the basic unit of data processing in the computer. It is customarily expressed in capital B
  • 1B(byte) = 8bit (bit)
  • Characters: letters, numbers, words and symbols used in computers.

Byte introduction

5. Type conversion

  • Because Java is a strongly typed language, type conversion is required for some operations
    • byte,short,char - > int - > long - > float - > double (from low to high)
  • In the operation, different types of data are converted to the same type first, and then the operation is carried out
  • Cast: (type) variable name high to low
  • Automatic type conversion: low to high
public class Demo05 {
    public static void main(String[] args) {
        int i = 128;
        byte b = (byte)i;//Because the maximum byte is 127, a memory overflow will occur below
        System.out.println(i);
        System.out.println(b);
        double d = i;//Automatic conversion
        System.out.println(d);
        System.out.println((int)23.7);
        System.out.println((int)-45.1);
        /**
         * Note:
         *     1.Boolean types cannot be converted
         *     2.You can't convert an object type into an irrelevant type, such as a person into a pig, but you can convert a man into a woman because they are all human
         *     3.When converting from high capacity to low capacity
         *     4.There may be memory overflow or precision problems during conversion
         */
    }
}

Operation results:

public class Demo06 {
    public static void main(String[] args) {
        //Pay attention to overflow when operating large numbers
        //JDK7's new feature, numbers can be separated by underscores
        int money = 10_0000_0000;
        int years = 20;
        int total = money*years;//The calculation has overflowed
        System.out.println(total);
        long total2 = money*years;//The default is int, because money*years is the int type, which has overflowed here, and the conversion is the result of the overflow of the conversion
        System.out.println(total2);
        long total3 = money*(long)years;//First convert a data to a long type
        System.out.println(total3);

    }
}

Operation results:

6. Variable

  • What is a variable: a variable is a variable
  • Java is a strongly typed language, and each variable must declare its type.
  • Java variable is the most basic storage unit in a program. Its elements include variable name, variable type and scope
  • matters needing attention
    • Each variable has a type, which can be a basic type or a reference type
    • Variable names must all be legal identifiers
    • Variable declarations must be a complete statement, so each declaration must end with a semicolon

7. Scope of variable:

  • Class variable

  • Instance variable

  • local variable

    public class Demo07 {
        //Attributes: Variables
        //Instance variable: subordinate to object; Calling through class without initialization will become the default value of this type, except for the eight basic types
        //The default values are null
        String name;
        int age;
        //Class variable
        static int salary = 25000;
        //main method 
        public static void main(String[] args) {
            //Local variables; Must declare and initialize values, valid only in this method body
            int i = 1;
            System.out.println(i);
            Demo07 demo07= new Demo07();
            demo07.name="cyz";
            System.out.println("name="+demo07.name+"\n"+"age="+demo07.age);
            System.out.println(salary);
    
        }
        //Other methods
        public void add(){
    
        }
    }
    
    

8. Constant

  • Constant: the value cannot be changed after initialization! Value that will not change.

  • The so-called constant can be understood as a special variable. After its value is set, it is not allowed to be changed during the operation of the program

    public class Demo09 {
        //The output of the following two statements is the same
        //static final is a modifier, independent of position
        static final double PI =3.14;
    //    final static double PI =3.14
        public static void main(String[] args) {
            System.out.println(PI);
        }
    }
    
    
  • Constants are usually in uppercase characters

9. Naming conventions for variables

  • All variables, methods and class names: see the meaning of the name
  • Class member variables: initial lowercase and hump principle, and other initial uppercase except the first word
    • Example: monthSalary, lastName
  • Local variables: initial lowercase and hump principle
  • Constants: uppercase letters and underscores
    • Example: PI_MAX
  • Class name initials metabolism and hump principle
  • Method name: initial lowercase and hump principle
    • Example: run()

10. Operator

  • Java supports the following operators

    • Arithmetic operators: +, -, *, /,% (remainder or module operation), + +, –

      long a =23421125152l;
              int b = 132;
              short c = 10;
              byte d =8;
              System.out.println(a+b+c+d);//long
              System.out.println(b+c+d);//int
              System.out.println(c+d);//int
              /**
               * Operations with long are long, and the rest are int
               */
      //++-- self increasing and self decreasing
              int a =3;
              System.out.println(a);
              int b =a++;//A + + a = a + 1 A + + executes + 1 only after executing this line of code, that is, it executes + 1 only after assigning a value to b
      
              System.out.println(b);
              int c =++a;//A + + a = a + 1 + + a executes + 1 before executing this line of code, that is, before assigning a value to c
              System.out.println(c);
      	    //Power operation 2 ^ 3 2 * 2 * 2 = 8 many operations we will use tool classes to calculate
              double pow =Math.pow(2,3);
              System.out.println(pow);	
      
    • Assignment operator:=

    • Relational operators: >, <, > =, < =, = =,! = instanceof

      • The result returned by the relational operator: true or false returns a Boolean value
    • Logical operators: & & (and), | (or)! (non)

      //And (and) or (or) not (negative)
              boolean a = true;
              boolean b =false;
              System.out.println("a&&b===="+(a&&b));//Logic and operation, both variables are true, and the result is true
              System.out.println("a||b===="+(a||b));//If one of the logical or operations is true, the result is true
              System.out.println("!(a&&b)===="+!(a&&b));//Logical non operation, if true, becomes false, if true, becomes false
              //Short circuit operation
              int c = 5;
              boolean d =(c<4)&&(c++<4);//Because c < 4 is false, it returns false directly instead of c + + < 4, so c will not increase automatically
              System.out.println(d);
              System.out.println(c);//c is still 4, because there is a short circuit in the previous step and the operation of c + + is not executed
      
      
    • Bitwise operators: &, |, ^, ~, > >, < <, < < < (understand)

    /**Bit operation
    * A = 0011 1100
    * B = 0000 1101
    * A&B = 0011 1101
    * A|B = 0000 1100
    * A^B = 0011 0001
    * ~B = 1111 1110
    * 28 = 16 2222
    *< shift left is equivalent to * 2
    *> > shift right is equivalent to / 2
    * 0000 0000 0
    * 0000 0001 1
    * 0000 0010 2
    * 0000 0100 4
    * 0000 1000 8
    * 0001 0000 16
    *Extremely efficient
    */
    System. out. println(2<<3);// The result is 16

    
    
    - Conditional operators::
    
    ~~~java
    //+: string connector
            //As long as one party is a string, the result is a string
            int a =10;
            int b =20;
            System.out.println("string"+a+b);//The result is string1020
            System.out.println(a+b+"string");//The result is 30string
            //The above two outputs are of type String
     		/**
             * Ternary operator
             * x ? y : z
             * If x is true, the result is y. if x is false, the result is z
             * Must master
             */
            System.out.println(80<60?"fail,":"pass");//Output pass
    
    • Extended assignment operators: + =, - =, * =/=

    Priority of Java operator:

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-NxGNFaY9-1642581512908)(C:/Users / Chao Yongzheng / appdata / roaming / typora / typora user images / image-20210416214752927. PNG)]

11. Package mechanism

The essence is the folder equivalent to Windows

  • In order to better organize classes, Java provides a package mechanism to distinguish the namespace of class names

  • The syntax format of the package mechanism is

    package pkg1[.pkg2...]
    
  • Generally, the company's domain name is used as the package name

  • In order to use the members of a package, we need to explicitly import the package in the Java program. This can be done using the import statement

    import packge1[.packge2...].(classname|*);//*Represents a wildcard, which guides all classes in the package
    

12,JavaDoc

  • The javadoc command is used to generate its own API documents

  • parameter information

    • @autor author name

    • @Version version number

    • @since fatal indicates that the earliest JDK version is required

    • @param parameter name

    • Return return value

    • throws exception thrown

13, java process control

1. User interaction Scanner

Get the user's input through the Scanner class

Basic syntax:

Scanner s = new Scanner(System.in)
  • Get the input string through the next() and nextLine() methods of the Scanner class. Before reading, we generally need to use hasNext() and hasNextLine() to determine whether there is any input data
package com.wwm.Scanner;

import java.util.Scanner;

public class Demo01 {
    public static void main(String[] args) {

        //Create a scan object, system In is used to receive data
        Scanner scanner = new Scanner(System.in);
        System.out.println("use next Method receiving:");

        //Judge whether the user has entered a string
        if (scanner.hasNext()){
            //Receive using the next method
            String str = scanner.next();  //The program waits for user input
            System.out.println("The input content is:"+str);
        }

        //All classes belonging to the IO stream will always occupy resources if they are not closed. Make a good habit of closing them when they are used up
        //I / O stream
        scanner.close();
    }
}
/*
Enter hello world
 Output hello
*/

package com.wwm.Scanner;

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("use nextLine Method reception:");

        if(scanner.hasNextLine()){
            String str  = scanner.nextLine();
            System.out.println("The output contents are:"+str);
        }

        scanner.close();
    }
}
/*
Enter hello world
 Output hello world
*/

next():
Be sure to read valid characters before you can end the input
The next () method will automatically remove the blank space encountered before entering valid characters
Only after entering a valid character will the blank space entered after it be used as a separator or terminator
==next() = = you cannot get a string with spaces
nextLine():
End with enter, that is, the nextLine () method returns all characters before entering the Enter key
Can get blank

package com.wwm.Scanner;

import java.util.Scanner;

public class Demo03 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter data:");

        String str = scanner.nextLine();

        System.out.println("The input content is:"+str);

        scanner.close();
    }
}
/*
  Input: welcome to learn Crazy God said java. Welcome to offline learning
  Output: welcome to learning crazy God said java, welcome to offline learning
*/
package com.wwm.Scanner;

import java.util.Scanner;

public class Demo04 {
    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... So....
        if (scanner.hasNextInt()){
            i = scanner.nextInt();
            System.out.println("Integer data:"+ i );
        }else{
            System.out.println("The input is not integer data!");
        }

        System.out.println("Please enter decimal:");

        if (scanner.hasNextFloat()){
            f = scanner.nextFloat();
            System.out.println("Decimal data:"+f);
        }else{
            System.out.println("The input is not decimal data!");
        }

        scanner.close();
    }
}

package com.wwm.Scanner;

import java.util.Scanner;

public class Demo05 {
    public static void main(String[] args) {
        //We can enter multiple numbers and find the sum and average of them. Press enter to confirm each number. Enter a non number to end the input and output the execution result:

        Scanner scanner = new Scanner(System.in);

        //and
        double sum = 0;
        //Calculate how many numbers are entered
        int m = 0;

        //Judge whether there is any input through circulation, and sum and count each time in it
        while(scanner.hasNextDouble()){
            double x = scanner.nextDouble();
            m = m+1;//m++
            sum = sum + x;
            System.out.println("You entered"+m+"Data, current result sum"+sum);
        }

        System.out.println(m + "The sum of the numbers is" + sum);
        System.out.println(m + "The average number is"  + (sum / m));

        scanner.close();
    }
}

2. Sequential structure (basic structure of java)

  • The basic structure of java is sequential structure. Unless otherwise specified, it should be executed sentence by sentence in order.
  • Sequential structure is the simplest algorithm structure
  • Statements are carried out in order from top to bottom. It is composed of several processing steps executed at one time. It is a basic algorithm structure that any algorithm cannot be separated from
package com.wwm.struct;

public class ShunXu {
    public static void main(String[] args){
        System.out.println("hello1");
        System.out.println("hello2");
        System.out.println("hello3");
        System.out.println("hello4");
    }
}


3. if selection structure

1. if single selection structure:

if (Boolean expression){

//Operation

}

package com.wwm.struct;

import java.util.Scanner;

public class ifDemo01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter:");
        String s = scanner.nextLine();

        //equals: determines whether the strings are equal
        if(s.equals("Hello")){
            System.out.println(s);
        }
        System.out.println("End");


        scanner.close();
    }
}

2. if double selection structure:

Syntax:

If (Boolean expression){

//If the value of the expression is true

}else{

//If the value of the Boolean expression is false

}

package com.wwm.struct;

import java.util.Scanner;

public class ifDemo02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        //Pass the exam with a score of more than 60

        System.out.println("Please enter your grade:");

        int score = scanner.nextInt();

        if(score>60){
            System.out.println("pass");
        }else{
            System.out.println("fail,");
        }
        scanner.close();
    }
}

3. if multiple selection structure

if (Boolean expression 1){

/ / statement to be executed if Boolean expression 1 is true

}else if (Boolean expression 2){

/ / statement to be executed if Boolean expression 2 is true

}else if (Boolean expression 2){

 //Statement to execute if Boolean expression 3 is true

}else{

/ / statement to be executed if all Boolean expressions are false

}

package com.wwm.struct;

import java.util.Scanner;

public class IfDemo03 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter your grade:");
        int score = scanner.nextInt();

        if(score==100){
            System.out.println("Congratulations, full marks!");
        }else if(score<100 && score>=90){
            System.out.println("A level");
        }else if(score<90 && score>=80){
            System.out.println("B level");
        }else if(score<80 && score>=70){
            System.out.println("C level");
        }else if(score<70 && score>=60){
            System.out.println("D level");
        }else if(score<60 && score>=0){
            System.out.println("fail,");
        }else{
            System.out.println("The input data is illegal!");
        }


        scanner.close();
    }
}

Note:

  • An IF statement can have at most one else statement, which follows all else if statements

  • An IF statement can have several elae if statements, which must precede the else statement

    Once one else if statement is detected as true, the other else if and else statements will skip execution

4. Nested if statements

Syntax:

if (Boolean expression 1){

//If the value of Boolean expression 1 is true, execute the code

if (Boolean expression 2){

//If the value of Boolean expression 2 is true, execute the code

}

5. switch multiple selection structure

The switch case statement determines whether a variable is equal to a value in a series of values. Each value is called a branch

switch(expression){
  case value1:
    //case
    break;//Not writing will output all the following (case penetration)
  case valuse2:
    //case
    break;
  default://Optional
    //default case
}

The variable types in the switch statement can be:

  • byte, short, int, or char
  • Start with java SE 7
  • switch supports String type
  • At the same time, the case tag must be a string constant or literal
package com.wwm.struct;

public class SwitchDeom01 {
    public static void main(String[] args) {
        //
        char grade = 'C';

        switch (grade){
            case 'A':
                System.out.println("excellent");
                break;  // Optional. If there is no break, the statement will continue to be executed. This phenomenon is case penetration
            case 'B':
                System.out.println("good");
                break;
            case 'C':
                System.out.println("pass");
                break;
            case 'D':
                System.out.println("make persistent efforts");
                break;
            case 'E':
                System.out.println("fail");
                break;
            default:
                System.out.println("Data error!");
        }
    }
}

package com.wwm.struct;

public class SwitchDemo02 {
    public static void main(String[] args) {
        String name = "Qin Jiang";
		//Only after jdk7
        switch (name){
            case "Qin Jiang":
                System.out.println("Qin Jiang");
                break;
            case "Mad God":
                System.out.println("Mad God");
                break;
            default:
                System.out.println("What kind!");
        }
    }
}

  • The essence of characters is still numbers
  • Decompile java - class (bytecode file) -- decompile (IDEA)

4. Cyclic structure

1. while loop

while (Boolean expression){

/ / loop content

}

As long as the Boolean expression is true, the loop will continue to execute
In most cases, we will stop the loop. We need a way to invalidate the expression to end the loop
In a few cases, the loop needs to be executed all the time, such as the request response listening of the server
If the loop condition is always true, it will cause infinite loop [dead loop]. We should try our best to avoid dead loop in normal business programming, which will affect the program performance or cause the program to get stuck and crash

package com.wwm.struct;

public class WhileDemo01 {
    public static void main(String[] args) {

        //Output 1 ~ 100

        int i = 0;

        while(i<100){
            i++;
            System.out.println(i);
        }

    }
}

package com.wwm.struct;

public class WhileDemo03 {
    public static void main(String[] args) {
        //Calculate 1 + 2 + 3 + + 100 =?

        //Gauss's story

        int i = 0;
        int sum = 0;

        while(i<100){
            i++;
            sum = sum +i;
        }
        System.out.println(sum);
    }
}

2. do ··· while loop

For the while statement, if the condition is not met, it cannot enter the loop. But sometimes we need even if the conditions are not met. Also at least once
The do ··· while loop is similar to the while loop, except that the do ·· while loop is executed at least once
do{
//Code statement

}while (Boolean expression);

Differences between while and do while:

While is to judge before execution, and do while is to execute before judgment
Do while always ensures that the loop will be executed at least once, which is their main difference

3. for loop

  • Although all loop structures can be represented by while or do... While, java provides another language - for loop, which makes some loop structures simpler

  • for loop is a general language that supports iteration. It is the most effective and flexible loop structure

100.for can quickly form a for loop structure

for(initialization; Boolean expression; (Updated){

//Code statement

}

~~~java
package com.wwm.struct;

public class ForDemo01 {
  public static void main(String[] args) {
      int a = 1;   //Initialization condition

      while(a<=100){  //Conditional judgment
          System.out.println(a);  //Circulatory body
          a+=2;   //iteration
      }

      System.out.println("while End of cycle!");

      //Initialization value condition judgment iteration
      for(int i = 1;i<=100;i++){
          System.out.println(i);
      }
//        100.for can quickly form a for loop structure
//        for (int j = 0; j < 100; j++) {
//
//        }


      System.out.println("for End of cycle");
  }
}

Note:

The initialization step is performed first. You can declare a type, but you can initialize one or more loop control variables or empty statements
Then, check the value of the Boolean expression. If it is true, the loop body is executed. How to be false, the loop terminates, and start executing the statements behind the loop body
After a loop is executed, the loop variable is updated (the iteration factor controls the increase or decrease of the loop variable)
Check the Boolean expression again and loop through the above procedure

Remove the three steps respectively: but the variables need to be initialized in advance

for (; a < 3; a++) {
            System.out.println(a);
        }
for (; true; b++) {
            if (b >= 3) {//Jump out of loop if conditions are met
                break;
            }
for (; true;) {
            if (c >= 3) {//Jump out of loop if conditions are met
                break;
            }

package com.wwm.struct;

/**
* Calculates the sum of odd and even numbers between 0 and 100
*/
public class ForDemoQuestion01 {
   public static void main(String[] args) {
       int a = 0;
       int sum1 = 0;
       int sum2 = 0;

       for(;a<=100;a++){
           if(a==1){
               sum2 = sum2 +1;
           }else{
               if(a%2==0){
                   sum1 = sum1+a;
               }else{
                   sum2 = sum2+a;
               }
           }
       }
       System.out.println("Even sum is"+sum1);
       System.out.println("Odd sum"+sum2);
   }
}

package com.wwm.struct;

public class ForDemoQuestion02 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        for(;a<=1000;a++){
            if(a>=5){
                if(a%5==0){
                    b++;
                    if(b==3){
                        System.out.println(a+" ");
                        b=0;
                    }else{
                        System.out.print(a+" ");
                    }
                }
            }
        }
    }
}

package com.wwm.struct;
/**
Print 99 multiplication table
*/
public class ForDemoQuestion03 {
    public static void main(String[] args) {
        //1. Let's print the first column first
        //2. We wrap the fixed 1 in another cycle
        //3. Remove duplicates
        //4. Adjust style

        for (int j = 1; j <= 9; j++) {
            for (int i = 1; i <=j;i++) {
                System.out.print(j+"*"+i+"="+(j*i)+"\t");
            }
            System.out.println();
        }
    }
}

4. Enhanced for loop

After array, focus on using

Java 5 introduces an enhanced for loop that is primarily used for arrays or collections

java enhanced for loop syntax format:

For (declaration statement: expression){
//Code sentence

}

Declaration statement: declare a new local variable. The type of the variable must match the type of the array element. Its scope is limited to the circular statement block, and its value is equal to the value of the array element at this time

Expression: an expression is the name of the array to be accessed, or a method whose return value is an array

package com.wwm.struct;

public class ForDemo05 {
    public static void main(String[] args) {
        int[] numbers = {10,20,30,40,50};  //An array is defined

        for(int i = 0;i<5;i++){
            System.out.println(numbers[i]);
        }
        System.out.println("=========================");


        //Traverse array elements
        for(int x:numbers){
            System.out.println(x);
        }
    }
}

5,break continue

Break in the body of any loop statement, you can use break to control the flow of the loop. Break is used to forcibly exit the loop without executing the remaining statements in the loop. (break statement can also be used in switch statement)

The continue statement is used in the body of a loop statement to terminate a loop process, that is, skip the statements that have not been executed in the loop body, and then determine whether to execute the loop next time

About goto keyword

Goto keyword appeared in programming language for a long time. Although goto is still a reserved word of java, it has not been officially used in the language; java has no goto. However, in the two keywords break and continue, we can still see some shadow of goto - labeled break and continue

	A label is a marker followed by a colon, for example: label
	yes java For example, the only place where labels are used is before the loop statement. The only reason to set the label before the loop is that we want to nest another loop in it, because break and continue Keywords usually only interrupt the current circular list. If they are used with the tag, they will interrupt to the place where the tag exists.

Break in the main part of any loop statement, you can use break to control the flow of the loop

Break is used to forcibly exit the loop without executing the remaining statements in the loop (break statements are also used in switch statements)

The continue statement is used in the body of a loop statement to terminate a loop process, that is, skip the statements that have not been executed in the loop body, and then determine whether to execute the loop next time

After array, focus on using

Java 5 introduces an enhanced for loop that is primarily used for arrays or collections

java enhanced for loop syntax format:

For (declaration statement: expression){
//Code sentence

}

Declaration statement: declare a new local variable. The type of the variable must match the type of the array element. Its scope is limited to the circular statement block, and its value is equal to the value of the array element at this time

Expression: an expression is the name of the array to be accessed, or a method whose return value is an array

package com.wwm.struct;

public class ForDemo05 {
    public static void main(String[] args) {
        int[] numbers = {10,20,30,40,50};  //An array is defined

        for(int i = 0;i<5;i++){
            System.out.println(numbers[i]);
        }
        System.out.println("=========================");


        //Traverse array elements
        for(int x:numbers){
            System.out.println(x);
        }
    }
}

5,break continue

Break in the body of any loop statement, you can use break to control the flow of the loop. Break is used to forcibly exit the loop without executing the remaining statements in the loop. (break statement can also be used in switch statement)

The continue statement is used in the body of a loop statement to terminate a loop process, that is, skip the statements that have not been executed in the loop body, and then determine whether to execute the loop next time

About goto keyword

Goto keyword appeared in programming language for a long time. Although goto is still a reserved word of java, it has not been officially used in the language; java has no goto. However, in the two keywords break and continue, we can still see some shadow of goto - labeled break and continue

	A label is a marker followed by a colon, for example: label
	yes java For example, the only place where labels are used is before the loop statement. The only reason to set the label before the loop is that we want to nest another loop in it, because break and continue Keywords usually only interrupt the current circular list. If they are used with the tag, they will interrupt to the place where the tag exists.

Break in the body of any loop statement, you can use break to control the flow of the loop

Break is used to forcibly exit the loop without executing the remaining statements in the loop (break statements are also used in switch statements)

The continue statement is used in the body of a loop statement to terminate a loop process, that is, skip the statements that have not been executed in the loop body, and then determine whether to execute the loop next time

Keywords: Java Back-end

Added by Buchead on Sun, 23 Jan 2022 17:49:07 +0200