Java笔记——50个JAVA常见代码大全:学完这篇从Java小白到架构师

Java,作为一门流行多年的编程语言,始终占据着软件开发领域的重要位置。无论是初学者还是经验丰富的程序员,掌握Java中常见的代码和概念都是至关重要的。本文将列出50个Java常用代码示例,并提供相应解释,助力你从Java小白成长为架构师。

基础语法

1. Hello World

这是学习任何编程语言的第一步,Java也不例外。

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

2. 数据类型

了解Java的基本数据类型对编写程序至关重要。

int a = 100;          // 整型
float b = 5.25f;      // 浮点型
double c = 5.25;      // 双精度浮点型
boolean d = true;     // 布尔型
char e = 'A';         // 字符型
String f = "Hello";   // 字符串型
int a = 100;          // 整型
float b = 5.25f;      // 浮点型
double c = 5.25;      // 双精度浮点型
boolean d = true;     // 布尔型
char e = 'A';         // 字符型
String f = "Hello";   // 字符串型

3. 条件判断

学习如何使用 if-else 语句来控制程序的流程。

int score = 75;
if (score > 70) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}
int score = 75;
if (score > 70) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

4. 循环结构

掌握 forwhiledo-while 循环对于执行重复任务至关重要。

for循环

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

while循环

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

do-while循环

int j = 0;
do {
    System.out.println("Iteration: " + j);
    j++;
} while (j < 5);
int j = 0;
do {
    System.out.println("Iteration: " + j);
    j++;
} while (j < 5);

5. 数组

数组是存储固定大小的同类型元素的集合。

int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = i * 2;
}
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = i * 2;
}

6. 方法定义与调用

方法允许你将代码组织成可重用的单元。

public static int multiply(int a, int b) {
    return a * b;
}

public static void main(String[] args) {
    int result = multiply(5, 10);
    System.out.println("Result: " + result);
}
public static int multiply(int a, int b) {
    return a * b;
}

public static void main(String[] args) {
    int result = multiply(5, 10);
    System.out.println("Result: " + result);
}

面向对象编程

7. 类与对象

类是对象的蓝图,对象是类的实例。

public class Car {
    String color;

    public void setColor(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }
}

Car myCar = new Car();
myCar.setColor("Red");
System.out.println("Car color: " + myCar.getColor());
public class Car {
    String color;

    public void setColor(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }
}

Car myCar = new Car();
myCar.setColor("Red");
System.out.println("Car color: " + myCar.getColor());

8. 构造方法

构造方法用于在创建对象时初始化对象。

public class Rectangle {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double getArea() {
        return width * height;
    }
}

Rectangle rect = new Rectangle(5, 3);
System.out.println("Area: " + rect.getArea());
public class Rectangle {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double getArea() {
        return width * height;
    }
}

Rectangle rect = new Rectangle(5, 3);
System.out.println("Area: " + rect.getArea());

9. 继承

继承允许一个类(子类)继承另一个类(父类)的属性和方法。

public class Animal {
    public void eat() {
        System.out.println("The animal is eating.");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println("The dog barks.");
    }
}

Dog myDog = new Dog();
myDog.eat(); // 继承的方法
myDog.bark(); // Dog特有的方法
public class Animal {
    public void eat() {
        System.out.println("The animal is eating.");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println("The dog barks.");
    }
}

Dog myDog = new Dog();
myDog.eat(); // 继承的方法
myDog.bark(); // Dog特有的方法

10. 接口

接口定义了一组相关方法的契约,可以被任何类实现。

public interface Runnable {
    void run();
}

public class ThreadImpl implements Runnable {
    public void run() {
        System.out.println("Running via implement Runnable interface");
    }
}

Thread thread = new Thread(new ThreadImpl());
thread.start();
public interface Runnable {
    void run();
}

public class ThreadImpl implements Runnable {
    public void run() {
        System.out.println("Running via implement Runnable interface");
    }
}

Thread thread = new Thread(new ThreadImpl());
thread.start();

11. 抽象类

抽象类不能被实例化,通常作为其他类的基类。

public abstract class Shape {
    abstract double getArea();
}

public class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    double getArea() {
        return Math.PI * radius * radius;
    }
}

