A method is a block of code that performs a specific task.
In object-oriented programming, method is a jargon used for function. Methods are bound to a class and they define the behavior of a class
A Method provides information about, and access to, a single method on a class or interface
-> The main advantage of using a method is code reusability
-> It makes the code readable
Method declarations have six components, in order:
-> Modifiers - defines access type whether the method is public, private.
-> The return type - the data type of the value returned by the method, or void if the method does not return a value.
-> The method name - The name of the method is an identifier. the rules for field names apply to method names as well, but the convention is a little different.
-> The parameter list in parenthesis - a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. Parameters or arguments are the values passed to a method. You can pass any number of arguments to a method
-> The method body - It defines what the method actually does, how the parameters are manipulated with programming statements, and what values are returned. The codes inside curly braces { } are the body of the method.
It should start with lowercase letter.
It should be a verb such as main(), print(), println().
Java follows the camel-case syntax for naming the class, interface, method, and variable.
If the name is combined with two words, the second word will start with uppercase letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.
The above syntax is used to define a method, how to call a Java method
The method can be called below
mySampleMethod();
While Java is executing the program code, it encounters mySampleMethod(); in the code.
The execution then branches to the mySampleMethod() method and executes code inside the body of the method.
After the execution of the code inside the method body is completed, the program returns to the original state and executes the next statement
Program:
Output:
We can pass values called "arguments" to a method when calling it. A method's declaration includes a list of variables that tell us the type and order of variables that the method can accept. This list is called the "method parameters.
Parameters can be passed by value or by reference
Pass by Value: The method parameter values are copied to another variable and then the copied object is passed
Pass by Reference: A reference to the actual parameter is passed to the method
Program
X is the parameter passed to the method.
Method overloading means a class containing one or more methods with the same name differentiated with the argument type.The arguments can be differentiated in the following ways
-> number of arguments
-> datatype of arguments
-> Sequence of arguments
use case with different number of arguments
Output: