编程语言·

Java速查表

这份速查表是针对Java初学者的速成课程,有助于复习Java语言的基本语法。

入门指南

Hello.java

public class Hello {
  // 主方法
  public static void main(String[] args)
  {
    // 输出: Hello, world!
    System.out.println("Hello, world!");
  }
}

编译和运行

$ javac Hello.java
$ java Hello
Hello, world!

变量

int num = 5;
float floatNum = 5.99f;
char letter = 'D';
boolean bool = true;
String site = "chatsheet.org";

基本数据类型

数据类型大小默认值范围
byte1 字节0-128 到 127
short2 字节0-2^15 到 2^15-1
int4 字节0-2^31 到 2^31-1
long8 字节0-2^63 到 2^63-1
float4 字节0.0fN/A
double8 字节0.0dN/A
char2 字节\u00000 到 65535
booleanN/Afalsetrue 或 false

{.show-header}

字符串

String first = "John";
String last = "Doe";
String name = first + " " + last;
System.out.println(name);

详见:Strings

循环

String word = "CheatSheets";
for (char c: word.toCharArray()) {
  System.out.print(c + "-");
}
// 输出: C-h-e-a-t-S-h-e-e-t-s-

详见:Loops

数组

char[] chars = new char[10];
chars[0] = 'a';
chars[1] = 'b';

String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

详见:Arrays

交换

int a = 1;
int b = 2;
System.out.println(a + " " + b); // 1 2

int temp = a;
a = b;
b = temp;
System.out.println(a + " " + b); // 2 1

类型转换

// 扩展
// byte<short<int<long<float<double
int i = 10;
long l = i;               // 10

// 缩小
double d = 10.02;
long l = (long)d;         // 10

String.valueOf(10);       // "10"
Integer.parseInt("10");   // 10
Double.parseDouble("10"); // 10.0

条件语句

int j = 10;

if (j == 10) {
  System.out.println("I get printed");
} else if (j > 10) {
  System.out.println("I don't");
} else {
  System.out.println("I also don't");
}

详见:Conditionals

用户输入

Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(str);

int num = in.nextInt();
System.out.println(num);

Java 字符串

基础

String str1 = "value";
String str2 = new String("value");
String str3 = String.valueOf(123);

连接

String s = 3 + "str" + 3;     // 3str3
String s = 3 + 3 + "str";     // 6str
String s = "3" + 3 + "str";   // 33str
String s = "3" + "3" + "23";  // 3323
String s = "" + 3 + 3 + "23"; // 3323
String s = 3 + 3 + 23;        // 不兼容类型

StringBuilder

StringBuilder sb = new StringBuilder(10);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
|   |   |   |   |   |   |   |   |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.append("QuickRef");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.delete(5, 9);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k |   |   |   |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.insert(0, "My ");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y |   | Q | u | i | c | k |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.append("!");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y |   | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

比较

String s1 = new String("QuickRef");
String s2 = new String("QuickRef");

s1 == s2          // false
s1.equals(s2)     // true

"AB".equalsIgnoreCase("ab")  // true

操作

String str = "Abcd";

str.toUpperCase();     // ABCD
str.toLowerCase();     // abcd
str.concat("#");       // Abcd#
str.replace("b", "-"); // A-cd

"  abc ".trim();       // abc
"ab".toCharArray();    // {'a', 'b'}

信息

String str = "abcd";

str.charAt(2);       // c
str.indexOf("a")     // 0
str.indexOf("z")     // -1
str.length();        // 4
str.toString();      // abcd
str.substring(2);    // cd
str.substring(2,3);  // c
str.contains("c");   // true
str.endsWith("d");   // true

对象

String str = "Abcd";

str.hashCode();  // 101574
str.getClass();  // java.lang.String

类型转换

String str = "123";

Integer.parseInt(str);    // 123
Integer.valueOf(str);     // 123

Integer.toString(123);    // "123"

表示

String str = "Hello world!";
System.out.println(str);      // Hello world!

System.out.printf("Print integer: %d", 123); // Print integer: 123

Java 循环

for 循环

for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

while 循环

int i = 0;
while (i < 5) {
  System.out.println(i);
  i++;
}

do while 循环

int i = 0;
do {
  System.out.println(i);
  i++;
} while (i < 5);

break 语句

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  System.out.println(i);
}

continue 语句

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    continue;
  }
  System.out.println(i);
}

Java 数组

定义数组

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myNum = {10, 20, 30, 40};

访问元素

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);

修改元素

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);

数组长度

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);

for each 循环

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
  System.out.println(i);
}

Java 条件语句

if 语句

int x = 20;
if (x > 18) {
  System.out.println("x 大于 18");
}

else if 语句

int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}

switch 语句

int day = 4;
switch (day) {
  case 1:
    System.out.println("星期一");
    break;
  case 2:
    System.out.println("星期二");
    break;
  case 3:
    System.out.println("星期三");
    break;
  case 4:
    System.out.println("星期四");
    break;
  case 5:
    System.out.println("星期五");
    break;
  default:
    System.out.println("周末");
}

三元操作符

int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);

Java 面向对象

创建类

public class MyClass {
  int x = 5;

  public static void main(String[] args) {
    MyClass myObj = new MyClass();
    System.out.println(myObj.x);
  }
}

public class MyClass {
  int x = 5;

  public static void main(String[] args) {
    MyClass myObj = new MyClass();
    System.out.println(myObj.x);
  }
}

访问修饰符

public class MyClass {
  public int x = 5;
  protected int y = 45;
  private int z = 9;

  public static void main(String[] args) {
    MyClass myObj = new MyClass();
    System.out.println(myObj.x);
  }
}

构造函数

public class MyClass {
  int x;  // 创建一个类构造函数

