Introduce Java Class Methods and give examples
In Java, a class method is a method that belongs to the class rather than to any specific instance of the class. Class methods are defined using the static
keyword. This means that you can call these methods without creating an instance of the class. Class methods are often used for utility or helper functions that do not require any instance-specific data.
static
keyword.Here’s a simple example to illustrate class methods in Java:
public class MathUtils {
// A static method to calculate the square of a number
public static int square(int number) {
return number * number;
}
// A static method to calculate the factorial of a number
public static long factorial(int number) {
long result = 1;
for (int i = 1; i <= number; i++) {
result *= i;
}
return result;
}
// A static method to find the maximum of two numbers
public static int max(int a, int b) {
return (a > b) ? a : b;
}
}
public class Main {
public static void main(String[] args) {
// Calling class methods without creating an instance of MathUtils
int num = 5;
System.out.println("Square of " + num + " is: " + MathUtils.square(num));
System.out.println("Factorial of " + num + " is: " + MathUtils.factorial(num));
System.out.println("Maximum of 10 and 20 is: " + MathUtils.max(10, 20));
}
}
square
, factorial
, and max
.main
method, we call the static methods of the MathUtils
class directly using the class name, without creating an instance of MathUtils
.Class methods in Java are a powerful feature that allows you to define methods that can be called without needing to instantiate a class. They are particularly useful for utility functions and operations that do not depend on instance-specific data.