How to compile and run a simple Java program relying on dependencies

As you know, compiling or running programmes relying on dependencies without build tools is a headache. I am an old-school guy who loves to test and run any program from the terminal. The purpose is to test an idea quickly without creating a project with a complex directory structure, such as a Maven-based project. In this post, we present to our audience how to compile and run a simple Java program that requires dependencies using the terminal, without relying on build tools such as Gradle or Maven.

How to compile and run a simple Java program

Let’s take a simple Java program below.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World! I am a newbie Java programmer!");
    }
}

Then, fire the following commands from the terminal to compile and run this simple program. The javac command will generate the source file HelloWorld.java to the binary one HelloWorld.class. When using the java command, the following argument is the class name which is HelloWorld for this example.

KWMGWJ2047 :: ~/Documents/java-test-dbconnection » javac HelloWorld.java
KWMGWJ2047 :: ~/Documents/java-test-dbconnection »
KWMGWJ2047 :: ~/Documents/java-test-dbconnection »
KWMGWJ2047 :: ~/Documents/java-test-dbconnection »
KWMGWJ2047 :: ~/Documents/java-test-dbconnection » java HelloWorld
Hello World! I am a newbie Java programmer!
KWMGWJ2047 :: ~/Documents/java-test-dbconnection » java -cp . HelloWorld
Hello World! I am a newbie Java programmer!

It’s easy peasy, lemonsqueezy! We can run the program without having -cp .  for this case.

If the Java program makes use of dependencies

To get a bit deeper level in the compilation, we take a more complex example to check and list out all databases hosted in a MySQL database server.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
// https://stackoverflow.com/a/55628316/865603
public class TestDbConnection {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:8889"; // pointing to no database.
        String username = "root";
        String password = "root";
        
        try {
            System.out.println("Connecting to server...");
        
            // load and register JDBC driver for MySQL
            Class.forName("com.mysql.cj.jdbc.Driver"); 

            Connection connection = DriverManager.getConnection(url, username, password);

            System.out.println("Server connected!");
            Statement stmt = null;
            ResultSet resultset = null;

            try {
                stmt = connection.createStatement();
                resultset = stmt.executeQuery("SHOW DATABASES;");

                if (stmt.execute("SHOW DATABASES;")) {
                    resultset = stmt.getResultSet();
                }

                while (resultset.next()) {
                    System.out.println(resultset.getString("Database"));
                }
            } catch (SQLException ex){
                // handle any errors
                ex.printStackTrace();
            } finally {
                // release resources
                if (resultset != null) {
                    try {
                        resultset.close();
                    } catch (SQLException sqlEx) { }
                    resultset = null;
                }

                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (SQLException sqlEx) { }
                    stmt = null;
                }

                if (connection != null) {
                    connection.close();
                }
            }
        } catch (SQLException e) {
            System.out.println("Cannot connect the server due to the error: " + e.toString());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Notes: Update the parameters of your database server accordingly if you want to test this program on your machine.

Getting you a closer look at the line Class.forName("com.mysql.cj.jdbc.Driver"), it is aimed to tell the JVM to load the driver for accessing the MySQL database which is not one of the core Java libraries. Therefore, we need to specify the location of the library when running the program.

java -cp .:/Users/tnguyen/.m2/repository/com/mysql/mysql-connector-j/8.0.33/mysql-connector-j-8.0.33.jar TestDbConnection
Connecting to server...
Server connected!
information_schema
jummp-biomodels
mysql
performance_schema
sys

If we use the relative path for the library location, the command syntax is slightly different. After the double colon, it requires the dot (.) before the path.

java -cp .:./repository/com/mysql/mysql-connector-j/8.0.33/mysql-connector-j-8.0.33.jar TestDbConnection
Connecting to server...
Server connected!
information_schema
jummp-biomodels
mysql
performance_schema
sys

If you use the same approach explained in the first section, you are likely to see errors such as java.lang.ClassNotFoundException.

Connecting to server...
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
    at java.net.URLClassLoader.findClass(URLClassLoader.java:387)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at TestDbConnection.main(TestDbConnection.java:17)

 

Nguyen Vu Ngoc Tung

I love making new professional acquaintances. Don't hesitate to contact me via nguyenvungoctung@gmail.com if you want to talk about information technology, education, and research on complex networks analysis (i.e., metabolic networks analysis), data analysis, and applications of graph theory. Specialties: researching and proposing innovative business approaches to organizations, evaluating and consulting about usability engineering, training and employee development, web technologies, software architecture.

https://www.itersdesktop.com/author/nvntung/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.