Escape special characters in java

Java Special Characters

Because strings must be written within quotes, Java will misunderstand this string, and generate an error:

String txt = "We are the so-called "Vikings" from the north."; 

The solution to avoid this problem, is to use the backslash escape character.

The backslash ( \ ) escape character turns special characters into string characters:

Escape character Result Description
\’ Single quote
« Double quote
\\ \ Backslash

The sequence \» inserts a double quote in a string:

Example

String txt = "We are the so-called \"Vikings\" from the north."; 

The sequence \’ inserts a single quote in a string:

Example

The sequence \\ inserts a single backslash in a string:

Example

String txt = "The character \\ is called backslash."; 

Other common escape sequences that are valid in Java are:

Code Result Try it
\n New Line Try it »
\r Carriage Return Try it »
\t Tab Try it »
\b Backspace Try it »
\f Form Feed

Источник

Characters

Most of the time, if you are using a single character value, you will use the primitive char type. For example:

char ch = 'a'; // Unicode for uppercase Greek omega character char uniChar = '\u03A9'; // an array of chars char[] charArray = < 'a', 'b', 'c', 'd', 'e' >;

There are times, however, when you need to use a char as an object—for example, as a method argument where an object is expected. The Java programming language provides a wrapper class that «wraps» the char in a Character object for this purpose. An object of type Character contains a single field, whose type is char . This Character class also offers a number of useful class (that is, static) methods for manipulating characters.

You can create a Character object with the Character constructor:

Character ch = new Character('a');

The Java compiler will also create a Character object for you under some circumstances. For example, if you pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character for you. This feature is called autoboxing—or unboxing, if the conversion goes the other way. For more information on autoboxing and unboxing, see Autoboxing and Unboxing.

Note: The Character class is immutable, so that once it is created, a Character object cannot be changed.

The following table lists some of the most useful methods in the Character class, but is not exhaustive. For a complete listing of all methods in this class (there are more than 50), refer to the java.lang.Character API specification.

Useful Methods in the Character Class

Method Description
boolean isLetter(char ch)
boolean isDigit(char ch)
Determines whether the specified char value is a letter or a digit, respectively.
boolean isWhitespace(char ch) Determines whether the specified char value is white space.
boolean isUpperCase(char ch)
boolean isLowerCase(char ch)
Determines whether the specified char value is uppercase or lowercase, respectively.
char toUpperCase(char ch)
char toLowerCase(char ch)
Returns the uppercase or lowercase form of the specified char value.
toString(char ch) Returns a String object representing the specified character value — that is, a one-character string.

Escape Sequences

A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. The following table shows the Java escape sequences:

Escape Sequences

Escape Sequence Description
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a form feed in the text at this point.
\’ Insert a single quote character in the text at this point.
Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \», on the interior quotes. To print the sentence

System.out.println("She said \"Hello!\" to me.");

Источник

Working with Strings and Special Characters in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Whether you create a String using the constructor or as a string literal, the most important thing to remember is that the entire sequence must be enclosed in quotation marks. This can pose a problem if the string itself must contain quotation marks. That is where character escaping comes in. Besides quotation marks, you can insert several special characters into a string in the same way. We will be looking at character escaping, escape characters, and special characters in this Java programming tutorial.

Character Escaping in Java

In Java, as in many other programming languages, character escaping is accomplished using the “backslash” (\) symbol. In Java, a backslash, combined with a character to be “escaped”, is called a control sequence. For example, \” is a control sequence for displaying quotation marks in a String. The control sequence tells the compiler that the quotation mark should be included as part of the String. Here is some example code that prints my favorite movie to the screen showing how to use escape characters in Java:

public class DoubleQuotesExample < public static void main(String[] args) < String myFavoriteMovie = "My favorite movie is \"Raiders of the Lost Ark\"."; System.out.println(myFavoriteMovie); // Outputs My favorite movie is "Raiders of the Lost Ark". > >

Special Characters in Java

