Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java have a way of specifying unescaped String literals?

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?

like image 966
shsteimer Avatar asked Mar 08 '09 16:03

shsteimer


People also ask

Does Java support multi line strings?

The good news is that Java 15 has native support for multiline strings via Text Blocks.

Can we use Backticks in Java?

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.

Does Java support string literals?

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.


3 Answers

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.

like image 53
Andrew Hare Avatar answered Sep 29 '22 23:09

Andrew Hare


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 image 34
Otávio Décio Avatar answered Sep 29 '22 23:09

Otávio Décio


Like said, mostly when you want to escape characters is for regexes. In that case use: Pattern.quote()

like image 42
nxadm Avatar answered Sep 29 '22 23:09

nxadm