// Circle circle = new Circle(5); // Cannot instantiate the abstract class
public abstract class Shape {
    abstract double getArea();
}

public class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    double getArea() {
        return Math.PI * radius * radius;
    }
}

// Circle circle = new Circle(5); // Cannot instantiate the abstract class

12. 方法重载

方法重载允许在一个类中定义多个同名方法,只要它们的参数列表不同。

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }

    public int add(int a, int b, int c) {
        return a + b + c;
    }
}

Calculator calc = new Calculator();
System.out.println(calc.add(5, 3));        // 调用第一个方法
System.out.println(calc.add(5.5, 3.1));    // 调用第二个方法
System.out.println(calc.add(5, 3, 2));     // 调用第三个方法
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }

    public int add(int a, int b, int c) {
        return a + b + c;
    }
}

Calculator calc = new Calculator();
System.out.println(calc.add(5, 3));        // 调用第一个方法
System.out.println(calc.add(5.5, 3.1));    // 调用第二个方法
System.out.println(calc.add(5, 3, 2));     // 调用第三个方法

13. 方法重写

方法重写是子类中覆盖继承自父类的方法。

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

public class Bird extends Animal {
    @Override
    public void sound() {
        System.out.println("Tweet tweet");
    }
}

Bird bird = new Bird();
bird.sound(); // 输出 "Tweet tweet"
public class Animal {
    public void sound() {
        System.out.println("Animal sound");
    }
}

public class Bird extends Animal {
    @Override
    public void sound() {
        System.out.println("Tweet tweet");
    }
}

Bird bird = new Bird();
bird.sound(); // 输出 "Tweet tweet"

14. 多态

多态允许将子类的实例视为父类类型。

public class Animal {
    public void makeSound() {
        System.out.println("Some generic sound");
    }
}

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Bark");
    }
}

public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow");
    }
}

Animal myAnimal = new Dog();
myAnimal.makeSound(); // Bark
myAnimal = new Cat();
myAnimal.makeSound(); // Meow
public class Animal {
    public void makeSound() {
        System.out.println("Some generic sound");
    }
}

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Bark");
    }
}

public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow");
    }
}

Animal myAnimal = new Dog();
myAnimal.makeSound(); // Bark
myAnimal = new Cat();
myAnimal.makeSound(); // Meow

15. 封装

封装是隐藏对象的内部状态和复杂性,只暴露操作该对象的接口。

public class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public boolean withdraw(double amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;
            return true;
        }
        return false;
    }

    public double getBalance() {
        return balance;
    }
}

BankAccount account = new BankAccount(1000);
account.deposit(500);
System.out.println("Balance: " + account.getBalance());
public class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public boolean withdraw(double amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;
            return true;
        }
        return false;
    }

    public double getBalance() {
        return balance;
    }
}

BankAccount account = new BankAccount(1000);
account.deposit(500);
System.out.println("Balance: " + account.getBalance());

16. 静态变量和方法

静态变量和方法是类的一部分,而不是对象的一部分。

public class MathUtils {
    public static final double PI = 3.14159;

    public static double add(double a, double b) {
        return a + b;
    }
    // 其他静态方法...
}

double circumference = MathUtils.PI * 2 * 5;
System.out.println("Circumference: " + circumference);
public class MathUtils {
    public static final double PI = 3.14159;

    public static double add(double a, double b) {
        return a + b;
    }
    // 其他静态方法...
}

double circumference = MathUtils.PI * 2 * 5;
System.out.println("Circumference: " + circumference);

17. 内部类

内部类是定义在另一个类中的类。

public class OuterClass {
    private String outerField = "From Outer";

    public class InnerClass {
        public void display() {
            System.out.println(outerField);
        }
    }

    public void createInner() {
        InnerClass inner = new InnerClass();
        inner.display();
    }
}

OuterClass outer = new OuterClass();
outer.createInner(); // 输出 "From Outer"
public class OuterClass {
    private String outerField = "From Outer";

    public class InnerClass {
        public void display() {
            System.out.println(outerField);
        }
    }

    public void createInner() {
        InnerClass inner = new InnerClass();
        inner.display();
    }
}

OuterClass outer = new OuterClass();
outer.createInner(); // 输出 "From Outer"

