0

I want to check if a variable is initialized before using it.

        java.io.File yDriveFolder;

        //move files to temp folder 
        for(int i=0; i<filesForDocument.length; i++){
          ...
          yDriveFolder = new java.io.File(yDrivePath + "/");
          ...
        }
        //delete source folder when it is done  
        if(filesForDocument.length> 1){
          if(yDriveFolder != null){
            yDriveFolder.delete();
          }
        }

error: variable yDriveFolder might not have been initialized

How should I check if a variable is initialized before using it?

4
  • In the code snippet you are showing the variable yDriveFolder is not even declared, not to talk about initialized. Commented Jun 12, 2024 at 20:38
  • the compiler will not accept reading an un-initialized local variable (a successfully compiled code will mean that the variable is initialized, no need or reason to check if it is initialized) -- you can initialize it with null (File yDriveFolder = null;) and then just check for null, as already coded Commented Jun 12, 2024 at 21:40
  • BTW, in Java language, assigning a null is considered initialization of a local variable Commented Jun 13, 2024 at 6:08
  • 1
    So you’re looping filesForDocument.length times, assigning yDriveFolder up to filesForDocument.length times but whatever happens to be the last assigned value is the file you want to delete? Is that really your intended logic? Commented Jun 13, 2024 at 9:15

1 Answer 1

1

Write something like java.io.File yDriveFolder = null; Then the compiler is happy.

Sign up to request clarification or add additional context in comments.

1 Comment

That’s not the right wording. The compiler does not “knows you know it is not initialized”. With that change, the variable is initialized. It’s initialized with null. And in the worst case, it’s still containing null after the loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.