How to Compare Strings in Java

How do I compare strings in Java?

== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they are logically "equal").

Objects.equals() checks for null before calling .equals() so you don't have to (available as of JDK7, also available in Guava).

Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().

// These two have the same value
new String("test").equals("test") // --> true

// ... but they are not the same object
new String("test") == "test" // --> false

// ... neither are these
new String("test") == new String("test") // --> false

// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" // --> true

// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true

// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
Objects.equals(null, null) // --> true

You almost always want to use Objects.equals(). In the rare situation where you know you're dealing with interned strings, you can use ==.

From JLS 3.10.5. String Literals:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Similar examples can also be found in JLS 3.10.5-1.

Other Methods To Consider

String.equalsIgnoreCase() value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see this question.

String.contentEquals() compares the content of the String with the content of any CharSequence (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.

How to Compare a String to Two Other Strings All in the Same Line Using .equals()

You can't use equals to compare with two strings unless you call it twice, like this:

String input = kb.next().toLowerCase(); 
boolean hit = input.equals("y") || input.equals("yes");

You could alternatively use a regex:

boolean hit = input.matches("y(es)?");

Or if you don't mind matching the string "ye" as well as "y" and "yes", you could use startsWith:

boolean hit = "yes".startsWith(input);

Compare two strings with numbers as words

You can use a map to code the Strings and their values. The benefit of this approach is that it has O(1) complexity as oppose to use of an array for instance.

Map<String, Integer> map = Map.of("one", 1, "two", 2, ...);

public int compare(String a, String b) {
return Integer.compare(map.get(a),map.get(b));
}

Full example:

public class Example {

private final static Map<String, Integer> STRING_VALUE =
Map.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5,
"six", 6, "seven", 7, "eight", 8, "nine", 9, "ten", 10);

public static int compare(String a, String b) {
return Integer.compare(STRING_VALUE.get(a),STRING_VALUE.get(b));
}

public static void main(String[] args) {
System.out.println(compare("one", "one"));
System.out.println(compare("one", "three"));
System.out.println(compare("five", "two"));
}
}

Output:

0
-1
1

Another solution is to use an ENUM:

Full Example:

public class Example {

enum Values {
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN;
}
public static int compare(String a, String b) {
Values vA = Values.valueOf(a.toUpperCase());
Values vB = Values.valueOf(b.toUpperCase());
return Integer.compare(vA.compareTo(vB), 0);
}

public static void main(String[] args) {
System.out.println(compare("one", "one"));
System.out.println(compare("one", "three"));
System.out.println(compare("five", "two"));
}
}

Output:

0
-1
1

How to Compare strings in java

First of all, it looks like you are dealing with the wrong variable sc. I think you meant to compare mood.

When dealing with strings, always use .equals(), not ==. == compares the references, which is often unreliable, while .equals() compares the actual values.

It's also good practice to either convert your string to all uppercase or all lower case. I'll use lower case in this example with .toLowerCase(). .equalsIgnoreCase() is also another quick way around any case problems.

I'd also recommend an if-else-statement, not a second if-statement. Your code would look like this:

mood=mood.toLowerCase()

if (mood.equals("happy")) {
System.out.println("test");
}

else if (mood.equals("sad")) {
System.out.println("I am sad");

}

These are all pretty basic java concepts, so I'd recommend reading more thoroughly about some of them. You can check out some of the documentation and/or other questions here:

  • if-else statement
  • Strings
  • Java String.equals versus ==

Comparing two time strings in java

You can do it in that way:

 LocalTime time1 = LocalTime.parse("02:03:45");
LocalTime time2 = LocalTime.parse("10:04:20");

an then call: time1.compareTo(time2)

how to compare two strings visually in java?

First of all, when you declare String variables, you don't have to make a constructor call each time.

String string1 = "0" // that is fine. No need to call constructor.

Then, I advise you to create a collection of all the characters that are supposed to look the same.

Iterate over all the characters of the first input, and check if :

  • each character of the first input is equal to each character of the second input
  • if it is a "look visually the same character", check if second input contains the associated(s) character(s).

According to the data you provided, I suggest you this solution, though it is not the perfect one :

import javafx.util.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

private static List<List<Character>> charactersVisuallyLookingTheSame = new ArrayList<>();

public static void main(String[] args) {
initCharactersThatLookTheSame();

Scanner sc = new Scanner(System.in);
System.out.println("Enter First String:");
String str1 = sc.nextLine();
System.out.println("Enter Second String:");
String str2 = sc.nextLine();
sc.close();
boolean equal = equalsVisually(str1, str2);
System.out.println(equal);
}

private static boolean equalsVisually(String first, String second)
{
// some checks just in case...
if(first == null || second == null)
{
return false;
}
// to be equal visually, they must have the same length.
if(first.length() != second.length())
{
return false;
}

char[] firstAsArray = first.toCharArray();
char[] secondAsArray = second.toCharArray();

for(int i = 0; i < firstAsArray.length; i++)
{
// if it is different
if(firstAsArray[i] != secondAsArray[i])
{
if(!isCharVisuallyLookingTheSame(firstAsArray[i], secondAsArray[i]))
{
return false;
}
}
}
return true;
}

private static boolean isCharVisuallyLookingTheSame(char first, char second)
{
// we check if it looks visually the same
for(List<Character> visuallyTheSameList : charactersVisuallyLookingTheSame)
{
boolean doesFirstStringContainVisualChar = false;
for(Character c1 : visuallyTheSameList)
{
if(first == c1)
{
boolean doesSecondStringCharVisuallyEquals = false;
for(Character c2 : visuallyTheSameList)
{
if((second == c2))
{
return true;
}
}
}
}
}
return false;
}


private static void initCharactersThatLookTheSame()
{
// these lists contain all the characters that look visually the same.
// add in here any list of characters that visually look the same.

List<Character> o = new ArrayList<>();
charactersVisuallyLookingTheSame.add(o);
o.add('0');
o.add('o');
o.add('Q');

List<Character> i = new ArrayList<>();
charactersVisuallyLookingTheSame.add(i);
i.add('1');
i.add('I');
i.add('T');

List<Character> z = new ArrayList<>();
charactersVisuallyLookingTheSame.add(z);
z.add('2');
z.add('Z');

List<Character> S = new ArrayList<>();
charactersVisuallyLookingTheSame.add(S);
S.add('5');
S.add('S');

List<Character> B = new ArrayList<>();
charactersVisuallyLookingTheSame.add(B);
B.add('8');
B.add('B');
}

}


Some outputs :

258 and ZSB


oQI528 and 0oTSZB


I guess that will do the job. don't hesitate to execute it in debug mode if there are any problems. I fast coded this and I could have made mistakes.

But overall, I suggest you to : use regular expressions. It was suggested by another answer and I think that can only be better than this. Nevertheless, regular expressions can be hard to understand...

how to Compare the second part of the text in java?

Get the inputs, split by a space and get the second item in the resulting array to get the last name. Then compare the two using a ternary operator.

Scanner s = new Scanner(System.in);
String firstLastName = s.nextLine().split(" ")[1];
String secondLastName = s.nextLine().split(" ")[1];
String result = firstLastName.equals(secondLastName) ? "ARE Brothers" : "NOT";
System.out.println(result);


Related Topics



Leave a reply



Submit