Java
Beginner
1 min read
Defining Methods, Return Types, and Parameters
Example
public class MethodBasics {
// Static utility method: belongs to the class
public static int add(int a, int b) {
return a + b;
}
// Static method returning a boolean
public static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
// Instance method using instance state
private String name;
public MethodBasics(String name) {
this.name = name;
}
public String greet(String greeting) {
return greeting + ", " + this.name + "!";
}
// Pass-by-value demo
static void tryToChange(int x, int[] arr) {
x = 999; // changes local copy, not caller's variable
arr[0] = 999; // mutates the actual array object
}
public static void main(String[] args) {
// Static method calls
System.out.println("3 + 4 = " + add(3, 4));
System.out.print("Primes up to 20: ");
for (int i = 2; i <= 20; i++) {
if (isPrime(i)) System.out.print(i + " ");
}
System.out.println();
// Instance method call
MethodBasics obj = new MethodBasics("Alice");
System.out.println(obj.greet("Good morning"));
// Pass-by-value demo
int num = 10;
int[] data = {1, 2, 3};
tryToChange(num, data);
System.out.println("num after tryToChange: " + num); // still 10
System.out.println("data[0] after tryToChange: " + data[0]); // 999
}
}