JAVA Interview Questions (1)..........pdf

prasadkhotkar916 16 views 33 slides Jan 29, 2025
Slide 1
Slide 1 of 33
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33

About This Presentation

Nothing special


Slide Content

BasicJavaInterviewQuestions
1.Whatis?
Javaisahigh-level,object-oriented,platform-independentprogramminglanguage.Key
features:
●Platform-independent:Codecanrunondifferentplatformswithoutmodification
usingJVM.
●Highperformance:JITcompilerconvertsbytecodetomachinecodeforfaster
execution.
●Multi-threaded:Supportsconcurrenttaskhandling.
●Nomultipleinheritancethroughclasses:Achievedusinginterfaces.
●Security:Noexplicitpointers;strongmemorymanagementwithgarbagecollection.
2.OOPConcepts
●Inheritance:Codereusebetweensuperclassesandsubclasses;privatemembersare
notinherited.
●Encapsulation:Protectscodebymakingvariablesprivateandusinggetter/setter
methods.
●Polymorphism:Objectsbehavedifferentlybasedontheirtype(methodoverriding).
●Abstraction:Hidesimplementationdetailswhileexposingessentialfeatures.
●Interface:Providesmultipleinheritancebydefiningmethoddeclarations.
3.AccessModifiers
●Default:Accessiblewithinthesamepackage.
●Private:Accessibleonlywithinthedeclaringclass.
●Protected:Accessibleinthesamepackageorsubclassesinotherpackages.
●Public:Accessibleeverywhere.
4.SOLIDPrinciples
●SingleResponsibility:Eachclasshasoneresponsibility.
●Open-Closed:Classesshouldbeopentoextensionbutclosedtomodification.
●LiskovSubstitution:Subtypesmustbesubstitutablefortheirbasetypes.

●InterfaceSegregation:Avoidforcingclientstoimplementunusedmethods.
●DependencyInversion:High-levelmodulesdependonabstractions,notconcrete
implementations.
5.PrimitiveDataTypes
●byte(1byte),short(2bytes),char(2bytes),int(4bytes),long(8bytes)
●float(4bytes),double(8bytes),boolean(1byte)
6.OrderofInitialization
1.StaticBlocks:Runoncewhentheclassisloaded.
2.InstanceInitializationBlocks:Executebeforeconstructors.
3.Constructors:Initializeobjects.
7.LambdaExpressionsvs.Closures
●LambdaExpressions:Anonymousfunctionsthattreatactionsasobjects;can't
accessvariablesoutsidetheirscopeunlessfinaloreffectivelyfinal.
●Closures:Notdirectlysupportedin;allowreferencingvariablesoutsidethe
parameterlist.
8.ObjectClassMethods
●Examples:clone(),equals(),toString(),hashCode(),notify(),wait(),getClass()
9.Atomic,Volatile,Synchronized
●Volatile:Ensuresvisibilityofvariableupdatesacrossthreads.
●AtomicInteger:Providesthread-safeoperationswithoutsynchronizationusingCAS.
●Synchronized:Allowsonlyonethreadatatimetoaccessablockormethod.
10.Serialization
●Convertsobjectstobytestreamsforpersistenceornetworktransfer.

●ImplementSerializableinterfacefordefaultserialization.
●CustomizeusingreadObjectandwriteObject.
●Usetransientorstaticforvariablesnottobeserialized.
11.Cloning
●ShallowCopy:Onlycopiesprimitivefields;objectreferencespointtothesame
memory.
●DeepCopy:Createsnewobjectsforallreferences,duplicatingalldata.
12.StringBuffervs.StringBuilder
●StringBuffer:Thread-safe,slower.
●StringBuilder:Non-thread-safe,faster.
13.XMLParsers
●DOM:Tree-based,memory-intensive.
●SAX:Event-driven,forward-only,lowmemory.
●StAX:Pull-based,allowsparsingandmodification.
14.NewFeaturesin
●8:Lambdaexpressions,StreamAPI,Optional,FunctionalInterfaces,DateAPI.
●11:isBlank(),lines(),strip(),HTTPclientupdates,readString(),writeString().
15.LambdaExpressions
Usedforinlineimplementationoffunctionalinterfaces,improvingcodereadability
andcompactness.
16.Exceptions
Abnormaleventsdisruptingprogramflow,managedusingtry-catchorthrows.
Ifyouneedfurtherexplanationonanyspecifictopic,letmeknow!

