⚡0 XP🔥0

Methods

Lesson 7 of 15 ⏱ 6 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs Java

Define and call static methods, parameters and return values, method overloading, pass-by-value for primitives and references, varargs and recursion.

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
}
▶ Try it YourselfJava
Ctrl + Enter to run
Output
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:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
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:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
m = 60
[70, 80, 90]
[70, 80, 90]

Varargs: any number of arguments#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
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:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
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
Common Mistake

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#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
4
-1

Summary#

  • Methods have modifiers, a return type, a name and parameters; static methods 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... name accepts any number of arguments; recursion needs a base case.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

isPrime method

Write static boolean isPrime(int n) and use it to print all primes between 30 and 70 on one line separated by spaces.

Expected output:
31 37 41 43 47 53 59 61 67
2

Recursive power and sum of digits

Write two recursive methods: long power(int b, int e) and int digitSum(int n). Print:

3^12 = 531441
digitSum(98765) = 35
Expected output:
3^12 = 531441
digitSum(98765) = 35

Quick Quiz

Q1.

Java passes arguments...

Q2.

Which is a valid overload of int sum(int a, int b)?

Q3.

What is int... nums in a parameter list?

Q4.

What happens if recursion has no base case?