Reputation: 4054
The code:
String s = "\d";
raises an compiler error, illegal escape character. Ok understood!!
But the code:
class Test
{
public static void main(String[] args)
{
String s = args[0];
System.out.println(s);
}
}
does not when invoked with the command java Test \d
or java Test "\d"
. Why??
Infact it even prints: \d
without using the double back-slashes ("\\d").
Aren't the arguments provided via command-line treated as Strings only?
I know it can't raise a compiler error because arguments provided at command-line are after compilation stage but then shouldn't it raise a runtime exception or something??
Or is it that once we have passed through the compilation stage it doesn't matter what the String contains (because the code is converted in bytecode and the whole code structure is altered)? If yes, then can someone please elaborate.
Thnx in advance!!
Upvotes: 1
Views: 209
Reputation: 385590
You don't realise that shell command lines and Java are two different languages. A command line given to a shell is parsed as a shell command. A Java program given to java
is parsed as Java.
You are possibly also confusing strings literals (pieces of code that produce strings) and strings (values consisting of a sequence of characters).
You want the two character string \d
to be stored in variable s
. You need to construct an appropriate string literal in order to do that.
\d
, one can use a cmd (Windows shell) string literal \d
.\d
, one can use a Java string literal "\\d"
.Upvotes: 1
Reputation: 1499880
Aren't the arguments provided via command-line treated as Strings only?
Yes, they're strings. String objects. That's fine.
However, in code, you've got string literals. Those are parsed by the Java compiler to produce String objects at execution time. The escaping is part of the Java language, not part of the String objects.
(Note that some other libraries - particularly regular expressions - may also have their own escaping mechanisms, but fundamentally if you run
java Foo \d
then assuming your shell doesn't do anything funny (which will depend on that shell!) then you end up with a two character string: a backslash followed by a d
.
Upvotes: 1
Reputation: 47608
Doubling backslahes is only a matter of syntax. In Java code, to represent a single backslash within quotes, you must type it twice. However what you are really representing is a single backslash.
When you pass it through the command line, you do not need escaping since it is not Java code.
Upvotes: 2