Java中最常用的函数示例
发布时间:2023-10-18 21:10:29
在Java中有许多常用的函数,以下是其中一些常见的函数示例:
1. System.out.println():该函数用于在控制台打印输出。例如:
System.out.println("Hello World!");
2. Math.sqrt():该函数用于计算给定数字的平方根。例如:
double result = Math.sqrt(16); System.out.println(result); // 输出4.0
3. String.length():该函数用于获取字符串的长度。例如:
String str = "Hello World!"; int length = str.length(); System.out.println(length); // 输出12
4. String.toUpperCase():该函数用于将字符串转换为大写。例如:
String str = "hello"; String upperCaseStr = str.toUpperCase(); System.out.println(upperCaseStr); // 输出HELLO
5. String.toLowerCase():该函数用于将字符串转换为小写。例如:
String str = "HELLO"; String lowerCaseStr = str.toLowerCase(); System.out.println(lowerCaseStr); // 输出hello
6. String.charAt():该函数用于获取字符串中指定位置的字符。例如:
String str = "Hello"; char ch = str.charAt(1); System.out.println(ch); // 输出'e'
7. String.substring():该函数用于截取字符串的子串。例如:
String str = "Hello World!"; String subStr = str.substring(6, 11); System.out.println(subStr); // 输出"World"
8. Integer.parseInt():该函数用于将字符串转换为整数。例如:
String str = "100"; int num = Integer.parseInt(str); System.out.println(num); // 输出100
9. Double.parseDouble():该函数用于将字符串转换为浮点数。例如:
String str = "3.14"; double num = Double.parseDouble(str); System.out.println(num); // 输出3.14
10. Arrays.sort():该函数用于对数组进行排序。例如:
int[] arr = {5, 2, 8, 1, 9};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // 输出[1, 2, 5, 8, 9]
以上只是Java中常用函数的一小部分示例,实际上还有许多其他常用的函数可以用于不同的用途。在编写Java程序时,根据具体的需求选择合适的函数能够提高开发效率和代码可读性。
