4

I came across an example in the OCJP book. It says

Integer y=new Integer("20");
y++;   (un-wraps it)
System.out.println(y);

Now, this would print 21. Hence, it makes me think, how did the compiler even know that at y++ it should unwrap it to int and increment it? Integer is just a normal class(may is say Wrapper class??), is it operator overloading that is inbuilt inside?

Is there a way I can do this for my own custom class if possible?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
codemania23
  • 913
  • 11
  • 19

1 Answers1

1

Java uses a feature called Autoboxing and Unboxing to unwrap that integer and increment it. You cannot implement this feature in your own user-defined classes. It is only available for those wrapper classes for Java primitive types.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • thanks for answering my question, i was not aware of autoboxing and unboxing, could u please confirm what happens in ==, when i do == on two objects, it checks for its reference, and when i do == on strings, it checks in the literal pool ? – codemania23 Jun 04 '15 at 15:39
  • 2
    @codemania23 Please search for answers to your questions instead of asking unrelated follow-up questions in comments. – Bill the Lizard Jun 04 '15 at 15:41
  • thanks for the help anyways :), appreciate it !! – codemania23 Jun 04 '15 at 15:43