Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Function does not return what I expected

Here's the code:

import java.util.*;

public class HelloWorld
{

public static void main(String[] args)
{
    String string1 = "randomString1";                       
    System.out.print(f(string1));
}

public static int f(String string)
{
    try { 
        String string2 = "randomString2";

        if(string.equals(string2) == true);
            return 0;
    }
    catch(Exception e){
        e.printStackTrace();
    }

    return 1;
}

}//end of class

Now, the output of this program is

0

But I expected it to be:

1

Because what I wanted the f function to do was to return 0 if the strings were the same and 1 if they weren't.

So, there's definitely something I know wrong here, and I'm guessing it has something to do with the equals method.

like image 496
George Cernat Avatar asked Jan 05 '23 04:01

George Cernat


2 Answers

this is the problem:

if(string.equals(string2) == true);
----------------------------------^

you'll need remove the semi-colon else, it is pretty much an expression on its own doing nothing:

if(string.equals(string2) == true) return 0;
like image 140
Ousmane D. Avatar answered Jan 06 '23 19:01

Ousmane D.


if(string.equals(string2) == true); you have a semicolon there which does not belong. Honestly you don't even need the == true part as well.

like image 41
Idos Avatar answered Jan 06 '23 17:01

Idos