Command Line Arguments in Java

Object Oriented Programming - Unit I

Introduction to Command Line Arguments

Command line arguments allow you to pass information to a Java program when it starts executing. These arguments are passed through the command line interface and can be accessed within the program.

What are Command Line Arguments?

  • Parameters passed to the main method at runtime
  • Provided after the class name when running the program
  • Stored in the String[] args parameter of the main method
  • Allow programs to be more flexible and configurable

Why Use Command Line Arguments?

  • Configure program behavior without modifying code
  • Pass input data directly to the program
  • Create flexible and reusable applications
  • Automate program execution with different parameters

Syntax and Structure

Main Method Signature

The main method accepts command line arguments through its parameter:

public static void main(String[] args)

Execution Syntax

java ClassName arg1 arg2 arg3 ... argN

How Arguments are Stored

  • Arguments are stored in a String array called args
  • Each argument becomes an element in the array
  • Array indexing starts from 0 (args[0], args[1], etc.)
  • The number of arguments can be obtained using args.length
Important: All command line arguments are received as Strings, regardless of what you type. You need to convert them to appropriate data types if needed.

Practical Examples

Example 1: Basic Argument Display

public class CommandLineDemo { public static void main(String[] args) { System.out.println("Number of arguments: " + args.length); // Display all arguments for(int i = 0; i < args.length; i++) { System.out.println("Argument " + i + ": " + args[i]); } } } // Execution: java CommandLineDemo Hello World Java // Output: // Number of arguments: 3 // Argument 0: Hello // Argument 1: World // Argument 2: Java

Example 2: Calculator Program

public class Calculator { public static void main(String[] args) { // Check if correct number of arguments provided if(args.length != 3) { System.out.println("Usage: java Calculator "); System.out.println("Operators: +, -, *, /"); return; } try { double num1 = Double.parseDouble(args[0]); String operator = args[1]; double num2 = Double.parseDouble(args[2]); double result; switch(operator) { case "+": result = num1 + num2; break; case "-": result = num1 - num2; break; case "*": result = num1 * num2; break; case "/": if(num2 == 0) { System.out.println("Error: Division by zero!"); return; } result = num1 / num2; break; default: System.out.println("Invalid operator: " + operator); return; } System.out.println(num1 + " " + operator + " " + num2 + " = " + result); } catch(NumberFormatException e) { System.out.println("Error: Please provide valid numbers"); } } } // Execution: java Calculator 15.5 + 7.3 // Output: 15.5 + 7.3 = 22.8

Example 3: File Processing

import java.io.File; public class FileProcessor { public static void main(String[] args) { if(args.length == 0) { System.out.println("Usage: java FileProcessor "); return; } String filename = args[0]; File file = new File(filename); if(file.exists()) { System.out.println("File Information:"); System.out.println("Name: " + file.getName()); System.out.println("Path: " + file.getAbsolutePath()); System.out.println("Size: " + file.length() + " bytes"); System.out.println("Readable: " + file.canRead()); System.out.println("Writable: " + file.canWrite()); if(file.isDirectory()) { System.out.println("Type: Directory"); String[] files = file.list(); System.out.println("Contains " + files.length + " items"); } else { System.out.println("Type: File"); } } else { System.out.println("File does not exist: " + filename); } } } // Execution: java FileProcessor test.txt // Output: File information about test.txt

Example 4: Student Grade Calculator

public class GradeCalculator { public static void main(String[] args) { if(args.length < 2) { System.out.println("Usage: java GradeCalculator ..."); return; } String studentName = args[0]; int numberOfSubjects = args.length - 1; int[] marks = new int[numberOfSubjects]; int total = 0; // Parse marks try { for(int i = 0; i < numberOfSubjects; i++) { marks[i] = Integer.parseInt(args[i + 1]); total += marks[i]; } } catch(NumberFormatException e) { System.out.println("Error: All marks must be valid integers"); return; } // Calculate average and grade double average = (double) total / numberOfSubjects; char grade; if(average >= 90) grade = 'A'; else if(average >= 80) grade = 'B'; else if(average >= 70) grade = 'C'; else if(average >= 60) grade = 'D'; else grade = 'F'; // Display results System.out.println("=== Student Report ==="); System.out.println("Name: " + studentName); System.out.println("Number of Subjects: " + numberOfSubjects); System.out.println("Total Marks: " + total); System.out.println("Average: " + String.format("%.2f", average)); System.out.println("Grade: " + grade); } } // Execution: java GradeCalculator "John Doe" 85 92 78 95 // Output: Student report with calculated grade

Real-World Applications

1. Configuration Management

Use command line arguments to configure application settings:

public class AppConfig { public static void main(String[] args) { String configFile = "default.properties"; boolean debugMode = false; int port = 8080; // Parse configuration arguments for(String arg : args) { if(arg.startsWith("--config=")) { configFile = arg.substring(9); } else if(arg.equals("--debug")) { debugMode = true; } else if(arg.startsWith("--port=")) { port = Integer.parseInt(arg.substring(7)); } } System.out.println("Configuration:"); System.out.println("Config File: " + configFile); System.out.println("Debug Mode: " + debugMode); System.out.println("Port: " + port); } }

2. Batch Processing

Process multiple files or data sources:

public class BatchProcessor { public static void main(String[] args) { if(args.length == 0) { System.out.println("Usage: java BatchProcessor ..."); return; } System.out.println("Processing " + args.length + " files..."); for(int i = 0; i < args.length; i++) { String filename = args[i]; System.out.println("Processing file " + (i+1) + ": " + filename); // Add file processing logic here } System.out.println("Batch processing completed!"); } }

3. Utility Tools

Create command-line utilities for various tasks:

public class TextAnalyzer { public static void main(String[] args) { if(args.length == 0) { System.out.println("Usage: java TextAnalyzer \"text to analyze\""); return; } // Join all arguments into one text StringBuilder text = new StringBuilder(); for(String arg : args) { text.append(arg).append(" "); } String fullText = text.toString().trim(); // Analyze text int wordCount = fullText.split("\\s+").length; int charCount = fullText.length(); int charCountNoSpaces = fullText.replaceAll("\\s", "").length(); System.out.println("Text Analysis Results:"); System.out.println("Text: \"" + fullText + "\""); System.out.println("Word Count: " + wordCount); System.out.println("Character Count: " + charCount); System.out.println("Characters (no spaces): " + charCountNoSpaces); } }

Best Practices and Guidelines

1. Input Validation

