Java Basics - basic syntax

Environment construction

**Note: because the blue bridge cloud course comes with its own environment, there is no need to build it. You can skip it directly. This is the environment for building a local host.**

● version 8 is used for learning

Download URL


Install jdk

Note: the path should not contain Chinese and spaces
○ right click my computer → properties → advanced system settings → advanced → environment variables
○ JAVA_ Home: JDK installation path
○ CLASSPATH : .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar; // Remember there's a "."
○ Path : %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;


○ start → movement → enter "cmd"
○ type commands: java -version, java and javac. The following information appears, indicating that the environment variable configuration is successful


eclipse or IDEA is recommended

brief introduction

All code in Java must be included in class. The Main method is the entry of the program, and Java is case sensitive. If it is written as Main, the program will not run because the program entry cannot be found. The class name (HelloWorld) decorated with public must be the same as the source code file name.

Compile source code

Enter javac If the program has no prompt and a file with. class extension is generated in the same level directory, the compilation is successful. Otherwise, the compilation fails.
Run the program: enter java HelloWorld. There is no need to add an extension at this time.


● the program changes the state of the whole program by changing the value of the variable. In order to facilitate the use of variables, variables need to be named, called variable names.
● format: data type and variable name;
● constant values cannot be modified. The final keyword in Java can be used to declare properties (constants), methods and classes. When final modifies an attribute, it means that the attribute must be initialized once the memory space is allocated. Its meaning is "this cannot be changed" or "final state". Add the keyword final in front of the variable to declare a constant. In the Java coding specification, constant names are required to be capitalized.
● format: final data type constant name = value;

data type

String (string)

String length

