-5

This should be very straightforward but it's got me stumped!

Lets say i have a page: mysite.com/mypage.jsp

When it gets submitted to itself the url is: mysite.com/mypage.jsp?myvalue=blah

I've got the following code which never equates to true, what am i doing wrong?

String myvalue = request.getParameter("myvalue");

if ( myvalue == "blah" ) {
 out.print("<h3>You submitted the page, my value = " + myvalue + "</h3>" );

} else {
  out.print("<h3>Page not submitted yet, my value = " + myvalue + "</h3>" );
}
Scott
  • 1,280
  • 4
  • 20
  • 35

6 Answers6

2

replace if ( myvalue == "blah" ) { to if ( myvalue.equals("blah") ) {

String myvalue = request.getParameter("myvalue");

if ( myvalue.equals("blah" )) {
 out.print("<h3>You submitted the page, my value = " + myvalue + "</h3>" );

} else {
  out.print("<h3>Page not submitted yet, my value = " + myvalue + "</h3>" );
}
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
1

You can use either contentEquals for string.

This link explain you diffrence b/w equal and contentEquals.

String myvalue = request.getParameter("myvalue");

    if ( myvalue.contentEquals("blah" ))
    {
      out.print("<h3>You submitted the page, my value = " + myvalue + "</h3>" );
    } 
    else 
    {
      out.print("<h3>Page not submitted yet, my value = " + myvalue + "</h3>" );
    }
Community
  • 1
  • 1
Prateek
  • 6,785
  • 2
  • 24
  • 37
0

To compare String objects in java use .equals() method instead of "==" operator

Replace the following code

if ( myvalue == "blah" ) 

to

if ( "blah".equals(myvalue)) 

if you want ignore case use equalsIgnoreCase()

if ( "blah".equalsIgnoreCase(myvalue)) 
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

I've got the following code which never equates to true, what am i doing wrong?

You should use equals method instead of == . Try to use null safe equals.

    "blah".equals(myvalue) 
Masudul
  • 21,823
  • 5
  • 43
  • 58
0

Use equals() or equalsIgnoreCase()

myvalue.equalsIgnoreCase("blah")
sasi
  • 4,192
  • 4
  • 28
  • 47
0

As with everyone above, you need to use .equals for string comparisons, otherwise it compares objects, rather than character content.

You should also be aware that when using .equals you should always put the constant on the left, to avoid null pointers.

Terrible:

// because strings are objects, this just compares the 2 objects with each other, 
//and they won't be the same, even if the content is, they are separate instances.
if (myvalue == "blah") 

Bad:

//if you didn't have a myvalue, this would go bang
//(unless you add a null check in as well)
if (myvalue.equals("blah"))

Good:

if ("blah".equals(myvalue)) 
M21B8
  • 1,867
  • 10
  • 20