static and a simple constructor
im using this class for password checking but when i use a constructor to construct a static array variable, in the program where i use this throws a NullPointerException, but i tried to make a static initializer and initializes that variable everything works fine,,
does it mean that constructors are only for instances? instance data member(fields)?
Code:
public class Password {
private static String[] passwords;
static {
passwords = new String[] {"123", "ABC"};
}
/**
public Password() {
passwords = new String[] {"123", "ABC"};
}
*/
public static boolean isPasswordAuthentic(String password) {
boolean isAuthentic = false;
for (int x = 0; x <= passwords.length - 1; x++) {
if (password.equals(passwords[x])) {
isAuthentic = true;
break;
}
}
return isAuthentic;
}
public static void addNewPassword(String newPassword) {
// UNSUPPORTED
throw new UnsupportedOperationException();
}
public static void deletePassword(String password) {
// UNSUPPORTED
throw new UnsupportedOperationException();
}
}
static and simple constructor answer
Yes a constructor will only run when an instance of a class is created. It sounds like you just called Password.isPasswordAuthentic directly. If so the reason you got the null pointer exception on line
for (int x = 0; x <= passwords.length - 1; x++) {
was that the passwords array was not initialised. Hence it was calling passwords.length on a null object and failing.