CollectionsInterviewQuestions
1.CollectionsTypeHierarchy
TheCollectionsFrameworkisstructuredaroundseveralcoreinterfaces:
●Iterable:Therootinterfaceenablingiterationoverelements(e.g.,for-eachloop).
●Collection:ExtendsIterableanddefinesmethodslikeadd,remove,size,andmore.
○List:Ordered,index-basedcollections(e.g.,ArrayList,LinkedList).
○Set:Unorderedcollectionswithuniqueelements(e.g.,HashSet,TreeSet).
○Queue:Supportselementorderingforprocessing(e.g.,PriorityQueue).
●Map:Key-valuepairs,distinctfromCollection,emphasizingmappingratherthan
collections.
Eachinterfaceservesauniquepurpose,ensuringflexibilityandscalabilityindesigning
applications.
2.MapImplementationsandUseCases
●HashMap:Bestforgeneral-purposeusewhereorderisnotaconcern.O(1)time
complexityforoperations.
●LinkedHashMap:Retainsinsertionorder,idealforaccess-order-sensitiveapplications
(e.g.,LRUcaches).
●TreeMap:Maintainskeysinsortedorder.Suitableforrangequeriesorordereddata
(logarithmicaccesstime).
●ConcurrentHashMap:Optimizedforconcurrentaccess,avoidinggloballocksfor
betterperformanceinmulti-threadedenvironments.
●Hashtable:Synchronizedbutoutdated;typicallyreplacedbyConcurrentHashMap.
3.LinkedListvs.ArrayList
●ArrayList:
○Backedbyaresizablearray.
○Fastrandomaccess(O(1)).
○Costlyinsertions/removalsinthemiddle(O(n))duetoshiftingelements.
●LinkedList:
○Usesadoubly-linkedlist.
○Efficientinsertions/removals(O(1)).
○Slowertraversal(O(n)).
○Highermemoryoverheadduetonodereferences.

UseCase:UseArrayListforfrequentaccess;preferLinkedListforheavy
insertions/deletions.
4.HashSetvs.TreeSet
●HashSet:
○BackedbyHashMap.
○Noorderguarantee.
○Fastoperations(O(1)).
●TreeSet:
○BackedbyTreeMap.
○Maintainsnaturalorcustomorder.
○Sloweroperations(O(logn)).
UseCase:UseHashSetforperformance;preferTreeSetfororderedsets.
5.HashMapImplementation
AHashMapemploys:
●Hashing:Calculatesthebucketindexfromthehashcodeofkeys.
●Buckets:Holdkey-valuepairs.Collisionsarehandledusinglinkedlistsorred-black
trees(since8).
●Resizing:Automaticallydoublesinsizewhentheloadfactorexceedsthethreshold.
KeyoperationslikeputandgetareoptimizedforO(1),butexcessivecollisionscandegrade
performancetoO(logn).
6.InitialCapacityandLoadFactor
●InitialCapacity:Startingsizeoftheinternalarray(roundedtothenearestpowerof2).
●LoadFactor:Threshold(default0.75)forresizingwhentheratioofelementsto
bucketsisexceeded.
Optimizingtheseparametersminimizesresizingoverhead.
7.SpecialCollectionsforEnums
●EnumSet:ExtremelyefficientSetforenumsusingbitwiseoperations.
●EnumMap:Usesenumsaskeysandarraysforstorage,providingfastlookups
withouthashing.

8.Fail-Fastvs.Fail-SafeIterators
●Fail-Fast:
○Detectsconcurrentmodificationsandthrows
ConcurrentModificationException.
○FoundincollectionslikeArrayList,HashMap.
●Fail-Safe:
○Operatesonacopyofthecollection.
○FoundinCopyOnWriteArrayList,ConcurrentHashMap.
9.Comparablevs.Comparator
●Comparable:
○NaturalorderingdefinedbycompareTomethod.
○Example:Sortingintegersinascendingorder.
●Comparator:
○Customorderingviacomparemethod.
○Example:Sortingstringsbylength.
BothinterfacesarepivotalforsortingcollectionsusingmethodslikeCollections.sortorfor
maintainingorderinTreeSet/TreeMap.
ConcurrencyInterviewQuestions
CreatingandRunningaThreadInstance:
UsingRunnable:
Threadthread1=newThread(()->System.out.println("Hellofrom
Runnable!"));
thread1.start();
1.
UsingaSubclassofThread:
Threadthread2=newThread(){
@Override

publicvoidrun(){
System.out.println("Hellofromsubclass!");
}
};
thread2.start();
2.
ThreadStatesandTransitions:
1.NEW:Threadcreatedbutnotstarted(Threadt=newThread()).
2.RUNNABLE:Aftercallingstart(),threadisreadyforexecution.
3.BLOCKED:Threadwaitingtoenterasynchronizedblock.
4.WAITING:Threadwaitingindefinitelyforanotherthread'ssignal.
5.TIMED_WAITING:Threadwaitingforaspecifiedduration.
6.TERMINATED:Threadcompletesexecution.
RunnablevsCallable:
●Runnable:Doesnotreturnaresultorthrowcheckedexceptions.
Callable:Returnsaresultandcanthrowcheckedexceptions.Example:
Callable<Integer>callable=()->42;

DaemonThreads:
●Definition:Threadssupportingnon-daemonthreads.JVMexitsonceallnon-daemon
threadsfinish.
Creation:
Threaddaemon=newThread(()->System.out.println("Daemon
thread!"));
daemon.setDaemon(true);
daemon.start();


InterruptFlagandExceptions:
●SetInterrupt:thread.interrupt().
●CheckInterrupt:Thread.interrupted()(clearsflag)orisInterrupted()
(doesn'tclearflag).
●Behavior:ThrowsInterruptedExceptionifinblockingoperationlikesleep().
ExecutorvsExecutorService:
●Executor:SimpleinterfaceforexecutingRunnabletasks.
●ExecutorService:Addslifecyclemanagement,tasktracking,andadvancedexecution
controls.
ExecutorServiceImplementations:
1.ThreadPoolExecutor:Managesapoolofthreads.
2.ScheduledThreadPoolExecutor:Schedulestaskswithdelaysorperiodicexecution.
3.ForkJoinPool:Efficientfordivide-and-conquertasksusingwork-stealing.
MemoryModel(JMM):
●Defineshowthreadsinteractthroughsharedmemory.
●Ensurespredictablememoryvisibilityandorderingforconcurrentthreads.
●KeyConcepts:Actions,Synchronizationactions,Happens-beforerelationships,and
Happens-beforeconsistency.
VolatileFieldsinJMM:
●Guarantees:
○Visibility:Changestovolatilevariablesareimmediatelyvisibletoother
threads.
○Atomicity:Singleread/writeoflongordoublevariables.
AtomicityofOperations:

●Atomic:Writestointorvolatilelong.
●Non-atomic:Incrementingavolatilelong.
FinalFieldGuarantees:
●finalensuresproperinitializationvisibilityacrossthreads.
SynchronizedKeyword:
●Synchronizesaccessusing:
○Instancemethods:Lockontheobject.
○Staticmethods:Lockontheclassobject.
○Block:Lockonaspecifiedobject.
StaticvsInstanceSynchronizedMethods:
●Instancemethods:Threadsaccessingdifferentinstancesdon'tblock.
●Staticmethods:Threadsshareasingleclass-levellock.
wait(),notify(),notifyAll():
●Purpose:Forthreadcoordinationinsynchronizedblocks.
●Behavior:
○wait():Releaseslockandwaitsfornotification.
○notify():Wakesasinglewaitingthread.
○notifyAll():Wakesallwaitingthreads.

JavaGarbageCollectionQuestions
WhatisGarbageCollection?
Garbagecollection(GC)istheprocessofautomaticallyreclaimingmemorybyidentifying
andremovingobjectsnolongerreferencedbytheapplication,thuspreventingmemory
leaks.
WhichPartoftheMemoryisInvolvedinGarbageCollection?
GarbagecollectionoccursintheHeapMemory,specificallyintheYoungGenerationand
OldGeneration.
MinorvsMajorGarbageCollection
1.MinorGC:
○CleanstheYoungGeneration(EdenandSurvivorspaces).
○Occursmorefrequentlyandisfaster.
○TriggerswhentheEdenspaceisfull.
2.MajorGC:
○CleanstheOldGeneration.
○Occurslessfrequentlyandismoretime-consuming.
○TriggerswhentheOldGenerationisfulloratJVM-definedthresholds.
AlgorithmforGarbageCollectioninJava
1.Mark-and-Sweep:
○MarkPhase:Identifiesreachableobjects.
○SweepPhase:Reclaimsmemoryoccupiedbyunreachableobjects.
2.GenerationalGC:
○Objectsarecategorizedintogenerations(YoungandOld).
○Differentstrategiesareappliedtoeachgeneration.
3.Stop-the-World:
○Allapplicationthreadspauseduringgarbagecollection.

4.CompactPhase(Optional):
○Fragmentedmemoryisconsolidatedforefficiency.
finalize()MethodinJava
●Purpose:Providesawaytoperformcleanupoperationsbeforeanobjectis
reclaimedbythegarbagecollector.
●WhenCalled:Thegarbagecollectorinvokesfinalize()ifitdetectsthatthe
objectiseligibleforGCandoverridesthemethod.
●Issues:
○Noguaranteethatfinalize()willbecalled.
○Cancauseperformanceissuesandunpredictablebehavior.
○DeprecatedasofJava9.
MakinganObjectEligibleforGarbageCollection
NullifyReferences:Setobjectreferencestonull.
obj=null;
1.
ReassignReferences:Pointthereferencetoanotherobject.
obj1=obj2;
2.
ScopeLimitation:Lettheobjectgooutofscope.
//Objectdeclaredinsideamethodisnolongeraccessibleoutsideit.
3.
WaystoCallGarbageCollector
1.ExplicitlySuggest:
○UsingSystem.gc()orRuntime.getRuntime().gc().
○NoguaranteethatGCwillrunimmediately.
2.JVMTriggered:
○HappensautomaticallybasedonJVM'smemorythresholdsand
requirements.

HeapvsStackMemoryinJava
Aspect HeapMemory StackMemory
Purpose StoresobjectsandJREclasses.Storesmethodcalls,local
variables,andreferences.
Allocation Dynamic(atruntime). Static(basedonthemethod
lifecycle).
Lifetime Existsthroughouttheapplication
lifecycle.
Existsonlyduringmethod
execution.
ThreadScopeSharedacrossthreads.Thread-local(eachthreadhasits
stack).
Speed Slowerduetoglobalaccessand
dynamicallocation.
Fasterbecauseofsimpler
memoryaccesspatterns.
Memory
Management
ManagedbyGarbageCollector.Managedautomaticallyvia
methodcalls.
PartsoftheHeapMemory
1.YoungGeneration:
○DividedintoEdenSpaceandSurvivorSpaces.
○Newobjectsareallocatedhere,andminorgarbagecollectionoccursto
removeshort-livedobjects.
2.OldGeneration(TenuredSpace):
○Storeslong-livedobjects.
○Majorgarbagecollectionhappenshere.
3.Metaspace(Java8andlater):
○Storesmetadataaboutclasses,methods,andotherreflectivedata.
4.PermanentGeneration(Java7andearlier):
○SimilartoMetaspacebuthadafixedsizeandwaspartoftheheap.
PermGenvsMetaspace
AspectPermGen(Java7andearlier)Metaspace(Java8andlater)
Purpose Storesclassmetadataand
reflectivedata.
Alsostoresclassmetadata,
replacingPermGen.

MemoryLimitFixedsize,configurableviaJVM
options.
Dynamicallyresized;growsas
needed.
Garbage
Collection
Partoftheheap,managedby
GC.
ManagedbyGC,butpartofnative
memory.
ForMoreClick

JavaAnnotationInterviewQuestions
1.WhatareMeta-Annotations,andWhatisthePurposeofEachinthe
java.lang.annotationPackage?
●@Retention:Definesthescopeoftheannotation.
○Policies:
■SOURCE:Annotationisdiscardedduringcompilation.
■CLASS:Annotationisintheclassfilebutnotavailableatruntime.
■RUNTIME:AnnotationisretainedintheJVMandavailablevia
reflection.
●@Target:Specifiesthekindsofelementsanannotationcanapplyto(e.g.,METHOD,
FIELD).
●@Inherited:Allowssubclassestoinheritannotationsfromtheirparentclasses.
●@Documented:Indicatesthattheannotationshouldappearinthegenerated
Javadoc.
●@Repeatable:Allowsmultipleinstancesofthesameannotationonanelement.
2.HowDoYouCreateaCustomAnnotation?
Example:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public@interfaceTest{
Stringdescription()default"Nodescription";
intpriority()default0;
Class<?extendsThrowable>expectedExceptions()defaultNone.class;
}
3.ExplaintheDifferenceBetweenRuntimeandCompile-TimeAnnotations.HowAre
TheyProcessed?
●Compile-TimeAnnotations:
○Examples:@Override,@Deprecated.
○Processedduringcompilation.
○EnsurescorrectnessandcompliancewithJavaconventions.
●RuntimeAnnotations:
○Examples:Customannotationswith@Retention(RUNTIME).
○Accessedusingreflectionduringruntime.
○CommonlyusedinframeworkslikeSpringandHibernate.

4.HowCanYouImplementaCustomAnnotationProcessor?
ExampleImplementation:
@SupportedAnnotationTypes("com.example.MyCustomAnnotation")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
publicclassMyAnnotationProcessorextendsAbstractProcessor{
@Override
publicbooleanprocess(Set<?extendsTypeElement>annotations,RoundEnvironment
roundEnv){
//Customprocessinglogic
returntrue;
}
}
5.DescribeAdvancedUseCasesofJavaReflectionwithAnnotations.
●DynamicMethodInvocation:Executemethodsbasedonannotations.
●RuntimeConfigurations:Modifybehaviordynamicallyusingannotations.
●DependencyInjection:FrameworkslikeSpringuseannotationsforDI.
●ValidationFrameworks:Buildfield-levelvalidatorswithannotations.
●TestFrameworks:Customtestrunnersandassertions.
6.WhatAretheLimitationsofAnnotations,andHowCanTheyBeOvercome?
●Limitations:
○Cannotcontainmethodimplementations.
○Limitedtospecificelementtypes.
○Mayintroduceruntimeoverhead.
●Strategies:
○Combineannotationswithreflectiveorbytecode-basedtools.
○Designminimalisticannotationstoreducecomplexity.
7.CompareandContrastAnnotationswithMarkerInterfaces.
●Annotations:
○Flexiblemetadata,nohierarchyconstraints.
○Bettersuitedfordeclarativeprogramming.
●MarkerInterfaces:
○Usedfortype-checkingandenforceablecontracts.
○Limitedflexibilitycomparedtoannotations.

8.HowWouldYouImplementaCustomValidationFrameworkUsingAnnotations?
Example:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public@interfaceValidate{
booleannotNull()defaultfalse;
intminLength()default0;
intmaxLength()defaultInteger.MAX_VALUE;
}
publicclassValidationProcessor{
publicbooleanvalidate(Objectobject){
//Implementreflection-basedvalidationlogic
returntrue;
}
}
9.HowDoFrameworksLikeSpringUtilizeAnnotationsforDependencyInjectionand
Configuration?
●Annotations:
○@Autowired:Forinjectingdependencies.
○@Component:MarksaclassasaSpringbean.
○@Configuration:Indicatesaconfigurationclass.
○@Bean:Definesbeansinconfigurationclasses.
●Mechanism:
○Frameworksscanannotationsatruntimeorcompile-timetoperforminjections
andconfigurations.
10.DemonstrateaComplexUseCaseofMeta-ProgrammingUsingAnnotations.
●Scenario:CreateaCustomORM(Object-RelationalMapping).Example:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public@interfaceColumn{
Stringname();
booleanprimaryKey()defaultfalse;
}
publicclassORMProcessor{

publicvoidmapObjectToDB(Objectentity){
//Usereflectiontomapfieldswith@Columntodatabasecolumns
}
}

JavaDependencyInjection(DI)InterviewQuestions
1.WhatisDependencyInjection(DI),andWhyisitImportant?
●Definition:DependencyInjectionisadesignpatterninwhichanobject’s
dependenciesareprovidedexternallyratherthancreatedinternallybytheobject.
●Purpose:
○Promotesloosecouplingbetweenobjects.
○Makescodeeasiertomaintain,test,andextend.
●ProblemsSolved:
○Avoidshard-codingdependencies.
○Facilitatesunittestingbyallowingtheuseofmockdependencies.
●Comparison:Traditionalobjectcreationcouplesaclasswithitsdependencies,
whereasDIseparatestheirlifecycle.
2.ExplaintheDifferentTypesofDependencyInjection
ConstructorInjection:
●Dependenciesareinjectedthroughtheconstructor.
●Ensuresdependenciesareimmutableandrequiredfortheobjecttofunction.
publicclassUserService{
privatefinalUserRepositoryrepository;
publicUserService(UserRepositoryrepository){
this.repository=repository;
}
}
SetterInjection:
●Dependenciesaresetthroughsettermethods.
●Allowsoptionalorlatedependencyinjection.
publicclassUserService{
privateUserRepositoryrepository;
publicvoidsetUserRepository(UserRepositoryrepository){
this.repository=repository;
}
}

InterfaceInjection:
●Dependenciesareprovidedthroughacustommethoddefinedinaninterface.
●Rarelyusedcomparedtoconstructororsetterinjection.
publicinterfaceRepositoryInjector{
voidinjectRepository(UserServiceservice);
}
3.AdvancedDIConcepts
●InversionofControl(IoC):
○Delegatestheresponsibilityofdependencymanagementtoacontainer.
●DependencyInversionPrinciple:
○High-levelmodulesshouldnotdependonlow-levelmodules;bothshould
dependonabstractions.
●ServiceLocatorPatternvsDependencyInjection:
○ServiceLocator:Centralizedaccesstodependencies.
○DI:Dependenciesarepusheddirectlyintoobjects.
●Pros/ConsofInjectionMethods:
○Constructor:Mandatorydependencies,immutability.
○Setter:Optionaldependencies,flexibility.
4.SpringFrameworkDIQuestions
Annotations:
@Component
publicclassUserService{
@Autowired
privateUserRepositoryrepository;
}
●@Autowired:Injectsdependenciesautomatically.
●@Component,@Service,@Repository:DefineSpring-managedbeans.
●@Scope:Definesbeanscope(singleton,prototype,etc.).
●@Qualifier:Resolvesambiguitywhenmultiplebeansofthesametypeexist.
5.ImplementingaCustomDependencyInjectionContainer
ExampleImplementation:

publicclassDIContainer{
privateMap<Class<?>,Object>instances=newHashMap<>();
public<T>voidregister(Class<T>type,Tinstance){
instances.put(type,instance);
}
public<T>Tresolve(Class<T>type){
return(T)instances.get(type);
}
}
6.ComplexDependencyInjectionScenarios
●CircularDependencies:
○AdependsonB,andBdependsonA.
○Solvedusing@Lazyinitializationorrefactoring.
●HandlingOptionalDependencies:
○UseOptional<T>orsetterinjection.
●LazyInitialization:
○Delaysthecreationofdependenciesuntilneeded.
●PrototypevsSingletonScopes:
○Prototype:Newinstanceperinjection.
○Singleton:Singlesharedinstance.
7.PerformanceandBestPractices
●ConstructorInjectionPreferred:
○Ensuresalldependenciesareavailableatobjectcreation.
@Service
publicclassUserService{
privatefinalUserRepositoryrepository;
@Autowired
publicUserService(UserRepositoryrepository){
this.repository=repository;
}
}
●BestPractices:
○Avoidtoomanydependencies.
○Usedependencygraphsjudiciously.

○Properlyscopebeanstoavoidmemoryleaks.
8.AdvancedDIwithGenerics
Example:
publicinterfaceGenericRepository<T>{
voidsave(Tentity);
}
@Service
publicclassGenericService<T>{
privatefinalGenericRepository<T>repository;
@Autowired
publicGenericService(GenericRepository<T>repository){
this.repository=repository;
}
}
9.TestingwithDependencyInjection
●UsemockingframeworkslikeMockitofordependencyinjectionduringtests.
publicclassUserServiceTest{
@Mock
privateUserRepositorymockRepository;
@InjectMocks
privateUserServiceuserService;
@Test
publicvoidtestUserCreation(){
//Testlogichere
}
}
●Strategies:
○Mockdependenciesforisolatedunittesting.
○Testintegrationwithactualdependenciesforend-to-endtesting.

10.JavaEEandJakartaEEDIAnnotations
Annotations:
@Named
@ApplicationScoped
publicclassUserService{
@Inject
privateUserRepositoryrepository;
}
●CDI(ContextandDependencyInjection):
○@Inject:Standardforinjectingdependencies.
○@Named:Bindsanametoabean.
○Scopeannotationslike@ApplicationScoped,@RequestScoped.

PatternsInterviewQuestions
CreationalPatterns
CreationalDesignPatternsarefocusedontheprocessofobjectcreation.Theyaimto
reducecomplexityandinstabilitybycreatingobjectsinacontrolledmanner.
SingletonDesignPattern
TheSingletonDesignPatternensuresthatonlyoneinstanceofaclassexiststhroughout
theVirtualMachine(JVM)andprovidesaglobalaccesspointtothatinstance.
●LazyInitializationwithStaticInnerClass:
publicclassSingleton{
privateSingleton(){}
privatestaticclassSingletonHolder{
publicstaticfinalSingletoninstance=newSingleton();
}
publicstaticSingletongetInstance(){
returnSingletonHolder.instance;
}
}
●EagerInitialization(NotLazy):

publicclassSingleton{
publicstaticfinalSingletonINSTANCE=newSingleton();
privateSingleton(){}
}
ProblemswithSerializationandDeserialization
IfyouserializeaSingletonclass,itcancreatenewinstancesduringdeserialization,violating
theSingletonproperty.ImplementingtheSerializableinterfacealonewon'tsolvethis.
ProblemswithReflection
AdvanceduserscanbreaktheSingletonbyusingreflectiontochangetheaccessmodifierof
theconstructoratruntime,allowingformultipleinstancesoftheSingleton.
SingletonwithEnum
Enumsprovideamuchmorerobustsolution.Sinceenumsareinherentlyserializable,they
avoidtheserializationandreflectionissues.Here’showyoucanimplementaSingletonwith
anenum:
publicenumSingletonEnum{
INSTANCE;
privateintvalue;

publicintgetValue(){
returnvalue;
}
publicvoidsetValue(intvalue){
this.value=value;
}
}
Usage:
publicclassEnumDemo{
publicstaticvoidmain(String[]args){
SingletonEnumsingleton=SingletonEnum.INSTANCE;
System.out.println(singleton.getValue());
singleton.setValue(2);
System.out.println(singleton.getValue());
}
}
WhentoUseSingletonDesignPattern
●Forexpensiveresourceslikedatabaseconnections.

●Tooptimizeperformance(e.g.,loggers).
●Forconfigurationsettingsinanapplication.
●Forresourcesaccessedinsharedmode.
FactoryDesignPattern
TheFactoryDesignPatterndefinesaninterfaceforcreatingobjects,butletssubclasses
decidewhichclasstoinstantiate.Thispatternisoftenusedtocreateobjectsbasedoninput,
suchasthenumberofsidesofapolygon.
●Example:
publicinterfacePolygon{
StringgetType();
}
publicclassPolygonFactory{
publicPolygongetPolygon(intnumberOfSides){
switch(numberOfSides){
case3:returnnewTriangle();
case4:returnnewSquare();
case5:returnnewPentagon();
case7:returnnewHeptagon();
case8:returnnewOctagon();
default:returnnull;
}
}

}
WhentoUseFactoryDesignPattern
●Whenimplementationsofaninterfaceorabstractclasschangefrequently.
●Whenthecurrentimplementationcannoteasilyaccommodatechanges.
●Whentheinitializationprocessissimpleandrequiresonlyafewparameters.
AbstractFactoryDesignPattern
TheAbstractFactoryDesignPatternisusedtocreatefamiliesofrelatedordependent
objects.It’sessentiallyafactoryoffactories.Thisisusefulwhendealingwithcomplex
objectsthatbelongtoaspecificfamilyandneedtobecreatedtogether.
BuilderDesignPattern
TheBuilderDesignPatternisusedwhenthecreationofanobjectbecomestoocomplex.It
separatestheconstructionofanobjectfromitsrepresentation.
●Example:
publicclassBankAccount{
privateStringname;
privateStringaccountNumber;
privateStringemail;
privatebooleannewsletter;
publicstaticclassBankAccountBuilder{
privateStringname;

privateStringaccountNumber;
privateStringemail;
privatebooleannewsletter;
publicBankAccountBuilder(Stringname,StringaccountNumber)
{
this.name=name;
this.accountNumber=accountNumber;
}
publicBankAccountBuilderwithEmail(Stringemail){
this.email=email;
returnthis;
}
publicBankAccountBuilderwantNewsletter(booleannewsletter)
{
this.newsletter=newsletter;
returnthis;
}
publicBankAccountbuild(){
returnnewBankAccount(this);
}
}

}
Usage:
BankAccountnewAccount=newBankAccount
.BankAccountBuilder("Jon","22738022275")
.withEmail("[email protected]")
.wantNewsletter(true)
.build();
WhentoUseBuilderPattern
●Whentheobjectcreationprocessiscomplexandhasmanymandatoryandoptional
parameters.
●Whenconstructorswithmanyparametersleadtoalargenumberofconstructors.
●Whenclientsexpectdifferentrepresentationsoftheobject.
StructuralPatterns
StructuralDesignPatternsdealwiththecompositionofclassesandobjects,focusingon
howobjectsarecomposedtoformlargerstructures.
ProxyPattern
TheProxyPatterncreatesanintermediaryobjectthatactsasaninterfacetoanother
resource,suchasafileordatabaseconnection.Itallowsforcontrolledaccessandprotects
theoriginalobjectfromcomplexity.
●Example:
publicinterfaceExpensiveObject{
voidprocess();
}

publicclassExpensiveObjectImplimplementsExpensiveObject{
publicExpensiveObjectImpl(){
heavyInitialConfiguration();
}
@Override
publicvoidprocess(){
System.out.println("Processingcomplete.");
}
privatevoidheavyInitialConfiguration(){
System.out.println("Loadinginitialconfiguration...");
}
}
publicclassExpensiveObjectProxyimplementsExpensiveObject{
privatestaticExpensiveObjectobject;
@Override
publicvoidprocess(){
if(object==null){
object=newExpensiveObjectImpl();
}
object.process();
}
}
WhentoUseProxyPattern

●Whenyouwanttosimplifyacomplexorheavyobject.
●Whentheoriginalobjectresidesinadifferentaddressspaceandneedstobe
accessedlocally.
●Whenyouneedtoaddalayerofsecuritytocontrolaccess.
DecoratorPattern
TheDecoratorPatternenhancesthebehaviorofanobjectdynamicallybyaddingadditional
responsibilitieswithoutmodifyingtheoriginalclass.
●Example:
publicinterfaceChristmasTree{
Stringdecorate();
}
publicclassChristmasTreeImplimplementsChristmasTree{
@Override
publicStringdecorate(){
return"Christmastree";
}
}
publicabstractclassTreeDecoratorimplementsChristmasTree{
privateChristmasTreetree;
publicTreeDecorator(ChristmasTreetree){
this.tree=tree;
}
@Override
publicStringdecorate(){

returntree.decorate();
}
}
publicclassBubbleLightsextendsTreeDecorator{
publicBubbleLights(ChristmasTreetree){
super(tree);
}
@Override
publicStringdecorate(){
returnsuper.decorate()+"withBubbleLights";
}
}
WhentoUseDecoratorPattern
●Whenyouwanttoadd,enhance,orremovethebehaviorofanobjectdynamically.
●Whenyouneedtomodifythefunctionalityofasingleobjectwithoutchangingothers.
Formorequestionsandanswers,youcan
followtheseadditionallinks:
●Devinterview-ioJavaInterviewQuestions
●AatulJavaInterviewQuestionsandAnswers
Tags