Check Instance of Double Class
In this step, we will explore the Double class in Java and learn how to check if an object is an instance of this class. In Java, primitive data types like double have corresponding wrapper classes, such as Double. The Double class provides useful methods for working with double-precision floating-point numbers.
First, let's create a new Java file named DoubleCheck.java in your ~/project directory. You can do this using the WebIDE's File Explorer on the left. Right-click in the ~/project directory, select "New File", and type DoubleCheck.java.
Now, open the DoubleCheck.java file in the editor and add the following code:
public class DoubleCheck {
public static void main(String[] args) {
// Declare a primitive double variable
double primitiveDouble = 123.45;
// Declare a Double object
Double doubleObject = 67.89;
// Declare an Integer object
Integer integerObject = 100;
// Check if primitiveDouble is an instance of Double (This will not work directly)
// System.out.println("Is primitiveDouble an instance of Double? " + (primitiveDouble instanceof Double)); // This line would cause a compile error
// Check if doubleObject is an instance of Double
System.out.println("Is doubleObject an instance of Double? " + (doubleObject instanceof Double));
// Check if integerObject is an instance of Double
System.out.println("Is integerObject an instance of Double? " + (integerObject instanceof Double));
}
}
In this code:
- We declare a primitive
double variable primitiveDouble.
- We declare a
Double object doubleObject.
- We declare an
Integer object integerObject for comparison.
- We use the
instanceof operator to check if doubleObject and integerObject are instances of the Double class.
- Note that the
instanceof operator cannot be used directly with primitive types like double.
Save the DoubleCheck.java file.
Now, let's compile and run the program. Open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory.
Compile the code using javac:
javac DoubleCheck.java
If there are no compilation errors, run the compiled code using java:
java DoubleCheck
You should see output similar to this:
Is doubleObject an instance of Double? true
Is integerObject an instance of Double? false
This output confirms that doubleObject is an instance of the Double class, while integerObject is not. This demonstrates how to use the instanceof operator to check the type of an object in Java.