How to create Immutable class in Java

Last updated on Dec 24 2022
Prabhas Ramanathan

There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members as the example given below:

Table of Contents

Example to create Immutable class

In this example, we have created a final class named Employee. It have one final datamember, a parameterized constructor and getter method.

1. public final class Employee{ 
2. final String pancardNumber; 
3. 
4. public Employee(String pancardNumber){ 
5. this.pancardNumber=pancardNumber; 
6. } 
7. 
8. public String getPancardNumber(){ 
9. return pancardNumber; 
10. } 
11. 
12. }

The above class is immutable because:
• The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
• The class is final so we cannot create the subclass.
• There is no setter methods i.e. we have no option to change the value of the instance variable.
These points makes this class as

Java toString() method

If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Advantage of Java toString() method

By overriding the toString() method of the Object class, we can return values of the object, so we don’t need to write much code.

Understanding problem without toString() method

Let’s see the simple code that prints reference.

1. class Student{ 
2. int rollno; 
3. String name; 
4. String city; 
5. 
6. Student(int rollno, String name, String city){ 
7. this.rollno=rollno; 
8. this.name=name; 
9. this.city=city; 
10. } 
11. 
12. public static void main(String args[]){ 
13. Student s1=new Student(101,"Raj","lucknow"); 
14. Student s2=new Student(102,"Vijay","ghaziabad"); 
15. 
16. System.out.println(s1);//compiler writes here s1.toString() 
17. System.out.println(s2);//compiler writes here s2.toString() 
18. } 
19. }

Output:Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let’s understand it with the example given below:

Example of Java toString() method

Now let’s see the real example of toString() method.

1. class Student{ 
2. int rollno; 
3. String name; 
4. String city; 
5. 
6. Student(int rollno, String name, String city){ 
7. this.rollno=rollno; 
8. this.name=name; 
9. this.city=city; 
10. } 
11. 
12. public String toString(){//overriding the toString() method 
13. return rollno+" "+name+" "+city; 
14. } 
15. public static void main(String args[]){ 
16. Student s1=new Student(101,"Raj","lucknow"); 
17. Student s2=new Student(102,"Vijay","ghaziabad"); 
18. 
19. System.out.println(s1);//compiler writes here s1.toString() 
20. System.out.println(s2);//compiler writes here s2.toString() 
21. } 
22. }

Output:101 Raj lucknow
102 Vijay ghaziabad

StringTokenizer in Java

The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string.
It doesn’t provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
Constructors of StringTokenizer class
There are 3 constructors defined in the StringTokenizer class.

Constructor Description
StringTokenizer(String str) creates StringTokenizer with specified string.
StringTokenizer(String str, String delim) creates StringTokenizer with specified string and delimeter.
StringTokenizer(String str, String delim, booleanreturnValue) creates StringTokenizer with specified string, delimeter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.

The 6 useful methods of StringTokenizer class are as follows:

Public method Description
booleanhasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
booleanhasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.

Simple example of StringTokenizer class

Let’s see the simple example of StringTokenizer class that tokenizes a string “my name is khan” on the basis of whitespace.

1. import java.util.StringTokenizer; 
2. public class Simple{ 
3. public static void main(String args[]){ 
4. StringTokenizer st = new StringTokenizer("my name is khan"," "); 
5. while (st.hasMoreTokens()) { 
6. System.out.println(st.nextToken()); 
7. } 
8. } 
9. }

Output:my
name
is
khan

Example of nextToken(String delim) method of StringTokenizer class

1. import java.util.*; 
2. 
3. public class Test { 
4. public static void main(String[] args) { 
5. StringTokenizer st = new StringTokenizer("my,name,is,khan"); 
6. 
7. // printing next token 
8. System.out.println("Next token is : " + st.nextToken(",")); 
9. } 
10. }

Output:Next token is : my
StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).

How to reverse String in Java

There are many ways to reverse String in Java. We can reverse String using StringBuffer, StringBuilder, iteration etc. Let’s see the ways to reverse String in Java.
1) By StringBuilder / StringBuffer
File: StringFormatter.java

1. public class StringFormatter { 
2. public static String reverseString(String str){ 
3. StringBuilder sb=new StringBuilder(str); 
4. sb.reverse(); 
5. return sb.toString(); 
6. } 
7. }

File: TestStringFormatter.java

1. public class TestStringFormatter { 
2. public static void main(String[] args) { 
3. System.out.println(StringFormatter.reverseString("my name is khan")); 
4. System.out.println(StringFormatter.reverseString("I am sonoo jaiswal")); 
5. } 
6. }

Output:
nahksiemanym
lawsiajoonos ma I

2) By Reverse Iteration

File: StringFormatter.java

1. public class StringFormatter { 
2. public static String reverseString(String str){ 
3. char ch[]=str.toCharArray(); 
4. String rev=""; 
5. for(int i=ch.length-1;i>=0;i--){ 
6. rev+=ch[i]; 
7. } 
8. return rev; 
9. } 
10. }

 

File: TestStringFormatter.java

1. public class TestStringFormatter { 
2. public static void main(String[] args) { 
3. System.out.println(StringFormatter.reverseString("my name is khan")); 
4. System.out.println(StringFormatter.reverseString("I am sonoo jaiswal")); 
5. } 
6. }

Output:
nahksiemanym
lawsiajoonos ma I

So, this brings us to the end of blog. This Tecklearn ‘How to create Immutable class in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "How to create Immutable class in Java"

Leave a Message

Your email address will not be published. Required fields are marked *