I'm creating a word processor similar to Microsoft Word (but much simpler). I'm having a problem with a dialog box.

When a user presses the 'new document' button, it prompts the user to enter the file name, and when the user does so, he presses ok, and the file name is stored in a variable. That works out fine, the problem is when the user presses cancel! I could think of no way to manipluate what happens when the user presses cancel, (the default action is that the file name is set as null, rather than just leaving it as it was before) so I added some code myself by identifying the length of the string - basically, if the length of the string is 0, then cancel was pressed because there was no input. However, I am getting an error. This is the code:

private void newDocument() {
        String tempFileName = JOptionPane.showInputDialog(null, "Please enter file name", "Please enter file name", JOptionPane.INFORMATION_MESSAGE);
        if (tempFileName.length() == 0) {
            tempFileName = "";

        } else {
            fileName = tempFileName;


If a variable is null, you can't test its length - it hasn't got a length!.
Use var == null

Thanks! :)

This question has already been answered. Start a new discussion instead.