Introduction to Java Methods and Functions

 

Methods (or functions) help organize your code and make it reusable.


What is a Method?

A method is a block of code that performs a specific task. You can call it anytime in your program.


Example Code:

public class MethodsExample { public static void greet(String name) { System.out.println("Hello, " + name + "!"); } public static void main(String[] args) { greet("Fuad"); greet("Reader"); } }

Explanation:

  • greet is a method that takes a String parameter.

  • main calls greet with different names.


Tips:

  • Keep methods short and focused.

  • Use parameters to make methods flexible.

  • Always give methods meaningful names, like calculateSum, printMessage, or showMenu.


Practice:

Write a method to:

  • Add two numbers and return the result.

  • Print your favorite quote.

  • Calculate the square of a number.

Comments

Popular posts from this blog

Java Loops Explained: For, While, and Do-While

Welcome to FuadCode – Learn Java Programming from Scratch