What are Methods in Java? || Instance Method in java.


INSTANCE METHOD 

📝What are Methods in Java: -  

  • A method is a collection of statements that perform some specific task and return the result to the caller. 
  • A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. 
  • In Java, every method must be part of some class which is different from languages like C, C++, and Python 
  • Methods are time savers and help us to reuse the code without retyping the code. 

Syntax of Method in java:
 return_type MethodName ()   
 {   
   // Body of the Method/logic/implementation return statement;   
 }   


Examples (1):
 class Dog{  
      void run()  
      {  
           //Body of the Method/logic/implementation (better word)  
      }  
 }  
📢// Return Nothing Because Void doesn't have any return type  

Examples (2):
 class Tap{  
      Water open()  
      {  
           //Body of the Method/logic/Implementation  
           return statement;  
      }  
 }  
 class water{  
 }  
📢//Return "Water"  

Examples (3):
 class Conductor{  
      Ticket issue() {  
           //Body of Method/logic/Implementation  
      }  
 }  
 class Ticket{  
 }  
📢//Returns "Ticket"  



Examples (4):


 class Shop{  
      Product sell() {  
           //Body of the Method/logic/Implementation  
           return statement;  
      }  
 }  
 class Product{  
 }  
📢//Returns "Product"  


📝Rules for Methods in java:- 

  • Methods must have either return type or void but not both. 
  • Void method cannot return any data. 
  • A method can have only one return type or only one return statement.  
  • The return type of method and the returning value must match. 
  • Inside a method, the return statement must be the last executable statement in java 



Return type means the data type of returning the value. 


Examples (1):
Examples (2):
Examples (3):
Examples (4):
Examples (5):

  • Here ‘t’ is called a local reference variable. 

Examples (6):
Examples (7):
Examples (8):
  • A Method gets executed only when we invoke it.
  • A Method can be invoked multiple times.
  • The main method is not required for compilation rather required for execution. 

Examples (9):
Examples (10):
Examples (11):

📢Next Topic:

Post a Comment

0 Comments