Method & its types

Method & its types

  • A method is a block of code that only runs when it is called.
  • You can pass data, known as parameters, into a method.
  • Methods are used to perform certain actions, and they are also known as functions.
  • Why use methods? To reuse code: define the code once, and use it many times.
Where to create or defining method?
  • A method must be declared within a class.
  • It is defined with the name of the method, followed by parentheses ().
  • Example:
System.out.println()
  • Syntax:
return_type method_name ()
{
Statements;
}
  • Example:
void input_data()
{
System.out.println("Hello Sarthak");
}
  • Here,void means that this method does not have a return value.
  • input_data() is the name of the method.
  • () has no arguments.
How to calling /executing method?

  • To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
  • Syntax:
object_name.method_name();
  • Example:
s1.input_data();
  • A method can also be called multiple times:
Example:
s1.input_data();
s1.input_data();
s1.input_data();

Types of methods:
1. no argument method or no-parameterized method
2. argument method or parameterized method
  • Information can be passed to methods as a parameter. 
  • Parameters act as variables inside the method.
  • Parameters are specified after the method name, inside the parentheses. 
  • You can add as many parameters as you want, just separate them with a comma.
  • Syntax:
return_type method_name (arguments)
{
Statements;
}
  • Example:
void input_data(String name)
{
System.out.println("Hello "+name);
}

How to call/executing parameterized method?
  • To call a method in Java, write the method's name followed by two parentheses (arguments) and a semicolon;
  • Syntax:
object_name.method_name(arguments);
  • Example:
name="CDPatel"
s1.input_data(name);
  • A method can also be called multiple times:
  • Example:
name1="CDPatel"
name2="ADPatel"
name3="SDPatel"
s1.input_data(name1);
s1.input_data(name2);
s1.input_data(name3);

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form