What is the difference between parse and valueof




















Another difference between parseInt and valueOf method is there return type. Integer returns an Integer object, while parseInt method returns an int primitive.

Though, after introduci ng Autoboxing in Java 1. If you look code of parseInt and valueOf method from java. Integer class, you will find that actual job of converting String to integer is done by parseInt method, valueOf just provide caching of frequently used Integer objects, Here is code snippet from the valueOf method which makes things clear:.

This method first calls parseInt method, in order to convert String to primitive int , a nd then creates an Integer object from that value. You can see it internally maintains an Integer cache. If primitive int is within range of cache, it returns Integer object from the pool, otherwise, it creates a new object.

There is always confusion, whether to use parseInt or valueOf for converting String to primitive int and java. Integer , I would suggest use parseInt if you need primitive int and use valueOf if you need java. Integer objects. Since immutable objects are safe to be pooled and reusing them only reduces the load on the garbage collector , it's better to use valueOf if you need an Integer object. Share to Twitter Share to Facebook. Labels: coding , core java , Java Programming Tutorials.

April 25, at PM Anonymous said Newer Post Older Post Home. Subscribe to: Post Comments Atom. Subscribe for Discounts and Updates Follow. Search This Blog. Interview Questions core java interview question data structure and algorithm 78 Coding Interview Question 75 interview questions 70 design patterns 35 SQL Interview Questions 34 object oriented programming 34 thread interview questions 30 spring interview questions 28 collections interview questions 25 database interview questions 16 servlet interview questions 15 Programming interview question 6 hibernate interview questions 6.

How to design a vending machine in Java? How HashMap works in Java? Why String is Immutable in Java? Translate This Blog. Improve Article. Like Article. Previous Integer valueOf Method in Java. Next String to Integer in Java - parseInt.

Recommended Articles. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment? Integer class parseInt. As we can see from the above code, valueOf method passes the String to the parseInt method which performs the actual conversion of String and returns the Wrapper Integer. Then it calls the actual valueOf method, which maintains the pool of Integers ranging to and if the primitive int is within the cache range it returns the Integer from object pool and if the primitive is not within the cache range it will create a new object.

Your email address will not be published. This site uses Akismet to reduce spam. Learn how your comment data is processed. We publish useful tutorials on Java, J2EE and all latest frameworks.



0コメント

  • 1000 / 1000