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

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

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

基础语法

1. Hello World

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

2. 数据类型

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

3. 条件判断

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

4. 循环结构

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

5. 数组

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

6. 方法定义与调用

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

面向对象编程

7. 类与对象

public class Dog {String name;public void bark() {System.out.println(name + " says: Bark!");}
}Dog myDog = new Dog();
myDog.name = "Rex";
myDog.bark();

8. 构造方法

public class User {String name;public User(String newName) {name = newName;}
}User user = new User("Alice");

9. 继承

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. 接口

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. 抽象类

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. 方法重载

public class Calculator {int add(int a, int b) {return a + b;```javadouble 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. 方法重写

public class Animal {void makeSound() {System.out.println("Some sound");}
}public class Dog extends Animal {@Overridevoid makeSound() {System.out.println("Bark");}
}Animal myDog = new Dog();
myDog.makeSound(); // 输出 "Bark"

14. 多态

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

15. 封装

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. 静态变量和方法

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. 内部类

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. 匿名类

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. 泛型

public class Box<T> {private T t;public void set(T t) {this.t = t;}public T get() {return t;}
}Box<Integer> integerBox = new Box<>();
integerBox.set(10);
System.out.println(integerBox.get()); // 应输出:10

20. 集合框架

ArrayList
import java.util.ArrayList;ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
System.out```java
.println(list); // 应输出:[Java, Python, C++]
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

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.");
}

22. 文件I/O

读取文件
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();
}
写入文件
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();
实现Runnable接口
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;}
}

25. 高级多线程

使用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();
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(); // this will wait for the task to finishSystem.out.println("Future result: " + result);
} catch (InterruptedException | ExecutionException e) {e.printStackTrace();
} finally {executorService.shutdown();
}

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/bicheng/83806.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Linux手册】冯诺依曼体系结构

目录 前言 五大组件 数据信号 存储器&#xff08;内存&#xff09;有必要吗 常见面试题 前言 冯诺依曼体系结构是当代计算机基本架构&#xff0c;冯诺依曼体系有五大组件&#xff0c;通过这五大组件直观的描述了计算机的工作原理&#xff1b;学习冯诺依曼体系可以让给我们更…

10_聚类

描述 聚类&#xff08;clustering&#xff09;是将数据集划分成组的任务&#xff0c;这些组叫作簇&#xff08;cluster&#xff09;。其目标是划分数据&#xff0c;使得一个簇内的数据点非常相似且不同簇内的数据点非常不同。与分类算法类似&#xff0c;聚类算法为每个数据点分…

【SSM】SpringBoot学习笔记1:SpringBoot快速入门

前言&#xff1a; 文章是系列学习笔记第9篇。基于黑马程序员课程完成&#xff0c;是笔者的学习笔记与心得总结&#xff0c;供自己和他人参考。笔记大部分是对黑马视频的归纳&#xff0c;少部分自己的理解&#xff0c;微量ai解释的内容&#xff08;ai部分会标出&#xff09;。 …

国产高性能pSRAM选型指南:CSS6404LS-LI 64Mb QSPI伪静态存储器

一、芯片基础特性 核心参数 容量 &#xff1a;64Mb&#xff08;8M 8bit&#xff09;电压 &#xff1a;单电源供电 2.7-3.6V &#xff08;兼容3.3V系统&#xff09;接口 &#xff1a;Quad-SPI&#xff08;QPI/SPI&#xff09;同步模式封装 &#xff1a; SOP-8L (150mil) &#…

Cilium动手实验室: 精通之旅---4.Cilium Gateway API - Lab

Cilium动手实验室: 精通之旅---4.Cilium Gateway API - Lab 1. 环境准备2. API 网关--HTTP2.1 部署应用2.2 部署网关2.3 HTTP路径匹配2.4 HTTP头匹配 3. API网关--HTTPS3.1 创建TLS证书和私钥3.2 部署HTTPS网关3.3 HTTPS请求测试 4. API网关--TLS 路由4.1 部署应用4.2 部署网关…

20250605在微星X99主板中配置WIN10和ubuntu22.04.6双系统启动的引导设置

rootrootrootroot-X99-Turbo:~$ sudo apt-get install boot-repair rootrootrootroot-X99-Turbo:~$ sudo add-apt-repository ppa:yannubuntu/boot-repair rootrootrootroot-X99-Turbo:~$ sudo apt-get install boot-repair 20250605在微星X99主板中配置WIN10和ubuntu22.04.6双…

MyBatis之测试添加功能

1. 首先Mybatis为我们提供了一个操作数据库的会话对象叫Sqlsession&#xff0c;所以我们就需要先获取sqlsession对象&#xff1a; //加载核心配置文件 InputStream is Resources.getResourceAsStream("mybatis-config.xml"); //获取sqlSessionFactoryBuilder(是我…

[论文阅读] 人工智能+软件工程 | MemFL:给大模型装上“项目记忆”,让软件故障定位又快又准

【论文解读】MemFL&#xff1a;给大模型装上“项目记忆”&#xff0c;让软件故障定位又快又准 论文信息 arXiv:2506.03585 Improving LLM-Based Fault Localization with External Memory and Project Context Inseok Yeo, Duksan Ryu, Jongmoon Baik Subjects: Software Engi…

