问题
I have small code as shown below
public class Testing {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstString = sc.next();
System.out.println("First String : " + firstString);
String secondString = "text\\";
System.out.println("Second String : " + secondString);
}
}
When I provide input as text\\ I get output as
First String : text\\
Second String : text\
Why I am getting two different string when input I provide to first string is same as second string.
Demo at www.ideone.com
回答1:
The double backslash in the console you provide as input on runtime are really two backslashes. You simply wrote two times ASCII character backslash.
The double backslash inside the string literal means only one backslash. Because you can't write a single backslash in the a string literal. Why? Because backslash is a special character that is used to "escape" special characters. Eg: tab, newline, backslash, double quote. As you see, backslash is also one of the character that needs to be escaped. How do you escape? With a backslash. So, escaping a backslash is done by putting it behind a backslash. So this results in two backslashes. This will be compiled into a single backslash.
Why do you have to escape characters? Look at this string: this "is" a string
. If you want to write this as a string literal in Java, you might intentionally think that it would look like this:
String str = "this "is" a string";
As you can see, this won't compile. So escape them like this:
String str = "this \"is\" a string";
Right now, the compiler knows that the "
doesn't close the string but really means character "
, because you escaped it with a backslash.
回答2:
In Strings \
is special character, for example you can use it like \n
to create new line sign. To turn off its special meaning you need to use another \
like \\
. So in your 2nd case \\
will be interpreted as one \
character.
In case when you are reading Strings from outside sources (like streams) Java assume that they are normal characters, because special characters had already been converted to for example tabulators, new line chars, and so on.
回答3:
Java use the \
as an escape character in the second string
EDITED on demand
In the first case, the input take all the typed characters and encapsulate them in a String, so all characters are printed (no evaluation, as they are read, they are printed).
In the second, JVM evaluate the String between
"
, character by character, and the first\
is read has a meta character protecting the second one, so it will not be printed.
回答4:
String internally sequence of char must not be confused with the sequence of char between double quotes specially because backslash has a special meaning: "\n\r\t\\\0" => { (char)10,(char)13,(char)9,'\\',(char)0 }
来源:https://stackoverflow.com/questions/11493006/backslash-behaving-differently