Methods:
Syntax:
static return_type method_name()
{
Statements;
}
Full Example:
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
Non-static methods:
- A method is a block of code which 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.
- How to create method?
- A method must be declared within a class.
- It is defined with the name of the method, followed by parentheses ().
- Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions.
- Static method
- Non-static method
static return_type method_name()
{
Statements;
}
- The void keyword, used in the above syntax, indicates that the method should not return a value.
- If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method.
How to call static method?
Syntax (in same class):
methodname(argument);
Syntax (in other class):
class_name.methodname(arguments);
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
Non-static methods:
Without arguments
- Syntax:
modifier return_type method_name()
{
Statments;
}
{
System.out.println("sum() method");
}
With arguments:
{
Statments;
}
- Example:
{
System.out.println("sum() method");
}
With arguments:
- When a parameter is passed to the method, it is called an argument.
- 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:
modifier return_type method_name(argument)
{
Statements;
}
{
System.out.println(x+y);
}
How to call non-static method?
Method Overloading in Java
{
return (x + y);
}
{
return (x + y + z);
}
2. Changing data type of arguments
{
Statements;
}
- Example:
{
System.out.println(x+y);
}
How to call non-static method?
- To call a method in Java, write the method's name followed by two parentheses () and a semicolon.
Method Overloading in Java
- If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
- Example:
- Addition for two numbers.
{
return (x + y);
}
- Addition for three numbers.
{
return (x + y + z);
}
- Advantage:
- Method overloading increases the readability of the program.
- Different ways to overload the method
- By changing the number of arguments
- By changing the data type
2. Changing data type of arguments
Tags:
Core java