Methods in JAVA
Lets get started
- 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.
Creating a 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:
syntax :
public class MINtech { static void MINtechJava() { // code to be executed } }
Explaination --
- MINtechJava() is the name of the method
- static means that the method belongs to the Main class and not an object of the Main class.
- void means that this method does not have a return value.
Calling the Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon; In the following example, myMethod() is used to print a text (the action), when it is called:
for example
public class MINtech { static void MINtechJava() { System.out.println("I just got executed!"); } public static void main(String[] args) { MINtechJava(); } }
Elaborate with a simple example :
- /*Create a Method(function) that will return whether the
- given input is a prime number or not */
- import java.util.*;
- public class MINtech{
- public static String MINtechJava(int n){
- //writing logic for a prime number
- int temp = 0 ;
- for(int i = 2 ;i<= n ;i++) {
- if(n%i == 0 ){
- temp++ ;
- }
- }
- if(temp == 1){
- return "Yeah its a prime number " ;
- }else{
- return "Nope its not a prime number " ;
- }
- }
- public static void main (String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter a number that you want to check : ");
- int n = sc.nextInt();
- // calling the fuction MINtechJava
- System.out.println(MINtechJava(n));
- }
- }
Output
Enter a number that you want to check : 199 Yeah its a prime number Enter a number that you want to check : 2024 Nope its not a prime number Enter a number that you want to check : 2023 Nope its not a prime number
No comments:
Post a Comment