Java – Create Immutable Class Example

[code lang=”java”]// declare class as final
final class Immutable {

// declare all variables as final
private final int val1;
private final String val2;

// provide constructor to set the values
public Immutable(int a, String s) {
val1 = a;
val2 = s;

// provide getters only
public int getVal1() {
return val1;

public String getVal2() {
return val2;
[code lang=”java”]public class ImmutableClassDemo {
public static void main(String[] args) {
Immutable obj = new Immutable(10, "Immutable Class Example");