Question

I have a simple program that reads all the files from a given directory into an array. The array is then looped through and the file names listed in a JFrame as individual JLabels.

I am also able to read the file extension using this code:

                String extension = "";
                int i = FileName.lastIndexOf('.');
                if (i > 0) {
                    extension = FileName.substring(i+1);
                }

This works fine, however when I try to use the extension in an if statement like this:

                    if(extension == "java")
                     {
                        System.out.println(FileName);
                     } 
                    else
                    {
                      System.out.println("error");
                    }

all i get is error statements in the console, even though there are several java files in the directory (as can be seen in the results JFrame!)

Can anyone tell me what the problem is? Thanks!

Was it helpful?

Solution

Change to this:

if (extension.equals("java"))

String comparisons using == compares the objects and not the values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top