Calling a Void Method

Calling a Void Method

Understanding Void Methods

  • A void method is a type of method that performs an action but does not return a value.
  • Void methods serve as a way for a programmer to pack a series of statements into a single, reusable package (the method itself).

Defining a Void Method

  • A void method is defined by using the word ‘void’ before the method name during its declaration.
  • For instance, a void method could be declared as: public void myMethod() {...}
  • Void methods may or may not mandate parameters.

Calling a Void Method

  • Calling a void method is done by simply stating its name followed by parentheses within the scope of its visibility.
  • For instance, calling a void method would look like: myMethod();
  • If the void method requires parameters, the parameters must be passed in the method call as follows: myMethod(parameter1, parameter2);
  • Void methods do not return a value, hence assigning the call to a variable or expecting a result would lead to an error.

Using Void Methods

  • Void methods are typically used to perform a function or action, such as updating variable values, printing out information, or performing an operation such as sorting or searching.
  • Since these methods don’t return a value, they are often used for their side effects, such as modifying the state of an object.
  • You can use them anywhere in your code where the performed action is needed - in control structures, in other methods, or in general program flow.

Methods Calling Syntax

  • Like non-void methods, to call a void method, you need an instance of the class (an object) in which the method is defined.
  • The syntax for calling a void method is object.MethodName(parameters); where parameters are the input values required by the method (if any).
  • The object used to call the method is also the one it will operate on and potentially alter.

Wrapping Up

  • The ability to create and use void methods is a critical skill in object-oriented programming. Void methods allow for meaningful organisation of code through encapsulation of functionality, enhancing code readability and maintainability.