Website For Developers

Methods in Java


  • In programming, method or function is a piece of code (sub-program) that acts on a data on the base of statements written in it.
  • Methods in Java are increase the readability of the code.
  • This main is also a method. public static void main(String[] args) {}
  • If you are new in programming, remember only one thing: method is the OOP word for function (no difference).

Built-in Methods


User-defined methods


Syntax

Modifier returntype name (arguments) {
Method body
}


1- Example with Void Return-type and null arguments

public class MethodVoid {

   public static void main(String[] args) {
     System.out.println( "This is main method statement." );
     print();
   }
   static void print() { //by default access modifier is private
     System.out.println( "This is User-defined method statement." );
   }
}

Output

This is main method statement.
This is User-defined method statement.


2- Example with a Return-type and null arguments

public class MethodStringReturn {

  public static void main(String[] args) {
     System.out.println( "This is main method statement." );
     String s = string();
     System.out.println(s);
   }
  public static String string() {
     String s = "This is Method Statement with a Return type.";
     return s;
   }
}

Output

This is main method statement.
This is Method Statement with a Return type.


3- Example with Void Return-type but has arguments

public class MethodWithArgument {

   public static void main(String[] args) {
     System.out.println( "This is main method statement." );
     String s = "This is Method Statement with has an argument.";
     print(s);
   }
   public static void print(String s) {
     System.out.println(s);
   }
}

Output

This is main method statement.
This is Method Statement with has an argument.


4- Example with a Return-type and has arguments.

public class MethodExample {

   public static void main(String[] args) {
     System.out.println( "Method with a returntype and arguments." );
     int a = 2;
     int b = 3;
     System.out.println( "Value of a: "+a );
     System.out.println( "Value of b: "+b );
     int sum = sum(a,b);
     System.out.println( "Total is: "+sum );
   }
   public static int sum(int a, int b) {
     int total = a+b;
     return total;
   }
}

Output

Method with a returntype and arguments.
Value of a: 2
Value of b: 3
Total is: 5