1. Basic structure of Java program

Time:2021-8-1

About the series of articles, I have moved to the community document and will not be updated in the blog related content. I hope you know. Welcome to subscribe to the documentJava notes~

Welcome to the original text:www.yuque.com/dobbykim/java-basic/…

1: Overview of cross platform and bytecode of Java language

JVM, machine code and bytecode

JVMNamely:Java Virtual Machinethat isJavaVirtual machine.

JavaLanguage has one characteristic:Platform independenceJVMIt is the key to realize this feature.

We know that software operation depends on the operating system(Operating System)。 The programming language used by early developers did not have good portability. If you want to run applications with the same function on different operating system platforms, you need to write code that can be recognized by the platform for each platform. Generally, the compiler will directly compile the source code of the program into a program that the computer can execute directlyMachine code

1. Basic structure of Java program

JavaLanguage is platform independent, that is, the so-calledWrite Once,Run Anywhere(compile once and run everywhere).JavaThe compiler does notJavaSource code compiled by0,1A sequence of machine code that can be directly executed by a computer, but compiled into a machine code with an extension of.classBytecode of. If you want to execute bytecode files, it must be installed on the platformJVMJVMThe interpreter interprets the bytecode as platform dependent machine code.

1. Basic structure of Java program

It can also be seen from the above figure that different operating systems need to be installed based on the operating systemJVMJVMIt shields the differences between operating systems and realizesJavaCross platform of language.

2: The basic unit of Java language — classes and packages

Class

stayJavaIn language, class is the smallest basic unit

One of the simplest classes

public class Cat {
}

Package

To better organize classes,JavaLanguage provides a package mechanism to distinguish the namespace of class names.

Example:

One belongs tomy.cuteUnder the bagCatclass

package my.cute;
​
public class Cat {
}

stayJavaIn languages, packages are generally named in the reverse order of domain names.

For example:

package com.alibaba.fastjson;

This avoids class name conflicts.

3: The basic structure of Java language — the meaning of package

Meaning and function of package:

  1. Organize similar or related classes in the same package to facilitate search and management

  2. Class names in the same package cannot be the same, but class names in different packages can be the same; When calling a class with the same class name in two different packages at the same time, the package name should be added to distinguish it. Therefore, the package can also avoid class name conflicts. Example: for classes with the same class name under different packages, we can use the fully qualified class name(Full Qualified Name)Make a distinction.

    package com.github.hcsp;
    
    public class Home {
      com.github.hcsp.pet1.Cat cat1;
      com.github.hcsp.pet2.Cat cat2;
    }
  3. The package limits access

4: Introducing third-party packages into Java

Example: introduce a class in a third-party package into the program:org.apache.commons.langs.StringUtils



If usedMavenFor project management, we first need topomImport from fileApache Commons LangPackage dependency

<dependency>
 <groupId>org.apache.commons</groupId>
 <artifactId>commons-lang3</artifactId>
 <version>3.11</version>
</dependency>

Then go back to our code and useimportKeyword to import a third-party package

As follows:

package com.github.hcsp;

import org.apache.commons.lang3.StringUtils;

public class Main {
  public static void main(String[] args) {
    System.out.println("Empty string is empty: " + StringUtils.isEmpty(""));
  }
}

Program input results:

Empty string is empty: true

We found that the above procedures, bothStringstillSystemNone of the classes passedimportAnd write fully qualified class names, but use them directly.

That’s becauseStringandSystemClass onjava.langUnder the bag.

JavaLanguage specification: if a class is placed injava.langUnder the bag, we don’t have to writeimportAnd fully qualified class names, but directly.

5: Methods, static methods and static member variables

Main method

JavaThe entry for program execution ismainmethod

Program example:

package com.github.hcsp;

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

 }
}

mainMethod signature:

  • publicModifier:publicRepresents the exposed class, which can be called freely without restriction

  • staticModifier:staticFor static, usestaticModified methods and variables are not bound to any object, which means that we can call them without creating any object

  • void: description the method has no return value

  • String[] args: pass tomainMethod, expressed as an array of strings

Static methods and static member variables

Program example 1:

package com.github.hcsp;

public class Main {
 public static void main(String[] args) {
 int i = 0;
 add(i);
 add(i);
 add(i);
 System.out.println(i);
 }

 public static void add(int i){
 i++;
 }
}

The program output result is:

0

The reason is,addParameters passed in methodiOnly works onaddMethod block, so themainVariables within methodsiHave any impact.

Program example 2:

package com.github.hcsp;

public class Main {
 public static int i = 0;

 public static void main(String[] args) {
 add();
 add();
 add();
 }

 public static void add() {
 i++;
 }
}

The result of this program is:

3

staticThe modified method or member variable is independent of any object of the class, or does not depend on any object. It exists inJVMA piece of memory in is a global storage unit that can be shared by all objects. thereforeaddMethods will affect it.

6: Objects, constructors, and member variables

JavaIs an object-oriented language.

Class is an abstract concept, while object is an instance of class and a concrete concept.

Example: create an object

Cat

package com.github.hcsp;

public class Cat {
  private String name;

  public Cat(){
  }

  public Cat(String name) {
    this.name = name;
  }
}

Main

package com.github.hcsp;

public class Main {
  public static void main(String[] args) {
    Cat cat = new Cat("Tom");
  }
}

The easiest way to create an object is to usenewkeyword

In this example, we created a namedTomYesCatObject, called with parametersconstructor

