8

I want to check the value of a char to see if it is double quote or not in Java. How can I do it?

Goran Jovic
  • 9,418
  • 3
  • 43
  • 75
Mehdi Ijadnazar
  • 4,532
  • 4
  • 35
  • 35

4 Answers4

13
if (myChar == '"') { // single quote, then double quote, then single quote
    System.out.println("It's a double quote");
}

If you want to compare a String with another one, and test if the other string only contains the double quote char, then you must escape the double quote with a \ :

if ("\"".equals(myString)) {
    System.out.println("myString only contains a double quote char");
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
7

If you are dealing with a char then simply do this:

 c == '"';

If c is equal to the double quote the expression will evaluate to true.

So, you can do something like this:

if(c == '"'){
  //it is equal
}else{
  //it is not
}

On the other hand, if you don't have a char variable, but a String object instead, you have to use equals method and the escape character \ like this:

if(c.equals("\"")){
  //it is equal
}else{
  //it is not
}
Goran Jovic
  • 9,418
  • 3
  • 43
  • 75
5

For checking double quote is present in a string, following code can be used. Double quote have 3 different possible ascii values.

if(testString.indexOf(8220)>-1 || testString.indexOf(8221)>-1 ||
     testString.indexOf(34)>-1)
   return true;
else 
   return false; 
kleopatra
  • 51,061
  • 28
  • 99
  • 211
Sreejesh.K.R.
  • 73
  • 1
  • 9
2

In my case what I do is, if you want to compare, for example, a server response that should be "OK", then:

if (serverResponse.equals("\"OK\"")) {
...
}
noloman
  • 11,411
  • 20
  • 82
  • 129