Получение странного результата при печати результата сравнения строк
У меня проблема с этой строкой (прокомментировано ниже):
System.out.println("Using == ::"+s3==s4)
который выводит false
.
Однако System.out.println(s3==s4)
выводит true
.
Теперь я не могу понять, почему я получаю этот результат:
public class string {
public static void main(String[] args){
String s3="Shantanu";
String s4=s3;
String s1=new String("java");
String s2=new String("javaDeveloper");
System.out.println("Using Equals Method::"+s1.equals(s2));
System.out.println("Using Equals Method::"+s3.equals(s4));
System.out.println("Using == ::"+s3==s4);//Problem is here in this line
System.out.println(s1+"Directly printing the s2 value which is autocasted from superclass to string subclass ");
System.out.println("Directly printing the s1 value which is autocasted from superclass to string subclass "+s2);
System.out.println(s3);
}
}
Output-Using Equals Method::false
Using Equals Method::true
Using == ::false
java Directly printing the s2 value which is autocasted from superclass to string subclass
Directly printing the s1 value which is autocasted from superclass to string subclass javaDeveloper
Ответы
Ответ 1
Вам не хватает набора скобок:
System.out.println("Using == ::" + (s3==s4));
В вашей версии "Using == ::" + s3
сравнивается с ==
до s4
, который не является тем, что вы хотите.
В общем случае +
имеет более высокий приоритет, чем ==
, поэтому "Using == ::" + s3==s4
оценивается как ("Using == ::" + s3) == s4
.
Ответ 2
Вы используете этот код:
System.out.println("Using == ::"+ s3==s4);
Что оценивается как:
System.out.println( ("Using == ::" + s3) == s4);
Следовательно, вы получаете false как вывод.
Причина в том, что согласно приоритету оператора +
выше ==
в соответствии с этой таблицей Operator Precedence
: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Как и другие ответы, вам нужно использовать скобки, содержащие ваше логическое выражение:
System.out.println("Using == ::" + (s3==s4));
Ответ 3
Строка верна:
"Using == ::"+s3
не равен s4
Вам нужно будет изменить свой код:
"Using == ::"+(s3==s4)
изменить
Выходной код команды:
Using Equals Method::false
Using Equals Method::true
false
javaDirectly printing the s2 value which is autocasted from superclass to string subclass
Directly printing the s1 value which is autocasted from superclass to string subclass javaDeveloper
Shantanu