• Post Reply Bookmark Topic Watch Topic
  • New Topic

Strings n Scriplet  RSS feed

 
Rekha
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a String object str, which holds a value �Test�
in my Java program I m checking a condition where in if (str==�Test�) then a set Of statements would execute otherwise another set will execute. This is working fine.

But if I write the same code as a scriplet in JSP always the else block is getting executed even if the expression is true. But if I use the String method equals (str.equals(�Test�)) then it is
Working fine.

//This piece of code is not working properly

<%
int flag=0;
System.out.println(request.getParameter("Submit"));
String str=request.getParameter("Submit");
System.out.println(str);
if(str=="Yes") {
flag=1;
}
else {
flag=0;
}
%>
<% if(flag==1) {
%>
<jsp:forward page="yes.jsp"/>
<% } else if(flag==0) { %>
<jsp:forward page="No.jsp"/>
<% }%>

//This piece of code is working properly, the only change is, I used the String method 'equals'

<%
int flag=0;
System.out.println(request.getParameter("Submit"));
String str=request.getParameter("Submit");
System.out.println(str);
if(str.equals("Yes")) {
flag=1;
}
else {
flag=0;
}
%>
<% if(flag==1) {
%>
<jsp:forward page="yes.jsp"/>
<% } else if(flag==0) { %>
<jsp:forward page="No.jsp"/>
<% }%>

What could be the problem, can anyone help me out of this confusion ??
 
Dave Salter
Ranch Hand
Posts: 293
Java Mac OS X Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to compare two strings with the .equals() method rather than ==.

== will check if two objects are equal. You may have two different objects that have the same string value. In that situation, == and .equals() will give different values.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66156
146
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Rajesh",

There aren't may rules that have been put into place here on the Ranch, but one that we take very seriously regards the use of proper names. Please take a look at the JavaRanch Naming Policy and adjust your display name to match it.

In particular, your display name must be a first and a last name separated by a space character, and must not be obviously fictitious.

Thanks!
bear
Forum Bartender
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!