Before the questions, make sure you can: label every part of a method heading; explain the
difference between a parameter and an argument; say exactly what Java passes to a method (and why
a method cannot swap two int variables of its caller); decide whether a method should be
static; state the rule that makes two methods valid overloads; use Math,
Character and the wrapper classes; convert between String and numbers; produce
formatted output with printf; and generate random numbers in a given range.
Why methods
A method is a named, reusable block of code. Methods eliminate duplication, give a name to an
idea, and let a large problem be solved one small piece at a time (top-down design, Chapter 2).
A helper method is a method that exists only to serve other methods of the same class;
it is usually private.
Anatomy of a method
public static double average(int a, int b) { // modifiers, return type, name, parameter list
double result = (a + b) / 2.0; // local variable
return result; // return statement
}
// called as: double avg = average(7, 10); <- 7 and 10 are the ARGUMENTS
- The return type says what kind of value comes back;
voidmeans nothing does. Avoidmethod may still containreturn;to exit early. - A non-
voidmethod must return a value on every path, or it does not compile. - Parameters are the variables in the heading; arguments are the values supplied at the call. They must match in number, order and (compatible) type.
- Local variables, including parameters, exist only while the method runs.
Argument passing: Java passes by value, always
A copy of the argument's value is given to the method.
- For a primitive, the copy is the number itself. Changing the parameter inside
the method has no effect on the caller's variable. A method cannot swap two
ints of its caller. - For a reference, the copy is the address. The method can therefore modify the object (change an array element, call a mutator), and the caller sees the change — but if the method assigns a new object to the parameter, the caller's variable still refers to the old one.
static (class) methods
A static method belongs to the class, not to any object, and is called through the class
name: Math.sqrt(2), Integer.parseInt("42"). Use static when the method needs no
object state — a pure calculation on its arguments. A static method may access other
static members directly, but it cannot use this or touch instance variables without an
object. This is why calling an instance method from main without creating an object is a
compile-time error.
A utility class is a class whose members are all static (like Math), plus
public static final named constants:
public class Geometry {
public static final double PI = 3.14159;
public static double circleArea(double r) { return PI * r * r; }
}
// used as: Geometry.circleArea(2.0)
Overloading
Two methods in the same class may share a name provided their signatures differ — the signature is the name plus the types, number and order of the parameters. The return type is not part of the signature, so changing only the return type is not overloading; it is a compile-time error.
void show(int a) // OK
void show(double a) // OK: different parameter type
void show(int a, double b) // OK: different number of parameters
void show(double a, int b) // OK: different order
int show(int a) // ERROR: same signature as the first
When several overloads could apply, the compiler chooses the most specific match after
promotion: byte and short widen to int, int widens to long, then
float, then double. So show((byte)2 + 1) calls show(int) — the arithmetic
has already produced an int.
The Math class
Math.abs(x) |
absolute value |
|---|---|
Math.pow(b, e) |
b^e, always a double |
Math.sqrt(x) |
square root, a double |
Math.max(a,b), Math.min(a,b) |
larger, smaller |
Math.round(x) |
nearest whole value (long for a double argument) |
Math.ceil(x), Math.floor(x) |
up, down — both return a double |
Math.random() |
a double in [0.0, 1.0) |
Math.PI, Math.E |
constants |
Random integer from lo to hi inclusive:
(int)(Math.random() * (hi - lo + 1)) + lo. A die roll is
(int)(Math.random() * 6) + 1.
Wrapper classes and Character
Each primitive has a wrapper class: Integer, Double, Character, Boolean,
Long, Short, Byte, Float. They provide constants (Integer.MAX_VALUE),
conversions (Integer.parseInt("42"), Double.parseDouble("3.5"),
String.valueOf(42)) and let primitives be stored in collections. Autoboxing converts
automatically between int and Integer.
Useful Character methods: isDigit, isLetter, isLetterOrDigit,
isUpperCase, isLowerCase, isWhitespace, toUpperCase, toLowerCase.
Formatted output
System.out.printf("%-10s %5d %8.2f%n", name, qty, price);
%d |
integer | %8.2f |
floating point, width 8, 2 decimals |
|---|---|---|---|
%f |
floating point (6 decimals by default) | %-10s |
string, width 10, left-aligned |
%s |
string | %n |
platform-independent newline |
%c |
character | %% |
a literal percent sign |
- Java passes copies: primitives cannot be changed by a method; objects can be mutated but not replaced.
- The signature is name + parameter list; the return type is not part of it.
- A non-
voidmethod must return on every path. staticmethods are called on the class and cannot use instance variables directly.Math.random()never returns 1.0.Math.ceilandMath.floorreturndouble;Math.roundreturnslong(for adouble).
- Declaring a method inside another method.
- Forgetting that
Math.powreturns adouble:int n = Math.pow(2,3);does not compile. - Trying to overload by return type alone.
- Calling an instance method from
mainwithout an object. - Writing
printf("%d", 3.5)— the conversion and the argument type must agree.
Ready? Close the notes and practise.
40 questions. Predict the output before you check — that is the skill the exam measures.