Java是一种广泛使用的编程语言,以其跨平台特性、面向对象的特性和丰富的生态系统而闻名。Java程序员在日常工作中会使用一些常用的代码片段来提高开发效率和代码质量。以下是一些Java中常用的代码示例和最佳实践。
基本语法和结构
Hello World:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
变量声明:
int number = 10; String name = "Kimi";
条件语句:
if (number > 0) { System.out.println("Number is positive."); } else { System.out.println("Number is non-positive."); }
循环:
- for循环:
for (int i = 0; i < 10; i ) { System.out.println(i); }
- while循环:
int i = 0; while (i < 10) { System.out.println(i); i ; }
- do-while循环:
int i = 0; do { System.out.println(i); i ; } while (i < 10);
- for循环:
集合操作
ArrayList:
List
list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); for (String fruit : list) { System.out.println(fruit); } HashMap:
Map
map = new HashMap<>(); map.put("Apple", 1); map.put("Banana", 2); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() " : " entry.getValue()); }
输入输出
使用Scanner读取输入:
Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello " name);
文件操作:
- 读取文件:
List
lines = Files.readAllLines(Paths.get("path/to/file.txt")); for (String line : lines) { System.out.println(line); } - 写入文件:
List
data = Arrays.asList("Line 1", "Line 2"); Files.write(Paths.get("path/to/file.txt"), data, StandardOpenOption.CREATE);
- 读取文件:
异常处理
try-catch:
try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); }
finally:
try { // Code that may throw an exception } finally { // Code that will always be executed }
多线程
创建线程:
class MyThread extends Thread { public void run() { System.out.println("Thread is running."); } } MyThread thread = new MyThread(); thread.start();
同步代码块:
synchronized (this) { // Critical section }
网络编程
- 使用Socket:
Socket socket = new Socket("hostname", port); OutputStream output = socket.getOutputStream(); output.write("Hello Server".getBytes());
设计模式
单例模式:
public class Singleton { private static Singleton instance; private Singleton() {} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
工厂模式:
interface Shape { void draw(); } class Circle implements Shape { public void draw() { System.out.println("Drawing a circle."); } } class ShapeFactory { static Shape getShape(String shapeType) { if (shapeType == null) return null; if (shapeType.equalsIgnoreCase("CIRCLE")) { return new Circle(); } return null; } }
结语
Java作为一种成熟的编程语言,提供了丰富的API和工具来支持各种编程任务。掌握这些常用的代码片段和最佳实践,可以帮助Java开发者更加高效地编写代码,同时也能够提高代码的可读性和可维护性。随着技术的不断进步,Java也在不断地更新和改进,为开发者提供更多的特性和工具。
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com