You can parse a String literal containing valid long value into long primitive type using parseLong() and valueOf() method of java.lang.Long class of JDK. Though there are couple of difference between valueOf() and parseLong() method e.g. valueOf() method return a Long object while parseLong() method return a Long object, but given we have autoboxing in Java, both method can used for parsing String to create long values. In last article, you have learned how to convert Long value to String in Java and in this tutorial, you will learn opposite, i.e. how to parse an String to long value in Java. As I said, there are couple of ways to do it, but the most important method is parseLong(). This method is responsible for parsing input String and creating primitive long value corresponding to input String. It does input validation and throws NumberFormatException if you pass String which is not valid long value e.g. alphanumeric String, String containing characters other than +, - and numbers, long values which are out of range, lonely + or - character etc. You can also use constructor of Long class which accepts a String and returns a Long object, but internally it also uses parseLong() method. BTW, if you have just started learning Java or looking forward to learn Java from scratch, I suggest you to take a look at Cay S. Horstmann's Core Java Volume 1, 9th Edition book. You will learn most of Java fundamentals in quick time.
Read more »
No comments:
Post a Comment