2️⃣

11.2 Why Methods?

 
 
We have learned about many different ways to execute certain things, but we can’t always put the code in the same spot (main method) otherwise it will get all muddled up and hard to read. If you want to accomplish a certain goal, it is better to create separate methods for each task inside of the goal, kind of like making a checklist. Methods can also be reused, so that we do not have to retype our code again and again which makes it more convenient for us. Additionally, since methods are self-contained, it makes it easier for us to test individual parts of our code rather than having to run the entire thing every time. Long story short, methods help to make code easier to read and maintain. As you can see in the example below, the different tasks we want to accomplish are placed in different methods.
import java.util.Scanner; public class WhyMethods { public static void main(String[] args) { // cleaner code because methods group actions printMessages(); printSum(); } /** Prints 3 messages */ public static void printMessages() { System.out.println("May the Force be with you"); System.out.println("Tahiti, it's a magical place"); System.out.println("Live long and prosper"); } /** Prints the sum of 2 numbers */ public static void printSum() { Scanner input = new Scanner(System.in); // prompt user to enter 2 numbers System.out.print("Enter number 1: "); double num1 = input.nextDouble(); System.out.print("Enter number 2: "); double num2 = input.nextDouble(); double sum = num1 + num2; // print the sum of those numbers System.out.println("Sum: " + sum); input.close(); } }
⚖️
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.