Methods in Java — practice with Laura’s calculator, her campus password and her grade report (and the format I changed in three places out of four)
My first Java calculator had everything inside main. I wrote the addition with its printf, copied the block for the subtraction, copied it again for the multiplication and once more for the division, changing the sign each time. It worked. Until the lecturer asked for the results with two decimals instead of one: I changed the %.1f in the addition, the subtraction and the division… and not in the multiplication. In the hand-in, 8,5 * 4,0 = 34,0 sat among three lines with two decimals, and that’s when I understood what methods are for: not to make the code look pretty, but to change each thing in one single place.
In the methods in Java theory you saw every piece of public static double finalGrade(double theory, double practice), the call stack and overloading. Now comes the part that really convinces you: three programs by Laura, the FP2 student who has been with us since the syntax topic, in which main stays short and the work is done by small methods with self-explanatory names. All three are intermediate level and read from the keyboard with Scanner, with data that looks like the real thing: a division by 0, a password with spaces, a grade of 11 that has to be rejected. They were compiled and run once, so every output is real. And they don’t use arrays: those come in the next topic, and the report card will show you why you’ll miss them.
Table of Contents
Before you start
You should be clear about:
- How a method header is written: visibility,
static, return type, name and parameters with their type. - That a method with a return type has to end in
returnon every path, and that avoidone returns nothing. - That parameters are copies and the result has to be collected (
x = method(x)). - What overloading is: same name, different parameters.
If any of these sounds shaky, review the theory before going on.
The three programs were run once on a computer set to Spanish, so the Scanner expects decimals typed with a comma (8,5) and printf writes them with a comma too. That’s what you’ll see in the outputs. On an English-language computer you’d type 8.5 and see points; if you type the separator your computer doesn’t expect, nextDouble() throws InputMismatchException, as you saw in Java flow control. To always type with a point, create the Scanner with new Scanner(System.in).useLocale(Locale.US). You can also try them in the website’s Java playground: the “Open in the playground” button appears on every complete program.
Methods in Java practice — Program 1: calculator with methods
Laura wants a calculator to check her Algebra sums: it asks for two numbers, shows the sum, the difference and the product, and the division only if the second one isn’t 0. What makes it tricky is exactly my anecdote: the format of the four lines has to be the same, and division by 0 with double doesn’t give an error, it gives a nonsense result.
The idea
Separate calculating from showing. Each operation is a method that receives two double values and returns a double, without printing anything. Showing a result is another method, void, the only one that knows the format. And for warnings (like “you cannot divide by 0”) we use a second version of that method with a single parameter: overloading. main only reads, calls and decides whether to divide.
Before coding, think about what repeats. If the answer is “the printf of each line”, that printf has to live in a method. Something repeated once is a slip; something repeated four times is a method waiting for a name.
The code
import java.util.Scanner;
public class Calculator {
// ---------- The four operations ----------
// public: they are the "visible face" of the calculator; another class could use them.
// double + double → double: they receive two numbers and return one. They don't print anything.
public static double add(double a, double b) {
return a + b; // return sends the result back to the caller
}
public static double subtract(double a, double b) {
return a - b;
}
public static double multiply(double a, double b) {
return a * b;
}
public static double divide(double a, double b) {
return a / b; // with double, dividing by 0 does NOT give an error: it gives Infinity
}
// ---------- How it is shown ----------
// private: it's a detail of this class. void: it prints and returns nothing.
// The format (%.2f) lives HERE: if it changes, it changes in a single place.
private static void showResult(double a, String operator, double b, double result) {
System.out.printf("%.2f %s %.2f = %.2f%n", a, operator, b, result);
}
// Overloading: same name with ONE parameter only, for the warnings.
// Java picks the version by the number (and type) of arguments.
private static void showResult(String warning) {
System.out.println("Warning: " + warning);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("=== LAURA'S CALCULATOR ===");
System.out.print("First number: ");
double a = sc.nextDouble();
System.out.print("Second number: ");
double b = sc.nextDouble();
System.out.println();
// main stays short: it only calls methods with self-explanatory names
showResult(a, "+", b, add(a, b));
showResult(a, "-", b, subtract(a, b));
showResult(a, "*", b, multiply(a, b));
// The check for 0 is ours: the language doesn't do it with double
if (b == 0) {
showResult("you cannot divide by 0"); // 1-parameter version
System.out.println("(divide would have returned " + divide(a, b) + ")");
} else {
showResult(a, "/", b, divide(a, b)); // 4-parameter version
}
sc.close();
}
}
The two versions of showResult, up close:
private static void showResult(double a, String operator, double b, double result) {
System.out.printf("%.2f %s %.2f = %.2f%n", a, operator, b, result);
}
// Overloading: same name with ONE parameter only, for the warnings.
// Java picks the version by the number (and type) of arguments.
private static void showResult(String warning) {
System.out.println("Warning: " + warning);
}
Both have the same name and both are void, but one receives four parameters (double, String, double, double) and the other one (String). Java doesn’t get confused: when it sees showResult("you cannot divide by 0"), with a single argument only the second fits. And the %.2f format appears once in the whole program.
And main, where the change shows:
// main stays short: it only calls methods with self-explanatory names
showResult(a, "+", b, add(a, b));
showResult(a, "-", b, subtract(a, b));
showResult(a, "*", b, multiply(a, b));
// The check for 0 is ours: the language doesn't do it with double
if (b == 0) {
showResult("you cannot divide by 0"); // 1-parameter version
System.out.println("(divide would have returned " + divide(a, b) + ")");
} else {
showResult(a, "/", b, divide(a, b)); // 4-parameter version
}
Output
With 8,5 and 4:
=== LAURA'S CALCULATOR === First number: 8,5 Second number: 4 8,50 + 4,00 = 12,50 8,50 - 4,00 = 4,50 8,50 * 4,00 = 34,00 8,50 / 4,00 = 2,13
The maths: 8.5 + 4 = 12.5; 8.5 − 4 = 4.5; 8.5 × 4 = 34; 8.5 / 4 = 2.125, which %.2f rounds to 2.13. The stored number is still 2.125: the rounding only affects what is shown.
With 7 and 0:
=== LAURA'S CALCULATOR === First number: 7 Second number: 0 7,00 + 0,00 = 7,00 7,00 - 0,00 = 7,00 7,00 * 0,00 = 0,00 Warning: you cannot divide by 0 (divide would have returned Infinity)
Look at the last line, which is there on purpose: divide(7, 0) returns Infinity. With double, dividing by 0 doesn’t throw any exception; with int, it does (ArithmeticException: / by zero). That’s why the b == 0 check is ours and comes before calling divide. And notice that Infinity is written like that because it’s joined to a text with +, just like the decimal point in the theory.
The drawing shows the order in which each line of main runs:
And the run with 7 and 0, line by line, so you can see what gets called and what doesn’t:
Line of main | What gets called | Why |
|---|---|---|
showResult(a, "+", b, add(a, b)) | add(7.0, 0.0) → 7.0; then the 4-parameter version | add knows nothing about the 0: it adds and returns |
| The subtraction and the multiplication | Same: 7.0 and 0.0 | Subtracting 0 or multiplying by 0 is legal |
if (b == 0) | Nothing: it only compares | b is exactly 0.0 because Laura typed it: it’s true and the program goes in |
showResult("you cannot divide by 0") | The 1-parameter version | A single String argument: only that one fits |
System.out.println("(divide would have returned " + divide(a, b) + ")") | divide(7.0, 0.0) → Infinity | With double there’s no exception, and the + turns Infinity into text |
else { … } | Nothing | if and else exclude each other: the 4-parameter version with "/" never gets called |
Questions you might ask
Why is add public and showResult private? Because add is something another class might want to use (a grade calculator, for instance), and showResult is just how things are printed in here. If you change the format tomorrow, you don’t break anyone outside.
Why don’t the operations print their result? Because then they could only be used for printing. An add that returns the value can be used to show it, compare it or pass it to another method. In the line showResult(a, "+", b, add(a, b)) you’re using the value of add as an argument to another method, something an add that prints wouldn’t allow.
Is a one-line method (return a + b;) worth it? Here it is: it gives the operation a name, keeps main readable and, if the addition changed (rounding, validating), you’d only touch one place. Don’t turn every line into a method, but don’t be afraid of short methods.
What happens if I write showResult(a, b, "+", add(a, b)), with the order changed? It doesn’t compile: there’s no version with the parameters (double, double, String, double). Arguments are paired with parameters by position, not by name. javac will tell you it can’t find a method that fits.
Why is b == 0 checked in main and not inside divide? Because divide has to return a double and has no good answer for “can’t be done”. It could return an odd value, but then the caller would have to check it anyway. When you see exceptions, divide will be able to throw one; for now, the decision belongs to the caller.
Comparing with == 0 a double that comes from a calculation (0.1 + 0.2 - 0.3 == 0 is false). Here it works because b comes straight from the keyboard and a typed 0 is exactly 0, but if the divisor were the result of a calculation, compare with a margin: Math.abs(b) < 1e-9.
What would happen if Laura swapped the doubles for ints (nextInt for reading and int in the operations)?
Three things, and none of them good:
- With 8,5 it doesn’t even reach the maths:
nextIntcan’t read decimals and throwsInputMismatchException. - With 7 and 2,
dividereturns 3, not 3.5: between twoints, division is integer division. Java converts the 3 todoublewithout complaining and you get7,00 / 2,00 = 3,00: wrongly worked out and nicely formatted. - With 7 and 0 the warning comes out, but the next line blows up:
divide(7, 0)withintthrowsArithmeticException: / by zero. Theb == 0check saves you from the 4-parameter version, not from the call you put inside theifyourself.
Try it yourself
- Add a fifth operation, the power, with
Math.pow(a, b). How many lines do you have to touch for it to come out in the same format as the others? - Add a third version of
showResultthat receives only the result (double) and prints it as= 12,50. With which call does Java use each of the three?
Methods in Java practice — Program 2: password validator
In the flow control practice Laura signed up for the virtual campus with six if statements in a row. Now the campus asks her to change her password, which has to meet four requirements: 8 characters or more, at least one capital letter, at least one digit and no spaces. The program shows which requirements are met and the verdict. What makes it tricky: the capital and the digit have to be searched for character by character, and a password can contain spaces, so next() won’t do.
The idea
One boolean method per requirement, each with a single responsibility, and all private: they’re internal bricks. A single public method, isValid, combines them with &&. The ones that search for something use the “found it, I’m off” pattern: return true as soon as it shows up and return false if the loop ends without finding it. And a tiny method, yesNo, turns each boolean into “yes” or “no” for the list.
Before coding, think about how you’d answer each question with a yes or a no. If a check can be written as return expression; (for example, pw.length() >= minimum), it doesn’t need an if: the comparison already is a boolean.
The code
import java.util.Scanner;
public class PasswordValidator {
// ---------- Small pieces: each one checks ONE thing ----------
// private: they are internal bricks. boolean: the answer is yes or no.
private static boolean hasMinimumLength(String pw, int minimum) {
return pw.length() >= minimum; // the comparison already IS a boolean: no if needed
}
private static boolean hasUppercase(String pw) {
for (int i = 0; i < pw.length(); i++) {
if (Character.isUpperCase(pw.charAt(i))) {
return true; // ONE is enough: return leaves the method, no break or flag
}
}
return false; // the loop ended without finding any
}
private static boolean hasDigit(String pw) {
for (int i = 0; i < pw.length(); i++) {
if (Character.isDigit(pw.charAt(i))) {
return true;
}
}
return false;
}
private static boolean hasSpaces(String pw) {
return pw.contains(" "); // contains: true if the text appears inside
}
// ---------- The piece that puts them together (the only public one) ----------
public static boolean isValid(String pw) {
// && stops at the first false: if the capital is missing, it doesn't even check the digit or the spaces
return hasMinimumLength(pw, 8)
&& hasUppercase(pw)
&& hasDigit(pw)
&& !hasSpaces(pw); // ! because we want it NOT to have one
}
// Turns a boolean into text for the list. A one-line method also deserves a name.
private static String yesNo(boolean b) {
return b ? "yes" : "no";
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("=== VIRTUAL CAMPUS PASSWORD ===");
System.out.print("Password: ");
String pw = sc.nextLine(); // nextLine: a password can contain spaces
System.out.println();
System.out.println("--- Requirements ---");
System.out.println("8 characters or more: " + yesNo(hasMinimumLength(pw, 8)));
System.out.println("At least one capital: " + yesNo(hasUppercase(pw)));
System.out.println("At least one digit: " + yesNo(hasDigit(pw)));
System.out.println("No spaces: " + yesNo(!hasSpaces(pw)));
System.out.println();
System.out.println(isValid(pw) ? "Valid password" : "Invalid password");
sc.close();
}
}
hasUppercase, up close:
private static boolean hasUppercase(String pw) {
for (int i = 0; i < pw.length(); i++) {
if (Character.isUpperCase(pw.charAt(i))) {
return true; // ONE is enough: return leaves the method, no break or flag
}
}
return false; // the loop ended without finding any
}
The return true is inside the for and leaves the whole method, not just the loop: no break and no flag like in the loops exercises. The return false is outside: it’s only reached if the loop went through the whole password without finding a capital. With Laura2026fp the loop does a single round, because the L is at position 0.
Round (i) | pw.charAt(i) | Capital? | What happens |
|---|---|---|---|
| 0 | 'L' | Yes | return true: the method ends |
With hola mundo the loop does all 10 rounds, no letter is a capital and the return false at the end is reached.
Round by round with hola mundo, without skipping any:
Round (i) | pw.charAt(i) | Capital? | Why |
|---|---|---|---|
| 0 | 'h' | No | Lowercase: the if doesn’t go in and the for carries on |
| 1 | 'o' | No | Same |
| 2 | 'l' | No | Same |
| 3 | 'a' | No | Same |
| 4 | ' ' | No | A space isn’t a letter: isUpperCase gives false |
| 5 | 'm' | No | Lowercase |
| 6 | 'u' | No | Same |
| 7 | 'n' | No | Same |
| 8 | 'd' | No | Same |
| 9 | 'o' | No | Last round: the positions go from 0 to 9 |
| 10 | — | — | 10 < 10 is false: the for ends and the return false is reached |
To find a capital, one round is enough; to say there isn’t one, you have to look at them all.
And isValid:
public static boolean isValid(String pw) {
// && stops at the first false: if the capital is missing, it doesn't even check the digit or the spaces
return hasMinimumLength(pw, 8)
&& hasUppercase(pw)
&& hasDigit(pw)
&& !hasSpaces(pw); // ! because we want it NOT to have one
}
Output
With Laura2026fp:
=== VIRTUAL CAMPUS PASSWORD === Password: Laura2026fp --- Requirements --- 8 characters or more: yes At least one capital: yes At least one digit: yes No spaces: yes Valid password
With hola mundo (Spanish for “hello world”):
=== VIRTUAL CAMPUS PASSWORD === Password: hola mundo --- Requirements --- 8 characters or more: yes At least one capital: no At least one digit: no No spaces: no Invalid password
Checking by hand: Laura2026fp has 11 characters (11 ≥ 8), the L is a capital, it has four digits and no spaces: four “yes” and it’s valid. hola mundo has 10 characters, so the first requirement is met (10 ≥ 8, even though it has a space, which also counts as a character); the other three fail.
And the verdict on Laura2026fp, condition by condition. Here && can’t take a shortcut: it has to check all four.
| Condition | Result | Carries on? | Why |
|---|---|---|---|
hasMinimumLength(pw, 8) | true | Yes | 11 ≥ 8 |
hasUppercase(pw) | true | Yes | The L is at position 0: one round |
hasDigit(pw) | true | Yes | The first digit, the 2, is at position 5: six rounds |
!hasSpaces(pw) | true | — | hasSpaces gives false and the ! flips it |
Four trues in a row, so isValid returns true. If you add the four lines of the list, eight checks run with Laura2026fp.
How many methods are called for the verdict on hola mundo? Fewer than it seems:
Questions you might ask
Wouldn’t a single giant if be shorter? It would be shorter and far less readable. With methods, isValid reads almost like a sentence and each requirement can be tested separately. If tomorrow the campus demands a symbol, you add a method and a line with &&.
Why does hasMinimumLength receive the 8 as a parameter? So that the number isn’t hidden inside the method. If the minimum becomes 10, you change it in the call. And the same method works for another field with another minimum.
Why hasSpaces and not hasNoSpaces? Because negative names read badly with a ! in front: !hasNoSpaces(pw) makes you think twice. Better a positive name and the ! where it’s used.
Why nextLine() and not next()? Because next() stops at the first space: with hola mundo it would read only hola, and the program would say there are no spaces. nextLine() reads the whole line.
What’s the point of a one-line yesNo method? The same expression b ? "yes" : "no" was repeated four times in main. If tomorrow you want “met / not met”, you change one line.
Putting the return false inside the loop, in an else: if (Character.isUpperCase(c)) return true; else return false;. The method would only look at the first character and say that lAURA2026 has no capitals. “I didn’t find it” is only known once the loop has finished.
What would happen if you removed the ! from !hasSpaces(pw) in isValid?
It still compiles, because hasSpaces(pw) is a boolean too, but the last requirement ends up backwards:
Laura2026fp: the list still shows four “yes” (that line ofmainhas its own!), buthasSpacesgivesfalseand the verdict is “Invalid password”.Laura 2026fp, with a space in the middle: 12 characters, theL, the2… andhasSpacesgivestrue: “Valid password”.
The compiler only complains when the types don’t fit, not when the logic is backwards. That’s why it pays to test with a good password and a bad one.
Try it yourself
- Add a fifth requirement,
hasSymbol, that looks for a character that is neither a letter nor a digit (!Character.isLetterOrDigit(c)), and add it toisValid. - Change the order of the conditions in
isValidso that the first one is!hasSpaces(pw). Withhola mundo, how many methods are called now for the verdict?
Methods in Java practice — Program 3: semester report card
Laura wants her programming report card: the grade for FP1, FP2 and IC2, checking that each one is between 0 and 10, the classification of each subject and the average with its classification. What makes it tricky: a mistyped grade (an 11) has to be asked for again without the program breaking, and that has to happen three times without copying the validation block three times.
The idea
Reading a valid grade is a complete task: ask, check, warn and repeat. It goes into a method, readGrade, that returns the good grade; the do-while inside doesn’t let it out until it is. classify receives a number and returns a text. average receives three grades. printLine draws a row using classify. And main coordinates: three readings, three lines, the average.
Before coding, think about what each method needs to work and what it hands back. readGrade needs the Scanner and the name of the subject; it hands back a double. If a method needs the Scanner, it’s passed as a parameter: another one isn’t created inside.
The code
import java.util.Scanner;
public class ReportCard {
// Receives the Scanner already created (it doesn't create another) and the subject name.
// Returns the grade ONLY when it is valid: the do-while doesn't let it out before.
private static double readGrade(Scanner sc, String subject) {
double grade;
do {
System.out.print("Grade for " + subject + ": ");
grade = sc.nextDouble();
if (grade < 0 || grade > 10) {
System.out.println(" The grade goes from 0 to 10. Again.");
}
} while (grade < 0 || grade > 10);
return grade;
}
// Receives a number and returns a text. Several returns: one per path.
private static String classify(double grade) {
if (grade >= 9) {
return "Distinction";
} else if (grade >= 7) {
return "Merit";
} else if (grade >= 5) {
return "Pass";
}
return "Fail";
}
// Three parameters and not an array: arrays come in the next topic
private static double average(double a, double b, double c) {
return (a + b + c) / 3;
}
// void: draws one row of the report card. It uses classify for the last column.
private static void printLine(String subject, double grade) {
// %-6s: text on the left in 6 slots; %5.2f: number in 5 slots with 2 decimals
System.out.printf("%-6s %5.2f %s%n", subject, grade, classify(grade));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // ONE Scanner for the whole program
System.out.println("=== LAURA'S REPORT CARD ===");
double fp1 = readGrade(sc, "FP1");
double fp2 = readGrade(sc, "FP2");
double ic2 = readGrade(sc, "IC2");
System.out.println();
System.out.println("--- Report ---");
printLine("FP1", fp1);
printLine("FP2", fp2);
printLine("IC2", ic2);
System.out.println("---------------");
double m = average(fp1, fp2, ic2);
System.out.printf("Average: %.2f (%s)%n", m, classify(m)); // classify also works for the average
sc.close(); // closed where it was created, at the end
}
}
readGrade, up close:
private static double readGrade(Scanner sc, String subject) {
double grade;
do {
System.out.print("Grade for " + subject + ": ");
grade = sc.nextDouble();
if (grade < 0 || grade > 10) {
System.out.println(" The grade goes from 0 to 10. Again.");
}
} while (grade < 0 || grade > 10);
return grade;
}
Output
With 7,5 for FP1, an 11 and then 9,5 for FP2, and 6 for IC2:
=== LAURA'S REPORT CARD === Grade for FP1: 7,5 Grade for FP2: 11 The grade goes from 0 to 10. Again. Grade for FP2: 9,5 Grade for IC2: 6 --- Report --- FP1 7,50 Merit FP2 9,50 Distinction IC2 6,00 Pass --------------- Average: 7,67 (Merit)
Round by round for the second call, readGrade(sc, "FP2"):
| Round | Typed | grade < 0 || grade > 10 | What happens |
|---|---|---|---|
| 1 | 11 | true | Warns; the do-while condition is true and it repeats |
| 2 | 9,5 | false | No warning; it leaves the loop and return 9.5 |
The maths: 7.5 is between 7 and 9, “Merit”; 9.5 ≥ 9, “Distinction”; 6 between 5 and 7, “Pass”. The average, (7.5 + 9.5 + 6) / 3 = 23 / 3 = 7.666…, which %.2f shows as 7,67, and since it’s between 7 and 9, “Merit”. The same classify works for a single grade and for the average: it only asks for a double, it doesn’t care where it comes from. (The classifications are an English rendering of the Spanish scale: Suspenso, Aprobado, Notable, Sobresaliente.)
What each method returns in this run, in the order main calls them:
| Call | Returns | Why |
|---|---|---|
readGrade(sc, "FP1") | 7.5 | It’s between 0 and 10: a single round of the do-while |
readGrade(sc, "FP2") | 9.5 | The 11 doesn’t get out of the loop (table above); the 9,5 does |
readGrade(sc, "IC2") | 6.0 | In range first time |
printLine("FP1", fp1) | Nothing (void) | It prints the row; inside, it calls classify(7.5), which returns "Merit" to it |
printLine("FP2", fp2) | Nothing | classify(9.5) returns "Distinction" to it |
printLine("IC2", ic2) | Nothing | classify(6.0) returns "Pass" to it |
average(fp1, fp2, ic2) | 7.666… | 23 / 3, stored in m without rounding |
classify(m) | "Merit" | It receives 7.666…, not the 7,67 you see: the rounding belongs only to the printf |
Questions you might ask
Why does average have three parameters instead of receiving “all the grades”? Because receiving a variable number of grades needs an array, and arrays come in the next topic. With three parameters it works, but notice the trap: if Laura adds a fourth subject, you have to change the header of average, all its calls, and add another variable and another line in main. That awkwardness is exactly what arrays solve.
Why is the Scanner passed as a parameter? Because if every call to readGrade created its own new Scanner(System.in), you’d have three readers of the same keyboard, and if one of them closed it, it would also close System.in for everyone. Just one, created in main and closed at the end.
Why do-while and not while? Because the grade has to be asked for at least once before it can be checked. With while, you’d have to read once before the loop and again inside.
Why %-6s in printLine? To line up the columns: the subject name takes 6 slots aligned left and the grade 5 slots with two decimals. Since the format lives in a single method, the three rows come out aligned with no effort.
Closing the Scanner inside readGrade “to tidy up”. The first call works, but closing the Scanner closes System.in, and the second call fails with NoSuchElementException even if you create another Scanner. It’s closed where it was created, at the end of main.
If methods are named after what they do (readGrade, classify, average, printLine), main reads like a recipe. When a piece of code needs a comment to explain what it does, that comment is usually the name of a method.
What would happen if you put if (grade >= 5) first in classify?
It compiles and runs without a single error, and the whole report card comes out wrong: FP1, FP2, IC2 and the average all come out as “Pass”. With 9.5, the first question is “is 9.5 ≥ 5?”, the answer is yes and the return leaves the method before it ever asks about the 9.
“Merit” and “Distinction” can never be reached any more. With several returns, the order of the questions is part of the logic: from the most demanding to the least.
Try it yourself
- Add a fourth subject (IC1) and count how many places you had to touch. Keep that number for when you see arrays.
- Make
readGradeaccept only grades with at most one decimal (rejecting 7,25). Hint:grade * 10has to be a whole number,grade * 10 == Math.floor(grade * 10).
Common mistakes in this practice
- Copying the
printfon every line instead of putting it in a method: the day the format changes, you’ll forget one (my anecdote). - Making the operations print instead of returning: they become useless for anything other than printing.
- Typing the decimal separator your computer doesn’t expect:
nextDouble()throwsInputMismatchException. - The
return falseinside the loop of a search: it only looks at the first character. - Creating or closing the
Scannerinside a method:System.ingets closed for the whole program. - Calling an overload with the arguments in another order: they’re paired by position, and if no version fits, it doesn’t compile.
Watch it step by step in Python Tutor
Python Tutor can’t run a Scanner, so here’s the core of the report card with fixed grades. Choose Java, paste the program and step through with Next:
public class Demo {
public static double average(double a, double b, double c) {
double sum = a + b + c;
return sum / 3;
}
public static String classify(double grade) {
if (grade >= 7) {
return "Merit";
}
return "Pass";
}
public static void main(String[] args) {
double fp1 = 7.5;
double m = average(fp1, 9.5, 6.0);
String texto = classify(m);
System.out.println(texto);
}
}
Output:
Merit
What to look at:
- When calling
average(fp1, 9.5, 6.0)a frame opens witha = 7.5,b = 9.5andc = 6.0. The 7.5 inais a copy of the one infp1: two different boxes. - Inside
average,sumappears in its frame with 23.0. It’s a local variable:maincan’t see it. - When
returnis reached, theaverageframe disappears witha,b,candsum, andm = 7.666…appears inmain. classify(m)opens its own frame, empty again except forgrade, and returns"Merit", which lands intext.
Summary
- A method is a task with a name: if a piece of code repeats or needs a comment to be understood, it’s a candidate for a method.
- Separate calculating from showing: the methods that calculate return the value and a single one takes care of the format.
publicfor what others will use;privatefor the internal bricks.returninside a loop leaves the whole method: it’s the “found it, I’m off” pattern, with nobreakor flag.- Overloading lets you use the same name with different parameters, and Java picks the version by the number and type of the arguments.
- The
Scanneris created once inmain, passed as a parameter and closed at the end.
Checklist: have you practised it?
- Have you run the three programs and checked the outputs?
- Can you explain why
divide(7, 0)returnsInfinityand doesn’t throw an exception? - Could you say which methods are called, and in what order, in
showResult(a, "+", b, add(a, b))? - Do you know why the
return falseinhasUppercasegoes outside the loop? - Do you know how many rounds the
do-whileinreadGradedoes with an 11 and a 9,5? - Have you tried the “Try it yourself” tasks without looking at the theory?
If you answered yes to almost everything, you’re ready for the methods in Java exercises, where I no longer give you the code: a converter, a week’s statistics without storing the data, and the guessing game of 31 finally turned into methods. See you there!
Next step: exercisesMethods in Java — exercises with a converter, a week of temperatures and the guessing game of 31 (and the return the compiler couldn’t see)Did this article help you? Here is how you can support SergioLearns →



