欢迎访问宙启技术站
智能推送

Java中常见的内置函数及其用法举例

发布时间:2023-06-10 21:57:17

Java中常见的内置函数包括字符串操作函数、数组操作函数、日期操作函数、数学函数等。下面将对它们的用法进行举例介绍。

1. 字符串操作函数

1.1 charAt(int index):返回指定位置的字符。

String str = "Hello World";
char c = str.charAt(6); // c = 'W'

1.2 substring(int beginIndex, int endIndex):返回字符串的子串。

String str = "Hello World";
String subStr = str.substring(6, 11); // subStr = "World"

1.3 replaceAll(String regex, String replacement):将字符串中的指定字符替换成新的字符。

String str = "Hello World";
String newStr = str.replaceAll("l", "L"); // newStr = "HeLLo WorLd"

1.4 length():返回字符串的长度。

String str = "Hello World";
int len = str.length(); // len = 11

2. 数组操作函数

2.1 sort(T[] arr):将数组按从小到大的顺序排序。

int[] arr = {4, 1, 6, 2, 8};
Arrays.sort(arr); // arr = {1, 2, 4, 6, 8}

2.2 copyOf(T[] original, int newLength):将原数组复制成一个新的数组。

int[] arr = {1, 2, 3, 4, 5};
int[] newArr = Arrays.copyOf(arr, 3); // newArr = {1, 2, 3}

2.3 binarySearch(T[] a, T key):在一个有序数组中查找指定元素,并返回它的索引值。

int[] arr = {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(arr, 3); // index = 2

3. 日期操作函数

3.1 getTime():返回当前时间的毫秒数。

Date date = new Date();
long currentTimeMillis = date.getTime(); // currentTimeMillis为当前时间的毫秒数

3.2 before(Date when):判断当前时间是否在指定时间之前。

Date date1 = new Date();
Date date2 = new Date(System.currentTimeMillis() + 1000); // 当前时间加上1秒
boolean b = date1.before(date2); // b = true

4. 数学函数

4.1 abs(int a):返回一个数的绝对值。

int result = Math.abs(-10); // result = 10

4.2 max(int a, int b):返回两个数中较大的那个。

int result = Math.max(10, 20); // result = 20

4.3 random():返回一个随机数。

double result = Math.random(); // 返回0.0到1.0之间的一个随机数