Java Methods

What is a Method?

A method is a reusable block of code that performs a specific task.

Loading...
Output:

Method Structure

A method has a return type, name, and optional parameters.

Loading...
Output:

Parameters

Parameters allow methods to accept input values.

Loading...
Output:

Return Values

Methods can return values instead of just printing them.

Loading...
Output:

Void vs Return

Loading...
Output:

Static vs Non-Static

In Java, methods can be either static or non-static.

  • Static methods belong to the class itself, not an object. You can call them directly using the class name.
    Example: Main.greet();
  • Non-static methods belong to objects (instances of a class). You must create an object to use them.

In the example below, sayHello() is a non-static method. That is why we create an object t using new Test() before calling it.

Key takeaway:

  • Use static for general utility methods
  • Use non-static when the method depends on object data
Loading...
Output:

Practice

Create a method that returns the maximum of two numbers.

Loading...
Output:

Need Help?