← Back to Core Java Course | Chapter 5: Methods & Arrays | Lesson 1 of 10

Java Methods Introduction

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

java
public class Main {
	static void greet() {
		System.out.println("Hello!");
	}
	public static void main(String[] args) {
		greet();
	}
}

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

java
public class Main {
	public static int square(int number) {
		return number * number;
	}
	public static void main(String[] args) {
		System.out.println(square(4));
	}
}

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

java
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");
	}
}

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

java
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
	}
}

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?

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.