Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Comparison of String to an element of an Array of Strings does not

  Asked By: Adelisa    Date: Jun 28    Category: Java    Views: 1381

I have an Array of Strings where I am trying to compare the String[2]
element to the String "YN".

I know what the value is of that element is "YN" but when it executes
it does not work. The elements are column values from an oracle
database that I retrieved from a ResultSet.
I tried answerColumns[2].toString() //which didnt work
and I tried to cast it answerColumns[2] which wont compile.
but when I say that they are NOT equal it executes why is that?

try {
while (surveyIter.hasNext()) {
System.out.println("got new row");
q = 0;
ArrayList row = (ArrayList)surveyIter.next();
ListIterator rowIter = row.listIterator();
out.println("<tr bgcolor=\"#F4F4F4\">");

while (rowIter.hasNext()) {
System.out.println("adding column");
System.out.println("Column number is " + q);
if (q == 1) {rowIter.next();}
if (q == 2) {
id = Integer.valueOf(rowIter.next().toString());
out.println("<td align=center><font size=\"2\"
face=\"Lucida sans Unicode\"> " + id + "</font>
System.out.println("Question number " + id);
} //end if

if (q == 3) {rowIter.next();} //end if
if (q == 4) {

String[] answerColumns = ((String[])answerIter.next());

out.println("<td align=center><font size=\"2\"
face=\"Lucida sans Unicode\"> " + rowIter.next().toString() + "
System.out.println(answerColumns[2] + "Type from array");
if (answerColumns[2] == "YN") {
out.println("<FORM ACTION=\"/test/InsertAnswers\"
out.println("Yes <INPUT TYPE=\"RADIO\"
NAME=\"ANSWER\" VALUE=" + answerColumns[0] + " CHECKED>");
out.println(" No <INPUT TYPE=\"RADIO\"
NAME=\"ANSWER\" VALUE=" + answerColumns[3] + ">");
System.out.println("it works");
} // end if
} //end if

} // end 2 while

} // end 1 while

} // end try
catch (Exception e) {
out.println("</center>"); }



3 Answers Found

Answer #1    Answered By: Garai Chalthoum     Answered On: Jun 28

Change the line

if (answerColumns[2] == "YN") {


if ( answerColumns[2].equals( "YN" ) {

with == you are comparing the address value of objects
or the value of primatives.

Answer #2    Answered By: Caitlin Brown     Answered On: Jun 28

String can not be compare  like that.
String has a method name compareTo.
this is the example:

String s1;
String s2;
if(s1.compareTo(s2)==0) {
// this means the value of s1 is equal to value s2

sometimes you also have to use trim before you compare Strings.
such as:


Answer #3    Answered By: Mamie Wallace     Answered On: Jun 28

Object cannot be compared with the '==' operator
Use the equals() method of the String class.
Replace your statement,
if (answerColumns[2] == "YN") {
with this,
if (answerColumns[2].equals("YN")) {