50个JAVA常见代码大全:学完这篇从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!");
    }
}

```

2. 数据类型

```java
int a = 100;
float b = 5.25f;
double c = 5.25;
boolean d = true;
char e = 'A';
String f = "Hello";

```

3. 条件判断

```java
if (a > b) {
    // 条件成立时执行
} else if (a == b) {
    // 另一个条件
} else {
    // 条件都不成立时执行
}

```

4. 循环结构

for循环
```java
for (int i = 0; i < 10; i++) {
    System.out.println("i: " + i);
}

```
while循环
```java
int i = 0;
while (i < 10) {
    System.out.println("i: " + i);
    i++;
}

```
do-while循环
```java
int i = 0;
do {
    System.out.println("i: " + i);
    i++;
} while (i < 10);

```

5. 数组

```java
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
// ...
int[] arr2 = {1, 2, 3, 4, 5};

```

6. 方法定义与调用

```java
public static int add(int a, int b) {
    return a + b;
}
int sum = add(5, 3); // 调用方法

```

面向对象编程

7. 类与对象

```java
public class Dog {
    String name;

    public void bark() {
        System.out.println(name + " says: Bark!");
    }
}

Dog myDog = new Dog();
myDog.name = "Rex";
myDog.bark();

```

8. 构造方法

```java
public class User {
    String name;

    public User(String newName) {
        name = newName;
    }
}

User user = new User("Alice");

```

9. 继承

```java
public class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

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

Dog dog = new Dog();
dog.eat(); // 继承自Animal
dog.bark();

```

10. 接口

```java
public interface Animal {
    void eat();
}

public class Dog implements Animal {
    public void eat() {
        System.out.println("The dog eats.");
    }
}

Dog dog = new Dog();
dog.eat();

```

11. 抽象类

```java
public abstract class Animal {
    abstract void eat();
}

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

Animal dog = new Dog();
dog.eat();

```

12. 方法重载

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

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

Calculator calc = new Calculator();
calc.add(5, 3); // 调用第一个方法
calc.add(5.0, 3.0); // 调用第二个方法
calc.add(5, 3, 2); // 调用第三个方法

```

13. 方法重写

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

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

Animal myDog = new Dog();
myDog.makeSound(); // 输出 "Bark"

```

14. 多态

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

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

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

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

```

15. 封装

```java
public class Account {
    private double balance;

    public Account(double initialBalance) {
        if(initialBalance > 0) {
            balance = initialBalance;
        }
    }

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

    public void withdraw(double amount) {
        if(amount <= balance) {
            balance -= amount;
        }
    }

    public double getBalance() {
        return balance;
    }
}

Account myAccount = new Account(50);
myAccount.deposit(150);
myAccount.withdraw(75);
System.out.println(myAccount.getBalance()); // 应输出:125.0

```

16. 静态变量和方法

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

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

    public static double subtract(double a, double b) {
        return a - b;
    }

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

double circumference = MathUtils.PI * 2 * 5;
System.out.println(circumference); // 打印圆的周长

```

17. 内部类

```java
public class OuterClass {
    private String msg = "Hello";

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

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

OuterClass outer = new OuterClass();
outer.printMessage(); // 输出 "Hello"

```

18. 匿名类

```java
abstract class SaleTodayOnly {
    abstract int dollarsOff();
}

public class Store {
    public SaleTodayOnly sale = new SaleTodayOnly() {
        int dollarsOff() {
            return 3;
        }
    };
}

Store store = new Store();
System.out.println(store.sale.dollarsOff()); // 应输出3

```

高级编程概念

19. 泛型

```java
public class Box {
    private T t;

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

    public T get() {
        return t;
    }
}

Box integerBox = new Box<>();
integerBox.set(10);
System.out.println(integerBox.get()); // 应输出:10

```

20. 集合框架

ArrayList
```java
import java.util.ArrayList;

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

```
HashMap
```java
import java.util.HashMap;

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

```

21. 异常处理

```java
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

读取文件
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

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

```
写入文件
```java
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. 多线程

创建线程
```java
class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread running");
    }
}

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

```
实现Runnable接口
```java
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("MyRunnable running");
    }
}

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

```

24. 同步

```java
public class Counter {
    private int count = 0;

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

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

```

25. 高级多线程

使用Executors
```java
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
```java
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 callableTask = () -> {
    return 10;
};

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

try {
    Integer result = future.get(); // this will wait for the task to finish
    System.out.println("Future result: " + result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
} finally {
    executorService.shutdown();
}

```

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

文章整理自互联网,只做测试使用。发布者:Lomu,转转请注明出处:https://www.it1024doc.com/6254.html

(0)
LomuLomu
上一篇 2025 年 1 月 14 日 上午3:12
下一篇 2025 年 1 月 14 日 上午4:12

相关推荐

  • 扣子又出新功能,支持一键部署小程序,太强了!!

    大家好,我是R哥。 作为一名程序员和技术博主,我一直关注如何使用工具提升生产力,尤其是在内容创作和应用开发领域。 拿我开发一个微信小程序为例,我需要懂前端、后端、运维 等全栈技术,开发流程和技术栈复杂,我还需要购买云服务器、云数据库 等各种基础设施,资源耗费非常多。 虽然现在有如 Cursor 这样的革命性 AI 开发工具,它突破了传统开发模式的壁垒,非开发…

    2025 年 1 月 11 日
    63500
  • 通过延时从库+binlog复制,恢复误操作数据

    通过延迟复制与binlog恢复意外删除的数据 一、环境概述 以下是我们操作的数据库环境的详细信息: 数据库版本 实例角色 IP地址 端口 GreatSQL 8.0.32-26 主库 192.168.134.199 5725 GreatSQL 8.0.32-26 从库 192.168.134.199 5726 二、主库设置 在主库上,我们首先需要创建一个复制用…

    2024 年 12 月 24 日
    49500
  • Java刷题常见的集合类,各种函数的使用以及常见的类型转化等等

    目录 前言 集合类 ArrayList 1. 创建和初始化 ArrayList 2.添加元素 add 3.获取元素 get 4.删除元素 remove 5.检查元素 6.遍历 ArrayList LinkedList Stack 1. 创建Stack对象 2. 压入元素 (push) 3. 弹出元素 (pop) 4. 查看栈顶元素 (peek) 5. 检查栈…

    2025 年 1 月 1 日
    62300
  • 实战指南:理解 ThreadLocal 原理并用于Java 多线程上下文管理

    目录 一、ThreadLocal基本知识回顾分析 (一)ThreadLocal原理 (二)既然ThreadLocalMap的key是弱引用,GC之后key是否为null? (三)ThreadLocal中的内存泄漏问题及JDK处理方法 (四)部分核心源码回顾 ThreadLocal.set()方法源码详解 ThreadLocalMap.get()方法详解 Th…

    2024 年 12 月 30 日
    55500
  • 【Java】还在死磕算法?懂“堆”与“优先级队列”,代码效率飙升

    个人主页:喜欢做梦 欢迎 💛点赞 🌟收藏 💫关注 🏆堆 一、🎯什么是堆 堆的概念 堆是一种特殊的完全二叉树 ,如果有一个关键码的集合K={k0,k1,k2,…,kn-1} ,把它所有的元素按照完全二叉树的顺序存储方式 在一维数组 中,并满足:Ki

    2025 年 1 月 6 日
    45200

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信