0

Why does this return true?

String b =  "(5, 5)";
String a =  "(7, 8)" ;
if(a.equals(b));
{

    System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
}

Output:

Somehow "(7, 8)" and "(5, 5)" are the same
Rahul
  • 43,125
  • 11
  • 82
  • 101
  • [Why do java if statement fail when it ends in semicolon?](http://stackoverflow.com/questions/12772221/why-do-java-if-statement-fail-when-it-ends-in-semicolon) – Bernhard Barker Feb 10 '14 at 07:34

5 Answers5

5

Your code is equivalent to:

if(a.equals(b)) { }
{
   System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
}

So the print statement in a block that'll be always executed regardless of the condition, since the body of the if doesn't include that statement.

See the JLS - 14.6. The Empty Statement:

An empty statement does nothing.

EmptyStatement:

; 

Execution of an empty statement always completes normally

Maroun
  • 91,013
  • 29
  • 181
  • 233
4

You have ; after your if statement.

use:

if(a.equals(b)) {
    System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
}

Take a look at this answer.

Community
  • 1
  • 1
BobTheBuilder
  • 18,283
  • 5
  • 37
  • 60
1
if(a.equals(b));<-----

You have an extre ; there and statements ends there.

That's like writing

if(a.equals(b));

and a block here

{

    System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
}

So get rid of that extra ;

Suresh Atta
  • 118,038
  • 37
  • 189
  • 297
0

Your if condition satisfied, but nothing will execute since ; in following.

if(a.equals(b)); // ;  this is equal to if(a.equals(b)){}

Correct this as follows

if(a.equals(b)){
 System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
}    
Ruchira Gayan Ranaweera
  • 33,712
  • 16
  • 72
  • 110
0

Because you typed a ; after the if statement. Then it will be evaluated as if(a.equals(b)){};, which means do nothing.

String b =  "(5, 5)";
String a =  "(7, 8)" ;
if(a.equals(b)); <-- remove this ';'
{
    System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
}
Weibo Li
  • 3,435
  • 2
  • 23
  • 35