OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 11 : Introducing Methods in Java

Unit - 2

Topic - 11 :Introducing Methods in Java

In Java, a method is a block of code that performs a specific task.
Methods make programs modular, reusable, and easy to maintain.


General Form of a Method

type name(parameter-list) { // body of method }

Where:

  • type → The data type of the value returned by the method.

    • Can be any valid type, including custom class types.

    • If no value is returned, use void.

  • name → The name of the method (must be a valid identifier).

  • parameter-list → A list of parameters (type and variable name), separated by commas.

    • If no parameters are needed, leave it empty.

  • return value; → Used to send a value back to the caller (for non-void methods).


Example 1: Method Without Return Value

Here, the method volume() computes and displays the volume of a box directly.

class Box { double width; double height; double depth; // Method to display volume void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); // Assign values to mybox1 mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; // Assign values to mybox2 mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // Display volumes mybox1.volume(); mybox2.volume(); } }

Output:

Volume is 3000.0 Volume is 162.0

💡 Note: This method prints the volume directly, which means it cannot be used for calculations elsewhere.


Example 2: Method with Return Value

This improved version of volume() returns the computed value so it can be used anywhere.

class Box { double width; double height; double depth; // Method to compute and return volume double volume() { return width * height * depth; } } class BoxDemo4 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // Assign values to mybox1 mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; // Assign values to mybox2 mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // Get and display volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // Get and display volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }

Output:

Volume is 3000.0 Volume is 162.0

Key Points

  • Void methods → Perform an action but do not return a value.

  • Return type methods → Return computed values for further use.

  • Modularity → Methods make code organized and reusable.

  • Parameters → Allow passing different values to a method, making it more flexible.

Comments

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies