java basic syntax II

Posted by Michael_C on Tue, 01 Feb 2022 17:08:13 +0100

1, Process control

1.1 user interaction Scanner

java. util. New features of scanner jdk5

Used to get user input

// Create a scanner object to receive keyboard data
Scanner sr = new Scanner(;
// Use next to get the string. The string cannot be ended without spaces.
String name =;
// Receive the string, ending with enter, and the string can contain spaces.
String address = sr.nextLine();
// Close the IO stream to save resources
// Receive integer, floating point type
int i = sr.nextInt();
double d = sr.nextDouble();
1.2 sequential structure

The basic structure of java is sequential structure, which is executed one by one. From top to bottom. Execute in sequence.

1.3 selection of structure
  • if single choice structure
  • if double selection structure
  • if multiple selection structure
  • Nested if structure
  • switch multiple selection structure

case value: 



The variable types in the switch statement can be:

byte, short, int or char

From Java SE 7, String type is supported, and the case label must be a String constant or literal.

1.4 circulation structure
  • while loop

    while(Boolean expression) {
      // Circular statement
  • do... while loop

    do {
        // Circular statement
    }while(Boolean expression);
  • for loop

    for(initialization;Boolean expression;Cyclic control variable){
    	// Circulatory body
  • The enhanced for loop for arrays is referenced in Java 5

    for(Declaration statement : expression){
    	// Circulatory body
    int[] numbers = {15,12,30,50};
    for(int i : numbers) {
1.5 break & continue

break terminate loop

continue terminates this cycle

2, Detailed explanation of method

2.1 what is a method

Is a piece of code used to complete a specific function

2.2 method definition and calling

Modifier return value type method name(Parameter type parameter name){

      // Method body
    return Return value;

Method call

Object name Method name (argument list);

java is value passing

2.3 method overload

(in a class)


  • Method names must be the same.
  • The parameter list must be different (different number, different type, different parameter arrangement order, etc.).
  • The return types of methods can be the same or different.
  • Just different return types are not enough to overload methods.
2.4 command line parameter transmission

It is realized by passing command line parameters to the main() function.

2.5 variable parameters

jdk1.5 start of use.

  • In the method declaration, add an ellipsis (...) after specifying the parameter type
  • Only one variable parameter can be specified in a method. It must be the last parameter of the method. Any ordinary parameter must be declared before it.
public static void printMax(int ... numbers) {
    if(numbers.length == 0) {
        System.out.println("No argument passed");
        return ;
    int result = numbers[0];
    // sort
    for(int i=1; i< numbers.length; i++) {
        if(numbers[i] > result) {
            result = numbers[i];
    System.out.println("The Max value is " + result);
2.6 recursion

Recursion includes two parts: recursion header and recursion body.

Call yourself.

// Recursive factorial
public class DiGui {
    public static void main(String[] args) {
        DiGui di = new DiGui();

    private int dg(int i) {
        if(i ==1 ){
            return 1;
        } else {
            return dg(i-1)*i;

3, Array

3.1 array overview
  • An ordered collection of data of the same type.
  • Each data in the array becomes an element, and the element is accessed through subscript. (subscripts start with 0)
3.2 array declaration creation

Type of array name of array = value of variable

// Defines a one-dimensional array with 10 elements
int[] arr = new int[10];

Use length to get the length of the array.

java Memory Analysis:

initiate static

int[] a = {1,2,3};
Food[] foods = {new Food("Chinese cabbage","radish"),new Food("cloud","water")};

Dynamic initialization

int[] a = new int[3];
a[0] = 1;
a[2] = 3;

Array features:

  • The length of the array is fixed. Once created, its size cannot be changed.
  • Elements must be of the same type. Mixed types are not allowed.
  • The elements in the array can be any data type, including basic data type and reference data type.
  • Array variables are of reference type, and arrays can also be regarded as objects.
3.3 array usage
public class Arrays {
    public static void main(String[] args) {
        int[] a = {10,8,3,2,1};
        a = reArry(a);
    // Flip array
    public static int[] reArry(int[] result) {
        int[] b = new int[result.length];
        for(int i=0, j=result.length-1; j>=0; i++,j--) {
            b[i] = result[j];
        return b;
    // Output array
    public static void printArr(int[] arrys) {
        for(int k : arrys) {
            System.out.print(k + " ");
3.4 multidimensional array

Multidimensional array is composed of one-dimensional array, and each element is a one-dimensional array.

int[][] a = new int[3][2];
3.5 Arrays

Arrays tool class in Java util. Under arrays

You can use the methods of the corresponding class by viewing the API. (before there, we need to import the corresponding classes)

Bubble sort:

// Bubble sorting
     *  1,Compare two adjacent elements in the array. If the first element is larger than the second element, exchange the elements.
     *  2,Each comparison will produce a maximum or minimum number
     *  3,The next round can be sorted less once
     *  4,Cycle successively until the end.
    public static  int[] sort(int[] arr) {
        for(int i = 0; i < arr.length-1; i++) {
            // flag logo can reduce meaningless comparison and improve efficiency.
            boolean flag = false;
            for(int j=0; j < arr.length - i -1; j++) {
                if(arr[j] > arr[j+1]) {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    flag = true;
            if (flag == false) {
        return  arr;
3.6 sparse array

When most elements in an array are 0 or an array with the same value, you can use a sparse array to save the array.

Sparse arrays are handled as follows:

  • There are several rows and columns in the record array, and how many different values there are.
  • Record the elements, rows, columns and values with different values in a small-scale array, so as to reduce the size of the program.

The left side is the original array and the right side is the sparse array. (compression to save space)

  1. To convert an original array to a sparse array:
  2. Get the number of valid values
  3. Create an array of sparse arrays
  4. Traverse the original array and store the non-zero values in the sparse array

Topics: Java Programming