Today we are going to learn the method (s) in java. We can not write all the logic inside main() method.
We need to separate block of code to perform specific takes.
Ques -- What is a method (s) in java?
Answer -- Method is a set of statements (instruction/code) to perform a specific task/operation.
Ques -- Why we create methods?
Answer -- because of Reusability of code.
Ques -- How we can create a method (s)?
Answer --
Access Modifires -- public, private, protected, no access specifire (default)
Specifires -- static,stictfp,volatile,syncornized etc
Return Type -- void, int, boolean etc
[ Will discuss these keywords in our next post ]
Ques -- How can we call a method (s) in java?
Answer -- There are two types of methods in java
- static method
- instance method
1 ) Static Methods
1 ) Instance Methods
# One Example of Add and Subtract method in java
package com.method.blog.demo;
//going to create 2 methods
// 1 - static method
// 2 - instance method (non-static method)
public class MethodDemo {
//method 1 -- static method
// return type is void
// taking two arguments
public static void addMethod(int num1,int num2){
int sum = num1 + num2;
System.out.println("sum is "+ sum);
}
//method 2 -- non-static method
//return type -- int
// taking two argument
public int subtractMethod(int num1,int num2){
int sub = num1 - num2;
return sub; // return type is must
}
public static void main(String[] args) {
// creating objectof the class
MethodDemo md = new MethodDemo();
// static method call
// this method wont return any thing
MethodDemo.addMethod(5, 6);
// non- static method call
//this method return -- integer value
int result = md.subtractMethod(6,5);
System.out.println("Subtaction is "+result);
}
}