Java Method

 

Method is a block of code which runs only when it is called or invoked.
Method is used to perform certain behaviors or actions.
Method can accept data which are called parameters.

To create a method, you need the follow things:
1. name
2. return type
3. parameters
4. statements
5. return value

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
int addOne(int num){
int answer = num +1;
return answer;
}
int addOne(int num){ int answer = num +1; return answer; }
int addOne(int num){
   int answer = num +1;
   return answer;
}

Methods must be inside of a class.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class MathClass{
int addOne(int num){
int answer = num +1;
return answer;
}
}
class MathClass{ int addOne(int num){ int answer = num +1; return answer; } }
class MathClass{

  int addOne(int num){
   int answer = num +1;
   return answer;
  }

}

Calling a method
A method can be called multiple times.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class MathClass{
static int addOne(int num){
int answer = num +1;
return answer;
}
public static void main(String[] args) {
int answer = addOne(5);
System.out.println("answer is "+answer);// 6
}
}
class MathClass{ static int addOne(int num){ int answer = num +1; return answer; } public static void main(String[] args) { int answer = addOne(5); System.out.println("answer is "+answer);// 6 } }
class MathClass{

  static int addOne(int num){
   int answer = num +1;
   return answer;
  }

  public static void main(String[] args) {
    int answer = addOne(5);
    System.out.println("answer is "+answer);// 6
  }
}

Method Parameters
You can pass in however many parameters you would like just separate them by comma.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
int add(int num1, int num2, int num3, int num4){
int answer = num1 + num2 + num3 +num4;
}
int add(int num1, int num2, int num3, int num4){ int answer = num1 + num2 + num3 +num4; }
int add(int num1, int num2, int num3, int num4){
   int answer = num1 + num2 + num3 +num4;
}

Return values
Our example above indicates that add must return an int. Every method must return either a value or void.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void sayHello(String name){
System.out.println("Hello "+name+"!");
}
void sayHello(String name){ System.out.println("Hello "+name+"!"); }
void sayHello(String name){
   System.out.println("Hello "+name+"!");
}

sayHello method has a return type of void.

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *