Mittwoch, 17. Oktober 2007

Comparing a Float to another Float is not working

Recently I changed my code, so now I am not anymore working with floats, but with Floats.

Somewhere in my code, I used to compare the float values with the "==" Operator. But now this won't work anymore.

Float is not the same as a float. Float is a Wrapper for floats. Because of this, you should compare two Float values with the compareTo method. Using the "==" Operator, you are comparing the Float Object and not the value.

Check out this code:

 

public class CompareFloatsExample {

Float f = new Float(20);

Float f1 = new Float(20);

public CompareFloatsExample(){
System.out.println(new Float(20) == new Float(20));
if (f == f1){
printEqual();
}
else {
printNotEqual();
}
if (f.compareTo(f1) == 0){
printEqual();
}
else {
printNotEqual();
}
}
public void printEqual(){
System.out.println("the value of f ("+f+") is equal to the value of f1("+f1+")");
}
public void printNotEqual(){
System.out.println("the value of f ("+f+") is not equal to the value of f1("+f1+")");
}
/**
* @param args
*/
public static void main(String[] args) {
new CompareFloatsExample();

}

}







Keine Kommentare: