If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, escape sequences are special characters that are used to represent non-printable and special characters within a string. When you want to include characters that cannot be easily typed or have special meanings, you use escape sequences to represent them.
Escape sequences start with a backslash \
followed by a specific character. Here are some commonly used escape sequences in Java:
\n
: Newline - Inserts a new line at the specified position.\t
: Tab - Inserts a horizontal tab at the specified position.\\
: Backslash - Inserts a backslash character.\"
: Double Quote - Inserts a double quote within a string.\'
: Single Quote - Inserts a single quote within a character literal.\r
: Carriage Return - Moves the cursor to the beginning of the line.\b
: Backspace - Moves the cursor back one character (not commonly used in modern applications).\f
: Form Feed - Advances the cursor to the next page or form.\uXXXX
: Unicode Escape - Represents a Unicode character specified by the four hexadecimal digits (XXXX).Here are some examples of using escape sequences in Java:
javaCopy codepublic class EscapeSequenceExample {
public static void main(String[] args) {
// Newline
System.out.println("Hello,\nWorld!");
// Tab
System.out.println("Name\tAge");
// Backslash
System.out.println("C:\\Users\\username\\Desktop");
// Double Quote
System.out.println("He said, \"Hello!\"");
// Single Quote
char letter = '\'';
System.out.println("This is a " + letter);
// Carriage Return
System.out.println("Hello\rWorld");
// Form Feed
System.out.println("Page 1\fPage 2");
// Unicode Escape
System.out.println("\u00A9 All rights reserved.");
}
}
Output:
vbnetCopy codeHello,
World!
Name Age
C:\Users\username\Desktop
He said, "Hello!"
This is a '
Hello
World
Page 1
Page 2
© All rights reserved.
Escape sequences help in representing special characters and formatting text in various Java applications, especially when working with strings and character literals.
Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.
Comments: 0