//Method prototype
public int length(){

string comparison

public class StringTest {
    public static void main(String[] args){
        String s = new String("Java");
        String m = "java";
        System.out.println("use equals()Comparison, java and Java The result is"+s.equals(m));
        System.out.println("use equalsIgnoreCase()Comparison, java and Java The result is"+s.equalsIgnoreCase(m));

be careful
○ if you want to ignore case, call equalsIgnoreCase(), which is the same as other methods
○ "= =" compares whether the addresses of two objects stored in memory are the same

The value of variable b is false. Because the address corresponding to s1 object is the address of "abc", and s2 uses the new keyword to apply for new memory, the memory address is different from the address of "abc" of s1, so the obtained value is false.

String connection

○ use +, such as String s = "Hello" + "World!".
○ use the concat() method of String class.
charAt() method
The function is to obtain the specified character in the string according to the index value (specify that the index value of the first character in the string is 0, the index value of the second character is 1, and so on).

String s = "abc";
char c = s.charAt(1);

===>    variable c The value of is 'b'. 

Common string extraction methods


String cannot be modified. Modifying a string actually creates a new string object. If you need to modify the contents of the string, you can use StringBuilder. It is equivalent to a container for storing characters.


Construct a StringBuilder that does not contain any characters and has an initial capacity of 16
StringBuilder a = new StringBuilder();
Construct a StringBuilder that does not contain any characters and has a capacity of cap
StringBuilder b = new StringBuilder(int cap);
Construct a StringBuilder and initialize the content to str

StringBuilder  c = new StringBuilder(String str);
public class StringBuilderTest {
    public static void main(String[] args){
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder(5);
        StringBuilder s3 = new StringBuilder("shiyanlou");
        System.out.println("s1:" + s1.toString() + "\tcap:" + s1.capacity());
        System.out.println("s2:" + s2.toString() + "\tcap:" + s2.capacity());
        System.out.println("s3:" + s3.toString() + "\tcap:" + s3.capacity());

$ javac
$ java StringBuilderTest
s1:java cap:16
s2:     cap:5
s3:shiyanlou    cap:25

The capacity of s3 is 25 because the initial capacity is 16 + the length of shiyanlou is 9.

common method

Arithmetic operator

! [insert picture description here](,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5pWyIOmSnyDkuro=,size_19,color_FFFFFF,t_70,g_se,x_16)

● prefix self increment and self subtraction (+ + i, – i): first perform self increment or self subtraction operation, and then perform expression operation.
● suffix self addition and self subtraction (i++,i –): first perform expression operation, and then perform self addition or self subtraction operation

Bitwise Operators

Remaining problem points: what is the difference between bitwise right shift and bitwise right shift zeroing?

Logical operator

&&And | are short-circuit. When the current expression is calculated according to the priority order, and the result of the expression can determine the result of the whole expression, it will not continue to judge and calculate backward, but directly return the result.

Relational operator

● ternary operator
○ Boolean expression? Expression 1: expression 2;
○ operation process: if the value of Boolean expression is true, return the value of expression 1; otherwise, return the value of expression 2.
● = = and= It is applicable to all basic data types. Other relational operators are not applicable to boolean, because boolean values only have true and false, and comparison has no meaning.
● = = and= It also applies to all objects. You can compare whether the references of objects are the same.

Operator priority




Access modifier:

Represents the permission range allowed to be accessed by the method, which can be public, protected, private or omitted (default). Public means that the method can be called by any other code.

return type

The type of the return value of the method. If the method does not return any value, the return value type is specified as void (representing no type); If the method has a return value, you need to specify the type of the return value and use the return statement in the method body to return the value.

Method name

Is the name of the method. A legal identifier must be used.

parameter list

The parameter list passed to the method. There can be multiple parameters. Multiple parameters are separated by commas. Each parameter consists of parameter type and parameter name, separated by spaces. When a method is called, a value is passed to the parameter. This value is called an argument or variable. Parameter list refers to the parameter type, order and number of parameters of a method. Parameters are optional, and methods can contain no parameters.

Method body

The method body contains specific statements that define the function of the method.
Methods can be divided into four categories according to whether they have parameters and return values:
● no parameter, no return value method
● return value method without reference
● method with parameter and no return value
● method with reference and return value

IF statement

Grammar one

Grammar II

Grammar III

if nesting

switch Statements


When the value of the expression after the switch is the same as the value after the case statement, execute downward from this position until the break statement or the end of the switch statement block is encountered; If there is no matching case statement, the code of the default block is executed.
● the default block is not required and is empty by default.

While and do while statements

while syntax:

  1. Judge whether the conditions after while are true or false
  2. When the condition is true, execute the code in the loop.

Do while syntax

  1. First execute the cycle operation, and then judge whether the cycle condition is true.
  2. If the condition is true, continue to execute 1 and 2 until the cycle condition is not true

for statement


Compared with the while and do while statements, the for statement structure is more concise and easy to read. Its execution order is as follows:

  1. Execute the loop variable initialization part (1) to set the initial state of the loop. This part is executed only once in the whole loop.
  2. Judge the loop condition (2). If the condition is true, execute the code in the loop body (4); If false, exit the loop directly.
  3. Execute the loop variable value operation part (3), modify the value of the loop variable, and then judge the next loop condition (2).

Exercise string processing

● enter a line of string from the console
● remove all spaces in the string
● print a string with spaces removed

import java.util.Scanner;
public class StringUtil {
    public static void main(String[] args) {
        Scanner in =new Scanner(;
        //Get String value
        String a=in.nextLine();
        StringBuilder stringBuilder = new StringBuilder(a);
        for (int i = 0; i < stringBuilder.length(); i++) {
            if (stringBuilder.charAt(i)==' ') {

Exercise comparison string

● enter string a and string b from the console
● compare whether string a and character b are completely consistent, and whether the length and content are completely consistent.
● if identical, the output is the same; if inconsistent, the output is different.
● the equals method is prohibited

import java.util.Scanner;
public class ContrastString{
    public static void main(String[] args){
            Scanner in=new Scanner(;
            String a = in.nextLine();
            String b = in.nextLine();
            boolean flag=true;
                for(int i=0;i<a.length();i++){

Jump statement

● break keyword is often used in condition and loop statements to jump out of loop statements.
Exercise print week
● obtain an integer parameter from the console
● when the number 1 is input, the output today is Monday
● when the number 2 is input, the output today is Tuesday

import java.util.Scanner;
public class PrintWeek{
    public static void main(String[] args){
        Scanner in=new Scanner(;
        int a=in.nextInt();
        System.out.print("Today is Sunday");
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:


An ordered sequence of elements. If you name a collection of a limited number of variables of the same type, this name is the array name. The variables that make up the array are called the components of the array, also called the elements of the array, and sometimes called subscript variables. The number used to distinguish the elements of an array is called a subscript. Array is a form in which several elements of the same type are organized in an unordered form for convenience in programming. The collection of these disorderly data elements of the same kind is called an array. An array is a collection used to store multiple data of the same type.

Subscripts start at 0 and end at array length - 1.


Grammar II


  1. Array subscripts start at 0. Therefore, the subscript range of the array is 0 to the array length - 1.
  2. The array cannot be accessed out of bounds, otherwise an error will be reported.
    for syntax reinforcement
public class JudgePrime{
    public static void main(String[] args){
        int[] ages={12,18,9,33,45,60};
        int i=1;
        for(int age:ages){
            System.out.println("No. in array"+i+"The first element is"+age);

Two dimensional array


Exercise array application

There is a transcript with the scores of 10 students (61, 57, 95, 85, 75, 65, 44, 66, 90, 32), requesting the average score and outputting it.

public class AverageScore{
    public static void main(String[] args){
        int[] score={61,57,95,85,75,65,44,66,90,32};
        double avg=0;
        int sum=0;
        for(int i=0;i<10;i++)

Knowledge points
● input
○ import java.util.Scanner;
○ define Scanner in= new Scanner(;
○ input
■ string in.nextLine();
■ shaping in.nextInt();
■ ...
○ close input
■ in.close();


The pictures and materials are from the blue bridge cloud course( /), Shang Silicon Valley and Baidu are compiled and released by Xiaobian after learning. If there is any error, please contact and correct it! thank you!

Tags: Java Eclipse intellij-idea

Posted on Mon, 29 Nov 2021 15:55:41 -0500 by catalinus