Methods represent the business logic of the application and it defined inside the class.
Ex: I have a java class, in that class, I want to do add two numbers so we should keep this logic of addition in methods.
Access modifiers for methods:Ex: I have a java class, in that class, I want to do add two numbers so we should keep this logic of addition in methods.
- The method should have a signature and signature represents method name and parameters.
- A java class contains multiple methods.
syntax
<access modifier> <return type> <method_Name>(parameters){ //method body //business code }
Access modifiers applicable to methods are public, private to check the visibility of methods to other classes.
Return type:
The return type is the data type of the value returned by the method, if the method doesn't return value, return type value should be void.
Method_Name:
The method name is any legal identifier.
Parameters:
Parameters should placed in parenthesis() by keeping(;).if there is no parameters ,we must use use empty parameters.
Naming a method
Method name is any legal identifier. method name should be the verb in lower case.if there is multi-word method name that begins with lowercase and first letter of each second word must capital letter.
How to invoke methods?
In java we have two types of methods
- Instance methods
- Static methods
Instance methods:
Instance methods are invoked by using Object reference a class.
package com.practice; public class Instance_Method_Demo { int x = 30;// instance variable declaration int y = 30;// instance variable declaration // instance method public void add() { System.out.println("sum of numbers:" + (x + y)); } public static void main(String[] args) { // Object creation Instance_Method_Demo instance_Method_Demo = new Instance_Method_Demo(); instance_Method_Demo.add();// invoking instance method with object // reference } }output
sum of numbers:60Static methods:
Static methods are invoked by using class name like below
<classname>.<static_method>
Example
package com.practice;
public class Static_Method_Demo { static int x = 30;// static variable declaration static int y = 30;// static variable declaration // static method public static void add() { System.out.println("sum of numbers:" + (x + y)); } public static void main(String[] args) { // invoking static method by using class name Static_Method_Demo.add(); } }output
sum of numbers:60Example for method with parameters
package com.practice; public class Static_Method_Demo { static int x;// static variable declaration static int y;// static variable declaration // static method public static void add(int x,int y) { System.out.println("sum of numbers:" + (x + y)); } public static void main(String[] args) { // invoking static method by using class name Static_Method_Demo.add(30,30); } }output
sum of numbers:60