CJCoding With Joseph
15free / daySign inCreate account

Mastering Java - Full Guide

Methods Mastery

Methods Mastery

A method is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, we can define a method once and call it whenever needed.

Using methods makes your code:

  • Easier to read – Each method has a clear purpose.

  • More organized – Code is broken into smaller, manageable parts.

  • Reusable – The same method can be called multiple times with different inputs.


Basic Method

A method can take in parameters, which are values that the method uses inside its body. This allows the method to work with different inputs instead of being fixed to a single value.

For example, the method below accepts an integer (num) and prints it to the screen:

public static void printNumber(int num) {
    System.out.println("The number is: " + num);
}

public static void main(String[] args) {
    printNumber(5); // Passing 5 as an argument
}

OUTPUT:

The number is: 5

In this example:

  • The method printNumber(int num) takes an integer as a parameter.

  • Inside the method, it prints "The number is: " followed by the value of num.

  • When calling the method in main(), we pass the value 5, so it prints "The number is: 5".

Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 14 more lessons in Mastering Java - Full Guide.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.