String comparison is a common programming task and Java provides several way to compare two String i

String comparison is a common programming task and Java provides several way to compare two String in Java. String is a special class in Java, String is immutable and It’s used a lot in every single Java program starting from simple test to enterprise Java application. In this Java String compare tutorial we will see different ways to compare two String in Java and find out how they compare String and when to use equals() or compareTo() for comparison etc.

Here are four examples of comparing String in Java
1) String comparison using equals method
2) String comparison using equalsIgnoreCase method
2) String comparison using compareTo method
4) String comparison using compareToIgnoreCase method

We will see String compare Example using each of this method in example section, before that let's get some theory:

This article is in continuation of my earlier post on String e.g. Difference between String and StringBuffer in Java and How to replace String in java using regular expression etc. If you haven’t read them already you may find them useful and worth reading.


Compare two String using equals method in Java

String comparison example - compare two strings using equalsequals()method compare two Strings for content equality. So if two string contains same letters, in same order and in same case they will be equals by equals() method. equals() method is defined in Object class and String class overrides that for character based comparison. Check 5 tips to override equals()method in Java for more details on equals and its implementation. For example for two Strings "Sony" and "Sony", equals() will return true but for "Sony" and "SONY" it will return false.


Compare String using equalsIgnoreCase method in Java

equalsIgnoreCase is more liberal than equals and compare two strings ignoring there case. So if two String contains same characters and in same order despite of there case e.g. lower case, upper case, Capital case or Camel case they will be equal by equalsIgnoreCase.For example "sony" and "SONY" two Strings will be same by equalsIgnoreCase and it will return true but "Sony" and " Samsung" will not be same and it will return false because they don't contain same characters.


Comparing String using compareTo

compareTo are actual comparison method unlike equals()and equalsIgnoreCase() and tell us whether two Strings are lexicographically equal, precedes or follows each other. if you want to sort Strings lexicographically compareTo() method is used. this is also called natural order of String. returns zero if two Strings are same, less than zero if calling string comes before argument string and greater than zero if calling string comes later than argument string as shown in example below. See things to remember while overriding compareTo method in Java for more detail on compareTo method.

Compare String using compareToIgnoreCase

Similar to compareTo() method with ignoring case like equalsIgnoreCase() and return same values as returned by compareTo during String comparison.


Don't use "==" for String comparison

Many Java programmer makes mistake of using "==" for string comparison. "==" just check if two reference variable are pointing two same object in Java heap and since String is immutable in Java and maintained in String pool two String literal refer same String object which gives sense that "==" can be used to compare string which is incorrect. always use equals() method for equality check and compareTo method for actual string comparison.

Another way of comparing String is writing custom Comparator in Java. write your comparison logic in compare() method and than you can use that logic to compare two strings.

public class StringComparisonExample {

public staticvoid main ( String args []) {

String tv = "Bravia" ;
String television = "Bravia" ;

// String compare example using equals
if (tv. equals (television )) {
System. out. println ( "Both tv and television contains same letters and equal by equals method of String" ) ;
}

// String compare example in java using compareTo
if (tv. compareTo (television ) == 0 ) {
System. out. println ( "Both tv and television are equal using compareTo method of String" ) ;
}

television = "BRAVIA" ;

// Java String comparison example using equalsIgnoreCase
if (tv. equalsIgnoreCase (television )) {
System. out. println ( "tv and television are equal by equalsIgnoreCase method of String" ) ;
}

// String comparison example in java using CompareToIgnoreCase
if (tv. compareToIgnoreCase (television ) == 0 ) {
System. out. println ( "tv and television are same by compareToIgnoreCase of String" ) ;
}

String sony = "Sony" ;
String samsung = "Samsung" ;

// lexicographical comparison of String in Java with ComapreTo
if (sony. compareTo (samsung ) > 0 ) {
System. out. println ( "Sony comes after Samsung in lexicographical order" ) ;
} else if (sony. compareTo (samsung ) < 0 ) {
System. out. println ( "Sony comes before Samsung in lexicographical order" ) ;
}
}

}

Output:
Both tv and television contains same letters and equal by equals method of String
Both tv and television are equal using compareTo method of String
tv and television are equal by equalsIgnoreCase method of String
tv and television are same by compareToIgnoreCase of String
Sony comes after Samsung in lexicographical order


These were some common examples of comparing string in Java. Avoid common mistake of using equality operator “==” for comparing String instead always use equals() method.


Read more: http://javarevisited.blogspot.com/2012/03/how-to-compare-two-string-in-java.html#ixzz2ki5793Sy
### 解决方案 在 Java 中,`java.sql.Timestamp` 和 `java.lang.String` 是两种不同的数据类型。直接比较这两种类型的对象会导致编译错误或运行时异常。为了修复这种无效的比较问题,可以采用以下方法之一: #### 方法一:将 Timestamp 转换为 String 进行比较 如果需要基于字符串形式进行比较,则可以通过调用 `Timestamp.toString()` 将时间戳转换为字符串后再执行比较操作。 ```java import java.sql.Timestamp; public class CompareExample { public static void main(String[] args) { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); String strTime = "2023-10-05 12:00:00"; // Convert Timestamp to String boolean isEqual = timestamp.toString().equals(strTime); System.out.println("Are they equal? " + isEqual); // Output based on equality check } } ``` 这种方法适用于仅需简单匹配的情况[^1]。 #### 方法二:将 String 转换为 Timestamp 后再比较 另一种方式是先将字符串解析为 `Timestamp` 对象,然后再进行比较。这通常通过 `SimpleDateFormat` 或其他日期处理工具完成。 ```java import java.text.ParseException; import java.text.SimpleDateFormat; import java.sql.Timestamp; public class CompareExample { public static void main(String[] args) throws ParseException { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); String strTime = "2023-10-05 12:00:00"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Timestamp parsedTimestamp = new Timestamp(sdf.parse(strTime).getTime()); boolean isEqual = timestamp.equals(parsedTimestamp); System.out.println("Are they equal? " + isEqual); // Output based on equality check } } ``` 此方法更适合于涉及复杂逻辑的时间对比场景[^2]。 #### 方法三:使用 compareTo() 函数实现精确比较 对于更精细的时间顺序判断,推荐利用 `compareTo()` 方法来代替简单的相等性测试。该函数返回负数表示前者小于后者;零意味着两者相同;正数值则表明第一个参数大于第二个参数。 ```java import java.sql.Timestamp; public class CompareExample { public static void main(String[] args){ Timestamp t1 = new Timestamp(1696478400000L); // Example time value Timestamp t2 = Timestamp.valueOf("2023-10-05 12:00:00"); int result = t1.compareTo(t2); if(result < 0){ System.out.println("t1 is before t2."); }else if(result == 0){ System.out.println("t1 equals t2."); }else{ System.out.println("t1 is after t2."); } } } ``` 以上三种策略均可有效解决 `java.sql.Timestamp` 和 `java.lang.String` 的不兼容比较问题[^1]^。 ### 注意事项 当涉及到数据库交互或者外部输入的数据验证时,请务必考虑潜在的安全隐患比如SQL注入等问题,并采取相应的防护措施如预编译语句PreparedStatement等技术手段加以规避.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值