18. 匿名类

匿名类是没有名称的类,常用于实现接口或继承抽象类。

public class TestAnonymous {
    public void performTask(Runnable task) {
        task.run();
    }

    public static void main(String[] args) {
        TestAnonymous test = new TestAnonymous();
        test.performTask(new Runnable() {
            public void run() {
                System.out.println("Running an anonymous class");
            }
        });
    }
}
public class TestAnonymous {
    public void performTask(Runnable task) {
        task.run();
    }

    public static void main(String[] args) {
        TestAnonymous test = new TestAnonymous();
        test.performTask(new Runnable() {
            public void run() {
                System.out.println("Running an anonymous class");
            }
        });
    }
}

高级编程概念

19. 泛型

泛型允许在编译时提供类型安全。

public class Box<T> {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
    return t;
}

public static void main(String[] args) {
    Box<Integer> integerBox = new Box<>();
    integerBox.set(10);
    System.out.println(integerBox.get()); // 输出:10
}
public class Box<T> {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
    return t;
}

public static void main(String[] args) {
    Box<Integer> integerBox = new Box<>();
    integerBox.set(10);
    System.out.println(integerBox.get()); // 输出:10
}

20. 集合框架

ArrayList

ArrayList 是一个可变的数组,允许存储任意数量的元素。

import java.util.ArrayList;

ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");
System.out.println(languages); // 输出:[Java, Python, C++]
import java.util.ArrayList;

ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");
System.out.println(languages); // 输出:[Java, Python, C++]

HashMap

HashMap 是一个键值对集合,通过键来快速访问数据。

import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
System.out.println(map.get("Apple")); // 输出:1
import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
System.out.println(map.get("Apple")); // 输出:1

21. 异常处理

异常处理是程序中错误处理的一种方法。

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} finally {
    System.out.println("This will always be printed.");
}
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} finally {
    System.out.println("This will always be printed.");
}

22. 文件I/O

读取文件

读取文件是文件I/O操作中的基本功能。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

写入文件

写入文件允许将数据保存到磁盘上。

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
    bw.write("Hello World!");
} catch (IOException e) {
    e.printStackTrace();
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
    bw.write("Hello World!");
} catch (IOException e) {
    e.printStackTrace();
}

23. 多线程

创建线程

多线程允许同时执行多个任务。

class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread running");
    }
}

MyThread myThread = new MyThread();
myThread.start();
class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread running");
    }
}

MyThread myThread = new MyThread();
myThread.start();

实现Runnable接口

Runnable 接口提供了另一种创建线程的方式。

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("MyRunnable running");
    }
}

Thread thread = new Thread(new MyRunnable());
thread.start();
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("MyRunnable running");
    }
}

Thread thread = new Thread(new MyRunnable());
thread.start();

24. 同步

同步是控制多个线程对共享资源访问的一种机制。

public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}
public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

25. 高级多线程

使用Executors

Executors 提供了一种更高级的线程管理方式。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

ExecutorService executor = Executors.newFixedThreadPool(2);

executor.submit(() -> {
    System.out.println("ExecutorService running");
});

executor.shutdown();
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

ExecutorService executor = Executors.newFixedThreadPool(2);

executor.submit(() -> {
    System.out.println("ExecutorService running");
});

executor.shutdown();

Future和Callable

Future 和 Callable 允许你异步执行任务并获取结果。

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

Callable<Integer> callableTask = () -> {
    return 10;
};

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> future = executorService.submit(callableTask);

try {
    Integer result = future.get(); // 这将等待任务完成
    System.out.println("Future result: " + result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
} finally {
    executorService.shutdown();
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

Callable<Integer> callableTask = () -> {
    return 10;
};

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> future = executorService.submit(callableTask);

try {
    Integer result = future.get(); // 这将等待任务完成
    System.out.println("Future result: " + result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
} finally {
    executorService.shutdown();
}

以上是Java编程中常见的50个代码示例的前25个,涵盖了从基础语法到高级编程概念的多个方面。掌握这些代码片段将极大提升你的编码技能,并为成长为一名优秀的Java架构师打下坚实基础。持续实践和学习,相信不久的将来,你将在Java的世界里驾轻就熟。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

啊健的影子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值