Command Line Arguments | Core Java Tutorial | Minigranth

Command Line Arguments : Introduction

  • Arguments that are passed to the program when we run it are called command line arguments.
  • Now this is the time to use the String[] args parameters in main().
  • Command line arguments are given from command line following the program name at the time of running it.
  • Command line arguments are stored as String array that is passed as parameter in main().

Command Line Arguments : The Discussion

  • We can give any number of arguments from the command line and they are stored in an array format like args[0] for the first argument, args[1] for the second ,……..args[n-1] for nth argument.
  • Still Confused? Let us try to explain the concept of command line arguments with an example. Let’s add n numbers by using command line arguments.
This image describes a sample problem of command line arguments in java.
Command Line Arguments : Example

This image describes output of the sample problem of command line arguments in java.
Command Line Arguments : Output
  • In the above output we can see that 10, 20, 30, 40, 50 are command line arguments and output shows their sum.

Garbage Collection

  • In Java objects are dynamically allocated, and after their use they need to be destroyed to free up the memory space. In Java object de-allocation is done automatically, this technique of de-allocating objects is called garbage collection.
  • Now the question arises, how Java decides which object to de-allocate. When no reference to an object exists, that object is de-allocated and the memory is freed.
  • Garbage collector program check for the non-referenced object time to time and de-allocates them when it finds one.
  • In other programming languages like C++, one has to define a destructor to destroy or de-allocate the object , but this is done automatically in Java.