BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java String to long Conversion

Last Updated: December 1, 2024 by Chaitanya Singh | Filed Under: java

In this tutorial, you will learn how to convert String to long in Java. We can use Long wrapper class for this purpose, this class contains couple of methods that we can use for this conversion. There are following three ways to convert a String to a long value.

  • Long.parseLong() Method
  • Long.valueOf() Method
  • Long(String s) Constructor of Long class

Java String to long Conversion Examples

1. Example Using Long.parseLong() Method

Long.parseLong(String): All the characters in the String must be digits except the first character, which can be a digit or a minus ‘-‘. For example: long var = Long.parseInt("-123"); is allowed and the value of var after conversion would be -123.

In this example, the string str2 has minus sign ‘-‘ in the beginning, which is why the value of variable num2 is negative in the output.

public class JavaExample {
    public static void main(String[] args) {
        String str = "21111";
        String str2 = "-11111";

        try {
            //Conversion using parseLong(String) method
            long num = Long.parseLong(str); //21111
            long num2 = Long.parseLong(str2); //-11111
            System.out.println(num+num2); //21111-11111 = 10000
        } catch (NumberFormatException e) {
            System.out.println("The string is not a valid long number.");
        }
    }
}

Output:

10000

2. Example Using Long.valueOf() Method

Long.valueOf(String): Converts the String to a long value. Similar to parseLong(String) method, this method also allows minus ‘-‘ as a first character in the String.

public class JavaExample {
    public static void main(String[] args) {
        String str = "11111";
        String str2 = "88888";

        try {
            //Conversion using valueOf(String) method
            long num = Long.valueOf(str);
            long num2 = Long.valueOf(str2);
            System.out.println(num);
            System.out.println(num2);
        } catch (NumberFormatException e) {
            System.out.println("The string is not a valid long number.");
        }
    }
}

Output:

11111
88888

Important Points

  1. Handling NullFormatException: Both methods valueOf() and parseLong() throw a NumberFormatException if the string cannot be parsed as a valid long. It’s good practice to handle this exception while doing the conversion using these methods.
  2. String Format: The String that we want to convert should be in the valid range of long data type in Java (-2^63 to 2^63-1).

3. Example Handling Invalid Input

In this example, we are demonstrating how to handle both valid and invalid string inputs during string to long conversion.

public class JavaExample {
public static void main(String[] args) {
String validStr = "12345";
String invalidStr = "12345xyz";

System.out.println("Valid String to long Conversion:");
convertStringToLong(validStr);

System.out.println("nInvalid String to long Conversion:");
convertStringToLong(invalidStr);
}

public static void convertStringToLong(String str) {
try {
long number = Long.parseLong(str);
System.out.println("The long value is: " + number);
} catch (NumberFormatException e) {
System.out.println("Error: '" + str + "' is not a valid long number.");
}
}
}

Output:

Valid String Conversion:
The long value is: 12345

Invalid String Conversion:
Error: '12345abc' is not a valid long number.

4. Using the Constructor of Long class

Long(String s) constructor: Long class has a constructor that allows String argument and creates a new Long object representing the specified string in the equivalent long value. The string is converted to a long value in exactly the manner used by the parseLong(String) method for radix 10.

public class JavaExample {
  public static void main(String[] args)
  {
    String str = "10000";
    String str2 = "22222";
    //Conversion using Long(String s) constructor
    long num = new Long(str);
    long num2 = new Long(str2);
    System.out.println(num);
    System.out.println(num2);
  }
}

Output:

10000
22222

Recommended Posts:

  • Java long to String Conversion
  • Java String to int Conversion
  • Java String to double Conversion
  • Java String to char Conversion
  • Java String to Object Conversion
  • Java String to float Conversion
  • Java String to Date Conversion
  • Java String to boolean Conversion

Tags: Java-Conversion

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap