Skip to content

Java Basics

Outline & Goals

  1. 编译型语言和解释性语言的区别 * Compile vs. Scripting language * Performance
  2. Java 是如何work的 * JVM, JRE, JDK的概念
  3. 什么是面向对象编程? OOP的4大原则
  4. Java这门语言本身的一些比较关键的语法和性质

1 编译型语言和解释型语言的区别

Compile vs. Scripting language

  • 编译型语言, 目标计算机以编译语言直接翻译程序, 转化为可以执行的机器代码. C++, C 和 Go. (.out vs .exe)

https://medium.com/@bdov_/what-happens-when-you-type-gcc-main-c-a4454564e96d

  • Pros

    i. 编译语言直接转换为处理器可以执行的机器代码, 编译为本地机器代码的程序往往比解释的代码要快. 这是因为在运行时翻译代码的过程增加了开销, 并可能导致程序整体变慢.

  • Cons

    i. 生成的二进制代码对平台的依赖性

  • 解释型语言, 源代码不会直接由目标计算机翻译, 而是由解释器读取并执行代码. PHP, Ruby, Python和JavaScript

  • a. Pros

    i. 解释型语言更加灵活, 并且通常具有诸如动态键入和程序较小的特点. 另外, 由于解释器自己执行源程序代码. 因此代码本身对于平台是独立的.

  • b. Cons

    i. 与编译型语言相比, 其最明显的缺点在于执行速度.

  • Java语言是一种编译型-解释型语言, 同时具备编译特性和解释特性.

Screenshot 2023-05-05 at 18.55.16

2 Difference between JDK, JRE & JVM

JVM (Java Virtual Machine) is an abstract machine. It provides the runtime environment in which Java bytecode can be executed.

Screenshot 2023-05-05 at 18.57.14

  • 类加载器 classloader

  • 运行时数据区域 runtime data area

  • PC程序计数器(PC Registers)

    • 存储下一步将执行的JVM指令
  • 本地方法栈(Native Method Stack)
    • 虚拟机使用到的本地方法服务
  • Java虚拟机栈(Java Stacks)
    • Java虚拟机栈也是线程私有的. 每一个JVM线程都有自己的Java虚拟机栈, 这个栈与线程同时创建, 它的生命周期与线程相同. 存储local variable和方法的调用.
  • Java堆(Heap Memory)
    • JVM用来存储对象实例以及数组值的区域, 可以认为Java中所有通过new创建的对象的内存都在此分配.
  • class People{string name: new People}
  • 方法区(Method Area)

    • 它用于存储每一个类的结构信息, 例如运行时常量池, 成员变量和方法数据, 构造函数和普通函数的字节码内容, 还包括一些在类, 实例, 接口初始化时用到的特殊方法. 当开发人员在程序中通过Class对象中的getName、isInstance等方法获取信息时, 这些数据都来自方法区.
  • 执行引擎 execution engine

  • Interpreter

    • Read the /class bytecode line by line and interpret to machine code that can be understood by machine.
  • JIT Compiler(Just-in-time)

    • Improves the performance of Java applications at run time.
  • Garbage Collector

    • People a = new People()

    b = a;

    b = null;

    a = null;

    • Reference counting:

    • 给对象中添加一个引用计数器, 每当一个地方应用了对象, 计数器加1; 当引用失效, 计数器减1; 当计数器为0表示该对象已死, 可回收.

    • 简单但速度很慢
    • 缺陷: 不能处理循环引用的情况

    • Stop-and-Copy

    • 将可用内存按容量划分为大小相等的两块, 每次只需要使用其中一块. 当一块内存用完了, 将还存活的对象复制到另一块上面, 然后再把刚刚用完的内存空间一次清理掉

    • 效率低, 需要的空间大
    • 优点: 不会产生碎片

    • Java的做法很聪明, 我们称之为”自适应“的垃圾回收器, 或者是”自适应的, 分代的, 停止-复制, 标记-清洗“式垃圾回收器. 它会根据不同的环境和需要选择不同的处理方式.

JRE is the environment within which the java virtual machine runs. JRE contains the Java Virtual Machine(JVM), class libraries, and other files excluding development tools such as compiler and debugger. JRE = JVM + core class library.

Screenshot 2023-05-05 at 21.10.17

JDK is a superset of the JRE, it contains everything that JRE has along with development tools such as compiler, debugger etc.

Screenshot 2023-05-05 at 21.11.36

3 什么是面向对象编程? OOP的4大原则

What is an Object?

  • Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail).
  • Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages)
  • State tells us how the object looks or what properties it has. Behavior tells us what the object does.
  • 面向对象编程: 把生活中的实际问题, 用编程语言来解决.

Four Principles of OOP

