Passing Arguments To Console In Java

April 29, 2017
Categorised in: Java Core
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
- REAL OUTPUT:
- Why?
- Java separates arguments by spaces.
My -> args[0]
Argument -> args[1]
- Java separates arguments by spaces.
- How to make your desired output work?
- Wrap your argument in double quotes:
- K:\>java Main “My Argument”
- Wrap your argument in double quotes:
- 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
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.