Methods
Methods
Methods are reusable blocks of code. You can pass data in and optionally return a value out.
A simple method
javapublic static void greet() { System.out.println(\"Hello from a method\"); }
You can call this method from main:
javapublic static void main(String[] args) { greet(); }
Parameters and return values
javapublic static int add(int a, int b) { return a + b; } public static void main(String[] args) { int result = add(3, 5); System.out.println(result); // 8 }
Method overloading
In Java you can have methods with the same name but different parameter lists.
javapublic static int add(int a, int b) { return a + b; } public static double add(double a, double b) { return a + b; }
Later in this track you will see how methods live inside classes and how they relate to objects.