// Java保留字示例代码
// 1. 使用 class 定义一个类
public class Example {
// 2. 使用 main 方法作为程序入口
public static void main(String[] args) {
// 3. 使用 if-else 条件语句
int number = 10;
if (number > 0) {
System.out.println("Positive number");
} else if (number < 0) {
System.out.println("Negative number");
} else {
System.out.println("Zero");
}
// 4. 使用 for 循环
for (int i = 0; i < 5; i++) {
System.out.println("Iteration " + i);
}
// 5. 使用 while 循环
int j = 0;
while (j < 3) {
System.out.println("While loop iteration " + j);
j++;
}
// 6. 使用 switch-case 语句
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other day");
}
// 7. 使用 try-catch 处理异常
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
// 8. 使用 final 关键字定义常量
final double PI = 3.14159;
System.out.println("Value of PI: " + PI);
// 9. 使用 abstract 和 interface 定义抽象类和接口
abstract class Animal {
abstract void makeSound();
}
interface Vehicle {
void start();
}
// 10. 使用 extends 和 implements 继承和实现
class Dog extends Animal implements Vehicle {
@Override
void makeSound() {
System.out.println("Bark");
}
@Override
public void start() {
System.out.println("Vehicle started");
}
}
// 创建对象并调用方法
Dog myDog = new Dog();
myDog.makeSound();
myDog.start();
}
}
以上代码展示了多个常见的 Java 保留字及其用法。
上一篇:java一个字符占几个字节
下一篇:java获取ip地址
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站