Object-Oriented Programming (CS F213) : BITS Pilani
Object-Oriented Programming (CS F213) : BITS Pilani
Command-Line Agruments/Parameters
Note : Actual Arguments starts after the name of the driver class.
Each Argument should be space separated
3 Object-Oriented Programming (CS F213)
Command-Line Arguments :
Example 1
// File Name: Test.java
class Test
{
public static void main(String args[])
{
System.out.println(Number of Arguments: + args.length);
}
}
F:\>java Test
Number of Arguments: 0
} // End of Method
} // End of class Test
F:\>java Test 1 2 3 4 Hello 5 6 I AM FINE F:\>java Test I Love India 20 30
F:\>java Test
Number of Arguments: 10 Number of Arguments: 5
Number of Arguments:
1 args[0] I
args[0]
0
2 args[1] Love args[1]
3 India .
4 . 20 .
Hello . 30 args[4]
5
6 .
I .
AM
FINE args[9]
5 Object-Oriented Programming (CS F213)
Retrieving The Actual Type of
Parameters
Every type of argument is stored in a String type array
To retrieve the actual primitive type value, following methods
can be used
1. int Integer.parseInt(String s) parseInt() is a static method of Integer library class. Takes a
String type as argument and returns an integer type.
2. float Float.parseFloat(String s) parseFloat() is a static method of Float library class. Takes a
String type as argument and returns a float type.
3. double Double.parseDouble(String s) parseDouble() is a static method of Double library class.
Takes a String type as argument and returns a double type
4. char charAt(int index) charAt() is a method of String library class. Returns the character from a
index.
5. long Long.parseLong(String s) parseLong() is a static method of Long library class. Takes a
String type as argument and returns a long type
6. byte Byte.parseByte(String s) parseByte() is a static method of Byte library class. Takes a
String type as argument and returns a byte type
7. boolean Boolean.parseBoolean(String s) parseBoolean() is a static method of Boolean library
class. Takes a String type as argument and returns a boolean type
8. short Short.parseShort(String s) parseShort() is a static method of Short library class. Takes a
String type as argument and returns a short type
Note: Each of the above Method [except charAt()] Throws a
NumberFormatException if the string does not represent the desired type
6 Object-Oriented Programming (CS F213)
Examples of parsing
int x = Integer.parseInt(10); // Executes Successfully
if( c == a) System.out.println(a+b);
else if( c == s) System.out.println(a-b);
else if( c == m) System.out.println(a * b);
} // End of Method
}// End of class Test
F:\>java Test 10 20 x
F:\>java Test 10 x 30
Exception in thread "main" java.lang.NumberFormatException: For input string: "x
"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Test.main(You.java:7)