Learn the basics of Java

What I bring you today is the basic knowledge of Java, including the basic syntax of Java, such as Java, variables, constants, data types, operators, various selection structures, loop structures, arrays, etc!!! The content and steps are super detailed, with source code of various cases (you can directly use O(∩)_ ∩)O~)!!! After reading it carefully, a solid foundation is no longer empty talk. When you have a solid basic knowledge and later learn object-oriented and project development, the pressure will be reduced a lot, so the basic knowledge can not be easily ignored.

1, Getting to know Java

Steps for developing the program using Notepad (Note: the whole operation process is in English):

1. Write source program

First, create a new text file, change its suffix to ". java" ---- > and then write the code we need

  public  class  HelloWorld{

    public  static  void main(string[] args){

       system.out.println("Hello  kh87");



Public: public, accessible everywhere.

Class: class, category, similar to dog, computer, etc.

HelloWorld: class name, there is a requirement, which must be consistent with the file name

public static void main(String[] args) {} ----- > >

static: keyword (we can't use the name already used in the computer)

Void: return value type, void means no return value

main: is the method name of the entry method

Error prone:

① Braces should appear in pairs

② "s" in String should be capitalized

③ We need to end each sentence with a semicolon in English

④ 's' in System needs to be capitalized

⑤ Class name needs to be consistent with file name

All output content needs to be in quotation marks

2. Compile source program

Because we write it, but the computer can't understand it, we need a "translation" to compile it into a ". Class" end file (semi machine language). In the dos command, enter the directory where the file is located, and enter the command javac xxx.java Class compilation also generates a bytecode file ending in "class"

3. Operation

After the compilation is successful, you can run it. Just enter java xxx. In the console, you can see the contents in double quotation marks in the print statement (all the contents to be printed need to be in double quotation marks)


Meaning of symbols:

\t: A tab space

\n: Move to the next line


Role of notes:
Explanation, will not be compiled and run
Single line comment://
Multiline comment: / **/
Document notes: / * **/

2, Variables, constants, data types, and operators

1. Variables

1.1 definition:

A representation of storage space whose value can be changed. (for example, if you buy a pair of shoes, the shoe box is used to hatch chickens. The shoe box is the variable, and shoes and chickens are the values inside.)

Through the variable name can easily and quickly find the data it stores!!!

1.2 operation steps:

Step 1: declare variables (variable name cannot be duplicate when declaring variables)

That is, according to the data type, space is applied for in memory

Data type variable name; int money; (int is data type, money is variable name)


Step 2: assignment

Store the data in the corresponding memory space

Variable name = value; money=1000;


The above two steps can be combined into one

int money =1000, which means: a space of type int is opened in memory, named money and assigned 1000;

Step 3: use

Take out the data

be careful:

Variable name cannot be duplicate when declaring variable

When "+" is used in the program, if there is a string on the left and right sides of the symbol, the two values will be spliced (if there are multiple "+" after it, the multiple values will be spliced); if both are numerical, the sum of

1.3 naming rules

1. Consists of numbers, letters, underscores, and $symbols, which cannot begin with a number

2. Cannot have the same name as the keyword in java

3. Try to follow the rules of name recognition and hump naming (there are more than one word with the first letter in lowercase followed by the first letter in uppercase)

public static void main(String[] args) {
     //1 statement
        int money;
        //2 assignment
         * First, second, merge
         * Variable name cannot be duplicate when declaring variable   
        int m = 100;
        String name="Zhang San";
        int age =27;
        double score=89.0;
        //Pass or not use true: pass false: fail
        boolean  flag =true;
        //3 use
        System.out.println("amount of money:: "+money);
        System.out.println("full name:"+name);

2. Constant

2.1 definition:

The value of a storage space representation cannot be changed.

Final modifier constant. The value of final modifier is assigned at the time of declaration and cannot be changed later (add final such as final int before data type)

2.2 advantages:

Once defined, it cannot be modified later, so it is relatively safe

2.3 naming rules:

Constant names should be capitalized. If they are composed of multiple words, they should be separated by underscores

public static void main(String[] args) {
        // TODO Auto-generated method stub
 * Constant case presentation
 * Calculate the area of a circle
        final   double       MY_PI =3.14;
        double  r=2;
        double  area=MY_PI * r * r;
        System.out.println("The area is:"+area);

3. Data type


3.1 basic data type:

1. Numerical type

1) Integer (integer can be stored):

byte(1 byte)

short(2 bytes)

int(4 bytes) (default)

long(8 bytes)

2) Floating point (for decimal):

float(4 bytes)

double(8 bytes) (default)

2. Non numerical type

1) Character type -- you need to add single quotation mark to the value, only one character can be saved

char(2 bytes): essentially an integer, the Unicode value of a character

2) Boolean -- only two true/false results


3.2 reference data type:

1) String: multiple characters can be stored and enclosed in double quotation marks
2) Array
3) Enumeration


