String comparison with logical operator in Java

前端 未结 7 1097
别那么骄傲
别那么骄傲 2020-12-03 23:59

When comparing two strings, I was taught that we shouldn\'t use the logical operator (==). We should use String.equals(String) for the comparison. However, I see that the fo

7条回答
  •  無奈伤痛
    2020-12-04 00:15

    == compares the object references

    You can understand it by observing the output in the following code:

    public class StringComp{
        public static void main(String args[]){
            String s = new String("hello");
            if(s=="hello"){
                    System.out.println("Hello Friend");
            }else{
                    System.out.println("No Hello");
            }
        }
    }
    

    This program would print No hello

    Because in this code, the variable s refers to new String Object which in turn refers to String literal "hello" from the String pool.

提交回复
热议问题