Uploaded by Suhil Haji

What is a Method

advertisement
What is a Method?
Method
• In Java, a method is a block of code that performs a specific
function and runs only when it is called.
• Methods are also commonly known as functions.
• Each method has its name. You can pass data into a method
via parameters.
• A method also has a return type defining the type of data it
returns.
Method
• The name of the method should be written in lowerCamelCase
where the first letter should be small.
• Method should have a proper name, preferably a verb referring
to what it does e.g.
▪ add()
▪ printContactList()
▪ updateInfo()
Why are Methods used?
• They allow code to be reused without rewriting it again and
again.
• Methods are timesavers and keep the code organized and
readable.
• It makes the code understandable to multiple coders. It helps in
modularizing the program.
Create a Method
public class Driver {
Modifier Return Type Method Name
Parameter List
public static void printName(String name) {
System.out.println("Hi, I am " + name + "!");
}
}
Method body
Method declaration
1.Modifier: Defines the access type i.e. from where the method can be
accessed in your program e.g. public, private, etc. It is public in this case,
which means this method can be accessed outside of the class too.
2.Return Type: The data type of the value that the method returns. In this case,
it is void i.e. does not return anything.
3.Method Name: It is the name of the method by which it will be called in our
program. The name of our method is printName.
4.Parameter List: It is the list of data that needs to be passed into the method.
It is comma-separated and each input data is preceded by its datatype. If
there is no data to be passed the brackets () are left empty. We have passed
one parameter name of type String.
5.Method body: It consists of the code that needs to be executed enclosed
within curly braces {}.
Call a Method
• Simply write the method’s name followed by two parentheses () and a
semicolon(;).
printName();
• If the method has parameters in the declaration, those parameters are
passed within the parentheses () but this time without their datatypes
specified. However, it is important to keep the sequence of arguments the
same as defined in the method definition. Let’s look at an example to
understand this better.
String name = "Mary";
printName(name);
public class Driver {
public static void printName(String name) {
System.out.println("Hi, I am " + name + "!");
}
public static void main(String[] args) {
String name = "Mary";
printName(name);
String name1 = "Lucy";
printName(name1);
String name2 = "Alex";
printName(name2);
String name3 = "Zoey";
printName(name3);
}
}
Output
Hi, I am Mary!
Hi, I am Lucy!
Hi, I am Alex!
Hi, I am Zoey!
Download