Methods : Basics (Part 1)




Java Methods

⏺ A method is a block of code which only runs when it is called.

⏺ Methods are used to perform certain actions, which are also known as functions.


➤Why use methods?

 To reuse code: define the code once, and use it many times.


Declaring a method

⏺ A method must be declared within a class. 

⏺ It is defined with the name of the method, followed by parentheses () .

⏺ Method is created by first specifying its dataType such as void , int , string , etc.
and then its name.

⏺ When method is called :
        void will not return any value
        int will return an integer
        String will return a string


➤Syntax:-
  dataType MethodName()   
  {   
  //block of code to be executed   
  }  
For example I created a method named start ( ) which will print out starting machine when called.
  static void start()   
  {   
  System.out.println("Machine Starting");   
  }  
🔔 static keyword is used when a method is declared and called in same class without instantiating i.e creating objects of it.


Calling a Method

⏺ To call a method in Java, write the method's name followed by two parentheses ( ) and a semicolon;

⏺ In the following example, start() is used to print a text (the action), when it is called:

  class MyClass {   
    static void start() {   
       System.out.println("Machine Starting.");   
    }    
    public static void main(String[] args) {    
       //calling the start() method   
         start();   
    }   
  }  
Output:-
  Machine Starting.  
⏺ A method can also be called multiple times.
  class MyClass {    
   static void start() {    
     System.out.println("Machine Starting.");    
   }    
   public static void main(String[] args) {    
     //calling the start() method    
      start();    
      start();    
      start();    
   }    
  }  
Output:-
  Machine Starting.   
  Machine Starting.   
  Machine Starting.  
More concepts of methods will be explained in the following tutorials.




< Previous Next >