  public MyClass() {
    x = 5;  // constructor
  }

  public static void main(String[] args) {
    MyClass myObj = new MyClass();
    System.out.println(myObj.x);
  }
}

继承

public class Car extends Vehicle {
  int maxSpeed = 120;

  public static void main(String[] args) {
    Car myCar = new Car();
    myCar.honk();
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}

接口

interface Animal {
  public void animalSound();
  public void sleep();
}

class Pig implements Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    System.out.println("Zzz");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig();
    myPig.animalSound();
    myPig.sleep();
  }
}

父类构造

class Animal {
  public Animal() {
    System.out.println("Animal");
  }
}

class Dog extends Animal {
  public Dog() {
    System.out.println("Dog");
  }

  public static void main(String[] args) {
    Dog myDog = new Dog();
  }
}

构造器

class Main {
  int x;

  public Main(int y) {
    x = y;
  }

  public static void main(String[] args) {
    Main myObj = new Main(5);
    System.out.println(myObj.x);
  }
}

例子

class Main {
  int x;

  public Main() {
    x = 5;
  }

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}

Java 异常

介绍

try {
  int[] myNumbers = {1, 2, 3};
  System.out.println(myNumbers[10]);
} catch (Exception e) {
  System.out.println("Something went wrong.");
} finally {
  System.out.println("The 'try catch' is finished.");
}

自定义

class Main {
  static void checkAge(int age) {
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    } else {
      System.out.println("Access granted - You are old enough!");
    }
  }

  public static void main(String[] args) {
    checkAge(15); // Access denied - You must be at least 18 years old.
  }
}

测试

class Main {
  static void checkAge(int age) {
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    } else {
      System.out.println("Access granted - You are old enough!");
    }
  }

  public static void main(String[] args) {
    checkAge(20); // Access granted - You are old enough!
  }
}

Java 输入/输出

文件读取

import java.io.File;  // 文件类

class Main {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      Scanner myReader = new Scanner(myObj);
      while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        System.out.println(data);
      }
      myReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

文件写入

import java.io.FileWriter;   // 文件写入

class Main {
  public static void main(String[] args) {
    try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("Files in Java might be tricky, but it is fun enough!\n");
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

网络

import java.net.URL;     // Java URL 类

class Main {
  public static void main(String[] args) {
    try {
      URL myUrl = new URL("https://www.w3cschool.cn/java/java-exceptions.html");
      Scanner myReader = new Scanner(myUrl.openStream());
      while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        System.out.println(data);
      }
      myReader.close();
    } catch (Exception e) {
      System.out.println("An error occurred.");
      e

.printStackTrace();
    }
  }
}

Java 多线程

线程

class Main extends Thread {
  public void run() {
    System.out.println("This code is running in a thread");
  }

  public static void main(String[] args) {
    Main myThread = new Main();
    myThread.start();
  }
}

同步

public class Main {
  public static void main(String[] args) {
    Printer p = new Printer();
    Thread1 t1 = new Thread1(p);
    Thread2 t2 = new Thread2(p);
    t1.start();
    t2.start();
  }
}

class Printer {
  synchronized void printDocuments(int numOfCopies, String docName) {
    for (int i = 1; i <= numOfCopies; i++) {
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println(">> Printing " + docName + " " + i);
    }
  }
}

class Thread1 extends Thread {
  Printer pRef;

  Thread1(Printer p) {
    pRef = p;
  }

  public void run() {
    pRef.printDocuments(10, "Java Basics.pdf");
  }
}

class Thread2 extends Thread {
  Printer pRef;

  Thread2(Printer p) {
    pRef = p;
  }

  public void run() {
    pRef.printDocuments(10, "Java Methods.pdf");
  }
}

资源

public class Main {
  public static void main(String[] args) {
    MyResourcePool pool = new MyResourcePool(3);
    for (int i = 0; i < 5; i++) {
      Thread t = new Thread(new MyThread(pool, "Thread-" + i));
      t.start();
    }
  }
}

class MyResourcePool {
  Semaphore semaphore;

  MyResourcePool(int count) {
    semaphore = new Semaphore(count);
  }

  void getResource() {
    try {
      semaphore.acquire();
      System.out.println(Thread.currentThread().getName() + " got the permit.");
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      semaphore.release();
      System.out.println(Thread.currentThread().getName() + " released the permit.");
    }
  }
}

class MyThread implements Runnable {
  MyResourcePool pool;
  String name;

  MyThread(MyResourcePool pool, String name) {
    this.pool = pool;
    this.name = name;
  }

  public void run() {
    System.out.println(name + " is waiting to get the permit.");
    pool.getResource();
  }
}

问题

import java.util.LinkedList;
import java.util.Queue;

public class Main {
  public static void main(String[] args) {
    Printer p = new Printer();
    Thread1 t1 = new Thread1(p);
    Thread2 t2 = new Thread2(p);
    t1.start();
    t2.start();
  }
}

class Printer {
  private final Queue<String> tasks = new LinkedList<>();

  public synchronized void addTask(String task) {
    tasks.add(task);
    notify();
  }

  public synchronized void printTask() throws InterruptedException {
    while (tasks.isEmpty()) {
      wait();
    }
    String task = tasks.poll();
    System.out.println("Printing task: " + task);
  }
}

class Thread1 extends Thread {
  private final Printer printer;

  Thread1(Printer printer) {
    this.printer = printer;
  }

  public void run() {
    printer.addTask("Task 1");
    printer.addTask("Task 2");
    printer.addTask("Task 3");
  }
}

class Thread2 extends Thread {
  private final Printer printer;

  Thread2(Printer printer) {
    this.printer = printer;
  }

  public void run() {
    try {
      printer.printTask();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}