If we’re not hereCatClass, the compiler will automatically declare a parameterless constructor for us; On the contrary, if we declare any constructor with parameters, the compiler will no longer automatically declare the constructor without parameters for us, and we need to declare it ourselves.

7: Instance method and null pointer exception

Sample program:

Cat

package com.github.hcsp;

Main

package com.github.hcsp;

public class Main {
  public static void main(String[] args) {
    Cat cat1 = new Cat("Tom");
    Cat cat2 = new Cat("Harry");

    cat1.meow();
    cat2.meow();
  }
}

Program output results:

Meow, this is Tom

Let’s look at this program:

Cat

package com.github.hcsp;
package com.github.hcsp;

public class Main {
  public static void main(String[] args) {
    Cat cat1 = new Cat();
    Cat cat2 = new Cat("Tom");

    cat1.meow();
    cat2.meow();
  }
}

Running program:

Exception in thread "main" java.lang.NullPointerException
  at com.github.hcspTest.Cat.meow(Cat.java:15)
  at com.github.hcspTest.Main.main(Main.java:8)

We will find that the program runs with errorsabnormal, this exception isNullPointerExceptionNamely:Null pointer exception

The reason iscat1Yesnamebynull, for an empty object, when we call the method of this object, a null pointer exception will be generated.

The method to avoid null pointers is very simple. We can add the logic processing of null judgment where null pointers may be generated:

public void meow(){

8: Object and reference details

Quote(Reference

for instance:

A a = new A();

aIt’s a reference, it points to aAObject. We operateaThis reference indirectly manipulates the object it points to.

Sample program:

Cat

package com.github.hcsp;

Home

package com.github.hcsp;

public class Home {
    Cat cat;

    public static void main(String[] args) {
        Home home = new Home();
        Cat mimi = new Cat();
        home.cat = mimi;
        mimi.name = "mimi";
    }
}

The memory diagram of the program is analyzed as follows:

1. Basic structure of Java program

Deep copy and shallow copy

The most fundamental difference between shallow copy and deep copy is whether the copied thing is oneCopy entity of object, not references.

Take an example to describe:

Suppose B is a copy of A

When we modify a, if B also changes, it is a shallow copy, indicating that we modify the same value in the heap memory;

When we modify a, if B does not change, it is a deep copy, indicating that we modify different values in heap memory

realizationCloneableInterfaces, rewritingclone()Method and call, we get a shallow copy of an object, such as the example program:

Cat

package com.github.hcsp;

public class Cat implements Cloneable {
    public String name;

    public Cat() {

    }

    public Cat(String name) {
        this.name = name;
    }

    @Override
    protected Object clone() {
        Cat cat = null;
        try {
            cat = (Cat) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return cat;
    }
}

Main

package com.github.hcsp;

So how to implement deep copy?

Deep copy sample program:

Cat

package com.github.hcsp;

public class Cat {
    public String name;

    public Cat() {
    }

    public Cat(String name) {
        this.name = name;
    }
}

Home

package com.github.hcsp;

public class Home {
    Cat cat;
}

DeepCopy

public class DeepCopy {
    public static void main(String[] args) {
        Home home = new Home();
        Cat cat = new Cat();
        cat.name = "mimi";
        home.cat = cat;

        Home newHome = deepCopy(home);
    }

    public static Home deepCopy(Home home) {
        Home newHome = new Home();
        Cat newCat = new Cat();
        String newName = new String(home.cat.name);

        newHome.cat = newCat;
        newCat.name = newName;

        return newHome;
    }
}

This enables a deep copy

9: Value passing vs reference passing of method

Let’s look at two procedures first

Procedure I:

package com.github.hcsp;

public class Main {
  public static void main(String[] args) {
    int i = 0;
    addOne(i);
    System.out.println(i);
  }

  static void addOne(int i) {
    i++;
  }
}

The output of the program is:

0

becauseaddOnePassed in methodijustmainIn methodiA copy of the value of, so it has no effect on it. After executionaddOneMethod, the method space is destroyed.

Procedure 2:

package com.github.hcsp;

public class Main {
  public static void main(String[] args) {
    Cat cat = new Cat();
    cat.name = "haha";

    renameCat(cat);

    System.out.println(cat.name);
  }

  static void renameCat(Cat cat){
    cat.name = "mimi";
  }
}

The result of this program is:

mimi

Why does the program changecatWhat’s your name? Because what is passed in the method isCatVariable reference(address)Copy of, so, inrenameIn methodcatIt also points to the same “cat” in memory.

  1. What is value passing? Value transfer(pass by value)It refers to copying and passing a copy of the actual parameters to the function when calling the function, so that if the parameters are modified in the function, the actual parameters will not be affected.

  2. What is reference passing? Reference passing(pass by reference)It means that the address of the actual parameter is directly passed to the function when calling the function, so the modification of the parameter in the function will affect the actual parameter.

JavaThere are two data types in:

  • Primitive Data Type

    • int

    • char

    • byte

    • boolean

    • float

    • double

    • short

    • long

  • Reference data type

stayJavaIn, the parameter passing of a method, whether it is a native data type or a reference data type, is essentially the same.

If it is a value transfer, copy the value. If it is a reference (address), copy the reference (address).

So, for basic types,JavaA copy of the value will be directly copied and transferred to the method. Therefore, the method only modifies the copied value and does not affect the original value; For a reference type,JavaWillMake a copy of the referenced address, pass it to the method as a value. What is passed in the method is the address in the heap memory, which is equivalent to operating on the same object in the heap memory, so the information of the object will be changed.

This work adoptsCC agreement, reprint must indicate the author and the link to this article