Java Methods Introduction
In this page:
Creating and Calling a Method
A method bundles a sequence of statements under one name, and that code only actually runs when something explicitly calls the method by name -- writing the method doesn't execute it.
Example: Creating and Calling a Method
public class Main {
static void greet() {
System.out.println("Hello!");
}
public static void main(String[] args) {
greet();
}
}
Login to try C/C++/Java/PHP code in the editor
Method Declaration Structure
A method's declaration specifies four things up front: who can call it (access modifier), what type of value it hands back (return type), its name, and what data it accepts (parameters in parentheses).
Example: Method Declaration Structure
public class Main {
public static int square(int number) {
return number * number;
}
public static void main(String[] args) {
System.out.println(square(4));
}
}
Login to try C/C++/Java/PHP code in the editor
Flow of Execution
Execution always begins in main; whenever the code reaches a call to another method, control jumps to that method's body, runs it to completion, and then returns to the exact line right after the original call.
Example: Flow of Execution
public class Main {
static void step2() {
System.out.println("Inside step2");
}
public static void main(String[] args) {
System.out.println("Before call");
step2();
System.out.println("After call");
}
}
Login to try C/C++/Java/PHP code in the editor
Variable Scope
A variable declared inside a method exists only for that method's execution and is invisible to every other method, even ones in the same class -- this isolation prevents methods from accidentally interfering with each other's local state.
Example: Variable Scope
public class Main {
static void methodA() {
int x = 5;
System.out.println(x);
}
public static void main(String[] args) {
methodA();
// x is not visible here
}
}
Login to try C/C++/Java/PHP code in the editor
Why Use Methods?
Extracting repeated logic into a method means you write and test it once, then call it from anywhere it's needed -- if you later need to fix a bug or change behavior, you only edit it in that one place.
Example: Why Use Methods?
public class Main {
static int addTax(int price) {
return price + (price / 10);
}
public static void main(String[] args) {
System.out.println(addTax(100));
System.out.println(addTax(200));
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: