Sign In
Sign In

Java main() Method

Java main() Method
Adnene Mabrouk
Technical writer
Java
31.07.2024
Reading time: 4 min

The main method in Java is a fundamental component for any standalone application. It serves as the entry point where the program begins execution. Understanding the syntax and functionality of this method is crucial for every Java programmer. This article delves into the specifics of the main method, explaining its syntax, the role of command-line arguments, and providing practical examples to illustrate its use.

Syntax Explanation: public static void main(String[] args)

The Java main method is defined as:

public static void main(String[] args)

Breaking down the syntax:

  • public: This is an access modifier, meaning the method is accessible from anywhere.

  • static: This keyword means the method belongs to the class rather than an instance of the class. It can be invoked without creating an object of the class.

  • void: This signifies that the method does not return any value.

  • main: This is the name of the method. The Java runtime environment looks for this specific method signature to start execution.

  • String[] args: This parameter is an array of String objects, which stores command-line arguments passed to the program.

Understanding the String[] args Parameter

The String[] args parameter in the main method is crucial for passing information to the program at runtime. Each element in this array is a command-line argument provided when the program is executed. For example, if a program is run with java MyClass arg1 arg2, args[0] would be arg1 and args[1] would be arg2.

public class MyClass {
    public static void main(String[] args) {
        for (String arg : args) {
            System.out.println(arg);
        }
    }

In the above code, each command-line argument passed to the program is printed to the console.

How to Use Command-Line Arguments

Command-line arguments allow users to pass data into a Java program at the time of execution, making the program more flexible and dynamic. Here's a simple example of how to use command-line arguments in a Java program:

public class SumArgs {
    public static void main(String[] args) {
        int sum = 0;
        for (String arg : args) {
            sum += Integer.parseInt(arg);
        }
        System.out.println("Sum: " + sum);
    }
}

If this program is run with java SumArgs 10 20 30, it will output Sum: 60. This demonstrates how command-line arguments can be used to input data without modifying the program's source code.

Typical Use Cases and Examples