Java开发中复用公共SQL的方法

在一次Java后端开发的面试中&#xff0c;面试官问了我一个问题&#xff1a;“你在写代码时会复用公共SQL吗&#xff1f;如果会的话&#xff0c;能详细介绍一下你是如何实现的吗&#xff1f;”这个问题让我眼前一亮&#xff0c;因为在实际项目中&#xff0c;SQL复用确实是一个非…

C#学习26天:内存优化的几种方法

1.减少对象创建 使用场景&#xff1a; 在循环或密集计算中频繁创建对象时。涉及大量短生命周期对象的场景&#xff0c;比如日志记录或字符串拼接。游戏开发中&#xff0c;需要频繁更新对象状态时。 说明&#xff1a; 重用对象可以降低内存分配和垃圾回收的开销。使用对象池…

【opencv】基础知识到进阶(更新中)

安装&#xff1a;pip install opencv-python 入门案例 读取图片 本节我们将来学习,如何使用opencv显示一张图片出来,我们首先需要掌握一条图片读取的api cv.imread("图片路径","读取的方式") # 图片路径: 需要在工程目录中,或者一个文件的绝对路径 # 读取…

【Part 3 Unity VR眼镜端播放器开发与优化】第二节|VR眼镜端的开发适配与交互设计

文章目录 《VR 360全景视频开发》专栏Part 3&#xff5c;Unity VR眼镜端播放器开发与优化第一节&#xff5c;基于Unity的360全景视频播放实现方案第二节&#xff5c;VR眼镜端的开发适配与交互设计一、Unity XR开发环境与设备适配1.1 启用XR Plugin Management1.2 配置OpenXR与平…

SQL进阶之旅 Day 16:特定数据库引擎高级特性

【SQL进阶之旅 Day 16】特定数据库引擎高级特性 开篇 在“SQL进阶之旅”系列的第16天&#xff0c;我们将探讨特定数据库引擎的高级特性。这些特性通常为某些特定场景设计&#xff0c;能够显著提升查询性能或简化复杂任务。本篇文章将覆盖MySQL、PostgreSQL和Oracle的核心高级…

c++算法学习4——广度搜索bfs

一、引言&#xff1a;探索迷宫的智能方法 在解决迷宫最短路径问题时&#xff0c;广度优先搜索&#xff08;BFS&#xff09;是一种高效而优雅的算法。与深度优先搜索&#xff08;DFS&#xff09;不同&#xff0c;BFS采用"由近及远"的搜索策略&#xff0c;逐层探索所有…

4.RV1126-OPENCV 图像轮廓识别

一.图像识别API 1.图像识别作用 它常用于视觉任务、目标检测、图像分割等等。在 OPENCV 中通常使用 Canny 函数、findContours 函数、drawContours 函数结合在一起去做轮廓的形检测。 2.常用的API findContours 函数&#xff1a;用于寻找图片的轮廓&#xff0c;并把所有的数…

Qt多线程访问同一个数据库源码分享(基于Sqlite实现)

Qt多线程访问同一个数据库源码分享&#xff08;基于Sqlite实现&#xff09; 一、实现难点线程安全问题死锁风险连接管理问题数据一致性性能瓶颈跨线程信号槽最佳实践建议 二、源码分享三、测试1、新建一个多线程类2、开启多线程插入数据 一、实现难点 多线程环境下多个线程同时…

双空间知识蒸馏用于大语言模型

Dual-Space Knowledge Distillation for Large Language Models 发表&#xff1a;EMNLP 2024 机构&#xff1a;Beijing Key Lab of Traffic Data Analysis and Mining 连接&#xff1a;https://aclanthology.org/2024.emnlp-main.1010.pdf 代码&#xff1a;GitHub - songmz…

贪心算法应用:多重背包启发式问题详解

贪心算法应用&#xff1a;多重背包启发式问题详解 多重背包问题是经典的组合优化问题&#xff0c;也是贪心算法的重要应用场景。本文将全面深入地探讨Java中如何利用贪心算法解决多重背包问题。 多重背包问题定义 **多重背包问题(Multiple Knapsack Problem)**是背包问题的变…

ES6 Promise 状态机

状态机&#xff1a;抽象的计算模型&#xff0c;根据特定的条件或者信号切换不同的状态 一、Promise 是什么&#xff1f; 简单来说&#xff0c;Promise 就是一个“承诺对象”。在ES6 里&#xff0c;有些代码执行起来需要点时间&#xff0c;比如加载文件、等待网络请求或者设置…

【Docker管理工具】部署Docker可视化管理面板Dpanel

【Docker管理工具】部署Docker可视化管理面板Dpanel 一、Dpanel介绍1.1 DPanel 简介1.2 主要特点 二、本次实践规划2.1 本地环境规划2.2 本次实践介绍 三、本地环境检查3.1 检查Docker服务状态3.2 检查Docker版本3.3 检查docker compose 版本 四、下载Dpanel镜像五、部署Dpanel…