How to Use Public Static Void Main String Args in Java

Avatar

By squashlabs, Last Updated: September 16, 2023

How to Use Public Static Void Main String Args in Java

The “public static void main(String[] args)” method is a crucial part of any Java program. It serves as the entry point for the application and is executed when the program is run. This method allows the program to interact with the user, perform operations, and produce output.

Syntax and Structure of Public Static Void Main String Args

The syntax of the “public static void main(String[] args)” method is as follows:

public static void main(String[] args) {
    // Code goes here
}

Let’s break down the structure of the method:

– “public” keyword: It denotes that the method can be accessed from anywhere within the program.
– “static” keyword: It indicates that the method belongs to the class itself and not to any specific instance of the class.
– “void” keyword: It specifies that the method does not return any value.
– “main” method name: It is the name of the method and serves as the entry point for the program.
– “String[] args” parameter: It is an array of strings that can be passed as command-line arguments to the program.

Related Article: How To Parse JSON In Java

Role of Public, Static, Void, Main, and String Args in the Method

– Public: The “public” keyword allows the main method to be accessed from outside the class and is necessary for the JVM to find and execute the method.
– Static: The “static” keyword makes the main method belong to the class itself rather than any specific instance of the class. This enables the JVM to call the main method without creating an object of the class.
– Void: The “void” keyword indicates that the main method does not return any value.
– Main: The “main” method name is predefined and serves as the entry point for the program. The JVM looks for this specific method to start the execution of the program.
– String Args: The “String[] args” parameter allows command-line arguments to be passed to the program. These arguments can be accessed within the main method using the “args” parameter.

Use Case: Implementing Public Static Void Main String Args in a Program

Let’s consider a simple use case where we want to create a program that calculates the sum of two numbers provided as command-line arguments.

public class SumCalculator {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Please provide two numbers as command-line arguments.");
            return;
        }
        
        int num1 = Integer.parseInt(args[0]);
        int num2 = Integer.parseInt(args[1]);
        int sum = num1 + num2;
        
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
}

In the above example, we first check if exactly two command-line arguments are provided. If not, we display a message and exit the program. Next, we parse the arguments as integers and calculate their sum. Finally, we display the result.

Best Practice: Organizing Code with Public Static Void Main String Args

To keep the code organized and maintainable, it is recommended to separate the main method from the rest of the program’s logic. This allows for better modularity and easier testing.

One common practice is to create a separate class responsible for handling the program’s logic and invoke it from the main method. Let’s consider an example where we calculate the factorial of a number using a separate class.

public class FactorialCalculator {
    public static int calculateFactorial(int number) {
        if (number == 0 || number == 1) {
            return 1;
        }
        
        int factorial = 1;
        for (int i = 2; i <= number; i++) {
            factorial *= i;
        }
        
        return factorial;
    }
}

public class Main {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Please provide a number as a command-line argument.");
            return;
        }
        
        int number = Integer.parseInt(args[0]);
        int factorial = FactorialCalculator.calculateFactorial(number);
        
        System.out.println("The factorial of " + number + " is: " + factorial);
    }
}

In this example, we have a separate class called “FactorialCalculator” that contains the logic for calculating the factorial of a number. The main method is responsible for getting the input from the command line, calling the factorial calculation method, and displaying the result.

Related Article: How To Convert Array To List In Java

Real World Example: A Console Application Using Public Static Void Main String Args

Let’s explore a real-world example of a console application that uses the “public static void main(String[] args)” method. Consider a simple program that simulates a basic banking system.

public class Bank {
    public static void main(String[] args) {
        // Initialize the banking system
        
        // Display a welcome message and options for the user
        
        // Handle user input and perform operations
        
        // Terminate the program
    }
}

In this example, the main method is responsible for initializing the banking system, displaying a welcome message and options for the user, handling user input to perform various banking operations, and terminating the program.

Performance Consideration: Optimizing Execution Time with Public Static Void Main String Args

