Sunday, 29 September 2024

Singleton class with lazy and unbreakable

Lazy initialization single ton class

package com.example.practice.student.service;

public class SingletonClassExample {
private static volatile SingletonClassExample singletonClassExample;

private SingletonClassExample() {
}

public static synchronized SingletonClassExample getInstance() {
if (singletonClassExample == null) {
System.out.println("pawankumar");
return singletonClassExample= new SingletonClassExample();
//return singletonClassExample = new SingletonClassExample();
}
return singletonClassExample;
}

public void displayMsg() {
System.out.println("call from singleton class");
}

public static void displayMsg1() {
System.out.println("call from singleton class");
}
}


For Eager Initialization on declaration on instance variable  do assignment of object 


private static volatile SingletonClassExample singletonClassExample= new SingletonClassExample();



 unbreakable singleton class



package com.example.practice.student.service;

import java.io.Serializable;

public class UnbreakableSingClass implements Serializable,Cloneable {

private static UnbreakableSingClass unbrak;
private static boolean objectCreated=false;


private UnbreakableSingClass UnbreakableSingClass() {
if(objectCreated) {
throw new RuntimeException("objet");
}else {
return unbrak;
}
}

public static UnbreakableSingClass getIntanance() {
if(unbrak==null) {
synchronized (UnbreakableSingClass.class) {
if(unbrak==null) {
return unbrak=new UnbreakableSingClass();
}
}
}
return unbrak;
}

@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Cloning of this singleton is not allowed.");
}

protected Object readResolve() {
return getIntanance();
}

}

Thursday, 19 September 2024

Java Collection methods.

Collection framework 

List Interface:-

List Interface extends Collection Interface
Collection Interface extends Iterable Interface

1 Iterable Interface Methods

Iterator:-
forEach:-



Collection interface methods:-

List Interface methods:- 





Set interface method:-



Map interface methods:-





Thursday, 12 September 2024

Class and inner class example

 public class OuterClass2 {

    private String outerField = "Outer Class Field";

public void outerMethod() {
// Local inner class inside a method
class LocalInnerClass {
public void display() {
System.out.println("Accessing outer class field from local inner class: " + outerField);
}
}

// Creating an instance of the local inner class inside the method
LocalInnerClass localInner = new LocalInnerClass();
localInner.display();
}

public static void main(String[] args) {
OuterClass2 outer = new OuterClass2();
outer.outerMethod();
}
}