Check Instance of Long Class
In this step, we will explore the Long
class in Java and learn how to check if an object is an instance of the Long
class.
In Java, primitive data types like long
are not objects. However, Java provides wrapper classes for each primitive type, and Long
is the wrapper class for the long
primitive type. Wrapper classes allow us to treat primitive values as objects, which is useful in many situations, such as when working with collections.
To check if an object is an instance of a specific class, we use the instanceof
operator. The instanceof
operator is a binary operator used to test if an object is an instance of a class, a subclass, or an interface.
Let's create a simple Java program to demonstrate how to use the instanceof
operator with the Long
class.
-
Open the HelloJava.java
file in the WebIDE editor if it's not already open.
-
Replace the entire contents of the file with the following code:
public class HelloJava {
public static void main(String[] args) {
// Create a Long object
Long myLong = 12345L;
// Create an Integer object
Integer myInteger = 67890;
// Check if myLong is an instance of Long
if (myLong instanceof Long) {
System.out.println("myLong is an instance of Long.");
} else {
System.out.println("myLong is not an instance of Long.");
}
// Check if myInteger is an instance of Long
if (myInteger instanceof Long) {
System.out.println("myInteger is an instance of Long.");
} else {
System.out.println("myInteger is not an instance of Long.");
}
}
}
In this code:
- We create a
Long
object named myLong
with the value 12345L
. The L
suffix indicates that it's a long
literal.
- We create an
Integer
object named myInteger
with the value 67890
.
- We use the
instanceof
operator to check if myLong
is an instance of Long
.
- We use the
instanceof
operator to check if myInteger
is an instance of Long
.
-
Save the file (Ctrl+S or Cmd+S).
-
Compile the program by running the following command in the Terminal:
javac HelloJava.java
If the compilation is successful, you will not see any output.
-
Run the compiled program:
java HelloJava
You should see the following output:
myLong is an instance of Long.
myInteger is not an instance of Long.
This output confirms that myLong
, which we created as a Long
object, is indeed an instance of the Long
class, while myInteger
, created as an Integer
object, is not.