When I launch the program via cmd, I want to immediately send the necessary arguments to it for further work with them. That is, I write something like C:> java Main arg1 arg2

I need to pass several integers as arguments to this program, but they are accepted as objects of type String. How to pass arguments so that they are perceived as numbers? Is it possible to convert the string "5" to the number 5 in Java? On the Internet, I found a way

a = Integer.parseInt(args[0]); 

But it works only if you take the args in the right cut. If, for example, try something like

 a = Integer.parseInt("5"); 

That leaves an error. I need to understand this behavior and explain how to transfer integers to a program when it starts via cmd

Also, I would like to know, on the contrary - how can I convert (integer) number (5) into a string ("5") (If possible)

  • five
    What error is coming out? There should be no error whatsoever. - Sergey Gornostaev
  • jvexp.java:9: error: incompatible types: char cannot be converted to String a = Integer.parseInt ('5'); ^ Note: Some messages have been simplified; recompile with -Xdiags: verbose to get full output 1 error - fedotsoldier
  • You are trying to assign a number to a string variable. Change to int a = Integer.parseInt("5") - Sergey Gornostaev
  • No no. Out of habit, I wrote the string "5" in single quotes from Python. Well, excuse me - the day before yesterday I began to learn the language, while a little confused. You do not tell me how to make a line back from the number - fedotsoldier
  • one
    String.valueOf(5) - Sergey Gornostaev

2 answers 2

If desired, the args array can be taken in the desired slice and appropriately assigned to a variable of numeric type:

 int a = Integer.parseInt(args[0]); 

In the same way, the string can be turned into a number:

 int a = Integer.parseInt("5"); 

And vice versa - the number in the string:

 String b = String.valueOf(5); // Спасибо пользователю @Sergey_Gornostaev 

    The main() method takes an array of strings as arguments. Even if Java allowed type changes, the above method would still work with string arguments.

    • Well, what if I need to transfer whole numbers to the program? - fedotsoldier
    • see above about parseInt() - Oleksiy Mororets