All TalkersCode Topics

Follow TalkersCode On Social Media

String To Long In Java

Last Updated : Aug 8, 2023

String To Long In Java

In this article we will show you the solution of string to long in java, the string containing long numbers is generally used for mathematical operations. A string is received whenever entered data is received from a text field or textarea.

The string needs to be converted to long if the entered data is long. To do so, we use the Long.parseLong() method.

The static method parseLong() of the Long class is called when the class is loaded.

In Java, you should use the parseLong(String x) method of the Long wrapper class to convert a String to a long.

We will now discuss the idea of how to create strings too long in java with an example.

Step By Step Guide On String To Long In Java :-

// Java Program to Convert String to Long
// Using Constructor of Long class
// Importing required classes
import java.util.*;
// Class
class TC {
    // Main driver method
    public static void main(String[] args)
        // Custom input string
        String str = "99999";
        System.out.println("String - " + str);
        // Converting above string to long
        // using Long(String s) constructor
        long num = new Long(str);
        // Printing the above long value
        System.out.println("Long - " + num);
  1. The first thing we do is import the required classes, which are '' and 'java.util. ', since we will be using the 'Scanner' class for receiving user input and the 'Long' class for converting strings to longs.
  2. The main method of our class will be defined in a class called 'TC'.
  3. A custom input string is defined inside the main method called 'str'. After this string has been converted to a long, it will be used for other purposes.
  4. In this example, we will use the 'println' method to output the string.
  5. As a result of this process, we create a variable called 'num' that will hold the converted long value of the string. To convert a string into a long value, we use the 'Long(String s)' constructor of the 'Long' class.
  6. The println method is used to print out the long value.
  7. In the next step, we'll print out the original string as well as the converted long value.

Conclusion :-

As a result, we have successfully learned how to create strings too long in java with an example.

The String class contains three methods to convert strings to longs, including Long.parseLong(), Long.valueOf(), and Long.constructor().

Strings containing positive or negative integer numbers cannot be converted with these methods.

I hope this article on string to long in java helps you and the steps and method mentioned above are easy to follow and implement.

Latest Tutorials