Loading JDBC Driver — Class.forName vs Service Loader
Fast recall
Quick revision
Core answer
Whether you know modern JDBC auto-registers drivers and Class.forName is legacy.
Still writing Class.forName(...) and thinking it's required.
Explain the META-INF/services/java.sql.Driver SPI auto-discovery mechanism.
Interview-ready guide
Interview answer
For example, with a current PostgreSQL driver on the classpath, DriverManager.getConnection("jdbc:postgresql://localhost/shop", user, password) can find the provider without Class.forName. A legacy driver might require Class.forName("vendor.Driver") before getConnection. A malformed MySQL URL is not accepted by a PostgreSQL driver even when both are registered.
Loading JDBC Driver — Class.forName vs Service Loader
Direct Answer
JDBC 4 drivers normally register through the Java service-provider mechanism when their JAR is available to the relevant class loader. Application code can then call DriverManager.getConnection or, preferably in managed applications, obtain a connection from DataSource. Class.forName was commonly required by older drivers and can still be useful in unusual class-loader/plugin environments.
Code Example
// Just add the driver dependency (e.g. mysql-connector-j) to the build.
// No Class.forName needed — SPI auto-registers the driver.
String url = "jdbc:mysql://localhost:3306/shop";
try (Connection con = DriverManager.getConnection(url, "user", "pass")) {
System.out.println("connected: " + con.getCatalog());
}
// Legacy (only for very old drivers):
// Class.forName("com.mysql.cj.jdbc.Driver");
The driver's META-INF/services/java.sql.Driver entry lets DriverManager find it automatically.
Common Mistakes & Pitfalls
- Still writing
Class.forName: unnecessary since JDBC 4.0 with modern drivers. - No driver on the classpath:
No suitable driver found— add the dependency. - Wrong driver class name: only matters if you use legacy loading.
- Assuming load = connect: registering a driver doesn't open a connection;
getConnectiondoes.
Check your understanding
Answer these without looking back at the article.
- What is JDBC and why does it exist? It provides a standard Java API for connecting to relational databases, executing SQL, and processing results without vendor-specific code.
- What is JDBC and what is its role in Java?
- What are the main components of the JDBC API?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.