UrbanPro
true

Learn Advanced Java coaching from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Create Immutable Class

Paras Chawla
30/05/2017 0 0

Snippet of an Immutable Class:

package com.stringhr;

/*Declare the class as 'final'. This would prevent any other class from extending it

and hence from overriding any method from it which could modify instance variable values.*/

final class ImmutableClass {

 // private variables, thus invisible beyond current class...

      private final int salary;

      private final String name;

 // private constructor, so that child class object can't be instantiated...

      private ImmutableClass(int salary, String name) {

            this.salary = salary;

            this.name = name;

      }

 // Only Getters, no Setter method so that no field can be modified

      public int getSalary() {

            return salary;

      }

      public String getName() {

            return name;

      }

}

Why is String immutable in Java?

The string is immutable for several reasons, here is a summary:

  • Security: Parameters are typically represented as String in network connections, database connection URLs, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
  • String pool: If String weren’t immutable, then we never had a String pool great feature in String class. Let say:

String a=“Paras”;

String b=“Paras”

We all know that a and b points to the same Object in a heap if a changed to ”Chawla”, b will still point to “Paras” which is not possible if String weren’t immutable.

String a="Paras";

String b=a;

System.out.println(a==b);

a="Chawla";

System.out.println(a +b);

Output:

true

  • Synchronization and Concurrency: Making String immutable automatically makes them thread safe thereby solving the synchronization issues. Since String is immutable it can safely share between many threads which are very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally.
  • Caching: When compiler optimizes your String objects, it seems that if two objects have the same value (a="test", and b=" test") and thus you need only one string object (for both a and b, these two will point to the same object). A string is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocations.
  • Class loading: String is used as arguments for class loading. If mutable, it could result in the wrong class being loaded (because mutable objects change their state). Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"

If I have a class with all static members is it immutable?

If your class has only static members, then objects of this class are immutable, because you cannot change the state of that object (you probably cannot create it either).

0 Dislike
Follow 0

Please Enter a comment

Submit

Other Lessons for You

Default Methods in Java 8
Java 8 was released in early 2014 (18th March 2014). Java 8 is a product version. It's development version is JDK1.8 ( Java Development Kit ). Java 8 has some new features that are most awaited in the...
A

Arundhati Pathak

1 0
0

Easy way to remember Java keyword.
ACCESS MODIFIER ACCESS SPECIFIER abstract, assert, const, final, native, static, strictfp, super, synchronized, this, transient, void, volatile public, private, protected, default DATA...

Rohit Deshbhratar

1 0
0

Java Overview
Java platform overview Java platform components The Java platform consists of the following components. The Java language Like any programming language, the Java language has its own structure, syntax...
A

Akshay Shende

0 0
0

JAVA - Object Cloning
JAVA - Object Cloning Is the way of creating the same copy of object without calling the class constructor. It means we can make any class object multiple times without calling its default constructor....

Solution to a trigonometric problem requested by one student
∫ sin 4x cos 2x dx as we don't have any ready made formulae for product of function in integration, let's split it into sum or difference. sin A cos B = 1/2 {sin (A + B ) + sin ( A - B )} A=...
X

Looking for Advanced Java coaching Classes?

The best tutors for Advanced Java coaching Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Advanced Java coaching with the Best Tutors

The best Tutors for Advanced Java coaching Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more