Java convert string to long type

Convert String to long in Java

Learn to convert a String to Long type in Java using Long.parseLong(String) , Long.valueOf(String) methods and new Long(String) constructor.

String number = "2018"; //String long value1 = Long.parseLong( number, 10 ); long value2 = Long.valueOf( number ); long value3 = new Long( number ); 

1. Using Long.valueOf(String)

The Long.valueOf() method parses the input string to a signed decimal long type. The characters in the string must all be decimal digits, except that the first character may be a minus (-) sign for negative numbers and a plus(+) sign for positive numbers.

The result long value is exactly the same as the string argument in base 10. In the following example, we convert one positive and one negative number to a long value.

String positiveNumber = "+12001"; long value1 = Long.valueOf(positiveNumber); //12001L String negativeNumber = "-22002"; long value2 = Long.valueOf(negativeNumber); //-22002L

If the string cannot be parsed as a long, it throws NumberFormatException.

Assertions.assertThrows(NumberFormatException.class, () -> < Long.valueOf("alexa"); >);

2. Using Long.parseLong(String)

The rules for Long.parseLong(String) method are similar to Long.valueOf(String) method as well.

  • It parses the String argument as a signed decimal long type value.
  • The characters in the string must all be decimal digits, except that the first character may be a minus (-) sign for negative numbers and a plus(+) sign for positive numbers.
  • The result long value is exactly the same as the string argument in base 10.
Читайте также:  Python datetime compare dates

Again, we will convert one positive number and one negative number to long value using parseLong() API.

String positiveNumber = "+12001"; long value1 = Long.parseLong(positiveNumber); //12001L String negativeNumber = "-22002"; long value2 = Long.parseLong(negativeNumber); //-22002L

If the input String is in another base then we can pass the base as second input to the method.

String numberInHex = "-FF"; long value = Long.parseLong(numberInHex); //-255L

3. Using new Long(String) Constructor

Another useful way is to utilize Long class constructor to create new long object. This method has been deprecated since Java 9, and recommended to use parseLong() API as discussed above.

long value = new Long("100"); //100L

Using any of the given approaches, if the input String does not have only the decimal characters (except the first character, which can be plus or minus sign), we will get NumberFormatException error in runtime.

String number = "12001xyz"; long value = Long.parseLong(number); //Error Exception in thread "main" java.lang.NumberFormatException: For input string: "12001xyz" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:589) at java.lang.Long.<init>(Long.java:965) at com.howtodoinjava.StringExample.main(StringExample.java:9)

Источник

How to Convert String to Long in Java

Scientech Easy

In this tutorial, we will learn how to convert Java String to wrapper Long class object or primitive type long value easily.

There are some situations where we need to convert a number represented as a string into a long type in Java.

It is normally used when we want to perform mathematical operations on the string which contains a number.

For example, whenever we gain data from JTextField or JComboBox, we receive entered data as a string. If entered data is a number in string form, we need to convert the string to a long to perform mathematical operations on it.

Convert string to long in Java

There are mainly four different ways to convert a string to wrapper Long class or primitive type long.

  • Convert using Long.parseLong()
  • Convert using Long.valueOf()
  • Using new Long(String).longValue()
  • Using DecimalFormat

Let’s understand all four ways one by one with example programs.

Converting String to Long in Java using Long.parseLong()

To convert string to a long, we use Long.parseLong() method provided by the Long class. The parseLong() of Long class is the static method. It reads long numeric values from the command-line arguments.

So, we do not need to create an object of class to call it. We can call it simply using its class name. The general signature of parseLong() method is as below:

public static long parseLong(String s)

This method accepts a string containing the long representation to be parsed. It returns long value. The parseLong() method throws an exception named NumberFormatException if the string does not contain a parsable long value.

Let’s create a Java program to convert string to long in java using parseLong() of Java Long class.

Program code 1:

// Java program to convert a string into a primitive long type using parseLong() method. package javaConversion; public class StringToLongConversion < public static void main(String[] args) < String str = "99904489675"; // Call parseLong() method to convert a string to long value. long l = Long.parseLong(str); System.out.println(l); ++l; System.out.println(l); >>
Output: 99904489675 99904489676

Converting String to Long in Java using Long.valueOf()

