How can I call the main Method with Arguments? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How can I call the main Method with Arguments?

There is the possibility of use the main Method with a String-Array, but how can I call it that way?

26th Apr 2018, 11:37 AM
Elias
Elias - avatar
7 Answers
+ 1
Say you have a class called "Car" with a constructor, and that constructor takes 2 parameters, "color" and "year", in the main method you instantiate an object of type Car like this: "Car myCar = new Car(arg[0],arg[1]);", with this you are saying "take the first and second index from main", then you save it and you get the "Car.java", from the console you first compile it "javac Car.java" and it would generate the "Car.class" file, and then you would call your class from the same console "java Car Blue 2018", and that's how you can call a main method with arguments. From Netbeans or any other java IDE just look in google how to provide the arguments "usually args" and the result should be the same. Hope this helps Elias.
26th Apr 2018, 12:25 PM
Roberto Guisarre
Roberto Guisarre - avatar
0
So I can use any arguments of the main method accessed by its array-index and then just have to call the program-file with as many arguments as I have used in my code, right?
26th Apr 2018, 1:11 PM
Elias
Elias - avatar
0
That's correct, the main method takes an array of type string arguments, you can set as many string arguments as you need.
26th Apr 2018, 1:16 PM
Roberto Guisarre
Roberto Guisarre - avatar
0
Thank you for the answers. How can I use it with the Code Playground in this App?
26th Apr 2018, 1:19 PM
Elias
Elias - avatar
0
When I want to take user input here are use Scanner, I honestly don't know the answer cause the code here get compile by the compiler on the server, which runs the code right after.
26th Apr 2018, 1:22 PM
Roberto Guisarre
Roberto Guisarre - avatar
0
Thanks
26th Apr 2018, 1:23 PM
Elias
Elias - avatar
0
when you execute you problems you use main to which you didn't create that means you are calling main method which accepts Arrey of String as Argument.This class is static
5th May 2018, 2:50 PM
Joash N
Joash N - avatar