CHAPTER 4 ■ OPERATORS
Listing 4-12 illustrates the comparison of primitives
Listing 4-12. Comparing primitives
int a = 0;
float b = 1.0f;
System.out.println(a > b);
That bit of code prints “false” in the console.
The instanceof operator can be a bit tricky, because a class that extends another class is also an
instance of the parent class. Consider the following small program, implemented in three classes (see
Listing 4-13).
Listing 4-13. instanceof test
package com.apress.javaforabsolutebeginners .examples.instanceofTest;
public class Person {
String firstName;
String lastName;
public Person (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
package com.apress.javaforabsolutebeginners .examples.instanceofTest;
public class Student extends Person {
String schoolName;
public Student (String firstName, String lastName, String schoolName) {
super(firstName, lastName);
this.schoolName = schoolName;
}
}
package com.apress.javaforabsolutebeginners .examples.instanceofTest;
public class InstanceofTest {
public static void main(String[] args) {
Student student = new Student("Sam", "Spade", "Noir U");
System.out.println(student instanceof Student);
System.out.println(student instanceof Person);
}
}