- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Primitive Wrapper Classes are Immutable in Java
In Java Immutable class is a class which once created and it's contents can not be changed.On same concept Immutable objects are the objects whose state can not be changed once constructed.
Wrapper classes are made to be immutable due to following advantages −
Since the state of the immutable objects can not be changed once they are created they are automatically synchronized.Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.
Once created the state of the wrapper class immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
The best use of the wrapper class as immutable objects is as the keys of a map.
Also due to immutability of wrapper class instances the purpose of caching is to facilitate sharing. So, if you have a dozen places in your application that needed to have the Integer instance with a value of 42, then you can use only one instance instead.
Example to show wrapper class as immutable.
class Demo { public static void main(String[] args) { Integer i = new Integer(20); //initialize a object of Integer class with value as 20. System.out.println(i); operate(i);// method to change value of object. System.out.println(i); //value doesn't change shows that object is immutable. } private static void operate(Integer i) { i = i + 1; } }
Output
20 20
- Related Articles
- What are wrapper classes in Java?
- Explain wrapper classes in Java?
- What is the need of wrapper classes in Java?
- Java Program to wrap a Primitive DataType in a Wrapper Object
- How to convert primitive data into wrapper class using Java?
- How to convert Wrapper value array list into primitive array in Java?
- Why string objects are immutable in java?
- What are primitive data types in Java?
- What are Java classes?
- What are final classes in Java?
- What are abstract classes in Java?
- What are inner classes in Java?
- Immutable String in Java
- Java Float Wrapper Class
- What are anonymous inner classes in Java?
