Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 938

How to add double quotes to a String in Java

$
0
0

You may come across a scenario when you would want to add double quotes to a String, but Java uses double quotes while initializing a String so it won't recognize that double quotes should be added with the String.

You should have guessed what needed to be done in this case. Yes you need escape character "\" to escape quotes. So let's see an example.

Example code


public class SetQuote {

public static void main(String[] args) {
// escaping the double quotes as quotes are
// needed with in the String
String value = "\"Ram\"";
System.out.println("Value - " + value );
}
}

Output


Value - "Ram"

Let's take another example. You have got a String and you want to enclose part of it in double quotes.

As example in XML you are reading first line has no double quotes.

You got it as

<?xml version=1.0 encoding=UTF-8?>

but it should be

<?xml version="1.0" encoding="UTF-8"?>

That can be done by using replace method of the String and escaping double quotes.


public class SetQuote {
public static void main(String[] args) {
SetQuote setQuote = new SetQuote();
//String value = "\"Ram\"";
//System.out.println("Value - " + value );
setQuote.replaceQuote();
}

public void replaceQuote(){
String xmlString = "<?xml version=1.0 encoding=UTF-8?>";
xmlString = xmlString.replace("1.0", "\"1.0\"").replace("UTF-8", "\"UTF-8\"");
System.out.println("xmlString " + xmlString);
}
}

Output

xmlString - <?xml version="1.0" encoding="UTF-8"?>

That's all for this topic How to add double quotes to a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Count number of words in a String
  2. Count total number of times each character appears in a String
  3. How to sort arraylist of custom objects in Java
  4. How to Sort elements in different order in TreeSet using Comparator
  5. How to read file from the last line in Java

You may also like -

>>>Go to Java Programs page


Viewing all articles
Browse latest Browse all 938

Trending Articles