When working with the “public static void main(String[] args)” method, it is important to consider performance implications, especially when dealing with large-scale applications or time-sensitive operations.

One performance optimization technique is to minimize the amount of work done directly in the main method. Instead, delegate complex tasks to separate methods or classes. This helps to maintain a clean and focused main method while improving code readability and maintainability.

Let’s consider an example where we calculate the sum of an array of numbers and measure the execution time.

public class SumCalculator {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        
        long startTime = System.currentTimeMillis();
        int sum = calculateSum(numbers);
        long endTime = System.currentTimeMillis();
        
        System.out.println("The sum is: " + sum);
        System.out.println("Execution time: " + (endTime - startTime) + " milliseconds");
    }
    
    public static int calculateSum(int[] numbers) {
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        return sum;
    }
}

In this example, we calculate the sum of an array of numbers by calling a separate method called “calculateSum”. We measure the execution time by capturing the start and end times using the “System.currentTimeMillis()” method. By delegating the sum calculation to a separate method, we keep the main method focused on timing and displaying the result.

Advanced Technique: Using Public Static Void Main String Args with Threads

The “public static void main(String[] args)” method can also be used in conjunction with threads to introduce concurrency and parallelism into Java programs.

Let’s consider an example where we use multiple threads to perform parallel processing of a list of tasks.

public class TaskProcessor {
    public static void main(String[] args) {
        List<String> tasks = Arrays.asList("Task 1", "Task 2", "Task 3", "Task 4", "Task 5");
        
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        
        for (String task : tasks) {
            executorService.execute(() -> processTask(task));
        }
        
        executorService.shutdown();
    }
    
    public static void processTask(String task) {
        // Perform task processing here
        System.out.println("Processing task: " + task);
    }
}

In this example, we create a list of tasks and use an ExecutorService to manage a pool of threads. Each task is processed by a separate thread, allowing for parallel execution. The main method initiates the processing of tasks and shuts down the executor service when all tasks are completed.

Related Article: How To Iterate Over Entries In A Java Map

Code Snippet Idea: Basic Console Output with Public Static Void Main String Args

The “public static void main(String[] args)” method is commonly used to display output to the console. Let’s explore a basic code snippet that prints a simple message.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

In this example, the main method prints the message “Hello, World!” to the console using the “System.out.println()” method. This is a common starting point for beginners learning Java programming.

Code Snippet Idea: Reading Input with Public Static Void Main String Args

The “public static void main(String[] args)” method can also be used to read input from the user. Let’s consider a code snippet that prompts the user for their name and displays a personalized greeting.

import java.util.Scanner;

public class Greeting {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        
        System.out.println("Hello, " + name + "!");
        
        scanner.close();
    }
}

In this example, we create a Scanner object to read input from the console. The main method prompts the user to enter their name and stores it in a variable. It then displays a personalized greeting using the entered name.

Code Snippet Idea: Error Handling with Public Static Void Main String Args

Proper error handling is essential in any program, including those that use the “public static void main(String[] args)” method. Let’s consider a code snippet that demonstrates error handling when parsing command-line arguments.

public class ArgumentParser {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Invalid number of arguments. Please provide a single argument.");
            System.exit(1);
        }
        
        try {
            int number = Integer.parseInt(args[0]);
            System.out.println("Parsed number: " + number);
        } catch (NumberFormatException e) {
            System.err.println("Invalid argument format. Please provide a valid integer.");
            System.exit(1);
        }
    }
}

In this example, we first check if the number of command-line arguments is not equal to 1. If so, we display an error message to the standard error stream (System.err) and exit the program with a non-zero status code using the System.exit() method.

If the number of arguments is valid, we attempt to parse the argument as an integer using the Integer.parseInt() method. If a NumberFormatException occurs, indicating that the argument is not a valid integer, we display an error message and exit the program.

Related Article: How To Split A String In Java

Code Snippet Idea: Invoking Other Methods with Public Static Void Main String Args

The “public static void main(String[] args)” method can be used to invoke other methods within the same class or different classes. Let’s consider a code snippet that demonstrates invoking a separate method to perform a specific task.

