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
  • 44,383
  • 11
  • 84
  • 103
  • [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
  • 94,125
  • 30
  • 188
  • 241
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,858
  • 6
  • 40
  • 61
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
  • 120,458
  • 37
  • 198
  • 307
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
  • 34,993
  • 17
  • 75
  • 115
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,565
  • 3
  • 24
  • 36