Reputation: 11
// trying to find whether two string match after toUppercase operation
package testapp1;
public class TestApp1
{
public static void main(String[] performing_a_simple_for_loop)
{
String firstName = "John";
char fname[] = {'J','O','H','N'};
System.out.println(firstName.toUpperCase());
String name2;
name2 = firstName.toUpperCase();
if(fname.equals(name2))
{
System.out.println("True");
}
else
{
System.out.println("False");
}
}
}
Upvotes: 1
Views: 47
Reputation: 48258
this is the reason why is always printing false
fname.equals(name2)
you are comparing a String against an array...
that return false because they are not the same data type
imagine if I do:
"1".equals(1)
yes, both are holding somehow the same information, but that is not enough in java to say they are equal...
so what you can do:??? you need to convert one type into the other...
// option 1: char[] -> string
System.out.println(new String(fname).equals(firstName.toUpperCase()));
// option 2: string -> char[]
System.out.println(Arrays.equals(firstName.toUpperCase().toCharArray(), fname));
and as you see, for comparing arrays you may need the Array.equals() method
Upvotes: 1
Reputation: 44834
fname
is an array, so can not be directly compared to a String
You can do
if(new String(fname).equals(name2))
Upvotes: 2