Java是一种适用于多种应用程序的编程语言,支持各种不同类型和规模的开发项目,其模板也相对较多,以下是Java的一些常见模板:
- 基础的Hello World模板:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
2.类和对象模板:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
3.try-catch-finally异常处理模板:
try {
// 可能会抛出异常的代码
} catch (ExceptionType e) {
// 异常处理代码
} finally {
// 可选的finally代码块
}
4.文件读写模板:
try {
File file = new File("filename.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}