Passing Array to Function In JavaFunctions are used to break and divide a huge code into small chunks so that the code becomes more understandable and thus reduces the complexity of the code. Arrays are the homogenous data structures for reducing the code complexity, increasing efficiency, and reducing the execution time of the code. We make use of the array and think of both these time-saving parts of programming are implemented together. Thereby exists the concept of Passing Array to Function. In this section, we will learn how we can pass an array to a user-defined function and will notice how it makes the code more optimistic as well as efficient. Generally, the purpose of passing an array to a function is to transfer a large amount of data between methods. To pass an array to a function, just pass the array as function's parameter (as normal variables), and when we pass an array to a function as an argument, in actual the address of the array in the memory is passed, which is the reference. Thus, any changes in the array within the method will affect the actual array values. We will implement some example codes through which we will get to know how to pass an array to a function. Example 1:Calculating the maximum and minimum values of a given array. In order to get the maximum and minimum value in an array, we can perform the below-shown code: Output: Code Explanation:
Example 2:Computing an array of Random Numbers Random numbers are those numbers whose occurrence is random and cannot be predicted reasonably. Below is the example code through which we can understand the passing of an array to a function and generate random numbers: On executing the code, we got the below-shown output: Note: In the case of random numbers, always the result will vary as the numbers are generated randomly.Example 3:Sorting numbers of an array Below is an example code where we pass an array to a function and sort the elements of the given array: When we executed the above code, we got the following result: These are some of the possible example implementations through which it is understandable that how one can pass an array to a function in Java. Next TopicJava Error |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India