Casting string to long in java

Java — Convert String to long

We also can use Long.parseUnsignedLong​(. ) to make sure the long is > 0.

Long.valueOf()

The difference between valueOf(. ) and parseLong(. ) is valueOf(. ) will return a Long (wrapper class) instead of primitive long.

  • static Long valueOf​(String s): Returns a Long object holding the value of the specified String.
  • static Long valueOf​(String s, int radix): Returns a Long object holding the value extracted from the specified String when parsed with the radix given by the second argument.
long l1 = Long.valueOf("888"); System.out.println(l1); // 101010101 long l2 = Long.valueOf("-FF", 16); System.out.println(l2); // -255 long l3 = Long.valueOf("01010101", 2); System.out.println(l3); // 85 

As you can see, implicit casting automatically unbox Long into long.

Deprecated: Long‘s Constructor

It is rarely appropriate to use this constructor. Use parseLong(String) to convert a string to a long primitive, or use valueOf(String) to convert a string to a Long object.

long l1 = new Long("123"); System.out.println(l1); // 123 long l2 = new Long("-0x8F"); // NumberFormatException System.out.println(l2); 

Long.decode()

static Long decode​(String nm): Decodes a String into a Long.

long l1 = Long.decode("321"); System.out.println(l1); // 321 long l2 = Long.decode("-0x88"); // hex System.out.println(l2); // -136 long l3 = Long.decode("#F3F3F3"); // hex System.out.println(l3); // 15987699 long l4 = Long.decode("066"); // octal System.out.println(l4); // 54 

DecimalFormat.parse()

parse​(String source) throws ParseException: Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.

import java.text.DecimalFormat; import java.text.ParseException;
DecimalFormat decimalFormat = new DecimalFormat(); try < long l = decimalFormat.parse("54321").longValue(); System.out.println(l); // 54321 >catch (ParseException e)

Since parse() method returns instance of Number, we need to call longValue() to get the long primitive value from it. The Number also has intValue() to get int primitive value, doubleValue() for double, etc.

And similar to Convert String to int, we also can use external libraries like Apache Commons NumberUtils, Spring’s NumberUtils, and Google’s Guava primitive Longs.

Apache Commons NumberUtils

  • static long toLong(String str): Convert a String to a long, returning zero if the conversion fails.
  • static long toLong(String str, long defaultValue): Convert a String to a long, returning a default value if the conversion fails.
  • static Long createLong(String str): Convert a String to a Long; since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations.
import org.springframework.util.NumberUtils;
long l1 = NumberUtils.toLong("365"); System.out.println(l1); // 365 long l2 = NumberUtils.toLong(null); System.out.println(l2); // 0 long l3 = NumberUtils.toLong("365", 0); System.out.println(l3); // 365 long l4 = NumberUtils.toLong("xyz", -1); System.out.println(l4); // -1 long l5 = NumberUtils.toLong("", -1); System.out.println(l5); // -1 long l6 = NumberUtils.createLong("365"); System.out.println(l6); // 365 long l7 = NumberUtils.createLong("-0xFF88"); System.out.println(l7); // -65416 

Spring NumberUtils

Similar like in Converting String to int, we can use Spring’s NumberUtils to parse String to number (in this case long).

import org.springframework.util.NumberUtils;
long i1 = NumberUtils.parseNumber("512", Long.class); System.out.println(i1); // 512 long i2 = NumberUtils.parseNumber("#F120", Long.class); System.out.println(i2); // 61728 

Google Guava Longs.tryParse()

The conversion also can be done using Guava’s Longs.tryParse().

  • static Long tryParse(String string): Parses the specified string as a signed decimal long value.
  • static Long tryParse(String string, int radix): Parses the specified string as a signed long value using the specified radix.
import com.google.common.primitives.Longs;
long l1 = Longs.tryParse("5123456789012346"); System.out.println(l1); // 5123456789012346 long l2 = Longs.tryParse("-18F1", 16); System.out.println(l2); // -6385 long l3 = Longs.tryParse("111111111", 2); System.out.println(l3); // 511 

Liked this Tutorial? Share it on Social media!

Читайте также:  Ozon api php sdk

Источник

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.

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.

Читайте также:  Html как отцентровать блок

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 ⇒

Источник

Casting string to long in java

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

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