Showing posts sorted by relevance for query how-to-parse-string-to-long-in-java. Sort by date Show all posts
Showing posts sorted by relevance for query how-to-parse-string-to-long-in-java. Sort by date Show all posts

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

Tuesday, December 10, 2019

2 Ways To Parse String To Int Inward Java

Java provides Integer.parseInt() method to parse a String to an int value, merely that's non the exclusively means to convert a numeric String to int inward Java. There is, inward fact, a amend way, which takes wages of the parsing logic of parseInt() method every bit good every bit caching offered past times Flyweight blueprint pattern, which makes it to a greater extent than efficient together with useful. Yes, you lot guessed it right, I am talking almost Integer.valueOf() method, which implements Flyweight blueprint pattern together with maintains a cached puddle of ofttimes used int values e.g. from -128 to 127. So every fourth dimension you lot overstep a numeric String which is inward the hit of -128 to 127, Integer.valueOf() doesn't create a novel Integer object merely render the same value from cached pool. The exclusively drawback is that Integer.valueOf() returns an Integer object together with non an int primitive value similar parseInt() method, merely given auto-boxing is available inward Java from JDK five onward, which automatically convert an Integer object to int value inward Java.



2 Examples to Parse String to int inward Java

Here is our Java programme to convert String to int inward Java. This instance shows how to purpose both Integer.parseInt() together with Integer.valueOf() method to parse a numeric String to an int primitive inward Java. In this program, nosotros inquire the user to travel into a number together with thus nosotros read user input from the console using Scanner cast every bit String. Later nosotros convert that String using both Integer.parseInt() together with Integer.valueOf() method to demo that both methods run together with you lot tin dismiss purpose either of them.




Java Program to Parse String to Int

