Course Content
Keywords
Operators
Loops
String
Array
Object Oriented Principle
Memory Management
Collection Framework
Exception Handling
Reflection API
Multi Threading
File Handling
Java Version wise Questions
Java Scenario Based Interview Questions
About Lesson
Scenario: You need to convert a String to an int in your application. What are the different ways to do this, and which one would you prefer?

Detailed Answer:

In Java, there are two common methods to convert a String to an integer:

 

  • Integer.parseInt(String):
    • This method converts a String to a primitive int.
    • It is lightweight and efficient because it directly returns a primitive value.
    • Example:
      String str = "123";
      int primitiveInt = Integer.parseInt(str); // Returns primitive int
      

 

  • Integer.valueOf(String):
    • This method converts a String to an Integer object (wrapper class).
    • It is useful when you need an Integer object instead of a primitive int.
    • It also leverages the Integer cache for values between -128 and 127, which can improve performance and memory usage.
    • Example:
      String str = "123";
      Integer wrapperInt = Integer.valueOf(str); // Returns Integer object

 


Why Use valueOf() for Wrapper Classes and parseInt() for Primitives?
  1. Integer.parseInt():
    • Use this when you need a primitive int.
    • It is faster and more memory-efficient because it avoids creating an additional Integer object.
    • Example use case: When performing arithmetic operations or storing values in primitive arrays.
  2. Integer.valueOf():
    • Use this when you need an Integer object.
    • It is useful when working with collections (e.g., ArrayList<Integer>) or APIs that require objects.
    • It also benefits from the Integer cache, which reuses Integer objects for small values (-128 to 127), reducing memory overhead.
    • Example use case: When storing values in collections or passing them to methods that expect objects.