1

i am trying to run this java & mysql program, but when i compile, it is not showing any errors.

But when i run the code, it is showing some exceptions..

What might be the error?

code:Version.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

class Version
{
    public static void main(String args[]) 
    {
        Connection con = null;
        Statement st = null;
        String cs = "jdbc:mysql://localhost:3306/google";
        String user = "root";
        String password = "root";
        try {
            con = DriverManager.getConnection(cs, user, password);
            st = con.createStatement();
            String query = "SELECT * FROM user";
            st.executeUpdate(query);
            } 
            catch (SQLException ex) 
            {
            Logger lgr = Logger.getLogger(Version.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
            finally
            {
            try 
            {
            if (st != null) 
            {
            st.close();
            }
            if (con != null) {
            con.close();
            }
            } catch (SQLException ex) 
            {
                Logger lgr = Logger.getLogger(Version.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
    }
}

When i run the code, i am getting this error message

Error Message

Exception in thread "main" java.lang.NoClassDefFoundError: Version
Caused by: java.lang.ClassNotFoundException: Version
        at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
Could not find the main class: Version.  Program will exit.
MintY
  • 603
  • 5
  • 11
  • 23

1 Answers1

3

The class needs to be declared as public

public class Version{
   //rest of code
}

By default classes are package-private as mentioned in Oracles Java Tutorials:

If a class has no modifier (the default, also known as package-private), it is visible only within its own package.

When the program attempts to run the Version class cannot be found because it is not publicly accessible.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189