How to Create Immutable Class in Java

In this tutorial, I am going to discuss what is immutable classes in java? How to create custom immutable class in java.

What is immutable class?

Immutable class means, once you created an object of a class you can’t change it’s state or attribute value. In Java, all the wrapper classes like Boolean, Short, Integer, Long, Float, Double, Byte, Char and String classes are the immutable class.

In Effective java, Joshua Bloch makes this compelling recommendation.


“Classes should be immutable unless there’s a very good reason to make them mutableā€¦.If a class cannot be made immutable, limit its mutability as much as possible.”

Best Time to Buy and Sell Stock

How to get maximum profit by buying and selling a stock when at most one transaction is allowed?

In this problem, we have given an array of stock prices, the ith element represents the stock price on ith day.

If we are allowed to complete at most one transaction (i.e.,buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one. If it’s not possible to achieve any profit return 0.

For example –

Example 1-

Input – { 9, 1, 6, 3, 7, 4}

Output – 6 (Buy on day 2 (1) and sell on day 5 (7))

Example 2-

Input – {5, 4, 3, 2, 1}

Output – 0 (It is not possible to do any transaction)

Rotting Oranges

In this tutorial, i am going to discuss a very interesting problem rotting oranges (minimum time required to rot all fresh oranges).

Given an m*n grid where each cell in the matrix can have values 0, 1 or 2.

0 represents an empty cell
1 represents cells have fresh oranges
2 represents cells have rotten oranges

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.