0

I'm wondering why it doesn't work, and why I cant't use the CHAR data type for variables a and b. The point is, how to compare the first and the last digits of number (pr) accordingly such way.

String  a, b;
for (int i=100; i<1000;i++) {
    for (int j=100; j<1000;j++) {
        pr=j*i;
        a = String.valueOf(pr).substring(0, 1);
        b= String.valueOf(pr).substring(4, 5);

        if ((a==b) )  {
            System.out.println(pr);
        }
    }
} 
Mat
  • 195,986
  • 40
  • 382
  • 396
Leo
  • 1,719
  • 5
  • 20
  • 41

3 Answers3

3

use equals functions
a.equals(b)

If you want to ignore case then use
a.equalsIgnoreCase(b)

asifsid88
  • 4,511
  • 19
  • 30
1

This is not JavaScript to use == for String comparison.

Go for equals method

LGAP
  • 2,245
  • 16
  • 49
  • 71
1

In Java, operator == compares object identities, so if there are two objects of type String with the same content, == will return false for them:

String x = new String ("foo");
String y = new String ("bar");
if (x == y)
    System.out.println ("Equal");
else
    System.out.println ("Now equal"); // This will be printed

In order to compare String object by content, not by identity, you need to use equals() method like this:

if (x.equals (y))
    System.out.println ("Equal"); // This will be printed
else
    System.out.println ("Now equal");

Note, that if x is null, then x.equals (y) will throw NullPointerException while x == y will return false if y is not null and true if y is null. To prevent NullPointerException you need to do something like this:

if (x == null && y == null || x != null && x.equals (y))
    System.out.println ("Equal"); // This will be printed
else
    System.out.println ("Now equal");
Mikhail Vladimirov
  • 13,154
  • 1
  • 34
  • 38