Java内置的常用函数库及使用示例
Java 是一门流行的编程语言,其内置了许多常用的函数库,使得编程变得更加方便和高效。本文将介绍 Java 常用函数库的用途和使用示例,帮助读者更好地理解和运用。
1. 字符串处理库
Java 的字符串处理库提供了丰富的字符串操作方法,包括字符串比较、分割、替换、连接、截取、大小写转换等。其中最常用的方法有:
(1)equals():比较两个字符串是否相等。
例如:String str1 = "Hello"; String str2 = "hello"; boolean isEqual = str1.equals(str2); // 返回 false
(2)substring():截取字符串的子串。
例如:String str = "abcdefg"; String subStr = str.substring(2, 5); // 返回 "cde"
(3)split():按照指定分隔符将字符串分割成数组。
例如:String str = "a,b,c,d,e,f,g"; String[] arr = str.split(","); // 返回 ["a", "b", "c", "d", "e", "f", "g"]
(4)replace():替换字符串中的字符或子串。
例如:String str = "Hello world"; String replaced = str.replace("world", "Java"); // 返回 "Hello Java"
(5)toUpperCase() 和 toLowerCase():将字符串转换为大写或小写。
例如:String str = "hello"; String upperCaseStr = str.toUpperCase(); // 返回 "HELLO"
2. 数组处理库
Java 的数组处理库提供了一系列的方法用于创建、操作和遍历数组。最常用的方法包括:
(1)sort():对数组进行排序。
例如:int[] arr = {5, 3, 2, 4, 1}; Arrays.sort(arr); // 返回 [1, 2, 3, 4, 5]
(2)binarySearch():在已排序的数组中查找指定元素。
例如:int[] arr = {1, 2, 3, 4, 5}; int index = Arrays.binarySearch(arr, 4); // 返回 3
(3)copyOf() 和 copyOfRange():复制数组或数组的一部分。
例如:int[] arr = {1, 2, 3, 4, 5}; int[] copyArr = Arrays.copyOf(arr, 3); // 返回 [1, 2, 3]
(4)fill():用指定元素填充数组。
例如:int[] arr = new int[5]; Arrays.fill(arr, 10); // 返回 [10, 10, 10, 10, 10]
3. 时间处理库
Java 的时间处理库提供了一系列的类和方法,用于处理日期、时间和时间间隔。最常用的类有:
(1)Date:表示日期和时间。
例如:Date date = new Date();
(2)Calendar:用于日期和时间计算。
例如:Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); int year = calendar.get(Calendar.YEAR);
(3)SimpleDateFormat:用于将日期和时间格式化为字符串。
例如:SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String strDate = sdf.format(new Date());
4. 输入输出库
Java 的输入输出库提供了一系列的类和方法,用于处理文件读写、网络通信、对象序列化等。最常用的类和方法有:
(1)FileOutputStream 和 FileInputStream:用于将数据写入文件和从文件中读取数据。
例如:FileOutputStream fos = new FileOutputStream("test.txt"); fos.write("Hello World".getBytes()); FileInputStream fis = new FileInputStream("test.txt"); byte[] buffer = new byte[1024]; fis.read(buffer); String str = new String(buffer); System.out.println(str);
(2)ObjectOutputStream 和 ObjectInputStream:用于将对象序列化和反序列化。
例如:Person p = new Person("Tom", 20); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.obj")); oos.writeObject(p); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.obj")); Person p1 = (Person)ois.readObject();
总之,Java 的内置函数库提供了丰富的工具和方法,可以帮助开发人员更加轻松地处理数据和实现功能。上述只是其中一部分的示例,有关于其它函数的相关使用还请查阅相关文档。
