Nearby lessons

50 of 125

Java - Number, Boolean and Character

📌 What You Will Learn
  • Why wrapper classes exist
  • How to convert primitive to object and object to primitive
  • Autoboxing and unboxing (automatic conversion)
  • Important methods: valueOf, parseXxx, toString, xxxValue
  • The famous Integer caching (range -128 to 127)

Number, Boolean and Character is a core concept of the Java language. This lesson explains Important Methods of Wrapper Classes with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Important Methods of Wrapper Classes

Wrapper classes give many useful static methods. Memorise these five families:

MethodPurposeExample
valueOf(String)Convert a String into a wrapper objectInteger.valueOf("100")
parseXxx(String)Convert a String into a primitiveInteger.parseInt("100") -> int 100
toString(xxx)Convert a primitive into StringInteger.toString(100) -> "100"
xxxValue()Convert wrapper to primitivei.intValue(), d.doubleValue()
MIN_VALUE / MAX_VALUERange constants of each typeInteger.MAX_VALUE
Trainer's Note: Classic interview question: what is the difference between parseInt and valueOf? parseInt("100") returns an int (primitive). valueOf("100") returns an Integer (object). One gives the gift, the other gives the gift in a box.
In simple words: `parseInt` returns a primitive `int`; `valueOf` returns an `Integer` object. Use parseInt when you need a number to calculate with, and valueOf when you need an object for a collection.
Example01
JCode Cell
1class WrapperMethods {
2 public static void main(String[] args) {
3 int x = Integer.parseInt("456"); // String -> int
4 double y = Double.parseDouble("45.67"); // String -> double
5 String s = Integer.toString(123); // int -> String
6 
7 Integer obj = Integer.valueOf("789"); // String -> Integer object
8 int back = obj.intValue(); // Integer -> int
9 
10 System.out.println(x + " " + y + " " + s + " " + back);
11 }
12}
Output
456 45.67 123 789
📝 Key Takeaways
  • Wrapper classes box each primitive into an object: int->Integer, char->Character, etc.
  • Autoboxing converts primitive to wrapper automatically; unboxing does the reverse.
  • parseInt returns primitive int; valueOf returns Integer object.
  • Use equals() not == for wrapper objects and Strings.
  • Integer values from -128 to 127 are cached, so == can be true for small values.
  • Collections can store only objects, so wrappers are essential there.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2