Java内置函数的详细介绍及用法示例
发布时间:2023-07-04 10:59:06
Java是一门强大的编程语言,提供了丰富的内置函数库,可以帮助程序员更高效地开发应用程序。本文将介绍一些常用的Java内置函数并提供用法示例。
1. System类的常用函数:
- currentTimeMillis():返回当前时间的毫秒数。
示例:
long currentTime = System.currentTimeMillis();
System.out.println("当前时间:" + currentTime);
- exit(int status):终止当前运行的Java虚拟机。
示例:
System.exit(0); // 正常终止程序 System.exit(1); // 异常终止程序
- arraycopy(Object src, int srcPos, Object dest, int destPos, int length):复制数组中的元素到另一个数组中。
示例:
int[] srcArray = {1, 2, 3};
int[] destArray = new int[3];
System.arraycopy(srcArray, 0, destArray, 0, srcArray.length);
System.out.println(Arrays.toString(destArray)); // [1, 2, 3]
2. Math类的常用函数:
- sqrt(double a):返回一个数的平方根。
示例:
double result = Math.sqrt(16);
System.out.println("平方根:" + result); // 4.0
- pow(double a, double b):返回a的b次幂。
示例:
double result = Math.pow(2, 3);
System.out.println("2的3次幂:" + result); // 8.0
- random():返回一个大于等于0且小于1的随机数。
示例:
double randomNum = Math.random();
System.out.println("随机数:" + randomNum);
3. String类的常用函数:
- length():返回字符串的长度。
示例:
String str = "Hello World";
int length = str.length();
System.out.println("字符串长度:" + length); // 11
- charAt(int index):返回字符串中指定位置的字符。
示例:
String str = "Hello World";
char ch = str.charAt(6);
System.out.println("第6个字符:" + ch); // 'W'
- substring(int beginIndex, int endIndex):返回字符串的子串。
示例:
String str = "Hello World";
String subStr = str.substring(6, 11);
System.out.println("子串:" + subStr); // "World"
4. Arrays类的常用函数:
- sort(T[] a):对数组进行升序排序。
示例:
int[] array = {5, 3, 1, 2, 4};
Arrays.sort(array);
System.out.println(Arrays.toString(array)); // [1, 2, 3, 4, 5]
- binarySearch(T[] a, T key):在数组中查找指定的元素并返回其索引值,如果未找到则返回负数。
示例:
int[] array = {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(array, 3);
System.out.println("元素3的索引:" + index); // 2
- toString(T[] a):将数组转换为字符串。
示例:
int[] array = {1, 2, 3, 4, 5};
String str = Arrays.toString(array);
System.out.println("数组:" + str); // [1, 2, 3, 4, 5]
Java内置函数库提供了许多常用的函数,可以大大提高开发效率。通过熟悉和灵活运用这些函数,程序员可以更轻松地完成各种任务。