  • Always check the number of arguments
  • Validate argument formats and values
  • Handle NumberFormatException for numeric arguments
  • Provide clear usage instructions

2. Error Handling

public class RobustProgram { public static void main(String[] args) { try { // Validate argument count if(args.length < 2) { System.err.println("Error: Insufficient arguments"); System.err.println("Usage: java RobustProgram "); System.exit(1); } // Process arguments with error handling int value1 = Integer.parseInt(args[0]); int value2 = Integer.parseInt(args[1]); // Additional validation if(value1 < 0 || value2 < 0) { System.err.println("Error: Values must be positive"); System.exit(1); } // Program logic here } catch(NumberFormatException e) { System.err.println("Error: Invalid number format"); System.exit(1); } catch(Exception e) { System.err.println("Unexpected error: " + e.getMessage()); System.exit(1); } } }

3. User-Friendly Design

  • Provide help information with --help or -h
  • Use meaningful argument names
  • Support both short and long option formats
  • Display progress for long-running operations

4. Common Patterns

Pattern Example Description
Flag options --verbose, -v Boolean flags to enable features
Key-value pairs --port=8080 Options with values
Positional args input.txt output.txt Arguments in specific positions
Multiple values file1.txt file2.txt Lists of similar items
Security Note: Be careful when handling command line arguments from untrusted sources. Always validate and sanitize input to prevent security vulnerabilities like command injection.

Advanced Topics

Quoted Arguments

Arguments containing spaces should be enclosed in quotes:

// Execution with quoted arguments java Program "Hello World" "Java Programming" // args[0] = "Hello World" // args[1] = "Java Programming"

Special Characters

Handling special characters and escape sequences:

// Execution with special characters java Program "C:\Program Files\MyApp" "user@domain.com" // Proper escaping in different shells // Windows: java Program "file with spaces.txt" // Unix/Linux: java Program 'file with spaces.txt'

Environment Variables

Combining command line arguments with environment variables:

public class EnvArgs { public static void main(String[] args) { // Access environment variables String userHome = System.getProperty("user.home"); String userName = System.getProperty("user.name"); System.out.println("User Home: " + userHome); System.out.println("User Name: " + userName); // Combine with command line arguments if(args.length > 0) { System.out.println("Command line arg: " + args[0]); } } }

Summary

Key Points Covered:

  • Concept: Command line arguments are passed to the main method
  • Format: All arguments are received as Strings
  • Access: Use String[] args array and args.length
  • Conversion: Parse strings to other data types as needed
  • Validation: Always validate and handle errors properly
  • Applications: Configuration, batch processing, utilities
Remember: Command line arguments make your programs more flexible and automation-friendly. They are essential for creating professional command-line tools and applications.