immutability in java | java immutability example | immutable classes in java | explain immutability
GIT Repository URL
https://github.com/ChandraKodam5/java
immutability in java | java immutability example | immutable classes in java | explain immutability in java
How to achieve immutability in java
best immutable example
#java #immutable
java interview questions | core java interview questions
Q : Explain about immutability in java ? Why String is immutable in java ? How to write custom immutable class in java ?
A : An immutable object (unchangeable object) is an object whose state cannot be modified after it is instantiated (created). In Java, String class and all the Wrapper classes (like Boolean, Byte, Short, Integer, Long and Double) are immutable. We can create our own immutable class as well.
Following are the requirements to create immutable class :
1. The class must be declared as final (So that child classes can’t be created)
2. Fields in the class must be declared as private (So that direct access is not allowed)
3. A parameterized constructor should initialize all the fields performing a deep copy (So that fields can’t be modified with object reference)
4. Fields in the class must be declared as final (So that no one can change the value, after object creation)
5. Deep Copy of objects should be performed in the getter methods (To return a copy rather than returning the actual object reference)
6. No setters (Do not have the option to change the value of the instance variable)
Take the source code from the below GIT repository,
Enter this URL on browser - https://github.com/ChandraKodam5/java
Click on Code Drop-down
Click on Download ZIP
Open eclipse IDE
Goto File → Import → Existing projects into workspace → Next → click on checkbox (select archive file) → click on Browse → choose the downloaded ImmutableProject ZIP file.
OR
Type the below command in git bash
$ git clone https://github.com/ChandraKodam5/java.git
Goto File → Import → Existing projects into workspace → Next → click on checkbox (select archive file) → click on Browse → choose the downloaded ImmutableProject ZIP file.
Import the ImmutableProject into eclipse as shown in the video.
Furthermore questions,
Q1 : Can we use non-immutable class in a immutable class ?
A1 : No. It is not recommended to use non-immutable class in a immutable class. Because, it makes the programmer to modify the state of the immutable class.
Q2 : How can you handle List & Map in immutable class ?
A2 : We have to handle or achieve by creating deep copy of the List and Map.
Q3 : Why do we need to add a immutable object to HashSet or HashMap ?
A3 : Immutable objects are good to add as keys in Map and elements in Set, since these are typically do not change once created.
Q4 : What is the difference between immutable and final ?
A4 : Final means that you can't change the object's reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g). Where immutable means that the object's actual value can't be changed, but you can change its reference to another one
Q5 : What are the advantages of having immutable concept in java ?
A5.
1. Immutable objects are thread-safe so you will not have any synchronization issue because their data cannot change.
2. They are less prone to error and more secure
3. Immutable objects are consistent in result because of that we are adding them into the Set and Map
4. Immutable classes are easier to design, implement
5. Never have to lock the immutable objects, which extremely improves concurrency. They can share structure, which reduces memory usage.
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «immutability in java | java immutability example | immutable classes in java | explain immutability», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.