Java - function does not return what I expected

Here is 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

0

But I expected it to be:

1

Because I wanted the function fto return 0if the strings were the same and 1if they were not.

So, there is definitely something wrong I know, and I assume this has something to do with the method equals.

+4
source share
6 answers

This is problem:

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

you will need to remove the second colon, it is rather an expression in itself:

if(string.equals(string2) == true) return 0;
+4
source

if(string.equals(string2) == true);you have a semicolon that does not belong. Honestly, you don’t even need a part == true.

+2

- if:

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

, , , , , return 0 , 0, 1

, :

if (string.equals(string2) == true){
   //do nothing
}
//pass to the next statement
return 0;

, :

if (string.equals(string2)){
   return 0;
}
+1

...

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

(;) if , ,

return 0; 

0

, .

...

if(string.equals(string2))
    return 0;

. .

+1

if semilocon. :

if(string.equals(string2)) {
     return 0;
}
+1

.

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

    return (!TextUtils.isEmpty(string) && string.equals(string2)) ? 0 : 1;
}

try-catch, TextUtils null .

0
source

Source: https://habr.com/ru/post/1674748/


All Articles