Java中常见的内置函数和其用法详解
Java中内置函数是指在Java编程语言中已经定义好的函数,因此不需要使用者自己定义,可以直接调用使用。Java中的内置函数分为以下几种:字符串函数、日期函数、数学函数、数组函数以及其他一些常用函数。下面就逐一介绍这些内置函数及其用法。
1. 字符串函数
字符串函数是Java中最常用的内置函数之一,以下是一些常用的字符串函数及其用法:
(1)length()函数:获取字符串长度
示例代码:
String str = "hello world";
int len = str.length(); // len = 11
(2)charAt()函数:获取指定位置字符
示例代码:
String str = "hello world";
char ch = str.charAt(6); // ch = 'w'
(3)indexOf()函数:查找子字符串位置
示例代码:
String str = "hello world";
int pos = str.indexOf("world"); // pos = 6
(4)substring()函数:截取字符串
示例代码:
String str = "hello world";
String subStr = str.substring(6); // subStr = "world"
2. 日期函数
日期函数主要用于获取和处理日期,以下是一些常用的日期函数及其用法:
(1)System.currentTimeMillis()函数:获取当前时间戳(毫秒级)
示例代码:
long timestamp = System.currentTimeMillis();
(2)Date()函数:获取当前时间
示例代码:
Date date = new Date();
(3)SimpleDateFormat()函数:日期格式化
示例代码:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date); // formattedDate = "2021-06-07 11:37:58"
3. 数学函数
数学函数主要用于一些数学计算,以下是一些常用的数学函数及其用法:
(1)Math.random()函数:生成随机数
示例代码:
double rand = Math.random(); // rand为0-1范围内的随机小数
(2)Math.round()函数:四舍五入
示例代码:
double num = 1.2345;
long roundedNum = Math.round(num); // roundedNum = 1
(3)Math.pow()函数:幂运算
示例代码:
double num = 2.0;
double result = Math.pow(num, 3); // result = 8.0
4. 数组函数
数组函数主要用于处理数组数据,以下是一些常用的数组函数及其用法:
(1)Arrays.sort()函数:数组排序
示例代码:
int[] arr = {3, 6, 1, 2, 7};
Arrays.sort(arr);
(2)Arrays.fill()函数:数组填充
示例代码:
int[] arr = new int[5];
Arrays.fill(arr, 5); // arr = {5, 5, 5, 5, 5}
(3)Arrays.copyOf()函数:数组复制
示例代码:
int[] arr = {3, 6, 1, 2, 7};
int[] newArr = Arrays.copyOf(arr, 3); // newArr = {3, 6, 1}
5. 其他常用函数
除了上述几类内置函数,Java还有一些其他常用函数,以下是一些常用的函数及其用法:
(1)System.out.println()函数:输出
示例代码:
System.out.println("hello world");
(2)Scanner()函数:从控制台读取输入
示例代码:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
总结:
Java中的内置函数非常多,上述只是其中的一部分常用函数。在编写Java程序时,我们可以充分利用这些内置函数,提高编程效率,减少代码量。同时,熟练掌握这些内置函数也是Java编程语言的基础之一。
