views:

251

answers:

3

This code is compile fine, but whenever I try to run, it gives an error says NoClassDefFound. What is the possible reason and solution, please explain.

package myPack;

    public class PasswordVerification
    {
    public boolean verify(String usrId, String pass)
    {
    if(usrId.equals("pranjut")&&pass.equals("password"))
    {
    return true;
    }else
    {
    return false;
    }
    }
    public static void main(String [] main)
    {
    PasswordVerification vp=new PasswordVerification();
    System.out.println(vp.verify("pranjut","password"));
    }

    }
+1  A: 

Are you sure you're calling with the correct package name prefix (i.e "java myPack.PasswordVerification")?

Also, there are some improvements you can make-

  • Testing a string variable, better to test the constant against the variable- e.g. if ("prajnut".equals(userId) rather than if (userId.equals), as the first form is immune to NullPtrExceptions if you happen to pass in an empty string.
  • you can simplify by removing the "else" clause -you really only need 1 line

    return "prajnut".equals(id)&& "password".equals(pass):

Steve B.
ya I am quite sure
Cuss
A: 

Be sure that you're at the root project.

if you type "dir" ( windows) or "ls" other Unix-like os, you should see a directory name "myPack".

then type java myPack.PasswordVerification

here some suggestion to code better and respect the Java coding conventions

package myPack;

public class PasswordVerification{


    public boolean verify(String usrId, String pass){
        if("pranjut".equals(usrId) && "password".equals(pass)){
            return true;
        }
        return false;

    }

    public static void main(String[] main){
       PasswordVerification vp=new PasswordVerification();
       System.out.println(vp.verify("pranjut","password"));
    }

}
Nettogrof
Actually I compiled the code like this javac -d \newfolder\classes PassworedVerification.java, then i go to the director c:\newfolder\classes and then i typed java myPack.PasswordVerification....but it throws NOClassDefFound error.
Cuss
like your package is "myPack" you need a directory named "myPack" and place your .class file in it.
Nettogrof
+1  A: 

Make sure you are in the directory that contains the myPack folder. You should not be within the myPack folder. I just tried it on my linux machine and it looks like it automatically included the working folder in the classpath, but only if the CLASSPATH environment variable is NOT set. If it is set, then you should either add the current folder to it, or specify the classpath on the command line as follows:

java -cp . myPack.PasswordVerification
digitaljoel