Java Tutorial
Java Methods
A method has a return type, a name, and a body. Call it to reuse work without copy-paste.
A method returns a value
Put helpers in the same class as main. Mark them static so main can call them without an object. The return type comes first.
Example
public class Main {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(8, 11));
}
}void returns nothing
A method that only prints can return void. It still runs when you call it. There is no value to store.
Example
public class Main {
static void greet(String name) {
System.out.println("Hi, " + name);
}
public static void main(String[] args) {
greet("Ada");
}
}Call, do not copy
The point of a method is reuse. Write the logic once, then call it with different arguments. When you spot the same few lines twice, that is the signal to pull them into a method.
Example
public class Main {
static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
System.out.println(isEven(4)); // true
System.out.println(isEven(7)); // false
}
}A value handed back with return must be used or stored — isEven(4); on its own throws the answer away. And the returned type must match the declared return type, or the code will not compile.
Try It Yourself
Exercise: Write a static method max3(int a, int b, int c) that returns the largest of three numbers, and print max3(4, 9, 2).
Show solution
static int max3(int a, int b, int c) {
return Math.max(a, Math.max(b, c));
}
// in main:
System.out.println(max3(4, 9, 2)); // 9Reusing Math.max twice is shorter and clearer than a chain of if statements.
Key Takeaways
- A method is
returnType name(parameters) { ... }; mark helpersstaticsomaincan call them. returnhands a value back;voidmeans there is nothing to return.- Parameters let one method do a whole family of jobs — change the arguments, not the body.
- A returned value must be used or stored, and must match the declared return type.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.
Physics
Gravitational PE
Potential energy near Earth is mgh. A method names that formula so main stays a list of values.
E = mgh
Example
public class Main {
static double pe(double m, double h) {
return m * 9.81 * h;
}
public static void main(String[] args) {
System.out.println(pe(0.50, 2.0) + " J");
}
}