Java, lesson 6
As programs grow, one long main gets hard to read. A method gives a piece of work a name, so
you can write it once and call it wherever you need it. In Java, functions are always methods that
belong to a class. For now you will write static methods inside Main, next to main.
A method declaration has:
static (it belongs to the class, so you can call it without creating an
object; you will meet objects in a later lesson),int here, or void if it returns nothing),camelCase, usually a verb: , , ,2 exercises to try what you just read.
squareprintBannerisValidreturn hands a value back to the caller and ends the method at once. A method with a non-void
return type must return a value on every path, or it will not compile:
A void method can use a bare return; to leave early.
Methods that answer a yes/no question usually return boolean and are named like a question:
isEven(n), hasDiscount(total). They read beautifully inside if statements.
Java passes arguments by value: the method gets a copy of each value. Changing a parameter inside the method does not change the caller's variable:
(With objects the copied value is a reference to the object, so the method can change the object's contents. More on that when you meet classes.)
A variable exists only inside the block { } where it is declared, from the declaration to the
closing brace. Variables declared in main are invisible in other methods, and vice versa. That
is a feature: each method is a small, self-contained unit that talks to the rest of the program
only through its parameters and its return value.
Two methods may share a name if their parameter lists differ:
Java picks the right one from the arguments. The return type alone is not enough to tell overloads apart.
Write a method static boolean isPrime(int n) that returns true when n is prime (a whole
number greater than 1 whose only divisors are 1 and itself). Then read one number N and print
every prime from 2 to N on one line, separated by single spaces. If there are none, print
none.
Hint: you only need to test divisors d while d * d <= n.
Sample input:
Sample output:
Each input line describes a shape: circle r, rectangle w h or triangle b h (base and
height). For every line, print the area with two decimal places. Write one method per shape:
circleArea, rectangleArea and triangleArea, each returning a double. Use Math.PI.
Sample input:
Sample output:
public class Main {
static int square(int x) {
return x * x;
}
public static void main(String[] args) {
System.out.println(square(4)); // 16
System.out.println(square(3) + square(4)); // 25
}
}static String sign(int n) {
if (n > 0) return "positive";
if (n < 0) return "negative";
return "zero";
}static void tryToChange(int n) {
n = 99; // only the copy changes
}static double area(double radius) { return Math.PI * radius * radius; }
static double area(double width, double height) { return width * height; }202 3 5 7 11 13 17 19circle 2
rectangle 3 4.5
triangle 6 312.57
13.50
9.00