A method is a named block of code inside a class that performs a task. You have been calling methods all along: System.out.println, Math.sqrt, sc.nextInt().
Defining a method#
modifiers returnType name(parameters) {
// body
return value; // if returnType is not void
}
144 84.33 =================== | Vindhyaedu Java | ===================
static- belongs to the class (no object needed). We will meet non-static (instance) methods in the OOP lessons.void- returns nothing.- The values passed in a call (
12,78, 85, 90) are arguments; the variables in the definition (x,a, b, c) are parameters.
Method एक काम करने वाला code का टुकड़ा है जिसे नाम देकर बार-बार इस्तेमाल किया जा सकता है। static method को सीधे main से call कर सकते हैं। जो method कुछ वापस नहीं देता उसका return type void होता है, बाकी return से value लौटाते हैं।
Method overloading#
Several methods can share a name if their parameter lists differ. Java chooses the best match at compile time:
Square: 36 Rectangle: 24 Circle: 28.27
Pass by value - primitives and references#
Java always passes a copy. For a primitive, the method gets a copy of the number. For an object or array, it gets a copy of the reference - so it can change the object's contents, but not replace the caller's object:
m = 60 [70, 80, 90] [70, 80, 90]
Varargs: any number of arguments#
0 5 100 C | C++ | Java
The varargs parameter must be the last one. printf itself is a varargs method.
Recursion#
A recursive method calls itself on a smaller problem until it reaches a base case:
10! = 3628800 0 1 1 2 3 5 8 13 21 34 Move disk 1 from A to C Move disk 2 from A to B Move disk 1 from C to B Move disk 3 from A to C Move disk 1 from B to A Move disk 2 from B to C Move disk 1 from A to C
Deep or endless recursion throws StackOverflowError. Naive recursive Fibonacci recomputes the same values exponentially many times - fine for small n, very slow for n = 45. Use a loop or store results (memoization) for big inputs.
Binary search as a method#
4 -1
Summary#
- Methods have modifiers, a return type, a name and parameters;
staticmethods can be called without an object. - Overloads share a name with different parameter lists.
- Java is always pass-by-value; for objects the reference is copied.
type... nameaccepts any number of arguments; recursion needs a base case.