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
1

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

5 Comments

Ahh.. language specification.
I was about to post this link!! Edit: @sᴜʀᴇsʜᴀᴛᴛᴀ Read this stackoverflow.com/a/14112532/1673391
Fast and furious......
@GrijeshChauhan That's an useful link.
He went to future in time and stole my link.
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.

1 Comment

It might be helpful to also explain what happens when you put the semi-colon there.
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 ;

4 Comments

a static block here - It is not a static block, AFAIK.
@Ɍ.Ɉ So what you think of it ?? Can you please correct me ?
It is an anonymous block. This is a static block - static { ... }.
@Ɍ.Ɉ I usually refer them static's :). There is a good reason to change it. Thanks.
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);
}    

Comments

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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.