Reading — step 1 of 5
Learn
Methods
In Java, functions are called methods, and every method belongs to a class. A method names a computation so you can run it many times, test it in isolation, and read code as intent ("square this") instead of mechanics.
public class Main {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
System.out.println(square(5)); // 25
}
}
Anatomy of a signature
static int square(int n) reads as a contract:
(int n)— takes oneintparameter, locally namednint(before the name) — RETURNS an int; the compiler holds you to itsquare— the name, camelCase by conventionstatic— belongs to the class itself, not to an object instance
return does two things at once: it ends the method immediately and hands the value back to the caller. The contract is enforced hard — every possible path through an int method must return an int, and returning a String from it is a compile error.
Why static (for now)?
main is static because the JVM calls it before any object exists. And a static method can only directly call other static methods of its class — so helpers you call from main must be static too. Drop the keyword and you meet the most famous beginner error in Java:
int square(int n) { return n * n; } // not static
public static void main(String[] args) {
System.out.println(square(5));
// error: non-static method square(int) cannot be referenced from a static context
}
When we reach classes and objects, non-static (instance) methods take center stage. Until then: helpers called from main are static.
Overloading
Java allows several methods with the same name, as long as their parameter lists differ:
static int max(int a, int b) { return a > b ? a : b; } // ?: means if a>b then a else b
static double max(double a, double b) { return a > b ? a : b; }
The compiler picks the overload at COMPILE time from the argument types. max(3, 9) calls the int version; max(3.0, 9.5) the double one.
Parameters are copies
Java passes arguments by value: the parameter is a copy. Reassigning it inside the method never changes the caller's variable:
static void bump(int x) { x = x + 1; }
int a = 5;
bump(a);
System.out.println(a); // still 5
To get a result OUT of a method, return it — that's the whole point of the return type.
Your exercise
The starter gives you a stubbed method:
static int square(int n) {
// Return n * n.
return 0;
}
Replace return 0; with return n * n;. That's the entire change — main already reads the input and prints square(n).
The mistake the grader will catch: leaving return 0; in place. The test with input 0 still passes (0 squared IS 0), which makes the stub feel deceptively fine — but 4 must print 16 and the hidden -5 must print 25, and the stub prints 0 for both. Negatives need no special handling: (-5) * (-5) is 25 — the multiplication does the sign math for you.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…