Jack Evans Jack Evans - 5 months ago 8
Java Question

Arguments in Java function

I'm trying to use another class to return data from another class.
This class will either return a password, or a key, depending on the arguments sent to the class.

This is the function in the class that returns the data:

public static String main(String args[]){
if (!args.equals(null)){
String gen = generatePassword(args[1]);
return gen;
}else{
String gen = generateRandomString();
return gen;
}
}


My error is:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at me.GaryIsASloth.KeyGenerator.main(KeyGenerator.java:34)


With 34 referring to:

if (!args.equals(null)){


The arguments provided will either be "pass", following "true"/"false" which will tell the class whether to include special characters or not.
Or for the key the args will be null.

I had the class working perfectly when I had it working with the key, and then after modification it worked fine with the password too. However I can't get it to work with both, dependant on the arguments. I've tried null check and length check. What can I do?

Answer

When checking for null you cannot check something.equals(null) as equals is a method and it cannot be called on null. Null is not an object. Secondly, elements in the arrays numbered starting from 0 so the first element will be arg[0].

public static String main(String args[]){
        String gen;
        if (args != null){
            gen = generatePassword(args[0]);
        }else{
            gen = generateRandomString();
        }
        return gen;
    }