Code Pumpkin

Wrapper Classes | Interview Questions

April 22, 2017
Posted by Pumpkin
Subscribe

In this post, we will discuss some of the most asked interview questions on wrapper classes.

Java is an object-oriented language and can view everything as an object.

A simple file can be treated as an object (with java.io.File), an address of a system can be seen as an object (with java.util.URL) and an image can be treated as an object (with java.awt.Image) .

Similarly a simple data type can also be converted into an object (with wrapper classes). Here are list of the questions:

  1. What Are Wrapper Classes?
  2. Why Wrapper Classes Were Introduced?
  3. What Is Autoboxing And Unboxing?
  4. When Do Autoboxing And Unboxing Occur ?
  5. Why == Operator Works For Integer Value Until 127 Number?
  6. Why Integer Wrapper Class Caches This Range ?
  7. Can We Increase The IntegerCache Array Range?
  8. What Is The MaxSize Of -XX:AutoBoxCacheMax?
  9. Do All The Wrapper Classes Support Caching?
  10. Why Are Java Wrapper Classes Immutable?


1) What are Wrapper Classes?

As the name suggests, a wrapper class wraps (encloses) around a data type and gives it an object appearance. Wherever, the data type is required as an object, this object can be used.

Wrapper classes also include methods to unwrap the object and give back the data type. 

There are eight wrapper classes available in java.lang package.

  1. Byte 
  2. Short  
  3. Integer  
  4. Long  
  5. Float  
  6. Double  
  7. Character  
  8. Boolean


2) Why Wrapper Classes were introduced?

There were mainly two reasons:

  1. If you have been using Collections like Stack or Vector before Java 1.5, then you are familiar with the issues like you can not directly put primitives into Collections, instead, you first need to convert them into Object and then only you can put them into Collections. Wrapper classes like Integer, Double and Boolean helps for converting primitive to Object.
  2. To convert Strings into data types (known as parsing operations), here methods of type parseXXX() are used i.e. Integer.parseInt() and Float.parseFloat()


3) What is Autoboxing and Unboxing?

When Java automatically converts a primitive type into corresponding wrapper class object e.g. int to Integer, than its called autoboxing  because primitive is boxed into wrapper class while opposite case is called unboxing, where an Integer object is converted into primitive int.

Since the whole process happens automatically without writing any code for conversion its called autoboxing and auto-unboxing.

Compiler uses valueOf() method to convert primitive to Object and uses xxxValue() i,e, intValue(), doubleValue() etc to get primitive value from Object.
 


4) When do Autoboxing and Unboxing occur ?

Autoboxing and unboxing can happen anywhere where an object is expected and primitive type is available and vice versa. For Example,

  1. Adding primitive types into Collection like ArrayList in Java
  2. Creating an instance of parameterized classes e.g. ThreadLocal which expect Type
  3. In method invocation, where an object argument is expected,  if you pass primitive, Java automatically converts primitive into equal value Wrapper Object.
  4. while assigning primitive types to object type references.


5) Why == operator works for Integer value until 127 number?

What will be the output of the below java code..?


class CodePumpkinDemo 
{
	public static void main(String[] args)
	{
		Integer n1 = new Integer(100);
		Integer n2 = new Integer(100);
		
		Integer n3 = 127;
		Integer n4 = 127;
		
		Integer n5 = 128;
		Integer n6 = 128;
		
		System.out.println(n1==n2);
		System.out.println(n3==n4);
		System.out.println(n5==n6);
	}
	
}

output :

false
true
false
 

Integer class caches value of integer from -128 to 127 using inner class IntegerCache. 256 Integer objects are created in the range of -128 to 127 which are all stored in an Integer array. 

As we discussed in Question 3, Compiler internally uses valueOf()  method for Autoboxing and whenever we try to assign Integer object with value from -128 to 127, it uses the cached object from IntegerCache array. So == operator will always return true in this range i.e. n3==n4 -> true

But when we assign any value which is out of this range, compiler creates new Integet()  object and hence == will  return false out of this range i.e.  n5==n6 -> false.

Also caching happens only if you use Integer.valueOf(int), not if you use new Integer(int). Here, n1 and n2  are created using Integer constructor Integer(int), so n1 == n2 -> false.


6) Why Integer wrapper class caches this range ?

To improve performance of Autoboxing and unboxing as compiler calls valueOf() method internally.

This short range are generally used for performance of public static valueOf(int n)  as this method is likely to yield significantly better space and time performance by caching frequently requested values.


7) Can we increase the IntegerCache array range?

Upto Java 5 and even in some older version of Java 6, this range was hardcoded from -128 to 127. You can check the internal code here.

From Java 7 (and some of the newer versions of Java 6), the implementation of the IntegerCache class has changed, and the upper bound is no longer hardcoded, but it is configurable.

The cache can be initialized on first usage.  The size of the cache may be controlled by the  -XX:AutoBoxCacheMax=<size> option and it is being set in property java.lang.Integer.IntegerCache.high during VM initialization.

For Example,

You can set the -XX:AutoBoxCacheMax=1000, and it will catch integer upto 1000 which means following code will results true


Integer integer1 = 1000;
Integer integer2 = 1000;

System.out.println(integer1 == integer2);   // true

Similar to IntegerCache, many changes have also been done in JVM String Pool implementations in Java 7 and Java 8.


8) What is the MaxSize of -XX:AutoBoxCacheMax?

Max cache size can’t be more than -Xmx (which is JVM heap size) . Heap size is defined by vm argument -Xmxm .

As soon as JVM is initialized, it allocates the memory for caching purpose.

You can’t allocate whole (-Xmx in byte)/4 (4byte is size of  int) for AutoBoxCache, because other objects are also  required to be loaded and you might end up with java.lang.OutOfMemoryError: Java heap space.


9) Do all the wrapper classes support caching?

Yes, all of them do support to increase performance of Autoboxing and Auto-unboxing.

But unlike Integer, they have fixed caching size upto 127 only. You can not enhance the range.


10) Why are Java wrapper classes immutable?

Here are some reasons for making wrapper classes immutable:

  1. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe and the overhead caused due to use of synchronisation is avoided.
  2. The references to the immutable objects can be easily shared or cached without having to copy or clone them as their state can not be changed ever after construction.
  3. The best use of the immutable objects is as the keys of a HashMap or Elements of HashSet. For detailed understanding of HashMap or HashSet internals, you can refer our articles
    – How does HashMap work internally in Java? 
    – How is HashSet implemented internally in Java?

That's all for this topic. If you guys have any suggestions or queries, feel free drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here

Happy Learning 🙂


Further Reading For interview Preparation

  1. interface VS abstract class
  2. Access Modifiers (public, private, protected and default scope)
  3. HashMap vs Hashtable Vs SynchronizedMap Vs ConcurrentHashMap
  4. CountDownLatch Vs CyclicBarrier
  5. How To Create Immutable Class In Java
  6. What is the use of private constructor in java?
  7. final Keyword
  8. transient Keyword

You can also check our articles on Java8 and Java9 Features like 


Tags: , , , , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.

Total Post : 80
Subscribe
Contribute Your Articles

Interview Experiences

Related Books

Like Us On Facebook

Alexa Page Rank