// Java关键字示例代码
// 1. 类定义使用 class 关键字
public class KeywordExample {
// 2. 方法定义使用 void 关键字表示无返回值
public void displayKeywords() {
// 3. 使用 if-else 关键字进行条件判断
int number = 10;
if (number > 5) {
System.out.println("Number is greater than 5");
} else {
System.out.println("Number is less than or equal to 5");
}
// 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("Invalid day");
}
// 7. 使用 try-catch 关键字进行异常处理
try {
int[] array = {1, 2, 3};
System.out.println(array[5]); // This will throw an ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught an exception: " + e);
}
// 8. 使用 final 关键字定义常量
final double PI = 3.14159;
System.out.println("Value of PI: " + PI);
// 9. 使用 static 关键字定义静态方法和变量
static int staticVariable = 10;
// 10. 使用 abstract 关键字定义抽象类和方法
abstract class Animal {
abstract void makeSound();
}
// 11. 使用 interface 关键字定义接口
interface Vehicle {
void drive();
}
// 12. 使用 extends 和 implements 关键字继承类和实现接口
class Car extends Animal implements Vehicle {
@Override
void makeSound() {
System.out.println("Car sound");
}
@Override
public void drive() {
System.out.println("Driving the car");
}
}
// 13. 使用 new 关键字创建对象
Car myCar = new Car();
myCar.makeSound();
myCar.drive();
// 14. 使用 this 关键字引用当前对象实例
class Person {
String name;
Person(String name) {
this.name = name;
}
void printName() {
System.out.println("Name: " + this.name);
}
}
// 15. 使用 super 关键字调用父类构造函数或方法
class Employee extends Person {
Employee(String name) {
super(name); // 调用父类构造函数
}
void printDetails() {
super.printName(); // 调用父类方法
}
}
// 16. 使用 synchronized 关键字确保线程安全
synchronized void synchronizedMethod() {
// 线程同步代码
}
// 17. 使用 volatile 关键字确保变量的可见性
volatile boolean flag = true;
// 18. 使用 transient 关键字标记不参与序列化的变量
transient int tempData;
// 19. 使用 strictfp 关键字确保浮点运算精度
strictfp class StrictFpClass {
float compute() {
return 1.0f / 3.0f;
}
}
// 20. 使用 package 和 import 关键字管理类和包
package com.example;
import java.util.ArrayList;
// 21. 使用 enum 关键字定义枚举类型
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
// 22. 使用 assert 关键字进行断言
assert number > 0 : "Number should be positive";
// 23. 使用 native 和 synchronized 关键字定义本地方法
native void nativeMethod();
}
}
以上代码展示了Java中常用的关键字及其用法。
上一篇:java手动分页怎么实现
下一篇:java报错找不到符号
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站