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
  • 202,337
  • 40
  • 393
  • 406
Leo
  • 1,787
  • 5
  • 21
  • 43

3 Answers3

3

use equals functions
a.equals(b)

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

asifsid88
  • 4,631
  • 20
  • 30
  • It is not clear why case matters for numerals? – merlin2011 Feb 20 '13 at 06:20
  • 1
    @merlin2011 It's about Objects, not numerals http://stackoverflow.com/questions/7311451/difference-between-equals-and-instanceof – MrLore Feb 20 '13 at 06:21
  • as he mentioned its a string.. so just to give him idea that something of ignoring case is also possible.. so in future it will help him – asifsid88 Feb 20 '13 at 06:21
1

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

Go for equals method

LGAP
  • 2,365
  • 17
  • 50
  • 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,572
  • 1
  • 38
  • 40