Method is a set of statements to perform an operation, methods are also known as procedures or functions.
Whenever we want perform same operations multiple times then we use methods, using methods we can reduce the code size.
Basically we have two types of methods in java.
System.out.println("CseWorld Online");
Methods in Objects oriented Programming equivalent of Functions in Non object oriented programming.
modifier return Type methodName(Parameters) { // Method body }
modifier -It is optional, it defines access type of the method
returnType - Method may retrun a value
methodName - Name of the method.
parameters - Parameters are optional, we can use mutiple parameters by separating with ,
method body - set of statements define that what the method does.
public static int add(int a, int b) { Statements ---------- }
dataType variableName = methodName(Values) -------------- int abc = add(5, 3); System.out.println(abc); } public static int add(int a, int b) { int result; result = a + b; return result; } }
modifier methodName(Parameters) { //Method body } public static void add(int a, int b) { Statements ----------- -------- }
public static void main(String [] args) { studentRank(499); } public static void studentRank(int marks) { if (marks >= 600) { System.out.println("Rank:A1"); } else if (marks >= 500) { System.out.println("Rank:A2"); } else { System.out.println("Rank:A3"); } }
package javaExamples; public class MethodOverLoading + { public static void main (String []args)+ { int x = add(5, 7); int y = add(5, 7, 9); double z = add(5.234, 7.23); System.out.println(x); System.out.println(y); System.out.println(z); } public static int add(int a, int b)+ { int result; result = a + b; return result; } public static int add(int a, int b, int c)+ { int result; result = a + b + c; return result; } public static double add(double a, double b)+ { double result; result = a + b; return result; } }