Tuesday, July 2, 2013

Compare Strings in Java

Example of Comparing Strings in Java:

package javaex_cmpstring;

/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaEx_CmpString {

String s1 = new String("java-buddy");
String s2 = new String("java-buddy");
String s3 = "java-buddy";
String s4 = "java-buddy";
String s5 = "java-" + "buddy";
//s3, s4, and s5 will reference to the same object of "java-buddy"

public static void main(String[] args) {
new JavaEx_CmpString().CmpString();
}

private void CmpString(){
System.out.println("s1==s2: " + String.valueOf(s1==s2));
System.out.println("s3==s4: " + String.valueOf(s3==s4));
System.out.println("s1==s3: " + String.valueOf(s1==s3));
System.out.println("s3==s5: " + String.valueOf(s3==s5));

System.out.println("s1.equals(s2): " + s1.equals(s2));
System.out.println("s3.equals(s4): " + s3.equals(s4));
System.out.println("s1.equals(s3): " + s1.equals(s3));
System.out.println("s3.equals(s5): " + s3.equals(s5));

}
}

Compare Strings in Java
Compare Strings in Java


No comments:

Post a Comment