Please disable adblock to view this page.

← Go home

Passing Arguments To Console In Java

java-display

April 29, 2017
Published By : Pratik Kataria
Categorised in:

Remember String [] args ?

  • This allows to pass values from console to Java application in the form of Strings.
  • You can use those arguments within Java application by the name of array (here args) and index number
    public class Main {
    	public static void main( String[] args) {
    		System.out.println(args[0]);
    	}
    }
  • Console:

    • K:\>javac Main.java
    • K:\>java Main MyArgument
    • OUTPUT:
      MyArgument

Guess the output:

  • Console:
    • K:\>javac Main.java
    • K:\>java Main My Argument
    • OUTPUT ?
      My Argument
  • WRONG!
    • REAL OUTPUT:
      My
  • Why?
    • Java separates arguments by spaces.
      My -> args[0]
      Argument -> args[1]
  • How to make your desired output work?
    • Wrap your argument in double quotes:
      • K:\>java Main “My Argument”
  • What would happen if you do this: 
    • K:\>javac Main.java
    • K:\>java Main
  • Exception!
    • Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 0
  • Above exception is ‘Fatal Exception’
    • Solution: Error handling