DEV Community

KIRAN RAJ
KIRAN RAJ

Posted on

Java Command-Line Arguments: A Step-by-Step Guide

Understanding Command-Line Arguments, Method Signatures, and Static Methods in Java
In this blog, we'll explore three essential concepts in Java: command-line arguments, method signatures, and static methods.

Command-Line Arguments
Command-line arguments are values passed to a Java program at runtime. They're received through the String[] args parameter in the main method.

Example
public class Practice {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("Command-line arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
} else {
System.out.println("No command-line arguments found!");
}
}
}
Method Signatures
A method signature in Java defines the unique identity of a method. It includes:

  • Method name
  • Parameter list (number, type, and order of parameters)

The return type and access modifiers are not part of the method signature.

Example
public static int calculateSum(int a, int b)
The signature is: calculateSum(int, int)

Static Methods
A static method belongs to the class itself, not to an instance (object). Static methods:

  • Can be called directly using the class name
  • Don't require object creation
  • Are useful for utility/helper methods

Example
public class Practice {
public static double square(double num) {
return num * num;
}

public static void main(String[] args) {
    double result = Practice.square(7.5);
    System.out.println("Square of 7.5 is: " + result);
}
Enter fullscreen mode Exit fullscreen mode

}
Key Takeaways

  • Command-line arguments allow passing data to a program at runtime.
  • Method signatures define the identity of a method (name + parameters).
  • Static methods enable code execution without object creation.

Clarifying Doubts
Regarding the findMax method:
public static int findMax(int x, int y) {
if (x > y) {
return x;
} else {
return y;
}
}
This method returns an int value, which is the maximum of x and y. The return type is correctly specified as int, matching the method's purpose.

By understanding these concepts, you'll be better equipped to write efficient and effective Java code.

Top comments (0)