In C#, if you want a String to be taken literally, i.e. ignore escape characters, you can use:
string myString = @"sadasd/asdaljsdl";
However there is no equivalent in Java. Is there any reason Java has not included something similar?
Edit:
After reviewing some answers and thinking about it, what I'm really asking is:
Is there any compelling argument against adding this syntax to Java? Some negative to it, that I'm just not seeing?
The good news is that Java 15 has native support for multiline strings via Text Blocks.
The ` backtick looks like ' (a single quote) and " (a double quote), which have been used as delimiters for character and string literals. The ` backtick will help Java programmers to easily see it as a delimiter for raw strings. A raw string literal uses ` as a delimiter.
A string literal in Java is basically a sequence of characters from the source character set used by Java programmers to populate string objects or to display text to a user. These characters could be anything like letters, numbers or symbols which are enclosed within two quotation marks.
Java has always struck me as a minimalist language - I would imagine that since verbatim strings are not a necessity (like properties for instance) they were not included.
For instance in C# there are many quick ways to do thing like properties:
public int Foo { get; set; }
and verbatim strings:
String bar = @"some
string";
Java tends to avoid as much syntax-sugar as possible. If you want getters and setters for a field you must do this:
private int foo;
public int getFoo() { return this.foo; }
public int setFoo(int foo) { this.foo = foo; }
and strings must be escaped:
String bar = "some\nstring";
I think it is because in a lot of ways C# and Java have different design goals. C# is rapidly developed with many features being constantly added but most of which tend to be syntax sugar. Java on the other hand is about simplicity and ease of understanding. A lot of the reasons that Java was created in the first place were reactions against C++'s complexity of syntax.
I find it funny "why" questions. C# is a newer language, and tries to improve in what is seen as shortcomings in other languages such as Java. The simple reason for the "why" question is - the Java standard does not define the @ operator such as in C#.
Like said, mostly when you want to escape characters is for regexes. In that case use: Pattern.quote()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With