0
public class tut4 {
public static void main(String[] args) {
    int num1 = 1234;
    int num2 = 1234;
    String str_num1 = String.valueOf(num1);
    String str_num2 = String.valueOf(num2);
    System.out.println(str_num1 == str_num2);

}

}

I am comparing two string having integral value and it return false even if both the variable have same value so pls tell me where I have done mistake in code.

3 Answers3

0

For comparing 2 strings , you have to use String1.equals(String2)

Satyam Shankar
  • 250
  • 2
  • 12
0

== 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.

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

Example:

Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
Objects.equals(null, null) // --> true
Julian
  • 86
  • 1
  • 8
0

To answer your question, simply replace the == with .equals()

System.out.println(str_num1.equals(str_num2));

When you use == operator, you are comparing the object references whereas equals() method runs the overriden String equals method which compares the actual String characters for equality.