English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 프로그램에서 Java에서 두 문자열을 비교하는 방법을 배울 것입니다.
public class CompareStrings { public static void main(String[] args) { String style = "Bold"; String style2 = "Bold"; if(style == style2) System.out.println("Equal"); else System.out.println("Not Equal"); } }
이 프로그램을 실행할 때, 출력은 다음과 같습니다:
Equal
위 프로그램에서 우리는 두 문자열 style과 style을 가지고 있습니다.2。우리는 단순히 동일성 연산자(==)를 사용하여 두 문자열을 비교합니다. 이 문자열은 값Bold와Bold비교하고 출력합니다Equal。
public class CompareStrings { public static void main(String[] args) { String style = new String("Bold"); String style2 = new String("Bold"); if(style.equals(style2)) System.out.println("Equal"); else System.out.println("Not Equal"); } }
이 프로그램을 실행할 때, 출력은 다음과 같습니다:
Equal
위 프로그램에서 우리는 두 문자열 스타일 style과 style을 가지고 있습니다.2,그들은 모두 같은Bold。
그러나, 우리는 String 생성자를 사용하여 문자열을 생성합니다. Java에서 이 문자열을 비교하려면 equals() 메서드를 사용해야 합니다.
이 문자열을 비교할 때 ==(동일성 연산자)를 사용하지 마세요. 왜냐하면 그들은 문자열의 참조를 비교하기 때문입니다. 즉, 그들은 동일한 객체인지 확인합니다.
그러나, equals() 메서드는 문자열의 값이 같은지 비교합니다. 객체 자체가 아니라.
그렇다면, 같은 연산자를 사용하여 프로그램을 변경하면 다음과 같이 됩니다.불일치,아래 프로그램을 참조하세요。
public class CompareStrings { public static void main(String[] args) { String style = new String("Bold"); String style2 = new String("Bold"); if(style == style2) System.out.println("Equal"); else System.out.println("Not Equal"); } }
이 프로그램을 실행할 때, 출력은 다음과 같습니다:
Not Equal
이것은 Java에서 수행할 수 있는 문자열 비교입니다.
public class CompareStrings { public static void main(String[] args) { String style = new String("Bold"); String style2 = new String("Bold"); boolean result = style.equals("Bold"); // true System.out.println(result); result = style2 == "Bold"; // false System.out.println(result); result = style == style2; // false System.out.println(result); result = "Bold" == "Bold"; // true System.out.println(result); } }
이 프로그램을 실행할 때, 출력은 다음과 같습니다:
true false false true