import java.util.Scanner;  /**  * two ways to convert String to int inward Java.  * User enters number, nosotros read it every bit String together with convert it to int using parseInt() method.  *   * @author WINDOWS 8  *  */ public class StringToInt {      public static void main(String args[]) {         System.out.println("Please travel into an integer number");                Scanner scnr = new Scanner(System.in);        String input = scnr.nextLine();                int i = Integer.parseInt(input);                System.out.println("String converted to int : " + i);                System.out.println("Please travel into closed to other integer number");                String str = scnr.nextLine();                int j = Integer.valueOf(str); // tin dismiss render cached value                System.out.println("String to int using valueOf() : " + j);              }       }  Output : Please travel into an integer number 100 String converted to int : 100 Please travel into closed to other integer number 300 String to int using valueOf() : 300

You tin dismiss come across that both Integer.valueOf() together with Integer.parseInt() method is able to parse a numeric String. You tin dismiss fifty-fifty overstep a numeric String amongst Plus together with Minus sign, both methods are capable of parsing them successfully every bit shown below :
Please travel into an integer number +201 String converted to int : 201 Please travel into closed to other integer number -203 String to int using valueOf() : -203

merely if you lot overstep a String which contains anything other than +, - together with digits, you lot volition acquire java.lang.NumberFormatException every bit shown below :
Please travel into an integer number ++201 Exception in thread "main" java.lang.NumberFormatException: For input string: "++201"     at java.lang.NumberFormatException.forInputString(Unknown Source)     at java.lang.Integer.parseInt(Unknown Source)     at java.lang.Integer.parseInt(Unknown Source)     at dto.ReverseIntegerTest.main(ReverseIntegerTest.java:22)

You tin dismiss come across fifty-fifty double sign is besides non allowed, let's endeavor an alphanumeric String :
Please travel into an integer number 2012a44 Exception in thread "main" java.lang.NumberFormatException: For input string: "2012a44"     at java.lang.NumberFormatException.forInputString(Unknown Source)     at java.lang.Integer.parseInt(Unknown Source)     at java.lang.Integer.parseInt(Unknown Source)     at dto.ReverseIntegerTest.main(ReverseIntegerTest.java:22)

You tin dismiss come across that Integer.parseInt() doesn't similar anything other valid values inward numeric String. You volition acquire same errors fifty-fifty if you lot purpose Integer.valueOf() method because valueOf() method internally calls parseInt() method to parse String to integer inward Java.

s non the exclusively means to convert a numeric String to int inward Java two ways to parse String to int inward Java

That's all almost how to parse String to int inward Java. Even though parseInt() is the criterion means to parse String to int, you lot should endeavor to purpose Integer.valueOf() method. It implements Flyweight blueprint pattern together with maintains a puddle of ofttimes used int values e.g. int primitives from -128 to 127 together with that's how it relieve retention together with time.

Though, you lot bespeak to last careful piece comparison it because if you lot purpose  equality operator (== )then Java compare their references together with render truthful exclusively if both variables are pointing to the same object e.g. ane of the Integer objects returned from a cached pool.

So you lot mean value that == operator is working merely thus you lot volition come across issues when Integer object is exterior of that range, inward that case, == operator volition non work. In short, you lot receive got created a põrnikas which is difficult to find. See this story to larn to a greater extent than almost this bug.

 BTW, if you lot are learning Java together with desire to master copy fundamentals, I advise you lot receive got a await at Head First Java 2d Edition, they explicate the concept inward the easiest means possible merely besides brings out of import details.



If you lot are novel to Java together with wants to larn almost how to convert ane type to another, cheque out my next information type conversion tutorials :
  • How to convert String to Double inward Java? (example)
  • How to convert ByteBuffer to String inward Java? (program)
  • How to convert double to Long inward Java? (program)
  • How to convert float to String inward Java? (example)
  • How to convert byte array to String inward Java? (program)
  • How to convert Enum to String inward Java? (example)
  • How to convert String to int inward Java? (example)
  • How to convert Decimal to Binary inward Java? (example)
  • How to convert String to Date inward a thread-safe manner? (example)
  • How to parse String to long inward Java? (answer)

Further Learning
Data Structures together with Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass

Wednesday, December 11, 2019

How To Convert String To Float Inward Coffee In Addition To Vice-Versa - Tutorial

There are 3 ways to convert a String to float primitive inwards Java parseFloat(), valueOf() method of Float cast in addition to new Float() constructor. Suppose you lot own got String which represents a floating betoken publish e.g. "3.14" which is the value of PIE, you lot tin convert it to float yesteryear using whatever of those 3 methods. Since String is ane of the most prominent information types inwards Java, you lot volition often detect yourself converting String to Int, Double, in addition to other information types in addition to vice-versa. Java designer knows most that in addition to they own got made scheme to behave out this basic project inwards a predictable in addition to consistent manner. Once you lot know the play a trick on to convert String to float, you lot should travel able to convert String to Integer, Double, in addition to Short. BTW, converting String to a byte array is a niggling chip tricky because String is text information in addition to bytes are binary, thence grapheme encoding comes into the picture. If you lot desire to larn to a greater extent than most how to create conversion betwixt String in addition to byte array, come across this step yesteryear measurement tutorial for String to a byte array.


String to Float Conversion inwards Java

As I said, at that spot are 3 primary ways to convert a String to float primitive inwards Java
  • Float.parseFloat()
  • Float.valueOf()
  • new Float()

The offset method should travel your default pick because its meant for that travel in addition to all to a greater extent than or less other method internally utilization this method for parsing floating betoken String to a existent float value. If you lot overstep an invalid floating betoken String e.g. something which has alphabets or grapheme other '+' or '-'.

In all cases, autoboxing volition accept attention of converting an object of Float wrapper cast to float primitive variable. One payoff of the minute method it reads good in addition to besides provides caching of oft used numbers. Third means internally uses the offset method to convert String to float variable in addition to and thence convert it to Float object.




Float to String Conversion inwards Java

On opposite side also, at that spot are 3 primary ways to convert a float variable to String inwards Java. It could travel Float object or float primitive, both volition work. Here are the methods to convert a float primitive or Float object dorsum to String containing floating betoken value :
  • String concatenation
  • Float.toString() method
  • String.valueOf() method

String concatenation amongst empty String method plant for both float primitive in addition to Float object, exactly the fundamental is to utilization empty String offset in addition to and thence position floating betoken value missive of the alphabet because in addition to thence solely Java sympathise that + operator is at that spot for String concatenation in addition to non for adding 2 floating betoken value. If you lot utilization Float object in addition to thence it's toString() method is called automatically.

You tin besides come across Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to larn to a greater extent than most unlike static mill methods to convert ane type of variable to other primitive or wrapper type inwards Java.

 There are 3 ways to convert a String to float primitive inwards Java  How to convert String to Float  inwards Java in addition to vice-versa - Tutorial


 BTW, if you lot already own got Float object in addition to thence you lot don't demand to create String concatenation because calling Float.toString()  will anyway give you lot floating betoken String you lot are looking for. The final method String.valueOf() takes a floating-point value in addition to convert it to String, which is returned yesteryear this method, thence don't forget to shop the lawsuit because String objects are Immutable inwards Java.
 There are 3 ways to convert a String to float primitive inwards Java  How to convert String to Float  inwards Java in addition to vice-versa - Tutorial

import java.util.Arrays; import java.util.List;   /**  * Java Program to convert String to float in addition to vice-versa.  *  * @author WINDOWS 8  */  public class Test {         public static void main(String args[]){             // let's offset larn how to convert String to float inwards Java         String decimal = "100.25";               // offset nosotros tin utilization parseFloat() method to convert String to Float         float f = Float.parseFloat(decimal);             System.out.println("float equvialent of String " + decimal + " is : " + f);               // yell back it's non necessary that String ever has floating point         // thence this is besides Ok               f = Float.parseFloat("200");         System.out.println("String 200 inwards float is : " + f);               // to a greater extent than or less other means to convert String to float is yesteryear using valueOf() method               String pie = "3.14";         float publish = Float.valueOf(pie);         System.out.println(pie + " inwards float is : " + number);                     // 3rd means to parse String to float is yesteryear using Float constructor         // though this volition render object of Float wrapper class         // autoboxing volition convert it to float primitive         String multiplier ="1.5";         float constant = new Float(multiplier);         System.out.println("String '1.5' is equal to float : " + constant);                     // Now let's create the reverse         // Now nosotros own got a float primitive in addition to nosotros demand to convert it to String inwards Java         // simplest means to create is String concatenation               float quarter = .25f;         String fromFloat = "" + quarter;         System.out.println("float " + f + " is converted to String : " + fromFloat);                     // Second tardily means to convert float variable to String is yesteryear using toString()         // method of Float wrapper cast               Float one-half = Float.valueOf(.5f);         String str = half.toString();         System.out.println("Float " + one-half + " is converted to String : " + str);                     // Another means to parse a floating betoken publish every bit String yesteryear using         // java.lang.String valueOf(float f) method         // this method render float equivalent of String passed in.         float onethird = .75f;         String floatingpoint = String.valueOf(onethird);         System.out.println("float " + onethird + " is equal to String : " + floatingpoint);     }   }   Output float equvialent of String 100.25 is : 100.25 String 200 inwards float is : 200.0 3.14 inwards float is : 3.14 String '1.5' is equal to float : 1.5 float 200.0 is converted to String : 0.25 Float 0.5 is converted to String : 0.5 float 0.75 is equal to String : 0.75


That's all on how to convert String to float inwards Java in addition to vice-versa. These kinds of niggling tricks aid to amend productivity because you lot don't demand to hold off dorsum to google to detect how to create this job. As an sense Java developer, you lot must know how to create to a greater extent than or less basic materials without looking at Google.

Further Learning
Data Structures in addition to Algorithms: Deep Dive Using Java
tutorial)
  • How to convert Double to Long inwards Java? (tutorial)
  • How to convert Array to String inwards Java? (tutorial)
  • 5 Ways to convert Java 8 Stream to List? (solution)
  • How to convert a binary publish to decimal inwards Java? (tutorial)
  • 5 examples of converting InputStream to String inwards Java? (tutorial)
  • How to convert Character to String inwards Java? (tutorial)
  • 3 examples of converting Array to ArrayList inwards Java (tutorial)
  • How to convert ArrayList to Set inwards Java? (tutorial)