How to Check If a Number Is a Long in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will explore different methods to determine if a number in Java is of the Long type. We will begin by learning how to use the instanceof operator to check if an object is an instance of the Long wrapper class.

Following that, we will delve into parsing strings to Long values, understanding how to handle potential errors during this process. Finally, we will differentiate between Long and Integer types, highlighting their key distinctions and how to work with each effectively.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java/BasicSyntaxGroup -.-> java/data_types("Data Types") java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/BasicSyntaxGroup -.-> java/type_casting("Type Casting") java/StringManipulationGroup -.-> java/strings("Strings") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("Classes/Objects") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("Wrapper Classes") java/SystemandDataProcessingGroup -.-> java/object_methods("Object Methods") subgraph Lab Skills java/data_types -.-> lab-559957{{"How to Check If a Number Is a Long in Java"}} java/if_else -.-> lab-559957{{"How to Check If a Number Is a Long in Java"}} java/type_casting -.-> lab-559957{{"How to Check If a Number Is a Long in Java"}} java/strings -.-> lab-559957{{"How to Check If a Number Is a Long in Java"}} java/classes_objects -.-> lab-559957{{"How to Check If a Number Is a Long in Java"}} java/wrapper_classes -.-> lab-559957{{"How to Check If a Number Is a Long in Java"}} java/object_methods -.-> lab-559957{{"How to Check If a Number Is a Long in Java"}} end

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.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

  2. 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.
  3. Save the file (Ctrl+S or Cmd+S).

  4. 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.

  5. 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.

Parse String to Long

In this step, we will learn how to convert a String representation of a number into a Long object or a long primitive type. This is a common task when you receive numerical data as text, for example, from user input or a file.

The Long class provides static methods to perform this conversion. The two most commonly used methods are:

  • Long.parseLong(String s): This method parses the string argument as a signed decimal long. It returns a primitive long value.
  • Long.valueOf(String s): This method returns a Long object holding the value represented by the string argument.

Let's modify our HelloJava.java program to demonstrate how to parse a string to a long and a Long.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the existing code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            String numberString = "9876543210";
    
            // Parse the string to a primitive long
            long primitiveLong = Long.parseLong(numberString);
            System.out.println("Parsed primitive long: " + primitiveLong);
    
            // Parse the string to a Long object
            Long longObject = Long.valueOf(numberString);
            System.out.println("Parsed Long object: " + longObject);
    
            // Demonstrate parsing a different string
            String anotherNumberString = "112233445566";
            long anotherPrimitiveLong = Long.parseLong(anotherNumberString);
            System.out.println("Parsed another primitive long: " + anotherPrimitiveLong);
        }
    }

    In this code:

    • We define a String variable numberString containing the text "9876543210".
    • We use Long.parseLong() to convert numberString into a primitive long and store it in primitiveLong.
    • We use Long.valueOf() to convert numberString into a Long object and store it in longObject.
    • We demonstrate parsing another string to show the flexibility of the method.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program:

    javac HelloJava.java

    Ensure there are no compilation errors.

  5. Run the program:

    java HelloJava

    You should see output similar to this:

    Parsed primitive long: 9876543210
    Parsed Long object: 9876543210
    Parsed another primitive long: 112233445566

This output shows that both Long.parseLong() and Long.valueOf() successfully converted the string representations of numbers into their corresponding long and Long values.

It's important to note that if the string does not contain a valid number that can be represented as a long, these methods will throw a NumberFormatException. We won't cover error handling in this basic lab, but it's something to keep in mind for real-world applications.

Differentiate Long from Integer

In this step, we will focus on understanding the key differences between long (and its wrapper class Long) and int (and its wrapper class Integer) in Java. While both are used to store whole numbers, they differ significantly in the range of values they can hold and their memory usage.

The primary difference lies in their size:

  • int: An int is a 32-bit signed two's complement integer. This means it can store values ranging from -2,147,483,648 to 2,147,483,647.
  • long: A long is a 64-bit signed two's complement integer. This allows it to store a much larger range of values, from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Let's modify our HelloJava.java program to illustrate this difference.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the existing code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            // Maximum value for int
            int maxInt = Integer.MAX_VALUE;
            System.out.println("Maximum value of int: " + maxInt);
    
            // Trying to store a value larger than maxInt in an int (will cause error if uncommented)
            // int tooBigInt = 2147483648; // This line would cause a compilation error
    
            // A value larger than maxInt, stored in a long
            long largeLong = 2147483648L; // Note the 'L' suffix
            System.out.println("A large value stored in long: " + largeLong);
    
            // Maximum value for long
            long maxLong = Long.MAX_VALUE;
            System.out.println("Maximum value of long: " + maxLong);
    
            // Demonstrating the size difference with literals
            System.out.println("Size of int in bits: " + Integer.SIZE);
            System.out.println("Size of long in bits: " + Long.SIZE);
        }
    }

    In this code:

    • We print the maximum value that an int can hold using Integer.MAX_VALUE.
    • We show a commented-out line that would cause a compilation error if uncommented, because the value 2147483648 is larger than the maximum value of an int.
    • We store the same large value in a long variable largeLong, using the L suffix to indicate it's a long literal.
    • We print the maximum value that a long can hold using Long.MAX_VALUE.
    • We print the size of int and long in bits using Integer.SIZE and Long.SIZE.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program:

    javac HelloJava.java

    Ensure there are no compilation errors.

  5. Run the program:

    java HelloJava

    You should see output similar to this:

    Maximum value of int: 2147483647
    A large value stored in long: 2147483648
    Maximum value of long: 9223372036854775807
    Size of int in bits: 32
    Size of long in bits: 64

This output clearly demonstrates that long can hold significantly larger values than int, and confirms their respective sizes in bits. When choosing between int and long, consider the range of values your variable needs to store. Use int for smaller numbers to save memory, and long for larger numbers.

Summary

In this lab, we learned how to check if a number is a Long in Java. We explored the Long wrapper class and its relationship to the primitive long type. We specifically focused on using the instanceof operator to determine if an object is an instance of the Long class. Through a practical example, we demonstrated how to apply instanceof to differentiate between Long and Integer objects.