https://medium.com/@cancerian0684/what-are-four-basic-principles-of-object-oriented-programming-645af8b43727

  • Abstraction: design level, hiding the implementation details and showing only functionality to the user. abstract class and interface.

  • Encapsulation(封装): wrapping object state (variables) and behavior (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. If you are creating a class, you are doing encapsulation.

  • Inheritance(继承): The process by which one class acquires the properties and functionalities of another class is called inheritance. Inheritance provides the idea of reusability of code and each subclass defines only those features that are unique to it, the rest of the features can be inherited from the parent class.

  • Polymorphism: Polymorphism is the ability of an object to take on many forms. It performs a single action in different ways.

Screenshot 2023-05-05 at 21.46.01

Abstraction vs. Encapsulation in Java

Abstraction is more about hiding the details at the design level, encapsulation is more about hiding the details at implementation level. For example, we have a vehicle, we know it can move, it might more using tiers, it might fly, all we need to know is it can move. Then for encapsulation, for example, when we implement a HashMap, to solve the collision, we either use a linked list, or we use a red-back tree for each bucket. We can change the internal implementation without affecting the clients who use the HashMap.

Abstract class

A class that is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body). It needs to be extended by implementing all abstract methods. It CAN NOT be instantiated.

Interface

An interface is a blueprint of a class, which can be declared by using the interface keyword. Interfaces can contain only constants and abstract methods (methods with only signatures and no body). Like abstract classes, interfaces CAN NOT be instantiated, they can only be implemented by classes or extended by other interfaces.

Abstract class vs Interface

Abstract class Interface
Abstract class doesn't support multiple inheritance, it can extend only one class or one abstract class at a time. Interface supports multiple inheritance, it can extend any number of interfaces at a time
Abstract class can have final, non-final, static and non-static variables with any access specifier Interface has only static, public and final variables
An abstract class can have both abstract and concrete methods An interface can only abstract methods. Since Java 8, it can have default and static methods also.
The abstract keyword is used to declare abstract class The interface keyword is used to declare interface
An abstract class can be extended using keyword "extends" An interface class can be implemented using keyword "implements"

When and which one to use?

  1. Abstract class is good if you have some functionality that you want its subclasses to have . For instance, if you have a set of functions that you want to all of the base abstract class's subclasses to have.
  2. Abstract class is also good if you want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
  3. Abstract class is good if you will need to add methods in the future. If you add a method to an interface, then all classes implementing the interface need to be changed.
  4. If you think the API will not change for a while, and you want a meaning as 'has an ability to do something', you can use interface.

Access modifier 访问修饰符

There are four types of access specifiers in java:

  • public: Accessible to all. Other objects can also access this member variable or function.

  • private: Not accessible by other objects. Private members can be accessed only by the methods in the same class.

  • protected: The scope of a protected variable is within the class which declares it and in the class which inherits from the class (Scope is class and subclass). Protected methods can be accessed via subclasses and classes in the same package.

  • default: The scope of a default variable is within the same package.

  • default private protected public
    Same Class Yes Yes Yes Yes
    Same package subclass Yes No Yes Yes
    Same package non-subclass Yes No Yes Yes
    Different package subclass No No Yes Yes
    Different package non-subclass No No No Yes

Method Overloading & Method Overriding

Polymorphism can be achieved by method overloading and method overriding(can also be achieved by using interface).

Method Overloading 重载

A class has multiple methods that that have the same name but different parameters.

  • The binding of an overloaded method call to its definition happens at compile time.
  • Must have a different parameter list.
  • May have different return types.
  • Static methods can be overloaded.

Method Overriding 重写

If a subclass has the same method as declared in the super class, this is known as method overriding. The binding of an overridden method call to its definition happens at runtime.

  • Must have the same parameter list.
  • Must have the same return type, allow more specific return type. (Number -> Integer)
  • Only inherited methods may be overriden.
  • Static methods cannot be overridden.

4. Java 这门语言本身的一些比较关键的语法和性质

People a = new People()

What is Class, Object/Instance and Reference?

  • A class is a template or blueprint from which objects are created. A class in Java can contain fields, methods, constructors, blocks and nested classes.
  • An entity that has state and behavior is known as an object. An object is an instance of a class.
  • Reference holds the address of an object or instance. Whenever we want to call instance methods, we use this reference which holds the address of the object.

Data Types in Java

Primitives vs. Reference Type

  • byte, short, int, long, float, double, boolean, char
  • Car, Vehicle, Student, Class, Animal, Missile, Integer, Float, Double, Boolean

Functions & Constructor

(access modifier) (static/non-static) (return type) (name) (parameter){}

What is constructor

