Java – Singleton Class Implementation

Following implementation shows a classic Singleton design pattern:
[code lang=”java”]public class ClassicSingleton {

private static ClassicSingleton instance = null;

protected ClassicSingleton() {
// Exists only to defeat instantiation.

public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
return instance;


Java – Generic Class Example

[code lang=”java”]public class Box {

private T t;

public void add(T t) {
this.t = t;

public T get() {
return t;

public static void main(String[] args) {
Box integerBox = new Box();
Box stringBox = new Box();

integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));

System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());

Integer Value :10
String Value :Hello World

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");