Java for Beginners · Module 5: Data and Methods
🎯 Why Methods?
You have written all your code inside main so far. Long programs written that way become impossible to read. A method is a named block of code that does one job. You write it once and call it as many times as you like, from anywhere.
1️⃣ Writing and Calling Methods
return n * n;
}
Figure 1: The parts of a method.
- Return type: the type of value the method gives back. Use
voidwhen it gives back nothing. - Parameters: the inputs, each with a type and a name, in brackets.
- return: sends a value back and ends the method immediately.
- static: for now, write
staticon every method you call frommain. Lesson 29 explains why.
Program 1: Four small methods
public class MethodBasics {
static void greet() {
System.out.println("Hello from a method!");
}
static int square(int n) {
return n * n;
}
static double average(int a, int b, int c) {
return (a + b + c) / 3.0;
}
static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
greet();
greet();
System.out.println("square(7) = " + square(7));
int r = square(4) + square(3);
System.out.println("4^2 + 3^2 = " + r);
System.out.println("average = " + average(70, 80, 90));
System.out.println("isEven(10) = " + isEven(10));
}
}
Hello from a method!
Hello from a method!
square(7) = 49
4^2 + 3^2 = 25
average = 80.0
isEven(10) = true
greet()is called twice and runs twice: write once, use many times.- A method that returns a value can be used inside an expression:
square(4) + square(3). - The values you pass when calling (
7,70, 80, 90) are arguments. They fill the parameters (n,a, b, c) in order. - Execution starts in
main, jumps into a method when it is called, and comes back to the next line when the method ends.
2️⃣ Pass by Value
int n = 5main
x becomes 99inside the method
n is still 5int[] amain: reference R
arr also points to Rarr[0] = 99 changes the shared array
a[0] is 99Figure 2: Java passes a copy of the value. For arrays and objects, the copy is of the reference.
When you call a method, Java gives it a copy of each argument. For primitives, changing the copy cannot affect the original. For arrays and objects the copy is a copy of the reference, so the method can change the shared array, but it cannot make the caller’s variable point somewhere else.
import java.util.Arrays;
public class PassByValue {
static void changeNumber(int x) {
x = 99;
System.out.println("inside changeNumber: x = " + x);
}
static void changeArray(int[] arr) {
arr[0] = 99;
}
static void reassignArray(int[] arr) {
arr = new int[]{7, 7, 7};
}
public static void main(String[] args) {
int n = 5;
changeNumber(n);
System.out.println("after changeNumber: n = " + n);
int[] a = {1, 2, 3};
changeArray(a);
System.out.println("after changeArray: " + Arrays.toString(a));
reassignArray(a);
System.out.println("after reassignArray: " + Arrays.toString(a));
}
}
inside changeNumber: x = 99
after changeNumber: n = 5
after changeArray: [99, 2, 3]
after reassignArray: [99, 2, 3]
nstays 5: the method changed only its own copyx.changeArraychanged the real array, because both names point to the same array (Lesson 21).reassignArraypointed its own copy of the reference at a new array. The caller’sastill points to the old one, so nothing changed.- So Java is always pass by value. With objects, the value passed is the reference.
3️⃣ Method Overloading
Several methods may share one name if their parameter lists differ (in number, type or order). This is called overloading. Java picks the best match from the arguments you give.
| Call | Chosen method | Why |
add(2, 3) | add(int, int) | exact match |
add(2, 3, 4) | add(int, int, int) | three arguments |
add(2.5, 3.5) | add(double, double) | decimals |
add("Ja", "va") | add(String, String) | text |
add(2, 3.5) | add(double, double) | int is widened to double |
add(b, b) (bytes) | add(int, int) | byte is widened to int |
Figure 3: How Java picks an overloaded method.
public class Overload {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
static double add(double a, double b) {
return a + b;
}
static String add(String a, String b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2, 3, 4));
System.out.println(add(2.5, 3.5));
System.out.println(add("Ja", "va"));
System.out.println(add(2, 3.5));
byte b = 1;
System.out.println(add(b, b));
}
}
5
9
6.0
Java
5.5
2
- This is how
printlnaccepts an int, a double, a String and more under one name. - When there is no exact match, Java widens the arguments (Lesson 9):
add(2, 3.5)uses thedoubleversion. - The return type alone does not make an overload. The parameter list must differ.
4️⃣ Varargs and Early return
public class Varargs {
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
static String describe(String label, int... values) {
return label + " has " + values.length + " values";
}
static int maxOf(int a, int b) {
return (a > b) ? a : b;
}
static void printStars(int n) {
if (n <= 0) {
return;
}
for (int i = 0; i < n; i++) System.out.print("*");
System.out.println();
}
public static void main(String[] args) {
System.out.println(sum());
System.out.println(sum(5));
System.out.println(sum(1, 2, 3, 4));
System.out.println(describe("scores", 90, 80));
System.out.println(maxOf(maxOf(3, 9), 5));
printStars(5);
printStars(-1);
printStars(3);
}
}
0
5
10
scores has 2 values
9
*****
***
int... numbers(varargs) accepts any number of ints, including none. Inside the method,numbersis an ordinary array. The varargs parameter must be the last one.- Methods can call other methods:
maxOf(maxOf(3, 9), 5)finds the largest of three. - In a
voidmethod, a barereturn;leaves early.printStars(-1)prints nothing.
5️⃣ Errors Beginners Meet
Wrong arguments
public class Bad1 {
static int twice(int n) {
return n * 2;
}
public static void main(String[] args) {
int x = twice("5");
twice(1, 2);
String s = twice(3);
}
}
Bad1.java:7: error: incompatible types: String cannot be converted to int
int x = twice(“5”);
^
Bad1.java:8: error: method twice in class Bad1 cannot be applied to given types;
twice(1, 2);
^
required: int
found: int,int
reason: actual and formal argument lists differ in length
Bad1.java:9: error: incompatible types: int cannot be converted to String
String s = twice(3);
^
3 errors
- The method expects one int and returns an int. Check the count and types of your arguments and what you store the result in.
A path with no return
public class Bad4 {
static int sign(int n) {
if (n > 0) {
return 1;
}
}
public static void main(String[] args) {
System.out.println(sign(5));
}
}
Bad4.java:6: error: missing return statement
}
^
1 error
- If
nis not positive, the method reaches the end without returning anything. Add areturnfor the other cases.
Overloading by return type only
public class Bad2 {
static int add(int a, int b) {
return a + b;
}
static double add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(1, 2));
}
}
Bad2.java:6: error: method add(int,int) is already defined in class Bad2
static double add(int a, int b) {
^
1 error
Calling an instance method from main
public class Bad3 {
void hello() {
System.out.println("hi");
}
public static void main(String[] args) {
hello();
}
}
Bad3.java:7: error: non-static method hello() cannot be referenced from a static context
hello();
^
1 error
mainis static, so it can call only static methods directly. Addstaticfor now. Lesson 29 shows the other way, with objects.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Forgetting static on a helper called from main | non-static method error | Add static |
| Not returning on every path | missing return statement | Return in every branch |
| Ignoring the returned value | Result thrown away | Store it or print it |
| Expecting a method to change a primitive argument | It only changes a copy | Return the new value |
| Overloading with only a different return type | Already defined | Change the parameters |
| Arguments in the wrong order | Wrong result, no error if types match | Check parameter order |
❓ Frequently Asked Questions
Q1. What is the difference between a parameter and an argument?
A parameter is the variable in the method definition. An argument is the actual value you pass when calling.
Q2. Can a method return more than one value?
Not directly. Return an array or an object, or split the work into separate methods.
Q3. Is Java pass by reference?
No. It is always pass by value. For objects the value copied is the reference, which is why a method can change the object but cannot re-point the caller’s variable.
Q4. Why is main static?
The JVM must call it before any object exists (Lesson 5).
✅ Key Takeaways
- A method has a return type, a name, parameters and a body.
voidmeans no return value. - Arguments fill parameters in order.
returnsends a value back and ends the method. - Java passes copies of values. A method cannot change a caller’s primitive.
- Overloading: same name, different parameter lists. The return type alone is not enough.
int... xaccepts any number of arguments and behaves as an array.
🎓 Practice questions: (1) Write a methodisPrime(int n)that returns a boolean, and use it to print the primes up to 30. (2) Write overloaded methodsareafor a circle, a rectangle and a square. (3) Write a method that returns the largest element of anint[]. (4) Why does a swap methodswap(int a, int b)not swap the caller’s variables? (5) Write a varargs method that returns the average of its arguments.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java