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

常用的Java函数分类及其示例

发布时间:2023-06-14 07:15:27

Java是一门非常流行的编程语言,在互联网领域广泛应用。其中,函数是Java程序中最常用的部分之一。函数是一些指定命令,它们执行某些特定的操作并在需要时返回值。在本篇文章中,我们将介绍一些常用的Java函数分类以及示例。

1. 字符串函数

Java中的字符串函数用来处理字符串,例如截取字符串、替换字符、比较字符串等等。下面是一些常用的字符串函数:

1). concat()函数:用于将一个字符串与另一个字符串连接起来,并返回一个新的字符串。

示例代码:

String str1 = "Hello";

String str2 = "world";

String str3 = str1.concat(str2);

输出结果:Helloworld

2). length()函数:用于获取字符串的长度。

示例代码:

String str1 = "Hello world";

int len = str1.length();

输出结果:11

3). charAt()函数:用于获取字符串中指定位置的字符。

示例代码:

String str1 = "Hello";

char ch = str1.charAt(1);

输出结果:e

4). contains()函数:用于检查一个字符串是否包含另一个字符串。

示例代码:

String str1 = "Hello world";

boolean result = str1.contains("world");

输出结果:true

2. 数组函数

Java中的数组函数用于处理数组,例如查找数组元素、排序数组等等。下面是一些常用的数组函数:

1). sort()函数:用于对数组进行排序。

示例代码:

int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5};

Arrays.sort(arr);

输出结果:1 1 2 3 4 5 5 6 9

2). binarySearch()函数:用于在数组中查找指定元素。

示例代码:

int[] arr = {1, 3, 5, 7, 9};

int index = Arrays.binarySearch(arr, 7);

输出结果:3

3). toString()函数:用于将数组转换为字符串。

示例代码:

int[] arr = {1, 2, 3, 4, 5};

String str = Arrays.toString(arr);

输出结果:[1, 2, 3, 4, 5]

3. 时间函数

Java中的时间函数用于处理日期和时间,例如获取当前时间、格式化日期等等。下面是一些常用的时间函数:

1). System.currentTimeMillis()函数:用于获取当前时间的毫秒值。

示例代码:

long time = System.currentTimeMillis();

输出结果:当前时间的毫秒值

2). SimpleDateFormat类:用于格式化日期。

示例代码:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

Date date = new Date();

String str = sdf.format(date);

输出结果:当前日期的格式化字符串

3). Calendar类:用于处理日期和时间。

示例代码:

Calendar calendar = Calendar.getInstance();

int year = calendar.get(Calendar.YEAR);

int month = calendar.get(Calendar.MONTH) + 1;

int day = calendar.get(Calendar.DAY_OF_MONTH);

输出结果:当前年、月、日

以上就是一些常用的Java函数分类及其示例。在实际编程中,我们经常会用到这些函数,希望本篇文章对读者有所帮助。