Java中常见的函数示例及用法演示
发布时间:2023-11-20 03:52:24
Java是一种面向对象的编程语言,具有丰富的函数库,以下是一些常见的函数示例及其用法演示。
1. 字符串处理函数
字符串是Java中最常用的数据类型之一,有很多函数可以用于处理字符串,比如:
- charAt(int index):返回指定索引位置的字符。
String str = "Hello World"; char ch = str.charAt(0); System.out.println(ch); // 输出 H
- toUpperCase():将字符串中的所有字符转换为大写。
String str = "hello"; String upperCaseStr = str.toUpperCase(); System.out.println(upperCaseStr); // 输出 HELLO
- substring(int beginIndex, int endIndex):返回指定索引范围内的子字符串。
String str = "Hello World"; String subStr = str.substring(0, 5); System.out.println(subStr); // 输出 Hello
2. 数组操作函数
Java中的数组是一组相同数据类型的元素的集合,可以使用以下函数进行操作:
- length:获取数组的长度。
int[] arr = {1, 2, 3, 4, 5};
int length = arr.length;
System.out.println(length); // 输出 5
- sort:对数组进行排序。
int[] arr = {5, 2, 1, 4, 3};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // 输出 [1, 2, 3, 4, 5]
- copyOf:复制数组的指定长度部分。
int[] arr = {1, 2, 3, 4, 5};
int[] newArr = Arrays.copyOf(arr, 3);
System.out.println(Arrays.toString(newArr)); // 输出 [1, 2, 3]
3. 文件操作函数
Java中有多种函数可用于文件操作,例如:
- FileReader:用于读取文件内容。
try {
File file = new File("file.txt");
FileReader reader = new FileReader(file);
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
- FileWriter:用于将内容写入文件。
try {
File file = new File("file.txt");
FileWriter writer = new FileWriter(file);
writer.write("Hello World");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
- mkdir:创建目录。
File dir = new File("mydir");
if (!dir.exists()) {
dir.mkdir();
}
4. 时间与日期函数
Java提供了丰富的时间与日期处理函数,例如:
- System.currentTimeMillis():返回自1970年1月1日以来的毫秒数。
long currentTimeMillis = System.currentTimeMillis(); System.out.println(currentTimeMillis); // 输出当前时间的毫秒数
- DateFormat:用于格式化日期。
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = dateFormat.format(date);
System.out.println(formattedDate); // 输出当前日期和时间,例如 2022-01-01 12:00:00
- Calendar:用于对日期进行操作。
Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, 1); Date tomorrow = calendar.getTime(); System.out.println(dateFormat.format(tomorrow)); // 输出明天的日期
以上仅仅是Java中常见函数的示例及用法演示,Java函数库十分庞大且功能强大,开发者可以根据具体的需求选择合适的函数进行使用。
