29 September 2020

What methods are in Java? (A more in-depth tutorial)

Welcome to another tutorial on the "How to code in Java" tutorial series. In the last tutorial, we learned about how type-casting work and when to use them. In this tutorial, we'll be learning what methods are, how to use them and when to use them. Since everything in Java is represented in the form of objects, Java doesn't have "functions" like some other programming language. Instead, Java has only methods. 


The main differences between a function and a method are that functions are independent of a class while methods are on an object. A function can interact with the arguments given, local variables and global variables. While a method can access the properties inside a class as well as what a function could access. Well, that's enough about methods and functions, let us now focus on methods.


Methods are actually a block of codes, and the code will only be executed when we told them to, or some conditions lead them to. We can execute a method by calling them using their names (identifiers). We can also pass data (known as parameters) into the methods when calling the methods so that the methods could process those data. We can also tell the methods to return us the result of the processed data back to the place where it is called. At the moment, just understand that a method could do these things, I'll walk you through with these, one by one. So there's no need for panicking.


So why are methods useful? Well, think about it. All we need to do is write the block of code once, and we can't always use them back whenever needed. This gives our code reusability, as we don't have to repeatedly write the same codes. By using methods also provides us with the ability to modified our code quickly. That's because whenever we need to change something in the code implementations, we just need to change it in one place, instead of modifying all the code from different sections one by one.


Index for the tutorial:



Structure of a method.


Before we continue with the example of using methods, let's start with how the structure of a method looks like and what are they for.


Structure of a method in Java.


  • Modifier - Define which access level the methods are. It defines which level the method could be seen or simply put, the visibility of the method to other methods and classes. More on the topic will be covered in another post. For now, just know that there are 4 types of modifiers: default, public, private, and protected. The short version of their explanations are:
    • Public - Could be accessed by everything in your Java program.
    • Protected - Could be accessed by methods of the same class and the subclasses of the method's class.
    • Private - Only the method's class can access the method.
    • Default (methods declared without any modifiers) - The methods could only be used by other classes and methods in the same package (same folder).
  • The return type - The data type of the data returned by the method or void when no data is being returned by the methods.
  • Method name - The unique name/identifier of the method. Using names that describe the functions of the method is recommended. 
  • Parameters list - A list of parameters with their data types, order and their names in an enclosed parenthesis. Parameters are used as the placeholder for the data that we need to pass to the methods to be processed. It is optional to define parameters in a method. Just use an empty Parenthesis if you don't need to pass any data to a method.
  • The method body - Defines what do the methods do with the defined codes to be executed.

A method also has something called the method's signature which is different for every method. The signature of a method will be discussed in the method overloading section. Where it is part of the Polymorphism section in the OOP concepts.



Types of methods in Java.


There are two types of methods in Java; pre-defined methods and user-defined methods.

Pre-defined methods are the methods that are built into Java's class libraries. For example, the Math class's methods like sqrt(), pow(),and sin(), and the String class's method such as length(), compareTo(), and concat(). Some method will require us to import the class libraries into our Java project, but some don't. This has something to do with "static" methods and properties. This topic would be covered in the future so don't worry much about it. For now, just know that since our main class is a static method to call another method in it, we'll need to make sure the method called is also a static method.

User-defined methods are methods that are defined and created by the programmers. These methods are modified by programmers according to their needs. Let's make a simple method that adds 5 to the addition of two number.


Code that calls a method 5 times with each call provides different arguments.


Result for the code.


As you can see in the picture above. In the main method, I called the method "addTogetherPlus5()" 5 times with each passing different arguments to the method. In the method, I added the two number together and then added a 5 into the result value. Then return the whole thing back to our main method and print it out to the terminal.


When calling a method, our program's control will be transferred to the called method. The program control will be given back to the caller when one of the three things occurred; A return statement has been executed, or the program control reaches the ending of the method closing parenthesis. Or an exception occurred during the execution of the program.


How methods call work.


The stack is used to implement the method call in Java. There is a stack pointer register which tracks the top position of the stack which is positioned accordingly. When a method is executed, a stack frame is created within the stack area. Arguments value, local variables and values to be returned by the called method are stored in the frame and when the method finished executing its task, the stack frame will be removed/deleted. Depending on the method called, data would be returned back to the caller's frame.



How to name a method?


The rules for naming a method is almost the same as naming a variable. The main thing to consider when naming a method is that its name should describe the function of the method. Another thing is that if possible, avoid using the same name for methods. Although, you might have seen some method defined with the same name, as Java allows programmers to use method overloading. Let's look at one good method name where the method will calculate the mean of an array of numbers.


Demonstrating finding the mean from an array of numbers.


Result for the code above.


Some tips when naming methods:

  • Names should be descriptive.
  • Avoid using underscores when possible.
  • Avoid using too many parameters for a method.
  • Length of the names doesn't matter, you should know what it is immediately after reading it.
  • Be consistent when naming the methods (even with variables).
  • If possible, structure the methods so that each only has one purpose. 



Method's arguments.


Java doesn't support default parameters value like C++ and Javascript. Therefore, you'll need to handle methods call while specifying all the required parameter. Although Java doesn't support the default parameter, we can achieve that by using method overloading. By using back the previous mean example, let's see what happens when we don't specify the total required arguments. 


Provide no arguments for the getNumbersMean() truck


The error occurred when executing the code.


The code will produce an error because nothing is passed to the method, where we specified that the method will need to accept an argument when a caller called this method. If you're using an IDE, the IDE will notify you if you forgot to pass the required arguments to the parameter or you used the wrong type for the value passed. 



 Method's return value.


When returning a value from a method back to the caller location, make sure that the returned value has the same data type as the return type specified when you define the method. If you didn't provide the correct return value type as the defined type, you'll get an error before you compile the code if you're using an IDE. That's due to Java being a strongly typed language (types are important in Java).


Using the wrong return type for the method.


When you return a value from a method to the method's caller, make sure you store the value either into a variable, or passed as another method's arguments or print out to the terminal.


Ways that you could use to use back the returned value from a method.


Well, that's about all the basic things I can write about using methods in Java. I hope you now know how methods work, how and when to use them in programming. As always, if you find this tutorial helpful, please share it with other people or to those that might need this information. If you have any questions, critics or suggestions, feel free to leave a comment below. For the next tutorial, we'll finally be learning about the concept of Object-Oriented Programming or OOP. So stay tuned.

No comments:

Post a Comment