A method with a void
return type does not return any value. It just performs an action.
public class VoidMethodExample {
// Method to print a message
public void printMessage() {
System.out.println("Hello, World!");
}
public static void main(String[] args) {
VoidMethodExample example = new VoidMethodExample();
example.printMessage(); // Call the void method
}
}
Hello, World!
Methods that return a value must specify the return type (e.g., int
, double
, String
, etc.) and use the return
statement to return a value.
xxxxxxxxxx
public class ReturnMethodExample {
// Method to return the square of a number
public int square(int x) {
return x * x;
}
public static void main(String[] args) {
ReturnMethodExample example = new ReturnMethodExample();
int result = example.square(5); // Call the method and store the result
System.out.println("Square of 5: " + result);
}
}
Square of 5: 25