Java 初步: 简化版

主要参考 java4python “Learn Java: Programiz” app 上的小课. Just a quick review.

Hello world

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
  • 每个 Java 程序必须定义一个类, 所有代码写在那个类里
  • 每个 Java 程序必须有一个 public static void main(String[] args) 函数
  • System 是一个类, 其中有 out 对象 (标准输出流), 再调用 println(String s) 方法 (末尾加上换行符)
  • String[] 表示 String 的 array
class Hello:
    @staticmethod
    def main(args: list[str]):
        print("Hello World!")

Datatypes

  • primitives: int, float, double, char, boolean
  • wrapper classes: Integer, Float, Double, Char, Boolean

优先用 primitives, 见 这里

/* 
* 类似 Python `from java.util import Scanner`
* 只能这么 import 一个类 (Scanner), 不能 `from java
 import util` 再用 `util.Scanner`
* java.util 称为 package
* 不 import 可以直接用 `java.util.Scanner`
*/
import java.util.Scanner;

public class Foo {
    public static void main(String[] args) {
        Double x;
        Scanner in;

        // 初始化实例
        in = new Scanner(System.in);
        System.out.println("Enter a number: ");
        x = in.nextDouble();
        System.out.println("The num is: " + x);
    }
}

String

Like Python, Java strings are immutable. However, manipulating strings in Java is not quite as obvious since Strings do not support an indexing or slicing operator. Java does not support any operator overloading.

Python Java
str[3] str.charAt(3)
str[2:4] str.substring(2,4)
len(str) str.length()

TODO: 比较字符串

Collections

Arrays

int[] data;  // declare
data = new int[4];  // allocate memory, 默认值 0
// 不能像 c++ 那样直接 int[4] data;
int[] data2 = new int[4];  // in one line
int[][] data2d = new int[3][4];

int[] data3 = {0, 1};
data3[0] = 233;
int size = data3.length;

int[] data4 = data3;  // c++ 不能这么写?

ArrayList

类似 C++ 的 Vector 或者 Python 的 list. 不能创建 primitives (int, double, char 等) 的容器, 但可以用它们的 wrapper classes (Integer, Double, Character).

import java.util.ArrayList;

ArrayList<String> languages = new ArrayList<>();
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;


public class Foo {

    public static void main(String[] args) {
        Scanner data = null;
        ArrayList<Integer> nums;
        
        try {
            data = new Scanner(new File("non-exist.txt"));
        }
        catch (IOException e) {
            System.out.println("Unable to open file");
            e.printStackTrace();
            // System.exit(0);
        }

        nums = new ArrayList<Integer>(10);
        for (Integer i = 0; i < 10; i++) {
            // public void add(int index, E element)
            nums.add(i, (int) Math.pow(i, 2));  // double to int
        }

        for(Integer i : nums) {
            System.out.println(i);
        }
    }
}

In Java we can not write nums[i] = nums[i] + 1. This is because in Java there is no overloading of operators. Everything except the most basic math and logical operations is done using methods. So, to set the value of an ArrayList element we use the set method.

  • 双向链表 java.util.LinkedList
  • 集合 java.util.HashSet
  • 字典 java.util.HashMap, java.util.TreeMap

java.util.Collectionssort 等方法.

Classes

By default, the classes visibility is package private, i.e. only visible for classes in the same package.

class Foo {
    int bar, a;
    // associated with the class not an instance
    static String s;
    
    Foo(int bar, int a) {
        this.bar = bar;
        this.a = a;
    }
}
class Animal {
    int age = 5;

    void eat() {
        System.out.println("eating");
    }
    
    abstract void foo();
}

class Dog extends Animal {
    void eat() {
        System.out.println("dog" + super.age);
        super.eat();
        // super() 调用父类的 constructor
    }
    
    void foo() {
        System.out.println("具体实现");
    }
}
// 只有抽象方法的类, cannot contain fields
interface Language {
    void getName(String name);
}
interface Bar {...}

class SomeLanguage implements Language, Bar {
    public void getName(String name) {
        System.out.println(name);
    }
}