You tin parse a String literal containing valid long value into a long primitive type using parseLong() together with valueOf() method of java.lang.Long shape of JDK. Though in that place are distich of departure betwixt valueOf() together with parseLong() method e.g. valueOf() method render a Long object spell parseLong() method render a Long object, but given nosotros receive got autoboxing inwards Java, both method tin used for parsing String to exercise long values. In the last article, you lot receive got learned how to convert a Long value to String inwards Java together with inwards this tutorial, you lot volition acquire opposite, i.e. how to parse a String to a long value inwards Java. As I said, in that place are the distich of ways to exercise it, but the most of import method is parseLong(). This method is responsible for parsing input String together with creating primitive long value corresponding to input String. It does input validation together with throws NumberFormatException if you lot locomote yesteryear String which is non valid long value e.g. alphanumeric String, String containing characters other than +, - together with numbers, long values which are out of range, lonely + or - grapheme etc.
You tin too job the constructor of Long shape which accepts a String together with returns a Long object, but internally it too uses parseLong() method.
BTW, if you lot receive got only started learning Java or looking forrad to learning Java from scratch, I advise you lot bring a hold off at Cay S. Horstmann's Core Java Volume 1, ninth Edition book. You volition acquire most of Java fundamentals inwards quick time.
Minor difference betwixt parseLong() together with valueOf() method is that erstwhile render a primitive long value spell afterwards render a Long object. Since Long.valueOf() is too used inwards autoboxing to convert primitive long to Long object, it too maintains a cache of Long object from -128 to 127. So it returns the same Long object for every telephone scream upwards inwards this range. This is OK because Long is Immutable inwards Java, but it tin exercise subtle bugs if you lot compare auto-boxed values using the == operator inwards Java, every bit seen inwards this article.
You tin too banking concern check Cay S. Horstmann's Core Java Volume 1 - Fundamentals to acquire to a greater extent than almost how to convert 1 information type to only about other inwards Java.
From output you lot tin run into that converted long values are same every bit master String, which way our programme is working properly.
same fault volition too come upwards if you lot job Long.valueOf() to exercise the parsing, this too proves that valueOf() internally calls to parseLong() method for parsing String :
1) Long.valueOf() method genuinely calls Long.valueOf(long, radix) method which is used to parse String to long inwards whatever radix e.g. binary, octal, decimal together with hexadecimal. Since to a greater extent than often you lot would similar parse decimal String to long, JDK has provided a valueOf() method only for that purpose. Here is the code snippet from java.lang.Long shape :
You tin run into that fifty-fifty this method is using parseLong() method to actually convert String to long inwards Java, valueOf() method is only used hither to automatically convert a primitive long to a Long object. Like valueOf() method of other wrapper classes e.g. Integer, Long too caches oft used primitive value together with render same event of Long object. Since Long is Immutable inwards Java, its rubber to part 1 event alongside multiple users. This is too a skillful instance of Fly weight pattern pattern. Here is the code snippet from JDK :
Since this method is too used inwards auto-boxing, you lot should never compare auto-boxed numeric values using == operator inwards Java.
2) Constructor of Long shape which takes an String object together with render a Long object too uses parseLong() method for parsing, every bit shown below :
3) The existent method, parseLong() which does all the run of parsing throws NumberFormatException for invalid inputs e.g. goose egg values, empty values, lonely summation or minus sign, alphanumeric String together with String alongside out of attain long values.
That's all almost how to convert String to long inwards Java. You should job Long.valueOf() method to parse String, if you lot bespeak a Long object together with job parseLong() method if you lot desire to convert String to primitive long value. Long.valueOf() method too provides caching inwards attain of -128 to 127. By the way, since nosotros receive got auto-boxing inwards Java, which too used Long.valueOf() method, It's e'er improve to job parseLong() method because it's readable, reveals the existent intention, handles invalid input together with specifically designed to parse String literal containing long values.
You tin too job the constructor of Long shape which accepts a String together with returns a Long object, but internally it too uses parseLong() method.
BTW, if you lot receive got only started learning Java or looking forrad to learning Java from scratch, I advise you lot bring a hold off at Cay S. Horstmann's Core Java Volume 1, ninth Edition book. You volition acquire most of Java fundamentals inwards quick time.
Three ways to convert String to long inwards Java
There are 3 primary ways to convert a numeric String to Long inwards Java, though internally all of them uses parseLong() method to parse numeric String to Long value.- By using Long.parseLong() method
- By using Long.valueOf() method
- By using novel Long(String value) constructor
Minor difference betwixt parseLong() together with valueOf() method is that erstwhile render a primitive long value spell afterwards render a Long object. Since Long.valueOf() is too used inwards autoboxing to convert primitive long to Long object, it too maintains a cache of Long object from -128 to 127. So it returns the same Long object for every telephone scream upwards inwards this range. This is OK because Long is Immutable inwards Java, but it tin exercise subtle bugs if you lot compare auto-boxed values using the == operator inwards Java, every bit seen inwards this article.
You tin too banking concern check Cay S. Horstmann's Core Java Volume 1 - Fundamentals to acquire to a greater extent than almost how to convert 1 information type to only about other inwards Java.
String to Long Java Example
Here is our sample Java programme to parse String to long values. In this example, I receive got used dissimilar long values to demonstrate how parseLong() method works e.g. a uncomplicated long value, a long value alongside summation sign, a long value alongside minus sign together with a huge long value which is out of range. Our programme volition throw NumberFormatException for that value together with that's why it is commented inwards source code. You tin un-comment together with run this programme to run into how it behaves./** * Java Program to convert String to long * * @author java67 */ public class StringRotateDemo { public static void main(String args[]) { // Some long values every bit String literal for testing String simpleLong = "2223349494943933"; String longWithPlusSign = "+45523349494943933"; String longWithMinusSign = "-745523349494943933"; String outOfBoundLong = "787888888888888888888888888888888888888883333333333333333333"; // converting String to long using Long.parseLong() method long value1 = Long.parseLong(simpleLong); long value2 = Long.parseLong(longWithPlusSign); long value3 = Long.parseLong(longWithMinusSign); // below volition throw NumberFormatException because long value is out of range //long value4 = Long.parseLong(outOfBoundLong); System.out.printf("String %s converted to long value %d %n", simpleLong, value1); System.out.printf("String %s converted to long value %d %n", longWithPlusSign, value2); System.out.printf("String %s converted to long value %d %n", longWithMinusSign, value3); //System.out.printf("String %s converted to long value %d %n", outOfBoundLong, value4); // minute method to convert a String literal to long value is // yesteryear using valueOf() method of Long class long value4 = Long.valueOf(simpleLong); long value5 = Long.valueOf(longWithPlusSign); long value6 = Long.valueOf(longWithMinusSign); // long value7 = Long.valueOf(outOfBoundLong); NumberFormatException System.out.println("String : " + simpleLong + " long : " + value4); System.out.println("String : " + longWithPlusSign + " long : " + value5); System.out.println("String : " + longWithMinusSign + " long : " + value6); // System.out.println("String : " + outOfBoundLong + " long : " + value7); } } Output String 2223349494943933 converted to long value 2223349494943933 String +45523349494943933 converted to long value 45523349494943933 String -745523349494943933 converted to long value -745523349494943933 String : 2223349494943933 long : 2223349494943933 String : +45523349494943933 long : 45523349494943933 String : -745523349494943933 long : -745523349494943933
Error spell Parsing String to Long
You volition acquire next fault when you lot endeavor to parse an out of attain long value every bit String literal using Long.parseLong() method :Exception inwards thread "main" java.lang.NumberFormatException: For input string: "787888888888888888888888888888888888888883333333333333333333" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Long.parseLong(Unknown Source) at java.lang.Long.parseLong(Unknown Source) at dto.ParseLongDemo.main(ParseLongDemo.java:24)
same fault volition too come upwards if you lot job Long.valueOf() to exercise the parsing, this too proves that valueOf() internally calls to parseLong() method for parsing String :
Exception inwards thread "main" java.lang.NumberFormatException: For input string: "787888888888888888888888888888888888888883333333333333333333" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Long.parseLong(Unknown Source) at java.lang.Long.valueOf(Unknown Source) at dto.ParseLongDemo.main(ParseLongDemo.java:45)
Important things to Remember
1) Long.valueOf() method genuinely calls Long.valueOf(long, radix) method which is used to parse String to long inwards whatever radix e.g. binary, octal, decimal together with hexadecimal. Since to a greater extent than often you lot would similar parse decimal String to long, JDK has provided a valueOf() method only for that purpose. Here is the code snippet from java.lang.Long shape :
public static Long valueOf(String s) throws NumberFormatException { return Long.valueOf(parseLong(s, 10)); }
You tin run into that fifty-fifty this method is using parseLong() method to actually convert String to long inwards Java, valueOf() method is only used hither to automatically convert a primitive long to a Long object. Like valueOf() method of other wrapper classes e.g. Integer, Long too caches oft used primitive value together with render same event of Long object. Since Long is Immutable inwards Java, its rubber to part 1 event alongside multiple users. This is too a skillful instance of Fly weight pattern pattern. Here is the code snippet from JDK :
public static Long valueOf(long l) { final int offset = 128; if (l >= -128 && l <= 127) { // volition cache return LongCache.cache[(int)l + offset]; } return new Long(l); }
Since this method is too used inwards auto-boxing, you lot should never compare auto-boxed numeric values using == operator inwards Java.
2) Constructor of Long shape which takes an String object together with render a Long object too uses parseLong() method for parsing, every bit shown below :
public Long(String s) throws NumberFormatException { this.value = parseLong(s, 10); }
3) The existent method, parseLong() which does all the run of parsing throws NumberFormatException for invalid inputs e.g. goose egg values, empty values, lonely summation or minus sign, alphanumeric String together with String alongside out of attain long values.
That's all almost how to convert String to long inwards Java. You should job Long.valueOf() method to parse String, if you lot bespeak a Long object together with job parseLong() method if you lot desire to convert String to primitive long value. Long.valueOf() method too provides caching inwards attain of -128 to 127. By the way, since nosotros receive got auto-boxing inwards Java, which too used Long.valueOf() method, It's e'er improve to job parseLong() method because it's readable, reveals the existent intention, handles invalid input together with specifically designed to parse String literal containing long values.
0 Response to "How to parse String to long inwards Java? Example"
Posting Komentar