Welcome back to Java Code Online. The character escape sequence in Java is highly useful when dealing with Strings. These escape sequence help in formatting the output as required. This gives the developer a greater control over the text and the output.
For example suppose that you need to print a String "Hello, I am Learning Java". Then the code for this will be:-
String str = "Hello, I am Learning Java";
Now suppose that you want to enclose Java in double quotes, like you want the output to be something like:-
Hello, I am Learning "Java"
For this you need to place double quotes withing the String statement. But oops, there is a problem, if you put double quotes in a String statement, then it will break the String. I mean, if you say that:
String str = "Hello, I am Learning "Java"";
Now this will create blunder as in Java the declaration of a String is done in double quotes, so Java will assume that the statement starting from the first double quote is the starting point of the String, and the second double quote will close the String. But this approach will leave the word "Java" outside the String declaration.
Java comes with a solution to that, here the Character Escape Sequence of Java comes to rescue. The escape sequence allows you to embed special characters like double quotes, line feed, carriage return, tab, etc. into the same String. The above example is corrected as follows:-
String str = "Hello, I am Learning \"Java\"";
Now this is the correct way as per Java. What Java sees is that anything after the "\" symbol is to be placed as it is, and is a part of the whole String overall. Though the symbol "\" has different implications with regard to other escape sequences, like "\n" inserts a new line, etc.
The Character escape Sequence in Java is shown below:-
Escape Sequence ------------Purpose
\ddd ------------ Octal character (ddd)
\uxxxx ------------ Hexadecimal UNICODE character (xxxx)
\’ ------------ Single quote
\” ------------ Double quote
\\ ------------ Backslash
\r ------------ Carriage return
\n ------------ New line (also known as line feed)
\f ------------ Form feed
\t ------------ Tab
\b ------------ Backspace
I hope the article was helpful in understanding the Character Escape Sequence in Java. If you liked the article then do leave a comment. For more info on Java, keep buzzing Java Code Online.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.