Зміст курсу
Java Extended
Java Extended
Methods Practice
Practice
Methods are not the easiest topic to understand, so this chapter will be filled with several examples of using different methods for different tasks. This way, you will be able to see more of how do methods work and where they can be used. We will also explore examples of using and writing two or more methods and their utilization.
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; public class Main { static int[] flipIntArray(int[] array) { int[] result = new int[array.length]; int index = 0; for (int i = array.length - 1; i >= 0; i--) { result[index] = array[i]; index++; } return result; } static void printIntArrayToTheConsole(int[] array) { for (int element : array) { System.out.print(element + " "); } System.out.println(); } public static void main(String[] args) { // do not change code from below int[] firstArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] secondArray = {0, 2, 4, 6, 8, 10, 12, 14, 16}; printIntArrayToTheConsole(flipIntArray(firstArray)); printIntArrayToTheConsole(flipIntArray(secondArray)); } // do not change the code above }
- First, let's pay attention to the method
flipIntArray
, 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 that increases to store the values in theresult
array; - Next, you can see the method from the previous chapter that I use to print the array in just one line of code;
- Now, let's move on to something interesting. You can see that I am calling 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
Let's move on to the next example. Suppose we need to write a method that calculates the factorial, taking an integer variable as input.
Note
The factorial is the product of all the numbers from 1 to the given number. For example, the factorial of 5 is calculated as 5 * 4 * 3 * 2 * 1, resulting in 120.
Main
package com.example; public class Main { static int calculateFactorial(int input) { int result = 1; for (int i = 1; i <= input ; i++) { result = result * i; } return result; } public static void main(String[] args) { // do not change code from below int first = 5; int second = 7; int third = 4; System.out.println("Factorial of the first number = " + calculateFactorial(first)); System.out.println("Factorial of the second number = " + calculateFactorial(second)); System.out.println("Factorial of the third number = " + calculateFactorial(third)); } // do not change the code above }
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
Let's move on to the third example. We will write a method that creates an abbreviation from an array of strings.
Note
An abbreviation is a shortened form of longer words or phrases, where only the first letter of each word is written in uppercase. For example, "UN" stands for "United Nations."
Main
package com.example; public class Main { static String makeAbbreviation(String[] input) { StringBuilder result = new StringBuilder(); for (String word : input) { result.append(word.toUpperCase().charAt(0)); } return result.toString(); } public static void main(String[] args) { // do not change code from below String[] firstArray = {"united", "nations"}; String[] secondArray = {"North", "Atlantic", "Treaty", "Organization"}; String[] thirdArray = {"Oh", "my", "God"}; System.out.println(makeAbbreviation(firstArray)); System.out.println(makeAbbreviation(secondArray)); System.out.println(makeAbbreviation(thirdArray)); } // do not change the code above }
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
.
Дякуємо за ваш відгук!