Search code examples
javastringnullstring-concatenation

Why is "null" treated as string here in the below code and is concatenated to the name of the file?


I have a method to check the operating system type and return a suitable path according to the type of OS. This path is used by another method which accepts this path and saves a file to t hat location. Now if the OS is not Windows, Linux or Mac then the method returns null. The problem is that this null is treated as a string and null gets added to the name of the saved file e.g; nullFile.txt and saves it in the location where the program is stored. What can I do to prevent this from happening?

public static String checkOS() {
    String store = "";
    String OS = System.getProperty("os.name").toLowerCase();
    if(OS.indexOf("win") >= 0){
        store = "C:/";
    } else if(OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ){
        store = "/home/";
    } else  if(OS.indexOf("mac") >= 0){
        store = "/home/";
    } else{
        return null;
    }
    return store;
}

Solution

  • You don't show the code, but you're probably doing

    String filename = checkOS() + "File.txt";
    

    In String concatenation, null values are converted to the string "null", so you have to code an explicit null check.

    String osName = checkOS();
    String fileName;
    if (osName == null)
        // do whatever you need to do
    else
        filename = checkOS() + "File.txt";
    

    As to the option of returning an empty string from checkOS instead of null, that is a possibility but in either case the caller of checkOS is going to need to test the result as I'm sure you want to do something different for that case. A null return is the most generic option.