Java标准库中常见函数的用法和实例介绍
发布时间:2023-06-30 14:12:39
Java标准库中包含了许多常见函数,这些函数能够帮助我们进行各种操作,例如字符串处理、日期和时间操作、文件操作等。下面将介绍一些常见函数的用法和实例。
1. String类的常见函数:
1.1 length():返回字符串的长度。
String str = "Hello World"; int length = str.length(); System.out.println(length); //输出11
1.2 charAt(index):返回字符串中指定索引位置的字符。
String str = "Hello World"; char c = str.charAt(6); System.out.println(c); //输出W
1.3 substring(startIndex, endIndex):返回字符串中从startIndex到endIndex-1位置的子串。
String str = "Hello World"; String subStr = str.substring(6, 11); System.out.println(subStr); //输出World
2. Math类的常见函数:
2.1 abs(x):返回x的绝对值。
int absValue = Math.abs(-10); System.out.println(absValue); //输出10
2.2 pow(x, y):返回x的y次幂。
double powResult = Math.pow(2, 3); System.out.println(powResult); //输出8.0
2.3 random():返回一个0到1的随机数。
double randomValue = Math.random(); System.out.println(randomValue); //输出0.123456(示例值,随机生成)
3. SimpleDateFormat类的常见函数:
3.1 format(Date date):将Date对象格式化为指定的日期字符串。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String formattedDate = sdf.format(date);
System.out.println(formattedDate); //输出2021-07-27(当前日期,示例值)
3.2 parse(String str):将格式化的日期字符串解析为Date对象。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String str = "2021-07-27";
Date parsedDate = sdf.parse(str);
System.out.println(parsedDate); //输出Tue Jul 27 00:00:00 CST 2021
4. File类的常见函数:
4.1 exists():判断文件或目录是否存在。
File file = new File("test.txt");
boolean exists = file.exists();
System.out.println(exists); //输出true(如果test.txt文件存在)
4.2 isDirectory():判断指定路径是否是一个目录。
File directory = new File("test");
boolean isDirectory = directory.isDirectory();
System.out.println(isDirectory); //输出true(如果test是一个目录)
4.3 createNewFile():创建一个新的文件。
File file = new File("test.txt");
boolean created = file.createNewFile();
System.out.println(created); //输出true(如果test.txt文件成功创建)
以上是一些Java标准库中常见函数的用法和实例,这些函数可以帮助我们简化代码,提高开发效率。熟练掌握这些函数的用法,能够更好地应对各种开发需求。
