Methods in Java- Types,Declaration and Naming (with Examples)
Methods in Java are blocks of code that perform a specific function. A method runs only when it is called. A method can accept data as its arguments. The main usability of methods is in code reuse: define the code once and use it many times.
What are Methods in Java?
In simple terms, a method is a block of code that performs a specific function. Methods provide for easy modification and code reusability. It will get executed only when invoked/called.
Method Declaration and Scope
A method in Java has various attributes like access modifier, return type, name, parameters etc.
Methods can be declared using the following syntax:
Let us see an example of a function and correlate the various attributes mentioned above. The logic of the function is to convert a given integer to a string datatype.
- returnType is String
- methodName is convertToString
- parameter is an integer called number
Let us understand what each attribute means -
- accessModifier: Where can you call this function?
Below is a table representing the visibility of a method in various locations within a program.
✅ - Can be accessed
❌ - Cannot be accessed
|Access Modifier||Within Class||Within package||Subclass outside package||Outside package|
- returnType : It represents data-type of the value returned by the function. For example, a method in Java declared with int return type should return an integer value.
- methodName: Represents the identifier that can be used to call the method when required.
- parameters: These are the arguments passed into a method necessary for the function's logic. If the methods with data, we can pass data to the methods by specifying them within the parentheses.
See Also- Complete Java Tutorial
The naming convention for a method in Java is generally a verb, in mixed case with the first letter in lowercase and the first letter of each internal word capitalized. This naming convention is called the Camel case.
Invoking a Method
What we saw above is declaring a method. To use the method's functionality, you need to "call" a method. This is as simple as writing the name of the method by passing its parameters. We should also take note of the function's return type.
In the above code snippet, the method findFactorial expects an Integer type parameter to be passed.
To use this method, we need to call it. In the main method (Driver method), we are calling the function by passing the integer 7 as the value of the argument number. The value returned by the method is stored in the variable result.
Behind the Scenes
When a method is called, the following executions are performed in sequence:
The program controller evaluates the values of the arguments passed to the method from left to right. Suppose an expression is passed as an argument. In that case, there needs to be an evaluation (Ex: 2 + 3 is passed as the argument, it needs evaluation), but if it is variable or literal, no evaluation is performed.
A new stack frame is pushed into the call stack. Think of the call stack as a general stack data structure maintained by the program to track all the function calls, variables, and their order of execution. So when a method is called, the following information is stored in the stack -
- Parameters and local variables storage: Memory is allocated in the stack frame to store the parameters of the method and the local variables declared within the method scope.
- Return Address: The address of the memory location from where to continue execution after the method call finishes is also stored.
Parameters are initialized by assigning them to local variables.
Execution of the statements within the method body.
When the keyword return is encountered, or the end of the method is reached, the method returns a value except in the latter case. As the method's execution is finished, the stack frame is popped from the call stack.
The call stack is what a program uses to keep track of method calls. The call stack is made up of stack frames — one for each method call.
The portion of the call stack allocated for a single function call is called a stack frame.
Parameters and Return Types of Methods in Java
A method in Java can have no parameters or multiple parameters in the same order as the method definition.
In the example below, there is a method to convert temperature from Celsius to Fahrenheit. The method celsiusToFahreheit expects a float type parameter.
Generally, we can pass parameters to a method in two ways-
- By value
- By reference
However, Java always passes arguments by value and not by reference.
If a method has been declared with a return type other than void, it is required to have a return statement at the end.
In the above example, the function celsiustoFahrenheit returns a float value.
Make sure that the data type of the method's return type matches the data type of the value being returned by it. For example, the variable inFahrenheit is of type float, which matches the method's required return type.
Types Of Methods in Java
Predefined methods in Java
These are methods that Java class libraries define. They are also called standard library methods or built-in methods. They can be used by directly calling them. Some examples include print() in the package java.io.PrintStream, min() and max() defined in Math class etc.
User-defined methods in Java
As you might have guessed, a method with custom logic is a user-defined method. The above example of converting temperature from Celsius to Fahrenheit is an example of a user-defined method in Java.
Further, there are some other sub-types of user-defined methods.
A method in a class declared as static does not need an object of the class to invoke it. All the above built-in methods are static, so you could invoke the sqrt() method without creating an object of the Math class. In the example of a user-defined method to convert Celsius to Fahrenheit, the method is static as well.
Instance methods in Java are attached to the objects of a class, rather than the class itself. Here, the method belongs to a class whose object must be created to call the function. This is seen in the below code snippet where an object obj of Demo class is created to call the addNumbers() method.
A method without any implementation but only the method signature is called an abstract method. An abstract method can be declared in an abstract class or an interface. A regular class can implement an abstract method by extending the abstract class containing the abstract method.
Abstract methods are used where you need to share the code among closely related classes or have many common parameters.
- Abstract method in an abstract class
- Abstract method in an interface
The factory method is responsible for creating and returning the objects to the client. A factory method may accept an input that denotes the type of object that needs to be created. Factory methods belong to a certain design pattern called "Factory pattern" which is a way to dynamically return an object of a class it belongs to, at run-time based on the user's choice.
For example, if we have a program to customize the choice of condiments you can add to your coffee, you can get the object for the chosen condiment on the go when it is created.
Memory Allocation for Method Calls in Java
Whenever we call a method, the Java Virtual Machine (JVM) allocates memory in two main ways - Heap and Stack memory.
At runtime, heap space is used for dynamic memory allocation of Java objects and JRE classes. New objects that are created within a method's body are allocated memory in heap space. The references to these objects are stored in stack memory. We can access these objects from anywhere in the application using their references.
Key Features of Heap Memory:
- If the heap space is full, Java throws java.lang.OutOfMemoryError.
- Access to this memory is comparatively slower than stack memory.
- Unlike the stack, this memory is not automatically deallocated. It requires Garbage Collector to free up unwanted objects in order to maintain memory efficiency.
- A heap, unlike a stack, is not threadsafe and must be protected by properly synchronizing the code.
It is used for static memory allocation and execution of a thread. Whenever we call a new method, as seen in the "Calling a method" section, the primitive values and references to objects used in method will be pushed into the call stack as a stack frame. The access to this is Last In First Out (LIFO). After the execution of the method finishes, the stack frame is popped out.
Let us understand this with an example: Consider the following two simple methods m1 and m2 -
The method m1 has a variable i. It is calling method m2 which is creating an object of a the Book class.
When we call the method m1, the following memory operations are performed:
- A stack frame having variables in m1 method is pushed into the call stack.
- When m2 is called within m1, another frame with reference to the object b1 in heap memory is pushed into the stack.
- This reference points to heap memory. The new Book() initialization will create an object of Book in heap memory.
- When the m2 method finishes, the top stack frame is removed, post which the stack frame corresponding to m1 method is popped out.
In Java, this is a reference keyword used to refer to the current object. this keyword is used inside a method to call another method from the same class or refer to the current class instance variable.
We can also pass this as a parameter to a method for triggering an event on the current object.
Variable Arguments (Varargs)
We can pass multiple parameters into a method. But what if we don't know how many arguments we need to pass? Variable Arguments (Varargs) is a Java method that accepts variable number of arguments.
Three main things to note are:
- Each method can have only one vararg parameter.
- In the case of multiple arguments, varargs must be the last parameter.
- Vararg Methods can also be overloaded, but it is ambiguous.
Let us see an example where we can pass varargs to add a bunch of integers.
Java compiler essentially appends varargs into an array which can be used to iterate as seen above.
Command Line Arguments
The java command-line argument is an argument that is supplied when the java program is run. The arguments given from the terminal can be received and used as input in the java program.
In the above example, once you execute the program, it lets you enter values in the console. The args string array stores all the entered values from the command line.
Make note that all the variables through the command line are considered as String. We will have to explicitly type-cast them to be used as integer or other data types.
Why do We Need Methods in Java?
- Methods are essentially used to divide the logic of the whole program into manageable chunks with logic separation.
- Code can be reused throughout the program by just calling the same method in multiple places. This is the single best use of methods in Java.
- Often, methods are used for hiding or encapsulating implementation details.
- Methods also improve code readability making it easier to understand the logic of the program.
Q: How many Varargs can we have in a function?
A: A method can have only one varargs parameter. Additionally, the varargs parameter must be the last argument to the method.
Q: Do we need to create an instance of the Main class to invoke the main method?
A: Main Method in Java is static, which implies there is no need to create an instance of the Main class to invoke the main method.
Q: What are memory allocation methods?
A: The two fundamental methods of memory allocation are static and dynamic memory allocation. The static memory (stack memory) allocation method assigns the memory to a process, before its execution. On the other hand, heap memory is allocated dynamically at runtime.
Q: Can Varargs be null?
A: As Java cannot determine the type of literal null, you must explicitly inform the type of the literal null to Java. Failing to do so will result in a NullPointerException.
- Java Methods are an integral part of the Java language used to maintain modularity in code.
- Methods in Java can have different access modifiers like public, private, protected, and default.
- There are mainly three types of methods - built-in, user-defined and abstract methods.
- this keyword can be used to refer to current class instance variables and invoke the instance methods.
- Varargs can be used to pass a variable number of arguments when the number of parameters is not known during method declaration.
- Static methods in Java can be invoked directly without needing the creation of an object of its class. However, instance methods require objects of the class where they are declared to be invoked.
- JVM does memory allocation for method calls through the heap and stack memories.
- We can also pass arguments to a Java program through the command line in the main method.