Why can not pass "int" as argument in main method [closed]
In java when i pass int
as argument in main method i got error
"Error: Main method not found in class dynamicInput, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application"
Here down is my code:
public class dynamicInput {
public static void main(int a, int b) {
System.out.printf("%d %d", a, b);
}
}
The error tell evething. either you forget to declare main method
or somthing missing in main method declaration
. In Java Programming The main()
method is a special method that serves as the externally exposed entrance point by which a Java program can be run. To compile a Java program, you doesn't really need a main()
method in your program. But, while execution JVM searches for the main()
method and starts executing from it.
You declare int argument in main method but it shoud be String[] args
. now one question arise in your mind Why String args[]?
because When you run a Java program from a command line, you are allowed to pass data into that program as comnand line arguments
.Your Java program will run from a main()
method, and the arguments you typed on the command line will appear to the Java program as Strings in that array.
Here down is right syntex:
public static void main(String[] args) {
// Some code inside main function....
}
And your code should be:
public class Main {
static void printSomeNumber()
{
int a = 10;
int b = 20;
System.out.printf("%d %d", a, b);
}
public static void main(String args[]) {
printSomeNumber();
}
}
This is due to you can't use different type of variable in main method as java compiler will search for main method with String[] as parameter. you should only use following method as it's an entry point for your console application
public static void main(String[] args) {
....
....
}
you can get your value provided into console from array of args
so you can do like following
public class DynamicInput {
public static void main(String args[]) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.printf("%d %d", a, b);
}
}
you can read about main method here Java main method