I am new to Java and I am asking myself why would I use void keyword such as in:
public static void main(String[] args) {
System.out.println("Hello, World!");
}
If the void keyword states that no data is returned…
That sorted, why would I want to chose not to return data, or am I missing something? As far as I read about it in forums, void means that there is no value returned in general…
If there is any wrong grammar, I apologize, still learning that too, I am not a native English-speaker.
>Solution :
No need to apologize, your question is perfectly clear! In Java, the void keyword is used as a return type for methods to indicate that the method does not return any value. It doesn’t mean that the method doesn’t do anything; it just means that the method doesn’t produce a result that can be used elsewhere in your program.
In the case of the main method you provided:
public static void main(String[] args) {
System.out.println("Hello, World!");
}
The void return type makes sense because the main method is the entry point of a Java program. It’s meant to start the execution of your program, and it doesn’t need to return any value.
In other methods, you might use a non-void return type (like int, double, String, etc.) when the method needs to provide a result that can be used by other parts of your program.
Here’s an example:
public class Example {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(3, 5);
System.out.println("The sum is: " + result);
}
}
In this example, the add method returns an int, allowing you to use the result of the addition in the main method.