已发布·持续改进
Java 指南 · 2/6
本章目前仅提供英文版。
Java is statically typed, and all code lives inside classes. Statements end with semicolons and blocks are wrapped in braces. This chapter covers classes and the main method, variables and var, methods, branching and loops, switch expressions, and working with strings.
A class bundles state (fields) with behavior (methods). A runnable program needs one class with a main method. The static keyword means the method belongs to the class itself, so it can be called without creating an object first.
package com.example.basics;
public class Greeter {
private final String greeting; // field
public Greeter(String greeting) { // constructor
this.greeting = greeting;
}
public String greet(String name) { // instance method
return greeting + ", " + name;
}
public static void main(String[] args) {
Greeter greeter = new Greeter("Hello");
System.out.println(greeter.greet("Java"));
}
}There are four access levels: public (visible everywhere), protected (same package plus subclasses), package-private (no modifier at all), and private (only inside the class). The usual habit is to keep fields private and expose only the methods callers actually need.
You declare a variable with a type and a name. For local variables you can write var and let the compiler infer the type from the initializer. This is not dynamic typing: the inferred type is fixed for the life of the variable. Mark a variable final to prevent reassignment.
int count = 10;
double ratio = 0.75;
boolean done = false;
String title = "Java";
var names = new java.util.ArrayList<String>(); // inferred as ArrayList<String>
names.add("Duke");
final int max = 100;
// max = 200; // compile error: cannot assign a value to final variablevar only works for local variables, not for fields or method parameters. It shines when the type is long and already obvious from the right-hand side.
A method declaration lists a return type, a name, and parameters; use void when nothing is returned. Overloading lets you define several methods with the same name as long as their parameter lists differ. Java always passes arguments by value; for objects, the value being copied is the reference.
public class MathUtil {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) { // overload
return a + b;
}
static int sum(int... values) { // varargs
int total = 0;
for (int v : values) total += v;
return total;
}
}The usual suspects are all here: /, the classic , the enhanced for-each loop, , and . Use to leave a loop early and to skip to the next iteration.
ifelseforwhiledo-whilebreakcontinueint score = 82;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else {
System.out.println("C");
}
for (int i = 0; i < 3; i++) {
System.out.println("i = " + i);
}
for (String lang : java.util.List.of("Java", "Kotlin", "Scala")) {
if (lang.equals("Kotlin")) continue;
System.out.println(lang);
}
int n = 3;
while (n > 0) {
n--;
}The old switch statement falls through to the next case whenever you forget a break. The arrow form (->) never falls through and produces a value, so you can assign or return it directly. When a case needs several statements, use a block and hand back the result with yield.
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
static String kind(Day day) {
return switch (day) {
case SAT, SUN -> "weekend";
case MON, TUE, WED, THU, FRI -> "weekday";
};
}
static int length(Object value) {
return switch (value) {
case String s -> s.length();
case java.util.List<?> list -> list.size();
case null -> 0;
default -> {
String text = value.toString();
yield text.length();
}
};
}When every enum constant is covered, no default branch is needed. The second example uses type patterns: each case checks the runtime type and binds the value to a new variable in one step.
String objects are immutable; every method that seems to modify a string actually returns a new one. Compare contents with equals, never ==, because == only checks whether two references point at the same object.
String s = " Hello, Java ";
String trimmed = s.strip(); // "Hello, Java"
boolean same = trimmed.equals("Hello, Java"); // true
String upper = trimmed.toUpperCase();
String[] parts = trimmed.split(", "); // ["Hello", "Java"]
String message = "%s has %d chars".formatted(trimmed, trimmed.length());
String json = """
{
"name": "Duke",
"lang": "Java"
}
"""; // text block
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i).append(',');
System.out.println(sb); // 0,1,2,When you build up a string piece by piece inside a loop, a StringBuilder avoids creating a pile of throwaway objects. For multi-line content, text blocks delimited by triple quotes keep the text readable without escape sequences.
main.var for inference, but their types remain static.equals and build large ones with StringBuilder.
0 条评论
登录 · 登录后即可发表评论。
来发表第一条评论吧。