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

10种常用的Java函数及其示例

发布时间:2023-06-04 06:07:05

Java是一个流行的面向对象编程语言,它包含了许多内置函数,可用于各种不同的任务。以下是10种常用的Java函数及其示例。

1. 字符串的长度(length)

length是Java内置函数中最简单的函数之一。它返回一个给定字符串的长度。例如:

String str = "Hello, world!";

int len = str.length();

System.out.println(len); //输出为13

2. 字符串的子串(substring)

substring函数可以从一个字符串中返回一个子字符串。它需要两个参数:起始和结束索引。例如:

String str = "Hello, world!";

String sub = str.substring(0, 5);

System.out.println(sub); //输出为Hello

3. 字符串的查找和替换(indexOf、replace)

indexOf函数可用来查找给定的字符串在另一个字符串中的位置。如果没有找到,它将返回-1。例如:

String str = "Hello, world!";

int idx = str.indexOf("world");

if (idx != -1) {

    System.out.println("Found 'world' at position " + idx);

}

replace函数可用来将一个字符串替换为另一个字符串。例如:

String str = "Hello, world!";

String newStr = str.replace("world", "Java");

System.out.println(newStr); //输出为Hello, Java!

4. 字符串的分割(split)

split函数可以将一个字符串拆分成一个字符串数组,根据指定的分隔符进行分割。例如:

String str = "apple,banana,orange";

String[] arr = str.split(",");

for (String s : arr) {

    System.out.println(s);

}

5. 字符串的转换(parseInt、valueOf)

parseInt函数将一个字符串转换为整数类型。例如:

String str = "123";

int i = Integer.parseInt(str);

System.out.println(i); //输出为123

valueOf函数可以将一个字符串转换为另一种类型。例如:

String str = "123";

double d = Double.valueOf(str);

System.out.println(d); //输出为123.0

6. 字符串的比较(equals)

equals函数用于比较两个字符串是否相等。例如:

String a = "Hello";

String b = "World";

if (a.equals(b)) {

    System.out.println("They are equal."); 

} else {

    System.out.println("They are not equal."); 

}

7. 数组的排序(sort)

sort函数可用于对一个数组进行排序。例如:

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

Arrays.sort(arr);

for (int i : arr) {

    System.out.println(i); 

}

8. 数组的查找(binarySearch)

binarySearch函数可用于在一个已排序的数组中查找特定的元素。例如:

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

int idx = Arrays.binarySearch(arr, 5);

System.out.println("Index of 5 is: " + idx); //输出为Index of 5 is: 4

9. 日期和时间的格式化(SimpleDateFormat)

SimpleDateFormat函数可用于将一个日期转换为指定的格式。例如:

Date date = new Date();

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

String formattedDate = sdf.format(date);

System.out.println(formattedDate); //输出的日期格式为:2021-03-29 17:20:45

10. 随机数的生成(Random)

Random函数可用于生成一个指定范围内的随机数。例如:

Random rand = new Random();

int n = rand.nextInt(10); //生成一个0到9之间的随机整数

System.out.println(n);

以上是10种常用的Java函数及其示例,它们涉及到了Java中许多基本的操作,对于想要学习Java编程的人们来说,这是一个很好的起点。