Java Syntax Basics: Variables, Types, Control Flow & Methods

Primitive and reference types, var keyword, operators, if/switch/for/while, arrays and method definitions — the complete syntax foundation for writing Java.

BeginnerUpdated 2026-10-3098K views

Variables and Data Types

Java has 8 primitive types (fixed size on every platform) plus reference types. Java 10 introduced var for local type inference.

// 基本类型
int age = 25;              // 32-bit integer
long id = 10000000000L;    // 64-bit integer
double price = 19.99;      // double precision float
boolean active = true;
char grade = 'A';
byte b = 127;              // -128 .. 127

// 引用类型
String name = "BackendWiki";
int[] nums = {1, 2, 3};

// var 类型推断(仅限局部变量)
var list = new ArrayList<String>();
TypeSizeRange / Usage
byte1 byte-128 to 127
int4 bytes-2^31 to 2^31-1, the default integer type
long8 byteslarge IDs, timestamps (append L)
double8 bytesdefault floating point type
boolean1 bit (JVM spec)true / false

Operators and Control Flow

int score = 85;

// if - else if - else
if (score >= 90) {
    System.out.println("A");
} else if (score >= 60) {
    System.out.println("B");
} else {
    System.out.println("F");
}

// switch 表达式(Java 14+)
String day = switch (score / 10) {
    case 9, 10 -> "Excellent";
    case 6, 7, 8 -> "Pass";
    default -> "Fail";
};

// for / while / 增强 for
int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
for (int n : arr) {       // 增强 for 循环
    sum += n;
}
while (sum > 0) {
    sum--;
}

// 三元运算符
String label = score >= 60 ? "pass" : "fail";

Strings

String is immutable; use StringBuilder for repeated concatenation in loops and String.format (or text blocks since Java 15) for templated text.

String s = "hello";
s = s + " world";            // 生成新对象

// 文本块(三引号,Java 15+)
String json = """
        {"name": "Java", "version": 21}
        """;

// 常用方法
"Java".length();            // 4
"Java".toUpperCase();       // JAVA
"a,b,c".split(",");         // [a, b, c]
String.format("%-8s:%d", "id", 7);

Arrays and Methods

// 数组
int[] a = new int[5];              // 默认值 0
int[] b = {10, 20, 30};
int len = b.length;

// 方法定义:修饰符 返回类型 方法名(参数列表)
public static int add(int x, int y) {
    return x + y;
}

// 可变参数
public static int sum(int... values) {
    int total = 0;
    for (int v : values) total += v;
    return total;
}

// 方法重载:同名不同参数
public static double add(double x, double y) {
    return x + y;
}

Friends & Partners