What is the use of args in Java?
The interesting use of args in Java.
args[ ] is an array of string objects, yep you already read that on top !
now you can add some args in your project by going to Run > Run configurations > Arguments >Insert your values.
As you see in the Picture i puted 3 Arguments one String and the other two as and integer, i can put more of course.
But i want to show you how will i get thoses args in my code and how can i turn a string args to an integer ?
As an answer to getting the args to my code it is simple by doing like this : args[0] instead of 0 mention the index you want.
And to turn a string args to an integer use this : Integer.parseInt(args[0]) also specify the index you want.
public static void main (String[] args) {System.out.println(" The First argument "+args[0]); // AhedSystem.out.println(" The second argument "+args[1]); // 22System.out.println(" the first letter of the first argument "+args[0].charAt(0)); //ASystem.out.println(" the second letter of the first argument"+args[0].charAt(1)); //h// converting from string to integer
int a = Integer.parseInt(args[1]); // a = 22int b = Integer.parseInt(args[2]); // b = 23int somme=a+b; // Somme = 22+23// for example this will be the result of a+bSystem.out.println("Somme : "+somme); // Somme : 45// converting from string to Floatfloat f =Float.parseFloat(args[2]); // f = 23.0System.out.println("Float : "+f); // Float : 23.0// This will also show you the argument caracter by caracter.
// PS : we choose the first argument args[0] which is Ahedfor(int i=0; i<args[0].length(); i++){ // returns the character at the specified index in a string. System.out.println(args[0].charAt(i)); } }}
Instead of writing System.out.println(“ ”); each time try to write only sysout then press ctrl + espace same time and you will have the same result.
Hope you like it ✌🏻