1️⃣

11.1 What are Methods?

 
A method is a group of statements that are related and help to complete an overall job. You’ve actually been using methods this entire time — so far, all of your code has been put inside of the main method, which is a special type of method that executes when you run your program.
 
However, you can break up your programs into more methods than just the main method. You can customize what these methods do to help you accomplish the entire task at hand. For example, if I told you to print “Hello World” 5 times, you could use a for loop with System.out.println("Hello World") inside the body. Alternatively, I could write a method called printMessage() which does that exact same thing, but there’s less typing (see highlighted code).
public class Methods { public static void main(String[] args) { // prints "Hello World" 5 times for (int i = 0; i < 5; i++) { printMessage(); } } /** Prints "Hello World" */ public static void printMessage() { System.out.println("Hello World"); } }
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.