Student-Friendly Notes for High School Computer Science
A method in Java is a named block of code that performs a specific task.
A method lets you group instructions together so they can be used whenever needed.
Think of a method like:
public static void sayHello() {
System.out.println("Hello!");
}
This method is named sayHello. When it is called, it prints Hello!.
Methods are important because they help programmers write better code.
Without methods, you might have to rewrite the same code again and again.
With methods:
This makes programs cleaner and easier to manage.
public static void methodName() {
// code to run
}
public static void sayHello() {
System.out.println("Hello!");
}
public → access modifierstatic → belongs to the class, not an objectvoid → this method does not return a valuesayHello → method name() → parentheses, where parameters go{ } → body of the methodDefining a method does not make it run. You must call the method.
public class MethodExample {
public static void sayHello() {
System.out.println("Hello!");
}
public static void main(String[] args) {
sayHello();
}
}
Hello!
A parameter is information given to a method.
public static void greetUser(String name) {
System.out.println("Hello, " + name);
}
Calling it:
greetUser("Joe");
greetUser("Maria");
Hello, Joe
Hello, Maria
Parameters make methods more flexible. One method can work for many different inputs.
Some methods do a calculation and send a value back.
public static int addNumbers(int a, int b) {
return a + b;
}
Calling it:
int sum = addNumbers(4, 6);
System.out.println(sum);
10
Important vocabulary:
int means the method returns an integerreturn sends a value back to where the method was calledA void method does something, but does not send a value back.
public static void printMessage() {
System.out.println("Welcome!");
}
A return method sends a value back.
public static int multiply(int x, int y) {
return x * y;
}
public class MethodsDemo {
public static void welcome() {
System.out.println("Welcome to the program.");
}
public static int squareNumber(int num) {
return num * num;
}
public static void main(String[] args) {
welcome();
int answer = squareNumber(5);
System.out.println("The square is " + answer);
}
}
Welcome to the program.
The square is 25
Method names should clearly describe what the method does.
Good examples:
printMenu()calculateAverage()checkWinner()displayScore()Poor examples:
stuff()doIt()x()public static void hello() {
System.out.println("Hi");
}
This will not run unless you call:
hello();
Wrong:
hello;
Correct:
hello();
Wrong:
public static int add(int a, int b) {
a + b;
}
Correct:
public static int add(int a, int b) {
return a + b;
}
If a method says it returns int, it must return an integer.
A method is a block of code that performs a task.
We use methods because they:
Methods can:
void method and a return method?return keyword do?