Java 的基础语法与 C++ 较为类似。以下代码均包含于 src/main/java/examples/introduction 中。
输入输出
IOExample.java
1package examples.introduction;
2 3import java.util.Scanner;
4 5public class IO {
6public static void main(String[] args) {
7// Console Output
8System.out.println("This is an output with a new line.");
9System.out.print("This is an output without a new line.");
10System.out.println("So this sentence will appear right after the last one.");
1112// Console Input
13Scanner input = new Scanner(System.in);
14System.out.print("Enter your name: ");
15String name = input.nextLine();
16System.out.print("Enter your age: ");
17int age = input.nextInt();
18System.out.println("Hello " + name + ", you are " + age + " years old!");
19 }
20}
这个程序中展现了 Java 中基础的输入输出方式。相较于 C++ 而言,输入输出所用函数名较长,但也并不繁琐。
1package examples.introduction;
2 3import java.util.InputMismatchException;
4import java.util.Scanner;
5 6public class ExceptionHandling {
7public static void main(String[] args) {
8Scanner sc = new Scanner(System.in);
9System.out.println("Enter a non-negative integer n, and I will try to calculate 100 / n: ");
10try {
11int n = sc.nextInt();
12int result = 100 / n; // if n = 0 then `ArithmeticException` will be thrown
13if (n < 0)
14throw new IllegalArgumentException("Number is negative."); // custom exception
15System.out.println("Result: " + result);
16 } catch (ArithmeticException e) { // will be executed if n = 0
17System.out.println("Number is zero.");
18 } catch (InputMismatchException e) {
19System.out.println("Number is not an integer.");
20 } catch (Exception e) { // will be executed if other exception occurs
21 e.printStackTrace();
22 } finally { // will be executed always
23System.out.println("Finally block is always executed.");
24 sc.close();
25 }
26 }
27}
1package examples.datastructures;
2 3import java.util.ArrayList;
4import java.util.Arrays;
5 6public class ArraysAndArrayListExample {
7public static void main(String[] args) {
8// Example usage of Arrays
9int[] numbersArray = {1, 1, 4, 5, 1, 4};
1011// Print the length of the array
12System.out.println("numbersArray.length = " + numbersArray.length);
1314// Print the first element of the array
15System.out.println("numbersArray[0] = " + numbersArray[0]);
1617// Use Arrays.toString to print the contents of the array
18System.out.println("Arrays.toString(numbersArray) = " + Arrays.toString(numbersArray));
1920// Check if the array is equal to itself
21System.out.println("Arrays.equals(numbersArray, numbersArray) = " + Arrays.equals(numbersArray, numbersArray));
2223// Use Arrays.binarySearch to perform binary search for the element 4
24System.out.println("Arrays.binarySearch(numbersArray, 4) = " + Arrays.binarySearch(numbersArray, 4));
2526// Use Arrays.copyOf to create a new array containing the first 3 elements of the original array
27System.out.println("Arrays.copyOf(numbersArray, 3) = " + Arrays.toString(Arrays.copyOf(numbersArray, 3)));
2829// Use Arrays.copyOfRange to create a subarray from index 1 to 3
30System.out.println("Arrays.copyOfRange(numbersArray, 1, 3) = " + Arrays.toString(Arrays.copyOfRange(numbersArray, 1, 3)));
3132// Use Arrays.sort to sort the array
33Arrays.sort(numbersArray);
34System.out.println("Arrays.sort(numbersArray) = " + Arrays.toString(numbersArray));
3536// Use Arrays.fill to fill the array with zeros
37Arrays.fill(numbersArray, 0);
38System.out.println("Arrays.fill(numbersArray, 0) = " + Arrays.toString(numbersArray));
3940// Print the hash code of the array after filling with zeros
41System.out.println("Arrays.hashCode(numbersArray) = " + Arrays.hashCode(numbersArray));
4243// Example usage of ArrayList
44ArrayList<String> sitesList = new ArrayList<>();
4546// Add elements to the ArrayList
47 sitesList.add("Google");
48 sitesList.add("Runoob");
49 sitesList.add("Taobao");
50 sitesList.add("Weibo");
5152// Print all elements in the ArrayList
53System.out.println("ArrayList<String> sitesList = " + sitesList);
5455// Example of other ArrayList operations
56// Check if the ArrayList contains a specific element
57System.out.println("sitesList.contains(\"Runoob\") = " + sitesList.contains("Runoob"));
5859// Get the size of the ArrayList
60System.out.println("sitesList.size() = " + sitesList.size());
6162// Remove an element from the ArrayList
63 sitesList.remove("Taobao");
64System.out.println("sitesList after removing \"Taobao\" = " + sitesList);
6566// Get an element at a specific index
67System.out.println("sitesList.get(1) = " + sitesList.get(1));
6869// Set an element at a specific index
70 sitesList.set(1, "Baidu");
71System.out.println("sitesList after setting index 1 to \"Baidu\" = " + sitesList);
7273// Clear all elements in the ArrayList
74 sitesList.clear();
75System.out.println("sitesList after clear() = " + sitesList);
76 }
77}
1package examples.datastructures;
2 3import java.util.LinkedList;
4import java.util.List;
5 6public class LinkedListExample {
7public static void main(String[] args) {
8// Create a new LinkedList instance
9List<String> linkedList = new LinkedList<>();
1011// Add elements to the LinkedList
12 linkedList.add("Element 1");
13 linkedList.add("Element 2");
14 linkedList.add("Element 3");
1516// Print the LinkedList
17System.out.println("Initial LinkedList: " + linkedList);
1819// Access the first element
20String firstElement = linkedList.get(0);
21System.out.println("First Element: " + firstElement);
2223// Access the last element
24String lastElement = linkedList.get(linkedList.size() - 1);
25System.out.println("Last Element: " + lastElement);
2627// Remove the first occurrence of an element
28 linkedList.remove("Element 2");
29System.out.println("LinkedList after removing 'Element 2': " + linkedList);
3031// Add an element at the beginning
32 linkedList.addFirst("New First Element");
33System.out.println("LinkedList after adding new first element: " + linkedList);
3435// Add an element at the end
36 linkedList.addLast("New Last Element");
37System.out.println("LinkedList after adding new last element: " + linkedList);
3839// Remove the first element
40 linkedList.removeFirst();
41System.out.println("LinkedList after removing the first element: " + linkedList);
4243// Remove the last element
44 linkedList.removeLast();
45System.out.println("LinkedList after removing the last element: " + linkedList);
4647// Get the size of the LinkedList
48int size = linkedList.size();
49System.out.println("Size of the LinkedList: " + size);
5051// Check if the LinkedList is empty
52boolean isEmpty = linkedList.isEmpty();
53System.out.println("Is the LinkedList empty? " + isEmpty);
5455// Clear all elements from the LinkedList
56 linkedList.clear();
57System.out.println("LinkedList after clear(): " + linkedList);
5859// Demonstrate iteration over LinkedList elements
60System.out.println("Iterating over LinkedList elements:");
61for (String element : linkedList) {
62System.out.println(element);
63 }
64 }
65}
1package examples.datastructures;
2 3import java.util.HashSet;
4import java.util.Set;
5 6public class HashSetExample {
7public static void main(String[] args) {
8// Create a new HashSet instance
9Set<String> set = new HashSet<>();
1011// Add elements to the HashSet
12 set.add("Apple");
13 set.add("Banana");
14 set.add("Cherry");
1516// Print the HashSet
17System.out.println("Initial HashSet: " + set);
1819// Check if the HashSet contains an element
20boolean contains = set.contains("Banana");
21System.out.println("Does the HashSet contain 'Banana'? " + contains);
2223// Remove an element from the HashSet
24 set.remove("Apple");
25System.out.println("HashSet after removing 'Apple': " + set);
2627// Get the size of the HashSet
28int size = set.size();
29System.out.println("Size of the HashSet: " + size);
3031// Check if the HashSet is empty
32boolean isEmpty = set.isEmpty();
33System.out.println("Is the HashSet empty? " + isEmpty);
3435// Clear all elements from the HashSet
36 set.clear();
37System.out.println("HashSet after clear(): " + set);
3839// Demonstrate iteration over HashSet elements
40System.out.println("Iterating over HashSet elements:");
41for (String fruit : set) {
42System.out.println(fruit);
43 }
4445// Add elements back to the HashSet and demonstrate uniqueness
46 set.add("Apple"); // Duplicate element
47 set.add("Apple"); // Attempt to add duplicate
48System.out.println("HashSet with duplicate 'Apple': " + set);
49 }
50}
1package examples.datastructures;
2 3import java.util.HashMap;
4import java.util.Map;
5 6public class HashMapExample {
7public static void main(String[] args) {
8// Create a new HashMap instance
9Map<String, Integer> map = new HashMap<>();
1011// Put key-value pairs into the HashMap
12 map.put("One", 1);
13 map.put("Two", 2);
14 map.put("Three", 3);
1516// Print the HashMap
17System.out.println("Initial HashMap: " + map);
1819// Get the value associated with a key
20Integer value = map.get("Two");
21System.out.println("Value for key 'Two': " + value);
2223// Check if a key exists in the HashMap
24boolean containsKey = map.containsKey("Three");
25System.out.println("Does the key 'Three' exist? " + containsKey);
2627// Remove a key-value pair from the HashMap
28 map.remove("One");
29System.out.println("HashMap after removing 'One': " + map);
3031// Get the size of the HashMap
32int size = map.size();
33System.out.println("Size of the HashMap: " + size);
3435// Check if the HashMap is empty
36boolean isEmpty = map.isEmpty();
37System.out.println("Is the HashMap empty? " + isEmpty);
3839// Clear all key-value pairs from the HashMap
40 map.clear();
41System.out.println("HashMap after clear(): " + map);
4243// Demonstrate iteration over HashMap entries
44System.out.println("Iterating over HashMap entries:");
45for (Map.Entry<String, Integer> entry : map.entrySet()) {
46System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
47 }
48 }
49}
面向对象程序设计
Java 最初的设计目标之一就是成为一种纯粹的面向对象语言。所有的代码都必须包含在类(Class)中,基本上所有元素都是对象(基本数据类型除外)。它支持封装、继承和多态等面向对象的核心概念,并鼓励开发者使用这些概念构建模块化和可重用的代码。具体地说,所有的 Java 代码都需要封装在类里,每一个 .java 文件恰有一个与其同名的 public 类。
1package examples.oop;
2 3public class StaticExample {
4static class Car {
5static int counter = 0;
6String name;
7 8Car(String name) {
9 this.name = name;
10 counter++;
11 }
12 @Override
13public String toString() {
14return "Car [name=" + name + "]";
15 }
16 }
17public static void main(String[] args) {
18Car a = new Car("Benz");
19System.out.println("First car: " + a + ". Total car count: " + Car.counter);
20Car b = new Car("Honda");
21System.out.println("Second car: " + b + ". Total car count: " + Car.counter);
22Car c = new Car("Volkswagen");
23System.out.println("Third car: " + c + ". Total car count: " + Car.counter);
24 }
25}
实例初始化块
在类中直接使用 {} 扩起来的部分称为实例初始化块,它会在任何构造器运行之前运行。
java
1class Test {
2 { System.out.println("This is an Instance Initialization Block."); }
3public Test() {
4System.out.println("This is a constructor.");
5 }
6}
当实例化一个 Test 类型的对象时,运行结果将会是
text
1This is an Instance Initialization Block.
2This is a constructor.
final
final 修饰的成员变量是常量,因此除了声明赋值、构造函数、实例初始化块之外,不允许对其进行其他修改。
通常使用 static final 来定义静态常量。一般使用 SCREAMING_SNAKE_CASE(全字母大写,用下划线分隔)来命名。例如:
java
1public class Wordle {
2static final int ALPHABET_SIZE = 26; // The size of the alphabet
3static final int WORD_LENGTH = 5; // The length of words
4static final int TOTAL_CHANCES = 6; // The chances in total
5// ...
6}