How to pass key-value parameter on command line - JAVA

How to work with key value pair during running the program from command line.

See the below example

public class Example
{
    public static void main(String[] args)
    {
        String name = System.getProperty("name");
        String age = System.getProperty("age");

        System.out.println(name + " : "+age);
    }

}

Syntax to run above program

c:/> java <-Dkey=value> <classname>

Explanation


  • java = command to run the program
  • -Dkey=value = should always start with -D and then key and value, note there should not be any space in between.
  • classname=class name




So once you compile the program, below is how you can run 

c:/> java -Dname=Umesh -Dage=30 Example

output

Umesh : 30





compiled and run on java 1.8



Comments

Popular posts from this blog

Comparator - Java 8

Java Installation on Windows System