public class TaskExecutor {
    public static void main(String[] args) {
        printWelcomeMessage();
        executeTask();
        printGoodbyeMessage();
    }
    
    public static void printWelcomeMessage() {
        System.out.println("Welcome to the task executor!");
    }
    
    public static void executeTask() {
        System.out.println("Executing task...");
        // Perform task execution here
    }
    
    public static void printGoodbyeMessage() {
        System.out.println("Task execution complete. Goodbye!");
    }
}

In this example, the main method invokes three separate methods: printWelcomeMessage(), executeTask(), and printGoodbyeMessage(). Each method is responsible for performing a specific task, and by invoking them in a specific order, we achieve the desired program flow.

Code Snippet Idea: Using Command Line Arguments with Public Static Void Main String Args

Command-line arguments can be passed to the “public static void main(String[] args)” method when running a Java program. Let’s consider a code snippet that demonstrates how to use command-line arguments to customize program behavior.

public class Greeting {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Please provide your name as a command-line argument.");
            System.exit(1);
        }
        
        String name = args[0];
        
        System.out.println("Hello, " + name + "!");
    }
}

In this example, we check if exactly one command-line argument is provided. If not, we display an error message and exit the program. If a single argument is provided, we store it in the name variable and display a personalized greeting.

Error Handling: Catching and Logging Exceptions in Public Static Void Main String Args

When working with the “public static void main(String[] args)” method, it is important to handle exceptions gracefully and provide appropriate error messages. Let’s consider a code snippet that demonstrates catching and logging exceptions.

public class FileProcessor {
    public static void main(String[] args) {
        try {
            // Code that may throw exceptions
        } catch (FileNotFoundException e) {
            System.err.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("An error occurred while processing the file: " + e.getMessage());
        } finally {
            // Cleanup code
        }
    }
}

In this example, we have a try-catch block that surrounds the code that may throw exceptions. If a FileNotFoundException occurs, indicating that a file could not be found, we display an appropriate error message. If an IOException occurs, indicating a general I/O error, we display a different error message.

The finally block is used to execute cleanup code after the try-catch block, regardless of whether an exception occurred or not.

Related Article: How To Convert Java Objects To JSON With Jackson

Advanced Technique: Overloading the Main Method

In Java, it is possible to overload the “public static void main(String[] args)” method by defining additional methods with different parameter types or a different number of parameters. This allows for more flexibility when running a Java program.

Let’s consider an example where we have two main methods: one that takes command-line arguments and another that does not.

public class Main {
    public static void main(String[] args) {
        System.out.println("Main method with command-line arguments");
    }
    
    public static void main() {
        System.out.println("Main method without command-line arguments");
    }
}

In this example, we have two main methods: one that accepts command-line arguments and another that does not. Depending on how the program is run, the appropriate main method will be invoked.

This technique can be useful when you want to provide different entry points to your program or when you want to perform certain tasks without relying on command-line arguments.

How to Generate Random Integers in a Range in Java

Generating random integers within a specific range in Java is made easy with the Random class. This article explores the usage of java.util.Random and ThreadLocalRandom... read more

How to Convert JSON String to Java Object

Converting JSON strings to Java objects can be a process when following simple methods. By creating a Java class, choosing a JSON parsing library, parsing the JSON... read more

How to Reverse a String in Java

This article serves as a guide on reversing a string in Java programming language. It explores two main approaches: using a StringBuilder and using a char array.... read more

How to Retrieve Current Date and Time in Java

Obtain the current date and time in Java using various approaches. Learn how to use the java.util.Date class and the java.time.LocalDateTime class to retrieve the... read more

Storing Contact Information in Java Data Structures

Storing contact information in Java data structures provides an way to organize and manage data. This article covers different data structures in Java and their... read more

Java Equals Hashcode Tutorial

Learn how to implement equals and hashcode methods in Java. This tutorial covers the basics of hashcode, constructing the equals method, practical use cases, best... read more