Return Datatypes:
A return type specifies what kind of value a method gives back when it finishes running. If a method doesn't return anything, we use void.
1). Returning an Integer
public int add(int a, int b) { return a + b; }
2). Returning a String
public String greet(String name) { return "Hello, " + name; }
3.
public void printMessage(String message) { System.out.println(message); }
the return datatype specifies what type of data a method will return, and it must match the actual returned value in the method body. If the method doesn't return anything, use void.
Example code for Return Datatype:
public class Calculator2 { // Adds two numbers and returns the result public int add(int no1, int no2) { // parameters & int retunr datatype return no1 + no2; } // Multiplies two numbers and returns the result public int multiply(int no1, int no2) { return no1 * no2; } // Divides two numbers, if no2 is not zero public void division(int no1, int no2) { // void return datatype if (no2 != 0) { System.out.println("Division result: " + (no1 / no2)); } else { System.out.println("Cannot divide by zero."); } } public static void main(String[] args) { Calculator2 calc = new Calculator2(); int result = calc.add(10, 20); System.out.println("Addition result: " + result); int multiplyOutput = calc.multiply(result, 2); System.out.println("Multiplication result: " + multiplyOutput); // Create a Calculator3 instance and use the subtractor method Calculator3 calculator3 = new Calculator3(); int subtractor = calculator3.subtractor(result, 5); System.out.println("Subtraction result: " + subtractor); int subtractor1 = calculator3.subtractor(multiplyOutput, 7); System.out.println("Subtraction by 7 result: " + subtractor1); calc.division(result, 2); // } } class Calculator3 { // Subtracts two numbers and returns the result public int subtractor(int no1, int no2) { return no1 - no2; } }
Key Takeaways
✔ Every method must declare a return type (or void).
✔ Return types enforce type safety (Java checks compatibility).
✔ void methods are for actions, not computations.
✔ Always return the correct data type (or face compiler errors).
Final Thought
Understanding return types is crucial for writing correct and reusable Java methods. Whether returning a value or performing an action, always choose the appropriate type to make your code clear and reliable.
Note: The formatting and structure were optimized for clarity with AI assistance.
--------------------------- End of the Blog ------------------------------
Top comments (0)