public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String imie1 = reader.readLine();
String imie2 = reader.readLine();
if (imie1 == imie2)
System.out.println("Imiona są identyczne");
else if(imie1.length() == imie2.length())
System.out.println("Imiona są takiej samej długości");
}
}
Dlaczego if (imie1 == imie2) nie działa?
Dyskutowane
Komentarze (4)
- Popularne
- Najnowsze
- Najstarsze
Musisz się zalogować, aby dodać komentarz
Artur
17 sierpnia 2021, 13:54
https://javastart.pl/baza-wiedzy/efektywne-programowanie/javatraps-001
Oto link gdzie do kursu Java gdzie piszą inaczej? Dlaczego piszą inaczej?
Wklejam przykład z ich strony żeby zaoszczędzić wam czasu
public class Test {
public static void main(String args[]){
String s1 = "Ala";
String s2 = "Ala";
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
String s3 = s1;
String s4 = new String("Ala");
System.out.println(s3==s4);
System.out.println(s3.equals(s4));
}
}
Wynikiem będzie: true true false true.
0
Vexxi
17 sierpnia 2021, 12:15
Aby porownac stringi musisz uzyc metody .equals();
np: string1.equals(string2); - sprawdza czy string 1 rowna sie string 2
+2
Artur
17 sierpnia 2021, 14:01
Ten program działa poprawnie:
public class Main {
public static void main(String[] args) {
String y = "abc";
String x = "abc";
if (y==x)
System.out.println("hello");
}
}
//Sam sprawdziłem
0
Gellert Varga
17 sierpnia 2021, 17:36
Strings are objects.
The equality of objects is not checked with the == operator, but with the equals() method.
The == operator only compares their addressing. Two objects stored at different addresses are guaranteed to != , even if they store the same values. Because their addresses are different.
A further explanation is "String pool".
Strings are put into a "String pool" by the JVM.
String str1 = "abc";
String str2 = "abc"; // since there is already a totally same string in the pool, the JVM does not create a new string object, it just assigns the same address to str2 as it did to str1.
Therefore:
str1 == str2; // true
String str3 = new String("abc"); // the 'new' operator forces a completely new String object to be created. This "abc" is now a new object, with a different address from str1 and str2.
Therefore:
str1 != str3; // true
str1.equals(str3); // true
+1