Skip to content

Java语法从入门到精通:零基础必备指南(附详细代码)

前言

对于零基础学习者,Java语法是编程的基石。本文从最基础的概念讲起,涵盖数据类型、运算符、输入输出、流程控制、数组、方法等核心内容,每个知识点都配有详细代码示例和注释,帮你从“看不懂”到“熟练用”,逐步建立Java编程思维。

一、数据类型:Java世界的“积木”

Java中的数据类型分为两类:基本数据类型(直接存储值)和引用数据类型(存储地址,如字符串、数组、对象)。

1. 基本数据类型(8种)

类型占用空间取值范围用途
byte1字节-128 ~ 127节省空间的整数(如文件传输)
short2字节-32768 ~ 32767中等范围整数
int4字节-2³¹ ~ 2³¹-1最常用的整数类型(默认)
long8字节-2⁶³ ~ 2⁶³-1大整数(需加L后缀,如100L
float4字节单精度浮点(6-7位有效数字)需加F后缀(如3.14F
double8字节双精度浮点(14-15位有效数字)小数默认类型(如3.14
char2字节0 ~ 65535(Unicode字符)单个字符(用单引号'A'
boolean1字节true / false逻辑判断

代码示例

java
public class BasicTypeDemo {
    public static void main(String[] args) {
        // 整数类型
        byte b = 100;       // 注意:不能超过-128~127
        int num = 1000;     // 最常用
        long bigNum = 1000000L;  // 大整数必须加L
        
        // 浮点类型
        float f = 3.14F;    // 必须加F
        double d = 3.14159; // 默认小数类型
        
        // 字符和布尔
        char c = 'A';       // 单引号
        boolean isTrue = true;
        
        // 打印值
        System.out.println("byte值:" + b);
        System.out.println("字符:" + c);
    }
}

新手注意

  • 整数默认是int,小数默认是double,超过范围需加后缀(L/F)。
  • char类型可以存数字(对应ASCII码),如char c = 65等价于'A'

2. 引用数据类型(入门必知3种)

  • String:字符串(用双引号"abc"),如String name = "张三"
  • 数组:存储多个相同类型数据(如int[] arr = {1,2,3})。
  • 对象:类的实例(如Student stu = new Student(),后续面向对象章节详解)。

代码示例

java
public class ReferenceTypeDemo {
    public static void main(String[] args) {
        String str = "Hello Java";  // 字符串
        int[] arr = {1, 2, 3};      // 数组
        System.out.println(str);    // 输出:Hello Java
        System.out.println(arr[0]); // 输出数组第一个元素:1
    }
}

二、运算符:数据的“计算器”

运算符用于处理数据,按功能分为5类,优先级:() > 单目运算符 > 算术 > 关系 > 逻辑 > 三元 > 赋值。

1. 算术运算符

运算符功能示例
+加/字符串拼接3+2=5"a"+"b"="ab"
-5-3=2
*2*3=6
/除(整数取整)5/2=25.0/2=2.5
%取余5%2=1
++自增(前++先加后用,后++先用后加)int a=1; a++ → a=2
--自减(规则同自增)int b=3; --b → b=2

代码示例

java
public class ArithmeticDemo {
    public static void main(String[] args) {
        int a = 5, b = 2;
        System.out.println(a + b); // 7(加法)
        System.out.println(a / b); // 2(整数除法取整)
        System.out.println(a % b); // 1(取余)
        
        // 自增示例
        int c = 1;
        System.out.println(c++); // 1(先用后加,c变为2)
        System.out.println(++c); // 3(先加后用,c变为3)
    }
}

2. 赋值运算符

基本赋值=,复合赋值+=/-=/*=//=/%=(简化代码)。

代码示例

java
public class AssignmentDemo {
    public static void main(String[] args) {
        int num = 10;
        num += 5; // 等价于 num = num + 5 → 15
        num *= 2; // 等价于 num = num * 2 → 30
        System.out.println(num); // 30
    }
}

3. 关系运算符(返回boolean)

运算符功能示例
==等于3==3 → true
!=不等于3!=5 → true
>大于5>3 → true
<小于5<3 → false
>=大于等于5>=5 → true
<=小于等于3<=2 → false

代码示例

java
public class RelationDemo {
    public static void main(String[] args) {
        int x = 5, y = 10;
        System.out.println(x == y); // false(5不等于10)
        System.out.println(x < y);  // true(5小于10)
    }
}

4. 逻辑运算符(连接boolean表达式)

运算符功能特点(短路特性)
&&短路与(两边都真才真)左边为false,右边不执行
``
!非(取反)!true → false

代码示例

java
public class LogicDemo {
    public static void main(String[] args) {
        boolean a = true, b = false;
        System.out.println(a && b); // false(短路与)
        System.out.println(a || b); // true(短路或)
        System.out.println(!a);     // false(非)
        
        // 短路特性演示
        int c = 1;
        // 左边为false,右边c++不执行
        if (false && (c++ > 0)) {} 
        System.out.println(c); // 1(c未变)
    }
}

5. 三元运算符(简化if-else)

语法:条件 ? 表达式1 : 表达式2(条件为true返回表达式1,否则返回表达式2)。

代码示例

java
public class TernaryDemo {
    public static void main(String[] args) {
        int score = 75;
        // 判断是否及格
        String result = score >= 60 ? "及格" : "不及格";
        System.out.println(result); // 及格
    }
}

三、Scanner:获取用户输入

Scanner是Java获取用户输入的工具类,需导入java.util.Scanner,步骤:创建对象→调用方法→关闭资源。

1. 常用输入方法

方法功能示例
nextInt()获取整数int age = sc.nextInt()
nextDouble()获取小数double height = sc.nextDouble()
next()获取字符串(空格停止)String name = sc.next()
nextLine()获取一行字符串(含空格)String address = sc.nextLine()

代码示例

java
import java.util.Scanner; // 必须导入

public class ScannerDemo {
    public static void main(String[] args) {
        // 创建Scanner对象
        Scanner sc = new Scanner(System.in);
        
        System.out.print("请输入姓名:");
        String name = sc.nextLine(); // 获取一行字符串
        
        System.out.print("请输入年龄:");
        int age = sc.nextInt(); // 获取整数
        
        System.out.print("请输入身高(米):");
        double height = sc.nextDouble(); // 获取小数
        
        // 打印结果
        System.out.println("姓名:" + name + ",年龄:" + age + ",身高:" + height);
        
        sc.close(); // 关闭资源
    }
}

2. 常见问题:nextInt()nextLine()冲突

nextInt()只读取数字,会遗留回车符,导致后续nextLine()直接读取空字符串。

解决方法:在nextInt()后加sc.nextLine()消耗回车符。

java
Scanner sc = new Scanner(System.in);
System.out.print("请输入年龄:");
int age = sc.nextInt();
sc.nextLine(); // 消耗回车符
System.out.print("请输入地址:");
String address = sc.nextLine(); // 正常获取输入

四、分支结构:让程序“做选择”

分支结构根据条件执行不同代码,包括if-elseswitch

1. if-else:灵活的条件判断

(1)基本if-else

java
public class IfDemo1 {
    public static void main(String[] args) {
        int num = 7;
        // 判断奇偶数
        if (num % 2 == 0) {
            System.out.println(num + "是偶数");
        } else {
            System.out.println(num + "是奇数"); // 输出:7是奇数
        }
    }
}

(2)if-else if-else:多条件判断

java
public class IfDemo2 {
    public static void main(String[] args) {
        int score = 85;
        // 判断成绩等级
        if (score >= 90) {
            System.out.println("优秀");
        } else if (score >= 80) {
            System.out.println("良好"); // 输出:良好
        } else if (score >= 60) {
            System.out.println("及格");
        } else {
            System.out.println("不及格");
        }
    }
}

2. switch:多值匹配(JDK 12+简化版)

适合判断变量是否等于多个固定值(如星期、月份)。

(1)传统语法(需break防止穿透)

java
public class SwitchDemo1 {
    public static void main(String[] args) {
        int week = 3;
        switch (week) {
            case 1:
                System.out.println("周一");
                break; // 跳出switch
            case 2:
                System.out.println("周二");
                break;
            case 3:
                System.out.println("周三"); // 输出:周三
                break;
            default:
                System.out.println("无效星期");
        }
    }
}

(2)JDK 12+箭头语法(无需break

java
public class SwitchDemo2 {
    public static void main(String[] args) {
        int week = 3;
        switch (week) {
            case 1 -> System.out.println("周一");
            case 2 -> System.out.println("周二");
            case 3 -> System.out.println("周三"); // 输出:周三
            default -> System.out.println("无效星期");
        }
    }
}

五、循环结构:让程序“重复做”

循环用于重复执行代码块,包括forwhiledo-while

1. for循环:已知循环次数

语法:for(初始化; 循环条件; 迭代){ 循环体 }

示例1:计算1-100的和

java
public class ForDemo1 {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 100; i++) { // i从1到100
            sum += i; // 累加
        }
        System.out.println("1-100的和:" + sum); // 5050
    }
}

示例2:增强for循环(遍历数组/集合)

java
public class ForDemo2 {
    public static void main(String[] args) {
        String[] fruits = {"苹果", "香蕉", "橙子"};
        // 增强for:依次取出数组元素
        for (String fruit : fruits) {
            System.out.println(fruit); // 依次输出3种水果
        }
    }
}

2. while循环:未知循环次数(先判断后执行)

语法:初始化; while(循环条件){ 循环体; 迭代 }

示例:猜数字(直到猜对为止)

java
import java.util.Scanner;

public class WhileDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int target = 66; // 目标数字
        int guess;
        
        while (true) { // 无限循环
            System.out.print("请猜数字:");
            guess = sc.nextInt();
            if (guess == target) {
                System.out.println("猜对了!");
                break; // 跳出循环
            } else if (guess < target) {
                System.out.println("猜小了");
            } else {
                System.out.println("猜大了");
            }
        }
        sc.close();
    }
}

3. do-while循环:至少执行一次(先执行后判断)

语法:初始化; do{ 循环体; 迭代 } while(循环条件);

示例:直到输入正确密码

java
import java.util.Scanner;

public class DoWhileDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String password;
        do {
            System.out.print("请输入密码(6位):");
            password = sc.next();
        } while (password.length() != 6); // 直到输入6位
        System.out.println("密码正确");
        sc.close();
    }
}

4. 循环嵌套:循环内部再套循环

示例:打印5行5列矩形

java
public class LoopNestDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) { // 控制行
            for (int j = 1; j <= 5; j++) { // 控制列
                System.out.print("* ");
            }
            System.out.println(); // 换行
        }
    }
}
// 输出:
// * * * * * 
// * * * * * 
// * * * * * 
// * * * * * 
// * * * * *

六、控制关键字:循环的“遥控器”

1. break:跳出循环/switch

java
public class BreakDemo {
    public static void main(String[] args) {
        // 找到第一个能被7整除的数
        for (int i = 10; i <= 100; i++) {
            if (i % 7 == 0) {
                System.out.println("第一个能被7整除的数:" + i); // 14
                break; // 跳出循环
            }
        }
    }
}

2. continue:跳过当前迭代,进入下一次

java
public class ContinueDemo {
    public static void main(String[] args) {
        // 打印1-10中的奇数
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                continue; // 跳过偶数
            }
            System.out.print(i + " "); // 1 3 5 7 9
        }
    }
}

3. return:结束当前方法

java
public class ReturnDemo {
    public static void main(String[] args) {
        System.out.println("方法开始");
        return; // 结束main方法
        // System.out.println("这里不会执行"); // 编译报错
    }
}

七、随机数:让程序“随机应变”

Java生成随机数有两种方式:Math.random()(简单)和Random类(灵活)。

1. Math.random()

返回[0.0, 1.0)的随机小数,生成[min, max)整数公式:(int)(Math.random() * (max - min) + min)

示例:生成1-100的随机数

java
public class MathRandomDemo {
    public static void main(String[] args) {
        // 生成[1, 100]的随机整数(+1调整范围)
        int randomNum = (int) (Math.random() * 100 + 1);
        System.out.println("随机数:" + randomNum);
    }
}

2. Random类(推荐)

支持多种数据类型,可指定种子(种子相同则随机序列相同)。

示例:生成多种随机数

java
import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        Random random = new Random(); // 无参:种子为系统时间
        
        int num1 = random.nextInt(100); // [0, 100)整数
        double num2 = random.nextDouble(); // [0.0, 1.0)小数
        boolean flag = random.nextBoolean(); // 随机布尔值
        
        System.out.println("整数:" + num1);
        System.out.println("小数:" + num2);
        System.out.println("布尔值:" + flag);
    }
}

八、数组:存储多个相同类型数据

数组是长度固定的容器,用于批量存储数据(如班级所有学生的成绩)。

1. 数组的初始化

java
public class ArrayInitDemo {
    public static void main(String[] args) {
        // 方式1:动态初始化(指定长度,默认值)
        int[] arr1 = new int[3]; // 长度3,默认值0
        arr1[0] = 10; // 给第一个元素赋值
        
        // 方式2:静态初始化(直接赋值)
        int[] arr2 = {1, 2, 3}; // 长度3,元素1,2,3
        
        // 方式3:动态初始化的另一种写法
        int[] arr3 = new int[]{4, 5, 6};
    }
}

2. 数组的访问与遍历

  • 索引:从0开始(arr[0]是第一个元素)。
  • 长度:arr.length(属性,非方法)。

示例:遍历数组

java
public class ArrayTraverseDemo {
    public static void main(String[] args) {
        String[] fruits = {"苹果", "香蕉", "橙子"};
        
        // 方式1:普通for循环(带索引)
        for (int i = 0; i < fruits.length; i++) {
            System.out.println(fruits[i]);
        }
        
        // 方式2:增强for循环(无索引)
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

3. 数组案例训练

案例1:数组反转

java
public class ArrayReverseDemo {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        // 左右对称交换
        for (int i = 0; i < arr.length / 2; i++) {
            int temp = arr[i];
            arr[i] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = temp;
        }
        // 打印反转后:5 4 3 2 1
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}

案例2:求数组最大值

java
public class ArrayMaxDemo {
    public static void main(String[] args) {
        int[] nums = {15, 30, 8, 42, 21};
        int max = nums[0]; // 假设第一个是最大值
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > max) {
                max = nums[i]; // 更新最大值
            }
        }
        System.out.println("最大值:" + max); // 42
    }
}

九、方法:封装功能,重复调用

方法是封装特定功能的代码块,避免重复编写,提高复用性。

1. 方法的定义与调用

语法:

java
修饰符 返回值类型 方法名(参数列表) {
    // 方法体
    return 返回值; // 无返回值用void,可省略return
}

示例1:无参无返回值

java
public class MethodDemo1 {
    public static void main(String[] args) {
        printHello(); // 调用方法
    }
    
    // 定义方法:打印Hello
    public static void printHello() {
        System.out.println("Hello, Method!");
    }
}

示例2:有参有返回值(求两数之和)

java
public class MethodDemo2 {
    public static void main(String[] args) {
        int sum = add(3, 5); // 调用方法,接收返回值
        System.out.println("和:" + sum); // 8
    }
    
    // 定义方法:参数a和b,返回它们的和
    public static int add(int a, int b) {
        return a + b; // 返回结果
    }
}

2. 方法重载:同名不同参

同一类中,方法名相同但参数列表不同(类型/个数/顺序),提高可读性。

示例:重载加法方法

java
public class MethodOverloadDemo {
    // 两个int相加
    public static int add(int a, int b) {
        return a + b;
    }
    
    // 三个int相加(参数个数不同)
    public static int add(int a, int b, int c) {
        return a + b + c;
    }
    
    // 两个double相加(参数类型不同)
    public static double add(double a, double b) {
        return a + b;
    }
    
    public static void main(String[] args) {
        System.out.println(add(1, 2)); // 3(调用第一个)
        System.out.println(add(1, 2, 3)); // 6(调用第二个)
        System.out.println(add(1.5, 2.5)); // 4.0(调用第三个)
    }
}

3. 参数传递:值传递 vs 引用传递

  • 基本类型:传递值的副本(方法内修改不影响外部)。
  • 引用类型(数组、对象):传递地址的副本(方法内修改会影响外部)。

示例

java
public class ParameterPassDemo {
    // 基本类型参数
    public static void changeInt(int num) {
        num = 100; // 仅修改副本
    }
    
    // 引用类型参数(数组)
    public static void changeArray(int[] arr) {
        arr[0] = 100; // 修改数组内容(影响外部)
    }
    
    public static void main(String[] args) {
        int a = 10;
        changeInt(a);
        System.out.println(a); // 10(未变)
        
        int[] arr = {1, 2, 3};
        changeArray(arr);
        System.out.println(arr[0]); // 100(已变)
    }
}

4. 方法案例训练

案例1:数组工具类(封装常用操作)

java
public class ArrayTool {
    // 求数组最大值
    public static int getMax(int[] arr) {
        int max = arr[0];
        for (int num : arr) {
            if (num > max) max = num;
        }
        return max;
    }
    
    // 数组排序(冒泡排序)
    public static void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    // 交换元素
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    
    public static void main(String[] args) {
        int[] nums = {5, 2, 9, 1, 5, 6};
        System.out.println("最大值:" + getMax(nums)); // 9
        bubbleSort(nums);
        for (int num : nums) {
            System.out.print(num + " "); // 1 2 5 5 6 9
        }
    }
}

案例2:猜数字游戏(综合应用)

java
import java.util.Random;
import java.util.Scanner;

public class GuessNumberGame {
    // 生成1-100的随机数
    public static int generateNum() {
        return new Random().nextInt(100) + 1;
    }
    
    // 游戏逻辑
    public static void start() {
        int target = generateNum();
        Scanner sc = new Scanner(System.in);
        int count = 0;
        
        while (true) {
            System.out.print("请猜1-100的数字:");
            int guess = sc.nextInt();
            count++;
            
            if (guess > target) {
                System.out.println("猜大了!");
            } else if (guess < target) {
                System.out.println("猜小了!");
            } else {
                System.out.println("猜对了!共猜了" + count + "次");
                break;
            }
        }
        sc.close();
    }
    
    public static void main(String[] args) {
        start(); // 启动游戏
    }
}

总结

本文覆盖了Java语法的核心知识点,从数据类型到方法封装,每个部分都通过代码示例直观展示。对于零基础学习者,建议:

  1. 逐段阅读,理解后手动敲写代码(不要复制);
  2. 修改代码参数(如循环次数、数组元素),观察结果变化;
  3. 完成案例训练后,尝试扩展功能(如给猜数字游戏添加难度选择)。

掌握这些基础后,可继续学习面向对象、集合框架等进阶内容,逐步构建完整的Java知识体系。

Released under the MIT License.