Methods in Java
Methods are blocks of code that perform a specific task. This tutorial will teach you about declaring, calling, and overloading methods.
Declaring and Calling Methods
To declare a method, use the following syntax:
public class Main {
public static void main(String[] args) {
sayHello();
}
public static void sayHello() {
System.out.println("Hello, World!");
}
}
Method Parameters and Return Values
Methods can take parameters and return a value:
public class Main {
public static void main(String[] args) {
int result = addNumbers(5, 10);
System.out.println("Sum: " + result);
}
public static int addNumbers(int a, int b) {
return a + b;
}
}
Method Overloading
Method overloading allows you to define multiple methods with the same name but different parameters:
public class Main {
public static void main(String[] args) {
System.out.println(addNumbers(5, 10));
System.out.println(addNumbers(5.5, 10.5));
}
public static int addNumbers(int a, int b) {
return a + b;
}
public static double addNumbers(double a, double b) {
return a + b;
}
}
Continue exploring our beginner tutorials to learn more about Java programming.