  1. Configuration Parameters: Command-line arguments are often used to pass configuration settings to a program. For example, specifying the path to a configuration file or setting a debug mode.

public class ConfigLoader {
    public static void main(String[] args) {
        if (args.length > 0) {
            String configFilePath = args[0];
            System.out.println("Loading configuration from: " + configFilePath);
            // Load and process the configuration file
        } else {
            System.out.println("No configuration file path provided.");
        }
    }
}
  1. File Processing: Programs that perform operations on files often accept file paths as command-line arguments.

public class FilePrinter {
    public static void main(String[] args) {
        if (args.length > 0) {
            String filePath = args[0];
            // Code to read and print file content
        } else {
            System.out.println("Please provide a file path.");
        }
    }
}
  1. Testing and Debugging: Command-line arguments can be used to quickly test and debug different scenarios by changing the input parameters without altering the source code.

Conclusion

The public static void main(String[] args) method is an essential part of any Java application. Its syntax and functionality are designed to provide a standardized entry point for program execution. Understanding how to leverage String[] args for command-line arguments can significantly enhance the flexibility and utility of your programs. By mastering the main method, Java developers can build more dynamic and configurable applications, making their code more versatile and easier to manage.

Java
31.07.2024
Reading time: 4 min

Similar

Java

Switching between Java Versions on Ubuntu

Managing multiple Java versions on Ubuntu is essential for developers working on diverse projects. Different applications often require different versions of the Java Development Kit (JDK) or Java Runtime Environment (JRE), making it crucial to switch between these versions efficiently. Ubuntu provides powerful tools to handle this, and one of the most effective methods is using the update-java-alternatives command. Switching Between Java Versions In this article, the process of switching between Java versions using updata-java-alternatives will be shown. This specialized tool simplifies the management of Java environments by updating all associated commands (such as java, javac, javaws, etc.) in one go.  Overview of Java version management A crucial component of development is Java version control, especially when working on many projects with different Java Runtime Environment (JRE) or Java Development Kit (JDK) needs. In order to prevent compatibility problems and ensure efficient development workflows, proper management ensures that the right Java version is utilized for every project. Importance of using specific Java versions You must check that the Java version to be used is compatible with the application, program, or software running on the system. Using the appropriate Java version ensures that the product runs smoothly and without any compatibility issues. Newer versions of Java usually come with updates and security fixes, which helps protect the system from vulnerabilities. Using an out-of-date Java version may expose the system to security vulnerabilities. Performance enhancements and optimizations are introduced with every Java version. For maximum performance, use a Java version that is specific to the application. Checking the current Java version It is important to know which versions are installed on the system before switching to other Java versions.  To check the current Java version, the java-common package has to be installed. This package contains common tools for the Java runtimes including the update-java-alternatives method. This method allows you to list the installed Java versions and facilitates switching between them. Use the following command to install the java-common package: sudo apt-get install java-common Upon completing the installation, verify all installed Java versions on the system using the command provided below: sudo update-java-alternatives --list The report above shows that Java versions 8 and 11 are installed on the system. Use the command below to determine which version is being used at the moment. java -version The displayed output indicates that the currently active version is Java version 11. Installing multiple Java versions Technically speaking, as long as there is sufficient disk space and the package repositories support it, the administrator of Ubuntu is free to install as many Java versions as they choose. Follow the instructions below for installing multiple Java versions. Begin by updating the system using the following command:   sudo apt-get update -y && sudo apt-get upgrade -y To add another version of Java, run the command below. sudo apt-get install <java version package name> In this example, installing Java version 17 can be done by running:  sudo apt-get install openjdk-17-jdk openjdk-17-jre Upon completing the installation, use the following command to confirm the correct and successful installation of the Java version: sudo update-java-alternatives --list Switching and setting the default Java version To switch between Java versions and set a default version on Ubuntu Linux, you can use the update-java-alternatives command.  sudo update-java-alternatives --set <java_version> In this case, the Java version 17 will be set as default: sudo update-java-alternatives --set java-1.17.0-openjdk-amd64 To check if Java version 17 is the default version, run the command:  java -version The output shows that the default version of Java is version 17. Managing and Switching Java Versions in Ubuntu Conclusion In conclusion, managing multiple Java versions on Ubuntu Linux using update-java-alternatives is a simple yet effective process. By following the steps outlined in this article, users can seamlessly switch between different Java environments, ensuring compatibility with various projects and taking advantage of the latest features and optimizations offered by different Java versions. Because Java version management is flexible, developers may design reliable and effective Java apps without sacrificing system performance or stability.
22 August 2025 · 4 min to read
Java

Catching and Handling Exceptions in Java

The Java programming language, like many others, has built-in tools for working with errors, i.e., exceptional situations (exceptions) where a program failure is handled by special code, separate from the basic algorithm. Thanks to exceptions, a developer can anticipate weak points in the codebase and preempt fatal errors at runtime. Therefore, handling exceptions in Java is a good practice that improves the overall reliability of code. The purpose of this article is to explore the principles of catching and handling exceptions, as well as to review the corresponding syntactic structures in the language intended for this. All the examples in this guide were run on Ubuntu 22.04, installed on a cloud server from Hostman. Installing OpenJDK and Running an Application The examples shown in this guide were run using OpenJDK. Installing it is straightforward. First, update the list of available repositories: sudo apt update Next, request the list of OpenJDK versions available for download: sudo apt search openjdk | grep -E 'openjdk-.*-jdk/' You’ll see a short list in the terminal: WARNING: apt does not have a stable CLI interface. Use with caution in scripts. openjdk-11-jdk/jammy-updates,jammy-security 11.0.25+9-1ubuntu1~22.04 amd64 openjdk-17-jdk/jammy-updates,jammy-security 17.0.13+11-2ubuntu1~22.04 amd64 openjdk-18-jdk/jammy-updates,jammy-security 18.0.2+9-2~22.04 amd64 openjdk-19-jdk/jammy-updates,jammy-security 19.0.2+7-0ubuntu3~22.04 amd64 openjdk-21-jdk/jammy-updates,jammy-security,now 21.0.5+11-1ubuntu1~22.04 amd64 [installed] openjdk-8-jdk/jammy-updates,jammy-security 8u432-ga~us1-0ubuntu2~22.04 amd64 We will use the openjdk-21-jdk version: sudo apt install openjdk-21-jdk You can then check that Java was installed correctly by requesting its version: java --version The terminal output will look something like this: openjdk 21.0.5 2024-10-15 OpenJDK Runtime Environment (build 21.0.5+11-Ubuntu-1ubuntu122.04) OpenJDK 64-Bit Server VM (build 21.0.5+11-Ubuntu-1ubuntu122.04, mixed mode, sharing) As shown, the exact version of OpenJDK is 21.0.5. All the examples in this guide should be saved in a separate file with a .java extension: nano App.java Then, fill the created file with an example code, such as: class App { public static void main(String[] args) { System.out.println("This text is printed to the console"); } } Note that the class name must match the file name. Next, compile the file: javac App.java And run it: java App The terminal will display the following: This text is printed to the console Types of Exceptions in Java All exceptions in Java have a specific type associated with the reason the exception occurred—the particular kind of program failure. There are two fundamental types of exceptions: Checked Exceptions — These occur at compile time. If they are not handled, the program won’t compile. Unchecked Exceptions — These occur at runtime. If unhandled, the program will terminate. The Error type is only conditionally considered an exception — it's a full-fledged error that inevitably causes the program to crash. Exceptions that can be handled using custom code and allow the program to continue executing are Checked Exceptions and Unchecked Exceptions. Thus, errors and exceptions in Java are different entities. However, both Errors and Exceptions (Checked and Unchecked) are types with additional subtypes that clarify the reason for the failure. Checked Exceptions Here's an example of code that triggers a compile-time exception: import java.io.File; import java.util.Scanner; public class App { public static void main(String[] args) { File someFile = new File("someFile.txt"); // create file reference Scanner scanner = new Scanner(someFile); // parse file contents } } Compilation will be interrupted, and you’ll see the following error in the terminal: App.java:7: error: unreported exception FileNotFoundException; must be caught or declared to be thrown Scanner scanner = new Scanner(someFile); ^ 1 error If you catch and handle this exception, the code will compile and be runnable. Unchecked Exceptions Here’s another example of code that triggers an exception only at runtime: class App { public static void main(String[] args) { int[] someArray = {1, 2, 3, 4, 5}; // create an array with 5 elements System.out.println(someArray[10]); // attempt to access a non-existent element } } No exception will occur during compilation, but after running the compiled code, you’ll see this error in the terminal: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5 at app.main(app.java:4) This means that such an exception can be handled using user-defined code, allowing the program to continue execution. Error Finally, here’s an example of code that causes a runtime error: public class App { static int i = 0; public static int showSomething(int x) { i = i + 2; return i + showSomething(i + 2); } public static void main(String[] args) { App.showSomething(i); // trigger stack overflow } } The compilation will succeed, but during execution, the terminal will show a StackOverflowError: Exception in thread "main" java.lang.StackOverflowError at java.base/java.io.BufferedOutputStream.implWrite(BufferedOutputStream.java:220) at java.base/java.io.BufferedOutputStream.write(BufferedOutputStream.java:200) at java.base/java.io.PrintStream.implWrite(PrintStream.java:643) In this case, the error cannot be handled; it can only be fixed in the code. Exception Classes in Java Internally, all exceptions (and errors) in Java are represented as a set of classes, some of which inherit from others. The base class for all errors and exceptions is Throwable. Two other classes inherit from it—Error and Exception, which serve as base classes for a broad range of subclasses associated with specific exception types. The Error class describes error-type exceptions, as mentioned earlier, while the Exception class describes checked exceptions. Furthermore, the RuntimeException class inherits from Exception and describes unchecked exceptions. A simplified class hierarchy of Java exceptions can be represented as the following nested list: Throwable Error Exception CloneNotSupportedException InterruptedException ReflectiveOperationException ClassNotFoundException IllegalAccessException InstantiationException NoSuchFieldException NoSuchMethodException RuntimeException NullPointerException ArithmeticException IllegalArgumentException IndexOutOfBoundException NumberFormatException Each exception class includes methods for retrieving additional information about the failure. You can find the complete classification of Java exceptions, including those from additional packages, in a dedicated reference guide. Exception Handling Syntax in Java try and catch All exceptions are handled using special try and catch blocks, which are standard across most programming languages, including Java. Inside the try block, you write code that may potentially contain an error capable of throwing an exception. Inside the catch block, you write code that handles the exception that occurred in the previously defined try block. For example, a try-catch structure might look like this: public class App { public static void main(String[] args) { try { // code that might throw an exception int someVariable = 5 / 0; System.out.println("Who said you can’t divide by zero?"); } catch (ArithmeticException someException) { // code that handles the exception System.out.println("Actually, you can't divide by zero..."); } } } The output of this code in the console will be: Actually, you can't divide by zero... This specific example is based on an illegal division by zero operation, which is wrapped in a try block and throws an ArithmeticException. Accordingly, in the catch block, this exception is handled by printing an error message to the console. Thanks to this structure, the program can continue running even after the error during division by zero. finally Unlike many other programming languages, Java includes a special finally block as part of the exception handling mechanism. It always executes—regardless of whether an exception occurred or not. So, we can extend the previously shown structure: public class App { public static void main(String[] args) { try { // code that might throw an exception int someVariable = 5 / 0; } catch (ArithmeticException someException) { // code that handles the exception System.out.println("Actually, you can't divide by zero..."); } finally { // code that always executes System.out.println("Who cares if you can divide by zero or not? This message will appear anyway!"); } } } After running this code, the console will display: Actually, you can't divide by zero... Who cares if you can divide by zero or not? This message will appear anyway! To understand the practical need for the finally block, consider the following example out of any specific context: try { parseJson(response.json); } catch (JSONException someException) { System.out.println("Looks like there’s something wrong with the JSON..."); } // a function that hides the loading indicator hideLoaderUI(); In a program using this structure, the hideLoaderUI() function will never execute if an exception occurs. In this case, you could try calling hideLoaderUI() inside the exception handler if an exception occurs and also call it afterward if no exception occurred: try { parseJson(response.json); } catch (JSONException someException) { hideLoaderUI(); // duplicate System.out.println("Looks like there’s something wrong with the JSON..."); } hideLoaderUI(); // duplicate However, this results in undesirable duplication of the function call. Moreover, instead of a function, it might be an entire block of code, and duplicating such code is considered bad practice. Therefore, to guarantee the execution of hideLoaderUI() without duplicating the call, you can use a finally block: try { parseJson(response.json); } catch (JSONException someException) { System.out.println("Looks like there’s something wrong with the JSON..."); } finally { // the loading indicator will be hidden in any case hideLoaderUI(); } throw Java allows you to manually create (throw) exceptions using the special throw operator: public class App { public static void main(String[] args) { throw new Exception("Something strange seems to have happened..."); } } You can even create a variable for the exception ahead of time and then throw it: public class App { public static void main(String[] args) { var someException = new Exception("Something strange seems to have happened..."); throw someException; } } throws Another important keyword, throws (note the “s” at the end), allows you to explicitly declare the types of exceptions (in the form of class names) that a method may throw. If such a method throws an exception, it will propagate up to the calling code, which must handle it: public class App { public static void someMethod() throws ArithmeticException, NullPointerException, InterruptedException { int someVariable = 5 / 0; } public static void main(String[] args) { try { App.someMethod(); } catch (Exception someException) { System.out.println("Dividing by zero again? Do you even know what insanity is?"); } } } The console output will be: Dividing by zero again? Do you even know what insanity is? Creating Custom Exceptions The hierarchical structure of exceptions naturally allows for the creation of custom exception classes that inherit from the base ones. Thanks to custom exceptions, Java enables you to implement application-specific error handling paths. Thus, in addition to standard Java exceptions, you can add your own. Each custom exception, like any predefined one, can be handled using standard try-catch-finally blocks: class MyOwnException extends Exception { public MyOwnException(String message) { super(message); // calls the parent class constructor System.out.println("Warning! An exception is about to be thrown!"); } } public class App { public static void main(String[] args) { try { throw new MyOwnException("Just an exception. No explanation. Anyone got a problem?"); } catch (MyOwnException someException) { System.out.println(someException.getMessage()); } } } The console output will be: Warning! An exception is about to be thrown! Just an exception. No explanation. Anyone got a problem? Conclusion This tutorial demonstrated, through examples, why exceptions are needed in Java, how they arise (including how to manually throw one), and how to handle them using the corresponding language tools. Exceptions that can be caught and handled come in two types: Checked Exceptions: Handled at compile time. Unchecked Exceptions: Handled at runtime. In addition to these, there are fatal errors that can only be resolved by rewriting code: Errors: Cannot be handled. There are several syntax structures (blocks) used to handle exceptions: try: Code that may throw an exception. catch: Code that handles the possible exception. finally: Code that executes regardless of whether an exception occurred. As well as keywords to control the process of throwing exceptions: throw: Manually throws an exception. throws: Lists possible exceptions in a declared method. You can find the full list of methods in the parent Exception class in the official Oracle documentation.
20 June 2025 · 11 min to read
Java

Exception Handling in Java

Exception handling is a cornerstone of robust software development in Java, serving as the bridge between theoretical correctness and practical resilience. While most developers grasp the basics of try-catch blocks, the true art of exception management lies in balancing technical precision, architectural foresight, and performance optimization. This article dives deep into Java exception handling, exploring not only core concepts but also advanced patterns, anti-patterns, and strategies for integrating error management into modern architectures such as microservices, reactive systems, and cloud-native applications. The Philosophy of Exception Handling: Beyond Syntax Java’s exception handling mechanism is more than just a syntax requirement—it embodies a philosophy of controlled failure. Unlike languages that rely on error codes or silent failures, Java enforces a structured approach to unexpected scenarios, ensuring developers confront errors explicitly. This design choice reflects two principles: Fail-fast: Identify and address issues at the earliest possible stage. Separation of Concerns: Decouple business logic from error recovery. Understanding these principles is critical for designing systems where exceptions are not merely "handled" but strategically managed to enhance reliability. class FailFastExample { public static void main(String[] args) { int age = -5; // Simulate invalid input // Fail-fast: Validate input and throw exception if invalid if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } System.out.println("Age: " + age); // This line won't execute if exception is thrown } } The Anatomy of Java Exceptions Java’s exception hierarchy is rooted in the Throwable class, with three primary categories: Checked Exceptions (Exception subclasses): Enforced by the compiler (e.g., IOException, SQLException). Represent recoverable errors (e.g., file not found, network issues). Require explicit handling via try-catch or propagation using throws. Unchecked Exceptions (RuntimeException subclasses): Not enforced by the compiler (e.g., NullPointerException, IllegalArgumentException). Often indicate programming errors (e.g., invalid arguments, logic flaws). Errors (Error subclasses): Severe, non-recoverable issues (e.g., OutOfMemoryError, StackOverflowError). Typically arise from JVM or system-level failures. The distinction between checked and unchecked exceptions is often debated. Modern frameworks like Spring have largely moved away from checked exceptions, favoring runtime exceptions to reduce boilerplate and improve code readability. import java.io.FileInputStream; import java.io.FileNotFoundException; class ExceptionTypesDemo { public static void main(String[] args) { // Unchecked exception (ArithmeticException) try { int result = 10 / 0; // Division by zero } catch (ArithmeticException ex) { System.out.println("Unchecked error: " + ex.getMessage()); } // Checked exception (FileNotFoundException) try { // Attempt to open a non-existent file new FileInputStream("ghost.txt"); } catch (FileNotFoundException ex) { System.out.println("Checked error: " + ex.getMessage()); } } } Custom Exceptions: Crafting Domain-Specific Errors While Java provides a rich set of built-in exceptions, custom exceptions enable domain-specific error signaling. For example, an e-commerce app might define: // Custom exception class class InvalidInputException extends RuntimeException { public InvalidInputException(String message) { super(message); // Pass the error message to the parent class } } class CustomExceptionDemo { public static void main(String[] args) { try { processInput(""); // Simulate empty input } catch (InvalidInputException ex) { System.out.println("Custom error: " + ex.getMessage()); } } // Method to validate input static void processInput(String input) { if (input.isEmpty()) { throw new InvalidInputException("Input cannot be empty"); } } } Best Practices for Custom Exceptions: Immutable State: Ensure exception objects are immutable to prevent unintended side effects. Rich Context: Include metadata (e.g., timestamps, error codes) to aid debugging. Avoid Overuse: Reserve custom exceptions for scenarios where standard exceptions are insufficient. Advanced Exception Handling Patterns Pattern 1: Exception Translation Wrap lower-level exceptions in higher-level abstractions to avoid leaking implementation details. For instance, convert a SQLException into a DataAccessException in a DAO layer: // Custom exception for wrapping low-level exceptions class CalculationException extends RuntimeException { public CalculationException(String message, Throwable cause) { super(message, cause); // Pass message and cause to the parent class } } class ExceptionTranslationDemo { public static void main(String[] args) { try { calculate(); // Perform calculation } catch (CalculationException ex) { System.out.println("Translated error: " + ex.getMessage()); System.out.println("Root cause: " + ex.getCause().getMessage()); } } // Method to simulate a calculation static void calculate() { try { int result = 10 / 0; // Division by zero } catch (ArithmeticException ex) { // Wrap the low-level exception in a custom exception throw new CalculationException("Calculation failed", ex); } } } Pattern 2: Circuit Breakers In distributed systems, use frameworks like Resilience4j to prevent cascading failures: class SimpleCircuitBreaker { private int failureCount = 0; // Track number of failures private static final int MAX_FAILURES = 2; // Maximum allowed failures public void execute() { // If failures exceed the limit, open the circuit if (failureCount >= MAX_FAILURES) { throw new RuntimeException("Circuit open: Service halted"); } try { // Simulate a failing service throw new RuntimeException("Service error"); } catch (RuntimeException ex) { failureCount++; // Increment failure count System.out.println("Failure #" + failureCount); } } public static void main(String[] args) { SimpleCircuitBreaker cb = new SimpleCircuitBreaker(); for (int i = 0; i < 3; i++) { try { cb.execute(); // Attempt to execute the service } catch (RuntimeException ex) { System.out.println(ex.getMessage()); } } } } Pattern 3: Global Exception Handlers In Spring Boot, use @ControllerAdvice to centralize exception handling: class GlobalHandlerDemo { public static void main(String[] args) { // Set a global exception handler for uncaught exceptions Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> { System.out.println("Global handler caught: " + ex.getMessage()); }); // Simulate an uncaught exception throw new RuntimeException("Unexpected error occurred!"); } } Performance Considerations Exception handling incurs overhead, particularly when stack traces are generated. Optimize with these strategies: class LightweightException extends RuntimeException { @Override public Throwable fillInStackTrace() { return this; // Skip stack trace generation for better performance } } class PerformanceDemo { public static void main(String[] args) { try { throw new LightweightException(); // Throw a lightweight exception } catch (LightweightException ex) { System.out.println("Caught lightweight exception"); } } } Avoid Exceptions for Control Flow: Using exceptions for non-error scenarios (e.g., looping) is inefficient. Lazy Initialization of Stack Traces: Use Throwable constructors that skip stack trace generation (Java 7+): Logging Wisely: Avoid logging the same exception multiple times across layers. Tools and Libraries Lombok: Simplify exception logging with @SneakyThrows. Guava Preconditions: Validate inputs and throw standardized exceptions. ELK Stack (Elasticsearch, Logstash, Kibana): Centralize exception monitoring. Sentry: Real-time error tracking with context-rich reports. Conclusion Exception handling is not an afterthought but a foundational design discipline. By embracing principles like context preservation, strategic logging, and architectural alignment, developers can transform error management from a chore into a competitive advantage. As Java continues to evolve—integrating with cloud platforms, reactive systems, and AI-driven observability tools—exception handling will remain a critical skill for building software that thrives in the face of uncertainty.
06 February 2025 · 8 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support