Зміст курсу
Java Extended
Java Extended
Methods Practice
Practice
Methods can be challenging to understand, so this chapter provides examples of various methods in action, showing how they work, where to use them, and how to write and combine multiple methods effectively.
Example 1
Let's start with a method that takes an array of type int
and reverses it so that the last value becomes the first and the first becomes the last:
Main
package com.example; // do not modify the code below this comment public class Main { // method to reverse an int array static int[] flipArray(int[] array) { int[] result = new int[array.length]; int index = 0; // iterate over the array backwards and store reversed values for (int i = array.length - 1; i >= 0; i--) { result[index] = array[i]; index++; } return result; } // method to reverse a char array static char[] flipArray(char[] array) { char[] result = new char[array.length]; int index = 0; // iterate over the char array backwards and store reversed values for (int i = array.length - 1; i >= 0; i--) { result[index] = array[i]; index++; } return result; } }
- First, let's pay attention to the method
flipIntArray
on line 4, which uses a loop that counts from the end of the array and stores its values in a newly created array of the same size. There is also anindex
variable on line 6 that increases to store the values in theresult
array; - Next, you can see the method on line 14 from the previous chapter, which I use to print the array in just one line of code;
- Now, let's move on to something interesting. You can see on lines 25-26 that I am passing a method as a parameter inside another method. This is because I am using a method that returns
int[]
inside a method that takesint[]
as a parameter, thus saving the memory allocated for creating variables. We can see that our methods are working and displaying the correct values.
Example 2
Suppose we need to write a method that calculates the factorial, taking an integer variable as input.
Main
package com.example; // do not modify the code below this comment public class Main { // method to calculate the factorial of a number static int calculateFactorial(int input) { int result = 1; // loop to calculate factorial by multiplying each number from 1 to input for (int i = 1; i <= input; i++) { result = result * i; } // return the final result of the factorial calculation return result; } public static void main(String[] args) { // initializing the first number for factorial calculation int first = 5; // initializing the second number for factorial calculation int second = 7; // initializing the third number for factorial calculation int third = 4; // calculating and printing the factorial of the first number System.out.println("Factorial of the first number = " + calculateFactorial(first)); // calculating and printing the factorial of the second number System.out.println("Factorial of the second number = " + calculateFactorial(second)); // calculating and printing the factorial of the third number System.out.println("Factorial of the third number = " + calculateFactorial(third)); } }
In this example, we have written a method that multiplies the accumulating variable by numbers from 1
to the given number in order to calculate the factorial. It's a straightforward approach, and you can see how we use this method multiple times in the main
method, which saves space and improves code readability.
Next, we use our method inside System.out.println
because the method returns an int
value.
Example 3
We will write a method that creates an abbreviation from an array of strings.
Main
package com.example; // do not modify the code below this comment public class Main { // method to create abbreviation by taking first letter of each word static String makeAbbreviation(String[] input) { StringBuilder result = new StringBuilder(); // iterate through each word and append the first letter to result for (String word : input) { result.append(word.toUpperCase().charAt(0)); } // return the abbreviation as a string return result.toString(); } public static void main(String[] args) { // initializing arrays with words for abbreviation String[] firstArray = {"united", "nations"}; String[] secondArray = {"North", "Atlantic", "Treaty", "Organization"}; String[] thirdArray = {"Oh", "my", "God"}; // printing abbreviation for the first array System.out.println(makeAbbreviation(firstArray)); // printing abbreviation for the second array System.out.println(makeAbbreviation(secondArray)); // printing abbreviation for the third array System.out.println(makeAbbreviation(thirdArray)); } }
In this method, we use the StringBuilder
class to call the append()
method and add the uppercase first letter to an initially empty string. This way, we iterate through each element of the array, take the letter at the zeroth position (the first letter of each word), convert it to uppercase using the toUpperCase()
method, and add it to our result using the append()
method. Finally, we use the toString()
method to convert our StringBuilder
to String
.
Дякуємо за ваш відгук!