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

10个Java函数快速上手指南

发布时间:2023-08-16 15:50:10

1. Print Function:

public static void print(String message) {
    System.out.println(message);
}

This function prints the specified message on the console.

2. Addition Function:

public static int add(int num1, int num2) {
    return num1 + num2;
}

This function takes two integers as parameters and returns their sum.

3. Subtraction Function:

public static int subtract(int num1, int num2) {
    return num1 - num2;
}

This function takes two integers as parameters and returns their difference.

4. Multiplication Function:

public static int multiply(int num1, int num2) {
    return num1 * num2;
}

This function takes two integers as parameters and returns their product.

5. Division Function:

public static double divide(int num1, int num2) {
    if(num2 == 0) {
        throw new ArithmeticException("Cannot divide by zero");
    }
    return (double) num1 / num2;
}

This function takes two integers as parameters and returns their division result. It also handles the case when the second number is zero.

6. String Length Function:

public static int getLength(String str) {
    return str.length();
}

This function takes a string as a parameter and returns its length.

7. String Concatenation Function:

public static String concatenate(String str1, String str2) {
    return str1 + str2;
}

This function takes two strings as parameters and returns their concatenation.

8. Array Sorting Function (Ascending Order):

public static void sortArray(int[] arr) {
    Arrays.sort(arr);
}

This function takes an array of integers as a parameter and sorts it in ascending order.

9. File Reading Function:

public static String readFile(String filePath) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    StringBuilder content = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        content.append(line);
    }
    reader.close();
    return content.toString();
}

This function takes a file path as a parameter and reads the content of the file. It throws an IOException if there is an error in reading the file.

10. File Writing Function:

public static void writeFile(String filePath, String content) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
    writer.write(content);
    writer.close();
}

This function takes a file path and content as parameters and writes the content to the specified file. It throws an IOException if there is an error in writing the file.