The return keyword causes a method to return to the method that called it, passing a value that matches the return type of the returning method.
Below diagram describe that the methods return int value:
Below diagram describe that the methods return int value:
return Java Keyword Example
The return keyword is used to stop the execution of a method and return a value for the caller.
Example 1: In below example, doOperation() method of AddOperation class calculate the sum and returns the integer value.
class AddOperation implements Operations {
@Override
public int doOperation(int num1, int num2) {
return (num1 + num2);
}
}
Example 2: In below example, doOperation() method of SubOperation class do subtraction and returns the integer value.
class SubOperation implements Operations {
@Override
public int doOperation(int num1, int num2) {
return (num1 - num2);
}
}
Example 3: In below example, doOperation() method of MultiplyOperation class does multiplication and returns the integer value.
class MultiplyOperation implements Operations {
@Override
public int doOperation(int num1, int num2) {
return (num1 * num2);
}
}
Example 4: In below example, doOperation() method of DivisionOperation does division operation and returns the integer value.
class DivisionOperation implements Operations {
@Override
public int doOperation(int num1, int num2) {
return (num1 / num2);
}
}
Complete Example
package com.javaguides.corejava.keywords;
public class ReturnKeyword {
public static void main(String[] args) {
Operations addOperation = new AddOperation();
Operations subOperation = new SubOperation();
Operations mulOperation = new MultiplyOperation();
Operations divOperation = new DivisionOperation();
int add = addOperation.doOperation(10, 20);
System.out.println("Addition of 10 and 20 ::" + add);
int sub = subOperation.doOperation(20, 10);
System.out.println("Substraction between 20 and 10 :: " + sub);
int mul = mulOperation.doOperation(10, 20);
System.out.println("Multiply 10 and 20 :: " + mul);
int div = divOperation.doOperation(20, 10);
System.out.println("Division of 20 by 10 :: " + div);
}
}
interface Operations {
public int doOperation(int num1, int num2);
}
class AddOperation implements Operations {
@Override
public int doOperation(int num1, int num2) {
return (num1 + num2);
}
}
class SubOperation implements Operations {
@Override
public int doOperation(int num1, int num2) {
return (num1 - num2);
}
}
class MultiplyOperation implements Operations {
@Override
public int doOperation(int num1, int num2) {
return (num1 * num2);
}
}
class DivisionOperation implements Operations {
@Override
public int doOperation(int num1, int num2) {
return (num1 / num2);
}
}
Output:
Addition of 10 and 20 ::30
Substraction between 20 and 10 :: 10
Multiply 10 and 20 :: 200
Division of 20 by 10 :: 2
Comments
Post a Comment
Leave Comment