We can also convert a string to long numeric value using valueOf() of Java long wrapper class. The valueOf() method of Long class converts a string containing a long number into Long object and returns that object.

It is a static utility method, so we do not need to create an object of class. We can invoke it using its class name.The general signature of valueOf() method is as below:

public static Long valueOf(String str)

Let’s write a Java program to convert a string into a long value using valueOf() method of Java Long wrapper class.

Program code 2:

// Java program to convert a string into a primitive long type using valueOf() method. package javaConversion; public class StringToLongConversion < public static void main(String[] args) < String str = "99904489675"; // Call parseLong() method to convert a string to long value. Long l = Long.valueOf(str); System.out.println(l); >>

Converting String to Long using new Long(String).longValue()

Another alternative approach is to create an instance of Long class and then call longValue() method of Long class. The longValue() method converts the long object into primitive long type value. This is called “unboxing” in Java.

Unboxing is a process by which we convert an object into its corresponding primitive data type.

Let’s create a Java program to convert String into a long object using longValue() method.

Program code 3:

// Java program to convert a string into a long using new Long(String).longValue(). package javaConversion; public class StringToLongConversion < public static void main(String[] args) < String str = "757586748"; Long l = new Long(str); long num = l.longValue(); System.out.println(num); >>

Converting String to Long using DecimalFormat

Java provides a class called DecimalFormat that allows to convert a number to its string representation. This class is present in java.text package. We can also use in other way to parse a string into its numerical representation.

Let’s create a Java program to convert a string to long numeric value using DecimalFormat class.

Program code 4:

// Java Program to demonstrate the conversion of String into long using DecimalFormat class. package javaConversion; import java.text.DecimalFormat; import java.text.ParseException; public class StringToLongConversion < public static void main(String[] args) < String str = "76347364"; // Create an object of DecimalFormat class. DecimalFormat decimalFormat = new DecimalFormat("#"); try < long num = decimalFormat.parse(str).longValue(); System.out.println(num); >catch (ParseException e) < System.out.println(str + " is not a valid numeric value."); >> >

In this tutorial, you learned how to convert a string to long numeric value in Java using the following ways easily. Hope that you will have understood the basic methods of converting a string into a long.

In the next tutorial, we will learn how to convert long numeric value to a string in Java.
Thanks for reading.
Next ⇒ Convert Long to String in Java ⇐ Prev Next ⇒

Источник

Java convert string to long type

  • A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
  • How to maintain polyglot persistence for microservices Managing microservice data may be difficult without polyglot persistence in place. Examine how the strategy works, its challenges.
  • Top developer relations trends for building stronger teams Learn about enterprise trends for optimizing software engineering practices, including developer relations, API use, community .
  • The basics of implementing an API testing framework With an increasing need for API testing, having an efficient test strategy is a big concern for testers. How can teams evaluate .
  • The potential of ChatGPT for software testing ChatGPT can help software testers write tests and plan coverage. How can teams anticipate both AI’s future testing capabilities .
  • Retail companies gain DORA metrics ROI from specialist tools DORA metrics and other measures of engineering efficiency are popping up in add-ons to existing DevOps tools. But third-party .
  • How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
  • Prices for cloud infrastructure soar 30% Tough macroeconomic conditions as well as high average selling prices for cloud computing and storage servers have forced .
  • Deploy a low-latency app with AWS Local Zones in 5 steps Once you decide AWS Local Zones are right for your application, it’s time for deployment. Follow along in this step-by-step video.
  • Multiple Adobe ColdFusion flaws exploited in the wild One of the Adobe ColdFusion flaws exploited in the wild, CVE-2023-38203, was a zero-day bug that security vendor Project .
  • Ransomware case study: Recovery can be painful In ransomware attacks, backups can save the day and the data. Even so, recovery can still be expensive and painful, depending on .
  • Supercloud security concerns foreshadow concept’s adoption Supercloud lets applications work together across multiple cloud environments, but organizations must pay particular attention to.
  • AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
  • Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
  • Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .

Источник

Java String to long Conversion With Examples

In this tutorial, you will learn how to convert String to long in Java. 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

1. Java – Convert String to long using Long.parseLong(String)

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.

Java Program

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.

Java String to Long conversion

2. Java – Convert String to long using Long.valueOf(String)

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.

Java Program

3. Java – Convert String to long 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.

Java Program

Источник

Оцените статью