Some characters, like the quotation mark, are part of the Java language; others, like the new line character, are simply a regular letter – the letter n in this case. However, when combined with the backslash symbol, these special characters tell the compiler to treat them differently than it usually would. When the compiler encounters \n in the text, it understands that this is not just a symbol and a letter to display in the console, but rather, a special command to start a new line – equivalent to pressing Enter. For example, this example Java code shows how to use the newline special character \n to to display the lyrics of a song:

public class NewLineExample < public static void main(String[] args) < String lyric I:\My Documents\quarterly reports\Q1.rpt";

Since the compiler does not recognize \ as anything other than a control sequence, it expects the backslash to be followed by a special character to be interpreted in a certain way. However, in this case, \ is followed by ordinary letters. The solution? Exactly the same as before: we just escape the \ character!

public class BackslashExample < public static void main(String[] args) < String reportPath = "I:\\My Documents\\quarterly reports\\Q1.rpt"; System.out.println(reportPath); // Outputs I:\My Documents\quarterly reports\Q1.rpt > >

Here is the full list of special characters in Java:

The code example below shows how to use several of these special characters in Java:

public class SpecialCharactersExample < public static void main(String[] args) < String strWithTabs = "Header1\tHeader2\tHeader3"; System.out.println(strWithTabs); // Outputs Header1 Header2 Header3 String strWithNewLines = "As I walk,\nmy life drifts\nbefore me"; System.out.println(strWithNewLines); /* Outputs: As I walk, my life drifts before me */ String strWithBackslash = "And\\Or"; System.out.println(strWithBackslash); // Outputs And\Or String strWithCarriageReturn = "Carriage\rReturn"; System.out.println(strWithCarriageReturn); /* Outputs: Carriage Return */ String strWithSingleQuote = "Other people\'s money"; System.out.println(strWithSingleQuote); // Outputs Other people's money String strWithDoubleQuotes = "Dwayne \"The Rock\" Johnson"; System.out.println(strWithDoubleQuotes); // Outputs Dwayne "The Rock" Johnson > >

Escaping Unicode Characters in Java

Unicode is a standard character encoding that includes the symbols of practically every written language in the world. All Unicode character codes have the form “u+ “. For example, the copyright symbol (©) is represented by u00A9. To include this character in a Java String, you need to escape it, as seen in the following code example:

public class CopyrightExample < public static void main(String[] args) < System.out.println("\"Star Wars\", \u00A9 1977 All Rights Reserved"); // Outputs "Star Wars", © 1977 All Rights Reserved >>

You can use Unicode to display special characters and text written in a multitude of different languages. Here is a program that provides just a glimpse at what is possible:

public class UnicodeCharactersExample < public static void main(String[] args) < char forwardSlash = '\u002F'; System.out.println(forwardSlash); // Outputs / char questionMark = '\u003F'; System.out.println(questionMark); // Outputs ? char number1 = '\u0031'; System.out.println(number1); // Outputs 1 char tilde = '\u007E'; System.out.println(tilde); // Outputs ~ char dollarSign = '\u0024'; System.out.println(dollarSign); // Outputs $ char lowercaseA = '\u0061'; System.out.println(lowercaseA); // Outputs a char uppercaseA = '\u0041'; System.out.println(uppercaseA); // Outputs A char japaneseYen = '\u00a5'; System.out.println(japaneseYen); // Outputs ¥ char romanAeWithAcuteAccent = '\u01FC'; System.out.println(romanAeWithAcuteAccent); // Outputs Ǽ char greekCapitalAlpha = '\u0391'; System.out.println(greekCapitalAlpha); // Outputs Α char greekCapitalOmega = '\u03A9'; System.out.println(greekCapitalOmega); // Outputs Ω > >

Final Thoughts on Special Characters in Java

In this programming tutorial, we delved into the topic of character escaping and special characters in Java, including the encoding of Unicode characters. Speaking of which, Unicode is a fairly expansive subject. If you are interested in exploring Unicode in more detail, there is plenty of good information to be found in the Oracle Java docs.

Источник

Escape special characters in java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Читайте также:  Php читать большой файл
Оцените статью