Java tips

11.29

多个文件编译运行

可以只编译运行入口文件(包含main的文件)。其它类,只要类名与文件名相同,会自动编译和引入这些类。

举例,有三个文件Deck.java, Suit.java, Rank.javaDeck.java 中使用了类Suit, Rank

javac Deck.java
java Deck

Stream Aggregate Operations

stream, filter, map, forEach, ...

persons
    .stream()
    .filter(p -> p.getGender() == Person.Sex.MALE)
    .map(p -> p.getEmailAddress())
    .forEach(email -> System.out.println(email));

Primitive data types and default values

Field variables

Data TypeDefault Value (for fields)
byte0
short0
int0
long0L
float0.0f
double0.0d
char'\u0000'
String (or any object)null
booleanfalse

Local variables

Local variables are uninitialized if you cannot initialize them.

Operator Precedence

OperatorsPrecedence
postfixexpr++ expr--
unary++expr --expr +expr -expr ~ !
multiplicative* / %
additive+ -
shift<< >> >>>
relational< > <= >= instanceof
equality== !=
bitwise AND&
bitwise exclusive OR^
bitwise inclusive OR|
logical AND&&
logical OR|
ternary? :
assignment= += -= *= /= %= &= ^= |= <<= >>= >>>=

Dependency Injection pattern

class Foo {
    private Database database;

    Foo() {
        this.database = new Database("/path/to/my/data");
    }
}

// Use dependency injection
class Foo {
    private Database database;

    Foo(Database database) {
        this.database = database
    }
}

可以使用guice,轻量级的 dependency injection framework.

Install java on ubuntu

JRE

<https://ubuntu.com/tutorials/install-jre#2-installing-openjdk-jre >

To install the OpenJDK JRE, we run

sudo apt update
sudo apt install default-jre

java --version

JDK

sudo apt install openjdk-11-demo openjdk-11-doc openjdk-11-jdk openjdk-11-source

Set JAVA_HOME

列出安装的 java 环境

sudo update-alternatives --config java

选择合适的,设置环境变量 JAVA_HOME

JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"

Glossary

JRE

Java software for your computer, or the Java Runtime Environment, is also referred to as the Java Runtime, Runtime Environment, Runtime, JRE, Java Virtual Machine, Virtual Machine, Java VM, JVM, VM, Java plug-in, Java plugin, Java add-on or Java download.

JDK

Java Development Kit, contains JRE.

📖