Wednesday, December 11, 2019

How To Parse String To Long Inward Java? Example

You tin parse a String literal containing valid long value into a long primitive type using parseLong() in addition to valueOf() method of java.lang.Long shape of JDK. Though in that place are pair of departure betwixt valueOf() in addition to parseLong() method e.g. valueOf() method render a Long object spell parseLong() method render a Long object, but given nosotros direct hold autoboxing inward Java, both method tin used for parsing String to practise long values. In the last article, you lot direct hold learned how to convert a Long value to String inward Java in addition to inward this tutorial, you lot volition larn opposite, i.e. how to parse a String to a long value inward Java. As I said, in that place are the pair of ways to practise it, but the most of import method is parseLong(). This method is responsible for parsing input String in addition to creating primitive long value corresponding to input String. It does input validation in addition to throws NumberFormatException if you lot transcend String which is non valid long value e.g. alphanumeric String, String containing characters other than +, - in addition to numbers, long values which are out of range, lonely + or - grapheme etc.

You tin equally good exercise the constructor of Long shape which accepts a String in addition to returns a Long object, but internally it equally good uses parseLong() method.

BTW, if you lot direct hold only started learning Java or looking forrard to learning Java from scratch, I advise you lot bring a await at Cay S. Horstmann's Core Java Volume 1, ninth Edition book. You volition larn most of Java fundamentals inward quick time.




Three ways to convert String to long inward Java

There are 3 principal ways to convert a numeric String to Long inward 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() in addition to valueOf() method is that one-time render a primitive long value spell afterward render a Long object. Since Long.valueOf() is equally good used inward autoboxing to convert primitive long to Long object, it equally good maintains a cache of Long object from -128 to 127. So it returns the same Long object for every telephone outcry upwardly inward this range. This is OK because Long is Immutable inward Java, but it tin practise subtle bugs if you lot compare auto-boxed values using the == operator inward Java, equally seen inward this article.

You tin equally good banking concern check Cay S. Horstmann's Core Java Volume 1 - Fundamentals to larn to a greater extent than close how to convert 1 information type to only about other inward Java.

 You tin parse a String literal containing valid long value into a long primitive type usi How to parse String to long inward Java? Example



String to Long Java Example

Here is our sample Java programme to parse String to long values. In this example, I direct hold used dissimilar long values to demonstrate how parseLong() method works e.g. a elementary long value, a long value amongst addition sign, a long value amongst minus sign in addition to a huge long value which is out of range. Our programme volition throw NumberFormatException for that value in addition to that's why it is commented inward source code. You tin un-comment in addition to run this programme to meet how it behaves.

/**  * Java Program to convert String to long  *   * @author java67  */  public class StringRotateDemo {      public static void main(String args[]) {          // Some long values equally 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);                           // bit method to convert a String literal to long value is         // past times 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 

From output you lot tin meet that converted long values are same equally master copy String, which agency our programme is working properly.



Error spell Parsing String to Long 

You volition acquire next mistake  when you lot sweat to parse an out of arrive at long value equally String literal using Long.parseLong() method :
Exception inward 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 mistake volition equally good come upwardly if you lot exercise Long.valueOf() to practise the parsing, this equally good proves that valueOf() internally calls to parseLong() method for parsing String  :
Exception inward 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

 You tin parse a String literal containing valid long value into a long primitive type usi How to parse String to long inward Java? Example


1) Long.valueOf() method truly calls Long.valueOf(long, radix) method which is used to parse String to long inward whatever radix e.g. binary, octal, decimal in addition to 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 meet that fifty-fifty this method is using parseLong() method to actually convert String to long inward 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 equally good caches oftentimes used primitive value in addition to render same event of Long object. Since Long is Immutable inward Java, its security to part 1 event amongst multiple users. This is equally good a skillful illustration of Fly weight blueprint 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 equally good used inward auto-boxing, you lot should never compare auto-boxed numeric values using == operator inward Java.

2) Constructor of Long shape which takes an String object in addition to render a Long object equally good uses parseLong() method for parsing, equally shown below :

public Long(String s) throws NumberFormatException {         this.value = parseLong(s, 10); }

3) The existent method, parseLong() which does all the operate of parsing throws NumberFormatException for invalid inputs e.g. nil values, empty values, lonely addition or minus sign, alphanumeric String in addition to String amongst out of arrive at long values.


That's all close how to convert String to long inward Java. You should exercise Long.valueOf() method to parse String, if you lot need a Long object in addition to exercise parseLong() method if you lot desire to convert String to primitive long value. Long.valueOf() method equally good provides caching inward arrive at of -128 to 127. By the way, since nosotros direct hold auto-boxing inward Java, which equally good used Long.valueOf() method,  It's ever improve to exercise parseLong() method because it's readable, reveals the existent intention, handles invalid input in addition to specifically designed to parse String literal containing long values.

Further Learning
Data Structures in addition to Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass

No comments:

Post a Comment