Basic knowledge of Java combing

Hello World

1. Create a new folder and store the code
2. Create a new java file

  • The file extension is .java
  • [Note] The system may not display the file extension, we need to open it manually;

3. Write code

public class Hello{
    public static void main(String args[]){
        System.out.println("hello world!")

4. Compiling javac will generate a class file
5. Run the class file, namely java Hello

possible problems

1. There should be no problem with the size of each word, JAVA is case sensitive;
2. Try to use English;
3. The file name and class name must be consistent, and the first letter is capitalized;
4. If the symbols are in Chinese, an error may be reported;

Java operating mechanism


Java Basic Grammar

There are three types of annotations in Java

  1. Single-line comment //Comment content
  2. Multi-line comment /comment content/
  3. Documentation comments /**
    Generate java documentation:
    javadoc -encoding UTF-8 -charset UTF-8


  1. Keywords, such as public static void, etc.;


  • What is a variable: it is the amount that can change;
  • Java is a strongly typed language, each variable must declare its type;
  • A Java variable is the most basic storage unit in a program, and its elements include variable name, variable type, and scope.
type varName [=value] [{,varName[=value]}]
//Data type variable name = value; multiple variables of the same type can be declared separated by commas.


  • Each variable has a type, which can be a basic type or a reference type;
  • Variable names must be legal identifiers;
  • A variable declaration is a complete statement, so each declaration must end with a semicolon;

variable scope

  • class variable
  • instance variable
  • local variable
public static Variable{
    static int allClicks=0;  // class variable 
    String str="hello world";  // instance variable

    public void method(){
        int i=0;  // local variable


  • Constant: the value cannot be changed after initialization, and the value will not change;
  • The so-called constant can be understood as a special variable whose value is not allowed to be changed during the running of the program after its value is set.
final constant name=value;
final double PI=3.14;   
  • Constant names generally use uppercase characters

Variable naming convention

  • All variables, methods, and class names: see the name and know the meaning
  • Class member variables: lowercase first letter and camel case Principle: monthSalary Except for the first word, the first letter of the following words is capitalized
  • Local Variables: Lowercase and CamelCase
  • Constants: capital letters and underscores: MAX_VALUE
  • Class names: capital letters and camelCase principles: Man, GoodMan
  • Method name: lowercase first letter and camel case principle run() runRun()


  • Arithmetic operators + - * / % ++ –
  • assignment operator =
  • Relational operators > < >= <= != instanceof
  • Logical operators && || !
  • Bitwise operators & | ^ ~ >> << >>>
  • conditional operator ? :
  • Spread assignment operators += -= *= /=

Java process control

  • The program interacts with the human, and the user can input. java.util.Scanner
  • Basic syntax:
    Scanner s = new Scanner(
    The input string is obtained through the next() and nextLine() methods of the Scanner class. Before reading, we generally use hasNext() and hasNextLine() to determine whether there is any input data.

    break continue

    • break In the main part of any loop statement, break can be used to control the loop flow. break is used to forcibly exit the loop without executing the remaining statements in the loop. (The break statement is also used in the switch statement)
    • The continue statement is used in the loop statement body for a certain loop process, that is, to skip the unexecuted statement in the loop body, and then to judge whether to execute the loop next time.

    Java method

    Definition: It is a piece of code used to complete a specific function.

  • A method consists of a method header and method body.
    • Modifier: defines the access type of the method;
    • Return value type: the method may return a value;
    • Method name: is the actual name of the method;
    • Parameter type: A parameter is like a placeholder. When the method is called, a value is passed to the parameter. This value is called an actual parameter. Parameters are optional, the method may not contain any parameters;
    • Method body: The method body contains specific statements that define the function of the method.
modifier return value type method name(parameter type parameter name){
    method body
    return return value;

method overloading

  • Overloading is a function in a class with the same function name but different parameters.
  • Method overloading rules:
    • The method names must be the same;
    • The parameter lists must be different (different numbers or types or different order of parameters);
    • The return types of the methods can be the same or different;
    • Merely having a different return type is not enough to be a method overload;

Passing parameters on the command line

package method;

public class Demo03 {
    // Execute java method/Demo03 under src after javac compilation
    public static void main(String[] args) {
        // arge.length array length
        for (int i = 0; i < args.length; i++){
            System.out.println("args[" + i + "]:" + args[i]);

variable parameter

package method;

public class Demo04 {
    public static void main(String[] args) {
        Demo04 demo04 = new Demo04();

    // Varargs must come last
    public void test(int x, int... i){
        for(int j = 0; j < i.length; j++){

Array declaration creation

  • Array variables must first be declared before the array can be used in the program. Following is the syntax for declaring array variables:
dataType[] arrayRefVar;  // preferred method
dataType arrayRefVar[];  // Same effect, but not the preferred method
  • The Java language uses the new operator to create an array, the syntax is as follows:
dataType[] arrayRefVar = new dataType[arraySize];
  • The elements of the array are accessed by index, and the array index starts from 0;
  • Get array length: arrayRefVar.length

Java memory

  • heap
    • Store new objects and arrays
    • Can be shared by all threads and will not store other object references
  • the stack
    • Store basic variable types (including specific values ​​of these basic types)
    • The variable that refers to the object (the specific address of the reference in the heap will be stored)
  • method area
    • can be shared by all threads
    • Contains all class and static variables

sparse array

package array;

public class ArrayDemo05 {
    public static void main(String[] args) {
        int[][] array1 = new int[11][11];
        array1[1][2] = 1;
        array1[2][3] = 2;
        // output the original array
        System.out.println("output the original array");

        for (int[] ints : array1){
            for (int anInt : ints){

        // Convert to sparse array to save
        // Get the number of valid values
        int sum = 0;
        for (int i = 0; i<array1.length; i++){
            for (int j = 0; j<array1[0].length; j++){
                if (array1[i][j]!=0){
        System.out.println("number of valid values"+sum);

        // 2. Create an array of sparse arrays
        int[][] array2 = new int[sum+1][3];

        array2[0][0] = array1.length;
        array2[0][1] = array1[0].length;
        array2[0][2] = sum;

        // Traversing a two-dimensional array, storing non-zero values ​​in a sparse array
        int count = 0;
        for (int i = 0; i<array1.length; i++){
            for (int j = 0; j<array1[0].length; j++){
                if (array1[i][j]!=0){
                    array2[count][0] = i;
                    array2[count][1] = j;
                    array2[count][2] = array1[i][j];

        //output sparse array
        System.out.println("sparse array");
        for (int i =0; i<array2.length;i++){

        // restore sparse array
        System.out.println("restore sparse array");
        // 1. Read sparse array
        int[][] array3 = new int[array2[0][0]][array2[0][1]];

        // 2. Restore the value in it
        for (int i = 1; i < array2.length; i++){
            array3[array2[i][0]][array2[i][1]] = array2[i][2];

        //output restore array
        for (int[] arr : array3){
            for (int val : arr){

object oriented

  • Object-Oriented Programming (OOP)
  • The essence of object-oriented: organize code in the form of classes, and organize (encapsulate) data in the form of objects;
  • abstract
  • Three characteristics
    • encapsulation
    • inherit
    • polymorphism
  • Objects are concrete things. A class is an abstraction, an abstraction of an object;
  • From the perspective of code operation, there are classes first and then objects. Classes are templates for objects.


  1. same as class name
  2. no return value
  3. The essence of new is to call the constructor
  4. initialize the value of the object
    be careful
    1. After defining a parameterized structure, if you want to use a parameterless structure, you need to explicitly define a parameterless structure
    Alt+Insert automatically generates construction methods based on attributes


property private, get/set

  1. Improve program security and protect data
  2. hide the implementation details of the code
  3. unified interface
  4. System maintainability increased


  • The essence of inheritance is the abstraction of a certain batch of classes, so as to achieve better modeling of the world
  • extends means extension. A subclass is an extension of a parent class.
  • Classes in Java have only single inheritance, no multiple inheritance
  • Inheritance is a relationship between classes and classes. In addition, the relationship between classes and classes includes dependency, composition, aggregation, etc.;
  • There are two classes in the inheritance relationship, one is the subclass (derived class) and the other is the parent class (base class). A subclass inherits from a parent class, represented by the keyword extends.
  • In a sense, there should be an "is a" relationship between the subclass and the parent class
  • All classes in java inherit the object class by default

super note

  1. super calls the constructor of the parent class, which must be the first in the constructor
  2. super must only appear in subclass methods or constructors
  3. super and this cannot call the constructor at the same time
    Vs this
  • Different objects are represented:
    • this: call this object itself
    • super: represents the application of the parent class object
  • premise:
    • this: Can be used without inheritance
    • super: can only be used when inheriting the adjustment
  • Construction method
    • this(); call the constructor of this class
    • super(); call the constructor of the parent class


There needs to be an inheritance relationship, and the subclass overrides the method of the parent class

  1. method names must be the same
  2. The argument lists must be identical
  3. Modifier: the scope can be expanded; public > Protected > Default > private
  4. The exception thrown; the scope can be narrowed, but not expanded;


That is, the same method can take many different behaviors depending on the sending object

Polymorphism Considerations

  1. Polymorphism is the polymorphism of methods, but no polymorphism of properties
  2. The parent class and the subclass must be connected, otherwise there will be a type conversion exception! ClassCastException!
  3. Existence conditions: inheritance relationship, methods need to be rewritten, and parent class references point to subclass objects! Father f1 = new Son();

Methods modified by the following modifiers are not polymorphic

  1. static method, which belongs to the class, it does not belong to the instance
  2. final constant
  3. private method

static keyword

public class Person {

        // Code block (anonymous code block) is created when the object is created, before the construction method
        System.out.println("anonymous code block");

    static {
        // The static code block is loaded when the class is loaded, and is only executed once
        System.out.println("static block");
    public Person(){
        // Construction method
        System.out.println("Construction method");

    public static void main(String[] args) {
        Person person1 = new Person();
        Person person2 = new Person();

static block
anonymous code block
Construction method
anonymous code block
Construction method

  1. Abstract classes cannot be new;
  2. Ordinary methods can be written in abstract classes
  3. Abstract method must be in abstract class
  4. Abstraction of abstraction: Constraints improve development efficiency


  1. constraint
  2. Define some methods for different people to implement
  3. All methods in the interface default to public abstract
  4. All variables in the interface are public static final by default
  5. The interface cannot be instantiated, there is no constructor in the interface
  6. implements can implement multiple interface calls
  7. The method in the interface must be overridden

Select the line that may have a problem, option + command + t can generate a try/catch/finally statement
Exception priority: Throwable > Error = Exception > both child exceptions

Tags: Java jvm programming language

Posted by jamiel on Sat, 26 Nov 2022 16:22:06 +1030