determines whether the method is available to other classes.
Method declaration: public
Allows any other class to access the method
Method declaration: private
Hides the method from other classes
Method declaration: protected
Lets subclasses use the method but hides the method from other classes
Method declaration: static
This optional keyword declares that the method is static, meaning you can call it without first creating an instance of the class in which it’s defined. The mainmethod must always be static, and any other methods in the class containing the main method should also be static.
Method declaration: return-type
indicates whether the method returns a value when it is called — and if so, what type the value is. If the method doesn’t return a value, specify void.
Method declaration: method-name
The rules for making up method names are the same as the rules for creating other identifiers: Use any combination of letters and numbers, but start with a letter.
Method declaration: parameterlist
You can pass one or more values to a method by listing the values in parentheses following the methodname. The parameter list in the method declaration lets Java know what types of parameters a method should expect to receive and provides names so that the statements in the method’s body can access the parameters as local variables.
Method declaration: statements
One or more Java statements that comprise the method body, enclosed in a set of braces. Unlike Java statements such as if, while, and for, the method body requires you to use the braces even if the body consists of only one statement.
How to create a user-defined method:
You can see three keywords public, static and void before the functionname.
The public keyword makes myMethod() method public. Public members can be accessed from outside of the class.
The static keyword denotes that the method can be accessed without creating the object of the class.
The void keyword signifies that the method doesn’t return any value.
Public keyword
Public members can be accessed from outside of the class.
Static keyword
denotes that the method can be accessed without creating the object of the class.
Void keyword
signifies that the method doesn’t return any value
How to call a Java method:
Before you can use (call a method), you need to define it.
Example. Method (return no value and no parameter)
// Welcometodisplayinformationmethod
Example. Method (return no value and no parameter)
//
display1
display2
Example. Method (return no value and have parameter)