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 executesit does not work. The elements are column values from an oracledatabase that I retrieved from a ResultSet.I tried answerColumns[2].toString() //which didnt workand 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");++q;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></td>");System.out.println("Question number " + id);} //end ifif (q == 3) {rowIter.next();} //end ifif (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\"METHOD=\"POST\">");out.println("Yes <INPUT TYPE=\"RADIO\"NAME=\"ANSWER\" VALUE=" + answerColumns[0] + " CHECKED>");out.println(" No <INPUT TYPE=\"RADIO\"NAME=\"ANSWER\" VALUE=" + answerColumns[3] + ">");out.println("</FORM>");out.println("</font></td>");out.println("</tr>");System.out.println("it works");} // end ifbreak;} //end if} // end 2 while} // end 1 while} // end trycatch (Exception e) {out.println("</table>");out.println("</center>"); }
Change the lineif (answerColumns[2] == "YN") {toif ( answerColumns[2].equals( "YN" ) {with == you are comparing the address value of objectsor the value of primatives.
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:s1.trim();s2.trim();
Object cannot be compared with the '==' operatorUse the equals() method of the String class.Replace your statement,if (answerColumns[2] == "YN") {with this,if (answerColumns[2].equals("YN")) {