4. Operator


4.1 assignment operator:

Assignment symbol: = assign the value on the right to the variable on the left

4.2 arithmetic operators:

Symbol: + - * /% + +--

++Put before variable means add 1 before use; put after variable means use before add 1

--Before a variable, first minus 1 is used; after a variable, first minus 1 is used

%Refer to the remainder

num+=2; (meaning num=num+2;)

public static void main(String [] args){
       //++ --
       int a=4;
       int b=2;
       int c=5;
       System.out.println(a++);//Output 4
       System.out.println(a);//Output is 5
       System.out.println(++a);//Output 6
       System.out.println(c%b);//Output is 1

4.3 relational operators

operator meaning give an example result
== be equal to 5==6 false
!= Not equal to 5!=6 true
> greater than 5>6 false
< less than 5<6 true
>= Greater than or equal to 5>=6 false
<= Less than or equal to 5<=6 true
be careful:

=For assignment operator, = = equals operator

The result types returned to us by expressions are all boolean types

4.4 logical operators:

operator meaning Operation rules
&& Short circuit and Both expression results are true, and the result is true
|| Short circuit or As long as one is true, the result is true
! Reverse Negate the result of the original expression


A B A&&B A||B

&&A holiday must be a holiday

||One true must be true

public static void main(String[] args) {
        // TODO Auto-generated method stub
      int a=4;
      int b=2;
      int c=5;
      //a> B is T, b > C is F, so a > b|b > C is T; a < C is T, so the whole expression is T
      System.out.println(a>b   ||    b>c    &&    a<c);

4.5 binomial operator (conditional operator):


boolean expression? Expression 1: expression 2;

Execute expression 1 when the result of the boolean expression is true

Execute expression 2 when the result of the boolean expression is false

  int a=5;
      int b=10;
      int c= a>b?  0:1;
      System.out.println(c);//The result is 1
   int a=5;
      int b=10;
      String c= a>b?  "correct":"error";
      System.out.println(c);//The result is an error

The data type of the return value needs to be consistent with the data type of the expression being executed

Operator priority



5. Type conversion

5.1 automatic type conversion

For example, in life, there are two water cups, one large one small one. If you pour the small one filled with water into the empty one, it's OK. A scene like this is called automatic type conversion in java

      double first=81.99;
      int duo=2;
      double  seconde=first+duo;


① In the whole expression, if there is double data type, the result of the whole expression will be automatically promoted to double type

② Data types need to be compatible in expressions for automatic type conversion

For example: all numerical

③ The target type should be greater than the original type

5.2 cast

For example, in life, there are two water cups, one large and one small. If you pour a large glass full of water into an empty one, it's OK, but it will overflow. Such a scenario is called self imposed type conversion in java


Data type variable name = (data type) (expression); -- first operate on the expression, and then convert the result

For example: int second = (int) (first + duo); or int second = (int) (first) + Duo; -- first convert first to int type in calculation, and finally convert the result to int type

Disadvantages: loss of precision, careful use (what double to int loses is that all values after the decimal point are not rounded)

  double  first=81.99;
  int  duo=2;
  int  seconde=(int) (first+duo);//The result is 83



Function: receive the value entered by the user on the keyboard

Use steps:

① Guide bag

import java.util.Scanner ; / import java.util .*; ( java.util Is the package name, scanner is the class name,

If * is used, it means java.util All classes under the package, either way)

② Create Scanner object

Scanner tx = new Scanner (System.in);

③ Use common methods

Receive int type int age= tx.nextInt();

Receive double score of double type= tx.nextDouble ();

Receive String type String name=tx.next();

be careful

In the second step, the name used in the new Scanner (tx) in the third step

For the reasons of tools, ln is removed when writing prompts; for example, if you System.out.println (please enter the age:); remove the ln of System.out.print("please enter age:");

package cn.kgc.tx.ketang;
//1. Guide bag
import java.util.Scanner;
public class Demo4 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //2. Create Scanner object
     Scanner  tx = new Scanner (System.in);
     //3. Use
     System.out.print("Please enter age:");
     int age=tx.nextInt();
     System.out.print("Please enter your name:");
     String name=tx.next();
     System.out.print("Please enter a score:");
     double score=tx.nextDouble();
     System.out.print("Age:"+age+",Name is:"+name+",The score is:"+score);


7. Use of package

The new package is composed of lowercase letters, and cannot have Chinese or special symbols

The new package uses the company domain name to remove 3w other content, such as www.kgc.cn cn.kgc . company definition

For each new class, the initial of each word we use is capitalized

There will be only one package + package name in each class (and on the first line of the code)


3, Program selection structure

3.1 basic selection structure


If (condition of boolean type){

If the condition is true, execute


Execute after brace when condition is false

flow chart


If Zhang Hao's Java score is greater than 98, Zhang Hao will get an MP4 as a reward
public static void main(String[] args){
       //  If... java>98
       //There are rewards
        double   javaScore=100;
        if(javaScore  >98){
            //If the condition is true, execute here and then execute down
            System.out.println("There's a hard drive reward");
       //If the condition result is false, jump here to execute directly
        System.out.println("End of program");


3.2 complex program structure

It is mainly used in combination with our various operators

For example, if Zhang Hao's Java score is greater than 98 and his music score is greater than 80, the teacher will reward him; or if his Java score is equal to 100 and his music score is greater than 70, the teacher will reward him

public static void main(String[] args) {
        // TODO Auto-generated method stub
    Scanner tx=new Scanner(System.in);
    System.out.print("Zhang Hao's Java The results are:");
    int javaScore=tx.nextInt();
    System.out.print("Zhang Hao's music achievements are:");
    int musicScore=tx.nextInt();
        System.out.println("Reward Zhang Hao MP5");
         System.out.println("End of program");


Why use if else?

Using the traditional if selection structure can also be done if not, but it may cause code redundancy and waste time.

For example:

        System.out.println("Reward one MP4");  
    //You can use the basic selection structure before, but it may cause code redundancy
    //The efficiency of execution is reduced
        System.out.println("30 push ups");

So we use if else


if(){    //Boolean expression
  //Enter execution code block 1 if the condition is true  
  //Condition is false entry code block 2

flow chart:


 if(zhangScore>98){            //If Zhang Hao's score is greater than 98, there will be a reward
         System.out.println("Reward one MP4");
    }else {  //Or 30 push ups
        System.out.println("30 push ups");

Multiple if selection structure


}else  if(){
}else  if(){

flow chart:



//Evaluation results of students' final examination scores > = 80: good scores > = 60: medium scores < 60: poor
    public static void main(String[] args) {
        // TODO Auto-generated method stub
      Scanner tx=new Scanner(System.in);
      System.out.print("Please enter the test score:");
      int score=tx.nextInt();
      }else if(score>=60){
      }else {

In the process of executing the program, the program is executed from top to bottom, so when the condition is judged, it will stop and execute when the first condition is satisfied, and the later content will not be executed again

Therefore, when judging conditions, the statement order of conditions should not be written casually, but in a certain order

Nested if selection structure


if(Condition 1){
  if(Condition 2){
   // Block 1 runs when both IFS are satisfied
    //Code block 2
  //Code block 3

flow chart:


    public void demo8(){
        System.out.print("Please enter your running results:");
        //Enter grades
        double score=tx.nextDouble();
        //Judge performance
            //If you pass the grade, you can judge gender
            System.out.print("Please enter your gender:");
            String sex=tx.next();
            //Judge gender
                System.out.println("Congratulations on entering the men's final");    
            }else if(sex.equals("female")){
                System.out.println("Congratulations on entering the women's final");
        }    else {
                System.out.println("Input error");
        System.out.println("I'm sorry you didn't make it to the finals");


switch selection structure


Switch (expression) {/ / expression is int, short, byte, char, enumeration, String
    case constant 1: / / evaluates the value of the expression
    Statement; / / if equal to constant 1
    case constant 2:
    Statement; / / if equal to constant 2
    Statement; / / if no matching value is found

be careful:

switch can only be followed by 6 types

Three integer types: byte, short, int

Two characters are related: char, String

An enumeration type

String needs to be used after jdk7.0



Han Yan takes part in the computer programming competition
 If you win the first prize, you will attend the one month summer camp organized by MIT
 If you get the second place, you will be rewarded with an HP laptop
 If you get the third place, you will be rewarded with a mobile hard disk
 Otherwise, no reward will be given
      public void demo3(){
          int mc=2;
              System.out.println("summer camp");
          }else if(mc==2){
          }else if(mc==3){
              System.out.println("one hard disk");
              System.out.println("continue to work next year");
          System.out.println("end of program");

The above is the completion of using multiple if selection structure, but from the perspective of code structure, it appears code redundancy, complex structure and multiple equivalent judgments.

In order to solve the above problems, we introduce the choice structure of switch


The use scenarios of if selection structure and switch selection structure

if selection structure is generally used in interval judgment, while switch selection structure is generally used in equivalent judgment

be careful:

① Constant name cannot be duplicate

② The constants after the case do not have to be in a certain order. The values after the switch will find their own matching constant values, and then execute the corresponding code block. If they are not found, the values in the default will be executed

③ Break ends the current execution content and executes after case. If there is no break code, it will continue to execute downward until the break or the entire switch statement is completed

④ default at the end, break can be omitted (not recommended). At other locations, it cannot be omitted. Otherwise, it will be executed downward until break is encountered


    public void demo9(){
        System.out.print("Enter 1 to 7 to select Monday to Sunday package:");
        String num=tx.next();
        case "1":
            System.out.println("Get up at 8 in the morning and write the code");
        case "2":
            System.out.println("Get up at 9am and write the code");
        case "3":
            System.out.println("Get up at 8:30 in the morning and write the code");
        case "4":
            System.out.println("Get up at 7:30 in the morning and write the code");
        case "5":
            System.out.println("Get up at 7 in the morning and write the code");
        case "6":
            System.out.println("Write the code to 12 p.m");
        case "7":
            System.out.println("Get up at 8 in the morning and write the code");
            System.out.println("Don't try to escape. It's no use losing");


Compare switch and multiple if selection structures


Are used to deal with the structure of multi branch conditions


if is often used to judge interval

switch used to judge equivalent conditions

What can be done with switch, can be done with if, but not vice versa

How to handle system exceptions

Use hasNextInt() to solve problem 2

Scanner input = new Scanner(System.in);
       //If you enter a number
    if (input.hasNextInt()) {
        int num = input.nextInt();
        switch (num) {
        case 1:
            //Display the system main menu;  
        case 2:
            System.out.println("Thank you for your use!");  break;
            System.out.println("Input error.");break;
    } else {     //If you do not enter a number
        System.out.println("Please input the correct number!");


4, Cyclic structure

Why cycle:

The same effect can be achieved with simpler code

public void demo1(){
        //Direct printing: error prone, large amount of code, low efficiency
        System.out.println("Study hard the first time");
        System.out.println("Study hard for the second time");
        System.out.println("Study hard for the third time");      
        System.out.println("Study hard for the fourth time");

Use cycle to solve


There's a beginning and an end to what's been done over and over

Characteristics of the cycle:

Cycle condition: start and end conditions

Loop operations: things that need to be done repeatedly all the time

Loop variable: the amount that can affect the result of a loop condition

4.1 while cycle


Judgment before execution

If the loop condition is not met at the beginning, the loop operation will not be performed again


While (loop condition / / boolean type expression){
  Cycle operation

flow chart:


/*Print 50 papers
     * Cycle characteristics:
     *            Cycle condition: start and end conditions
     *            Loop operations: things that need to be done repeatedly all the time
     *            Loop variable: the amount that can affect the result of a loop condition
    public void demo3(){ 
        int a=1;
        while (a<=50){     //Cyclic condition
            //Cycle operation
            System.out.println("Print page"+a+"Papers");
            a++;   //Cyclic variable


4.2 do while loop

Why do - while loop?

There are often things in life that we need to do first and then judge. For example: one semester before the final exam


  Cycle operation
 }While (loop condition); / / boolean type when loop condition

flow chart:

Implementation features:

Execute first, then judge.

If the condition is false, perform at least one loop operation


After several days of study, the teacher gave Zhang Hao a test,
//Let him write the program on the computer first,
//Then the teacher checks whether it is qualified. If not, continue to write 
public void demo1(){
        String answer;
        do {
            //Cycle operation
            System.out.println("Computer test first");
            System.out.println("Teacher, am I qualified?");
        }while ("n".equals(answer));
        System.out.println("End of program");         


4.3 for cycle

Why use the for loop:

The code is simpler: some expressions in the while loop are found in for

Applicable scenario: use when the number of cycles is fixed


For (initialize loop variable; loop condition; modify value of loop variable){
  Cycle operation

Error prone:

The initial loop variable can be omitted, but it needs to be written on for

Loop conditions and changing the value of a loop variable cannot be omitted or the loop will die

If the value of initialization loop variable, loop condition and modification loop variable are not written (semicolon cannot be omitted), the loop will die


Shopping malls investigate the age level of customers
//Calculate the proportion of customers of all ages
    public void demo6(){
        double num2=0; //Statement of number of people under 30
        double num3=0; //Statement of number of people over 30
        for (int i=1;i<=10;i++){
            System.out.print("Please enter the"+i+"Age of customers:");
            int num1=tx.nextInt();
            if (num1<=30){
            }else {
        System.out.println("30 Below the age of:"+(num2/(num2+num3)));
        System.out.println("30 The comparison of over-years-old is:"+(num3/(num2+num3)));


4.4 indissoluble relationship between break and continue


break: terminate this cycle and continue to execute backward

continue: terminate this cycle, and then execute the next cycle

break function:

Change program control flow

When used in do while, while, for, you can jump out of the loop and execute the statement after the loop

break is usually used in loops with conditional statements



Record the scores of 5 courses of a student and calculate the average score. If a score is entered as negative, stop the entry and prompt for an error
//Record the results in a circular way, and judge the correctness of the entry. If the input is wrong, use the break statement to jump out of the loop immediately; otherwise, add up
    public void demo7(){
        int sum=0;    //Total score
        boolean flag=false;   // false indicates that the score entered is not a negative number true indicates that the score entered is a negative number
        for (int i=0;i<5;i++){
            System.out.print("Please enter the"+(i+1)+"Results of the course:");
            //Results of circular entry
            int score=tx.nextInt();
            if (score<0){
                flag =true;
            System.out.println("Input error");     
        }else {
            int avg= sum/5;
            System.out.println("The average score is:"+avg);



     * Enter the student scores of Java courses in a circular way, and count the proportion of students whose scores are greater than or equal to 80
    public void demo9(){
        int sum=0;  //Variables used to accumulate the number of students
        System.out.print("The total class size is:");
        int penNo=tx.nextInt();
        for (int i=1;i<=penNo;i++){
            System.out.print("Enter the"+i+"Results of students:");
            double score=tx.nextDouble();
            if (score<80){
        double a=(double)sum/penNo*100;
        System.out.println("80 The number of students with scores above is:"+sum);
        System.out.println("80 The proportion of students with score above is:"+a+"%");

Compare break and continue:

Occasion of use:

break is often used in switch and loop structures

continue is generally used in loop structure

Action (in cyclic structure):

break statementterminates a loop, and the program jumps to the next statement outside the loop block

continue to jump out of this cycle and enter the next cycle


5, Array

What is an array:

An array is a variable that stores a set of data of the same data type

Basic elements of array:


The name of the array, which is used to distinguish different arrays

Array element:

Data stored in array

Element subscript:

Number array elements. Starting from 0, each element in the array can be accessed by subscript

Element type:

Data type of array element

be careful:

To declare a variable is to draw a suitable space in the memory space

To declare an array is to draw a series of continuous spaces in memory space

The length of the array is fixed to avoid out of bounds

All elements in an array must be of the same data type

How to use arrays:

1. Declare array

Array type array name [];

Array type [] array name;

int[] a; int a[];

2. Allocate space

Array type [] array name = new data type [size];

a=new int[5];

3. Assignment

Array name [element subscript] = value to assign;



1, Assign while declaring: several values are given when assigning, and the length of the array is

Array type [] array name = {X; Y; Z};

int[ ] score = {89, 79, 76};

Array type [] array name = {X; Y; Z};

int[ ] score = new int[ ]{89, 79, 76};

2, Dynamically input information from the keyboard and assign values (array length needs to be defined first)
Scanner input = new Scanner(System.in);
for(int i = 0; i < 30; i ++){
     score[i] = input.nextInt();
4. Processing data


Arrays class

return type Method name explain
boolean equals(array1,array2) Compare array1 and array2 arrays for equality
  sort(array) Ascending elements of array
String toString(array) Convert an array to a string
  fill(array,val) Assign all elements of array to val
What is the type of the original array? What is the type of the new array copied copyOf(array,length) Copy the array array to a new array with length, and the return type is the same as the copied array
int binarySearch(array, val) Query the subscript of element value val in array (it is required that the elements in array have been arranged in ascending order)
    public void test05(){
        int[] array1 ={12,21,13};
        int[] array2 ={12,21,13};
        int[] array3 ={12,21,13,24};
        //int binarySearch(array, val) queries the subscript of element value val in array (it is required that the elements in array have been arranged in ascending order)
        int i =Arrays.binarySearch(array3,13);
        //copyOf(array,length) copies the array into a new array with length. The return type is the same as the copied array
        /*int array4[] =Arrays.copyOf(array3,6);
        /*//void fill(array,val)    Assign all elements of array to val
        Arrays.fill (array3,22);
        //sort(array)        Ascending elements of array
        //String toString(array)    Convert an array to a string
     // boolean equals(array1,array2);        Compare array1 and array2 for equality
        boolean a=Arrays.equals(array1,array2);
        boolean b=Arrays.equals(array1,array3);



6, equals

Finally, I would like to add a little more about the difference between equals and = =!!!

==What's the difference with equals?


You can compare numeric types as well as reference data types. When the value type is compared, the value is compared. When the reference data type is referred to, the address value is compared


If the equals method is not overridden, the comparison method is the same as = = method. If it is overridden, the comparison method is rewritten

When using equals, we will write variables with certain values in the front to avoid null pointer exceptions


    public void test2(){
        String i =null;//The default value of String is null
        if (i.equals("")){
        System.out.println("End of program");
    }//At this time, the operation will report an error
    public void test2(){
        String i =null;
        if ("".equals(i)){
        System.out.println("End of program");
    }//Normal operation after transposition

Tags: Java less Programming Mobile

Posted on Tue, 23 Jun 2020 00:58:05 -0400 by toms