In Java, a constructor is a block of code similar to the method. It is called when an instance of the object is created, and memory is allocated for the object.

Super keyword

The super keyword in Java is a reference variable which is used to refer to the immediate parent class object. Whenever you create an instance of a class, an instance of the parent class is created implicitly which is referred to by the super reference variable.

Static vs non-static

Static keywords can be used with class, variable, method and block. Static members belong to the class instead of a specific instance, this means if you make a member static, you can access it without an object.

  • Static block: Static block is used for initializing the static variables. This block gets executed when the class is loaded in the memory.

  • Static variable: A static variable is common to all the instances (or objects) of the class because it is a class level variable.

  • Static method: A static method belongs to the class rather than the object of a class, it can be invoked without the need for creating an instance of a class and can access static data members and can change the value of it.

  • Static class: A class can be made static only if it is a nested class.

https://blog.csdn.net/iispring/article/details/46490319

final / finally / finalized

https://blog.csdn.net/iispring/article/details/46490319

The final keyword in java is used to restrict the user, it can be used in many contexts, such as variable, method and class.

  • Java final variable

A final variable that has no value is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.

  • Java final method

If you make any method final, you cannot override it.

  • Java final class

If you create any class as final, you cannot extend it.

Passing by value

(Example) https://www.tutorialspoint.com/cplusplus/cpp_passing_pointers_to_functions.htm

https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value#:~:text=Pass%2Dby%2Dvalue%20means%20that,always%20pass%2Dby%2Dvalue

When calling a function, each input parameter variable from the caller will be copied for the callee. The caller and callee have two sets of independent parameter variables. If the callee modifies the parameter variable, the effect is not visible to the caller. Caller's parameter variables value won't be changed.

For object type variables(String, List, Person, Vehicle), callee's parameter variables point to the address of the object (the value is the address). If the callee modifies the value of the parameter variable, this means callee's parameter variables point to a new address / object. The effect is not visible to the caller, because the parameter variable of the caller and callee points to different addresses / objects.

public class Main {
    static class Person{
        String name;
    }
    // Primitive Type
    public static void function1(int j){
        j = 10;
        System.out.println(j);
    }

    // Object Type
    public static void function2(Person b){
        b.name = "xyz";
        System.out.println(b.name);
    }

    // Object Type
    public static void function3(Person b){
        b = new Person();
        b.name = "xyz";
        System.out.println(b.name);
    }

    //Object Type - String
    public static void function4(String b){
        b = "xyz";
        System.out.println(b);
    }

    public static void main(String[] args) {
        int i = 5;
        function1(i);         // output 10
        System.out.println(i); // output 5
        // Explanation: j is a copy of i, i and j are independent variables

        Person a = new Person();
        a.name = "abc";
        System.out.println(a.name); // output abc
        function2(a);               // output xyz
        System.out.println(a.name); // output xyz
        // Explanation: b is a copy of a, a and b pointing to the same address of the
        // Person object. Variable a and b's value is the address.
        // Variable b did not change it's value(address), it only changed the Person
        // object stored in the address. So, variable a will be affected.

        Person a3 = new Person();
        a3.name = "abc";
        System.out.println(a3.name);     // output abc
        function3(a3);        // output xyz
        System.out.println(a.name);    // abc
        // Explanation: b is a copy of a, a and b pointing to the same address of the Person object. Variable a and
        // b's value is the address.
        // Valuable b changed it's value (address) and pointed to a new Person object.
        // So, variable a will not be affected


        String a4 = "abc";
        System.out.println(a4);    //output abc
        function4(a4);            //output xyz
        System.out.println(a4);    //output abc
        // Explanation: b is a copy of a, a and b pointing to the same address of the String object.
        // Because String is immutable, when given to a new value, a new String object will be created.
        // Variable b's value (address) is changed and pointed to a new String object(xyz). So,
        // Variable a will not be affected.

    }
}

Screenshot 2023-05-05 at 23.02.11

Java Versions

java versions release cycles 7

Reference Book

Core Java Volume I--Fundamentals (Core Series): Horstmann, Cay: 9780135166307

Effective Java: Bloch, Joshua: 9780134685991

Example code

Example1: https://drive.google.com/file/d/1I6V1-RzI6sioMftUkBIvawsm97DNzMNX/view?usp=sharing

Example 2: https://drive.google.com/file/d/1wooeqC30QSI6JO2RSEZlPBqqOwj4vaBB/view?usp=sharing

Example 3:https://drive.google.com/file/d/1rUv80Ub_ctIPOJfEFgA2UMzo1uLXecAe/view?usp=sharing

Example4: https://drive.google.com/file/d/1EkBPE5yuFi5WeZ2NKKjHXMwG0DKjl6eN/view?usp=sharing