overexchange
overexchange

Reputation: 1

Query on backslash character

Below is the line that builds the path of a directory in java.

Here, File.separator is "\" on windows and "/" on Unix.

String path = System.getProperty("user.home") + File.separator + "workspace" + 
                                              File.separator + "JavaCode";

If i hardcode the path, it should look as shown below:

File path = new File("C:\\users\\david\\workspace\\JavaCode");

My question:

Why do we mention \\ in second case?

Upvotes: 1

Views: 87

Answers (2)

fge
fge

Reputation: 121820

This is because of how string literals are defined in Java. A backslash is used for some escape sequences (such as "\n", "\r" and others), therefore a literal backslash is also an escape sequence ("\\").

Back to your code however, don't bother, use java.nio.file instead:

final Path path = Paths.get(System.getProperty("user.home"), "workspace",
    "JavaCode");

Works for every OS the JVM (7+) runs on.

It will correctly return a Path for "C:\\users\\david\\workspace\\JavaCode" on your machine the same way it returns one for "/home/fge/workspace/JavaCode" on mine.

Upvotes: 2

Scott Hunter
Scott Hunter

Reputation: 49896

Because, with a string, \ is an escape character: it says to interpret the following character in a special way (which is why \n isn't an n). In your case, you want \ itself to be interpretted specailly by not treating it special, so you need 2 of them: the first says "treat the next character special", the next gets treated specially for a \.

Upvotes: 2

Related Questions