A method is a block of code, a group of statements, or a set of code that performs a specific task or operation. These are also known as functions in other programming languages.
Method attributes such as visibility, return type, name, and arguments are all listed in the method declaration.
Modifier | Class | Package | Subclass | Global |
Public | Yes | Yes | Yes | Yes |
Protected | Yes | Yes | Yes | No |
Default | Yes | Yes | No | No |
Private | Yes | No | No | No |
Access_specifier return-type methodName(parameter-list) //method header
{
//method-body method signature
}
public String getDetails(String st, int age, float per)
{
String details=details+" "+st+" "+a+" "+per;
return details;
}
In a program, calling a method is straightforward. The program control passes to the called method when we call or invoke a user-defined method.
for instance,
String ans=getDetails("Rabecca Fatima",20,89.70);
It will return a value Rabecca Fatima 20 89.70 after appending the argument passed during the method call.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=sc.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
By providing different inputs, we get different values accordingly.
Enter the number: 34
34 is even
Enter the number: 91
91 is odd
There are two types of methods in Java:
An argument can be passed to a method in two ways.
Important: Java is Strictly Pass by Value
Note: also read about the OOPs in Java
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…