Java p3
Java p3
1 Introduction
Java command-line argument: is an argument i.e. passed at the time of running the Java
program. In Java, the command line arguments passed from the console can be received
in the Java program and they can be used as input. The users can pass the arguments
during the execution bypassing the command-line arguments inside the main() method.
We need to pass the arguments as space-separated values. We can pass both strings and
primitive data types(int, double, float, char, etc) as command-line arguments. These
arguments convert into a string array and are provided to the main() function as a string
array argument.
When command-line arguments are supplied to JVM, JVM wraps these and supplies
them to args[]. It can be confirmed that they are wrapped up in an args array by checking
the length of args using args.length.Internally, JVM wraps up these command-line
arguments into the args[ ] array that we pass into the main() function. We can check these
arguments using args.length method.
JVM stores the first command-line argument at args[0], the second at args[1], the third
at args[2], and so on.
}
//Output
In Java, the parse() method is used to convert a string into an object of a specific class.
There are many Java classes that have the parse() method. Usually, the parse() method
receives some string as input, “extracts” the necessary information from it and converts
it into an object of the calling class. For example, it receives a string and returns the date
that was “hiding” in this string.
1.2 Java program to find sum of two numbers by passing arguments from command
line.
public class Sum {
public static void main(String args[]) {
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int sum = x + y;
System.out.println("The sum of”+ x + “ and”+ y + “ is: " +sum);
}
}
//Output
Conclusion:-
Java command-line arguments serve as a crucial means of interacting with Java programs
from the command line interface. These arguments provide a way to pass external inputs,
configuration settings, or parameters to a Java application during its execution. By
allowing developers to customize program behaviour without modifying the source code,
Java command-line arguments enhance the versatility and reusability of applications.