Search⌘ K

Different Classifications of Methods

Learn to distinguish various Java method classifications such as void and non-void methods, static versus non-static, public versus private, and method overloading. Understand when and how each type is used, enabling you to write more effective object-oriented code in Java.

Void method vs. non-void method

As we discussed in the last lesson, a method may or may not return a value.

  • A void method is a method that does not return anything. It is declared using the keyword void.

  • A method that returns a value can be classified as a non-void method. The return type for such functions can be primitive or reference type.

Java
class VoidVsNonVoid
{
// A void method has a 'void' return type
public static void greet(String name)
{
System.out.format("Happy reading %s!%n", name);
return;
}
// A non-void method can have any primitive or reference data type as its return type
public static int addFive(int number)
{
return number + 5; // a void method uses 'return' keyword at the conclusion to return an output
}
public static void main(String args[])
{
// calling a void method
greet("Frodo");
// calling a non-void method, value returned by function is stored in 'num'
int num = addFive(10);
System.out.println(num);
}
}
  • A void method may or may not use the return keyword (lines 4-8). Even if it uses it, it cannot return anything, so it is not followed by any expression. When calling a void method (line 19 ...