iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii INTERNAL i iASSIGNMENT
NAME i: iROHIT iSHARMA
ROLL iNO i: i2214509351
SUBJECT iNAME i: iJAVA iPROGRAMMING
SUBJECT iCODE i: iDCA2202 i
SEMESTER i: i4TH
SESSION i: iMARCH i2024
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii SET i-1
Q.NO i1 iExplain iany ifive ifeatures iof iJava i?
Ans i iJava iis ia iwidely-used iprogramming ilanguage iknown ifor iits iversatility iand
iperformance. iHere iare ifive ikey ifeatures iof iJava:
1. iPlatform iIndependence
Java iis idesigned ito ibe iplatform-independent iat iboth ithe isource iand ibinary
ilevels, iwhich imeans iJava iprograms ican irun ion iany idevice ithat ihas ia iJava
iVirtual iMachine i(JVM). iThis iis iachieved ithrough ithe iuse iof ibytecode, ian
iintermediate icode icompiled ifrom iJava isource icode, iwhich ican ibe iexecuted ion
iany iJVM, iregardless iof ithe iunderlying ihardware iand ioperating isystem. iThe
iphrase i"write ionce, irun ianywhere" iencapsulates ithis ifeature.
2. iObject-Oriented
Java iis iinherently iobject-oriented, iwhich imeans iit ifocuses ion iobjects iand
iclasses irather ithan iprocedures iand ifunctions. iThe ikey iprinciples iof iobject-
oriented iprogramming i(OOP) ithat iJava isupports iinclude:
• Encapsulation: iBundling iof idata iand imethods ithat ioperate ion ithe idata
iwithin ia isingle iunit, iknown ias ia iclass.
• Inheritance: iMechanism ito icreate inew iclasses ibased ion iexisting iones,
ipromoting icode ireuse.
• Polymorphism: iAbility ito iprocess iobjects idifferently ibased ion itheir idata
itype ior iclass.
• Abstraction: iHiding icomplex iimplementation idetails iand iexposing ionly
ithe inecessary ifeatures.
3. iRobust iand iSecure
Java iemphasizes ireliability iand isecurity ithrough ivarious imeans:
• Exception iHandling: iProvides ia ipowerful imechanism ito ihandle iruntime
ierrors, iensuring ismooth iprogram iexecution.
• Memory iManagement: iJava iuses ian iautomatic igarbage icollector ito
imanage imemory, iwhich ireduces ithe ilikelihood iof imemory ileaks iand
irelated iissues.
• Security iFeatures: iThe iJava iplatform iprovides iseveral isecurity ifeatures,
isuch ias ibytecode iverification, ia isecurity imanager, iand iJava iAPI isecurity,
ito icreate isecure iapplications. iIt ialso ihas ia irobust iclass iloader
imechanism ithat iprevents ithe iloading iof iuntrusted iclasses.
4. iMultithreading
Java ihas ibuilt-in isupport ifor imultithreading, iwhich iallows iconcurrent iexecution
iof itwo ior imore ithreads ifor imaximum iutilization iof iCPU. iJava iprovides ia ihigh-
level iAPI ifor icreating iand imanaging ithreads, imaking iit ieasier ito idevelop
iapplications ithat iperform imultiple itasks isimultaneously, isuch ias ihandling iuser
iinput, iprocessing ibackground itasks, iand iperforming icomplex icalculations
iconcurrently.
5. iRich iStandard iLibrary
Java icomes iwith ia icomprehensive istandard ilibrary i(Java iStandard iEdition i- iJava
iSE) ithat iprovides ia iwide irange iof iclasses iand iinterfaces ifor ivarious
ifunctionalities:
• Data iStructures: iCollections iframework i(e.g., ilists, isets, imaps).
• Utilities: iUtility iclasses ifor ihandling itasks ilike idate iand itime
imanipulation, istring iprocessing, iand ifile iI/O.
• Networking: iAPIs ifor inetwork iprogramming i(e.g., iTCP/IP isockets, iHTTP
irequests).
• GUI iDevelopment: iJavaFX iand iSwing ifor ibuilding igraphical iuser
iinterfaces.
• Concurrency: iClasses iand iinterfaces ifor imultithreaded iprogramming.
Q.NO i2 iWhat iare ithe idifferent itypes iof ioperator iused iin iJava i?
Ans i iJava isupports ia iwide ivariety iof ioperators ithat iperform idifferent ikinds iof
ioperations. iHere iis ian ioverview iof ithe idifferent itypes iof ioperators iused iin
iJava:
1. iArithmetic iOperators
These ioperators iare iused ito iperform ibasic iarithmetic ioperations:
• Addition i(+): iAdds itwo ioperands.
iiiiiiiiiii int ia i= i5 i+ i3; i// ia iis i i8
i
iiiiiiiiiiSubtraction i(-): iSubtracts ithe iright ioperand ifrom ithe ileft ioperand.
iiiiiiiiiiiiiiii int ia i= i5 i- i3; i// ia iis i2
iiiiiiiiii
iiiiii Increment i(++): iIncreases ithe ivalue iof ithe ioperand iby i1
iiiiiiiiiiiiiiii int ia i= i5;
iiiiiiiiiiiii a++; i// ia iis i6
Decrement i(--): iDecreases ithe ivalue iof ithe ioperand iby i1.
iiiiiiiiiiiiiiiiiiiii int ia i= i5;
iiiiiiiiiiiiiiiiii a--; i// ia iis i4
Logical icomplement i(!): iInverts ithe ivalue iof ia iBoolean
iiiiiiiiiiiiiiii boolean ib i= itrue;
iiiiiiiiiiiiiii boolean inotB i= i!b; i// inotB iis ifalse
2. iUnary iOperators
These ioperators ioperate ion ia isingle ioperand iand iperform ivarious ioperations
isuch ias iincrementing/decrementing ia ivalue iby ione, inegating ian iexpression, ior
iinverting ithe ivalue iof ia iboolean.
Unary iplus i(+): iIndicates ia ipositive ivalue i(typically iused ito iemphasize ipositivity)
iiiiiiiiiiiiiiiiiiiiiiii Int ia i= i+5; i// ia iis i5
Unary iminus i(-): iNegates ithe ivalue iof ithe ioperand
iiiiiiiiiiiiiiiiiiiiiiiii int ia i= i-5; i// ia iis i-5
Increment i(++): iIncreases ithe ivalue iof ithe ioperand iby i1
iiiiiiiiiiiiiiiiiiiiiiiiiii int ia i= i5;
iiiiiiiiiiiiiiiiiiiiiiiii a++; i// ia iis i6
Decrement i(--): iDecreases ithe ivalue iof ithe ioperand iby i1
iiiiiiiiiiiiiiiiiiiiiiiiiii int ia i= i5;
iiiiiiiiiiiiiiiiiiiiiiiiii a--; i// ia iis i4
Logical icomplement i(!): iInverts ithe ivalue iof ia iBoolean
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii boolean ib i= itrue;
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii boolean inotB i= i!b; i// inotB iis ifalse
3. iAssignment iOperators
These ioperators iare iused ito iassign ivalues ito ivariables.
Simple iassignment i(=): iAssigns ithe iright ioperand ito ithe ileft ioperand
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii int ia i= i5;
Add iand iassign i(+=): iAdds ithe iright ioperand ito ithe ileft ioperand iand iassigns ithe
iresult ito ithe ileft ioperand. i
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii int ia i= i5;
iiiiiiiiiiiiiiiiiiiiiiiiiiiiii a i+= i3; i// ia iis i8
Subtract iand iassign i(-=): iSubtracts ithe iright ioperand ifrom ithe ileft ioperand iand
iassigns ithe iresult ito ithe ileft ioperand.
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii int ia i= i5;
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii a i-= i3; i// ia iis i2
Multiply iand iassign i(*=): iMultiplies ithe iright ioperand iwith ithe ileft ioperand iand
iassigns ithe iresult ito ithe ileft ioperand.
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii int ia i= i5;
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii a i*= i3; i// ia iis i15
Divide iand iassign i(/=): iDivides ithe ileft ioperand iby ithe iright ioperand iand
iassigns ithe iresult ito ithe ileft ioperand. i
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii int ia i= i5;
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii a i/= i3; i// ia iis i1
Modulus iand iassign i(%=): iTakes ithe imodulus iusing itwo ioperands iand iassigns
ithe iresult ito ithe ileft ioperand. i
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii int ia i= i5;
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii a i%= i3; i// ia iis i2
4. iRelational iOperators
These ioperators iare iused ito icompare itwo ivalues.
Equal ito i(==): iChecks iif ithe ivalues iof itwo ioperands iare iequal
iiiiiiiiiiiiiiiiiiiiiiii boolean iresult i= i(5 i== i3); i// iresult iis ifalse
Not iequal ito i(!=): iChecks iif ithe ivalues iof itwo ioperands iare inot iequal
iiiiiiiiiiiiiiiiiiiiiiiiiiiii boolean iresult i= i(5 i!= i3); i// iresult iis itrue
Greater ithan i(>): iChecks iif ithe ileft ioperand iis igreater ithan ithe iright ioperand
iiiiiiiiiiiiiiiiiiiiiiiiiiiiii boolean iresult i= i(5 i> i3); i// iresult iis itrue
Less ithan i(<): iChecks iif ithe ileft ioperand iis iless ithan ithe iright ioperand
iiiiiiiiiiiiiiiiiiiiiii boolean iresult i= i(5 i< i3); i// iresult iis ifalse
Greater ithan ior iequal ito i(>=): iChecks iif ithe ileft ioperand iis igreater ithan ior
iequal ito ithe iright ioperand
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii boolean iresult i= i(5 i>= i3); i// iresult iis itrue
Less ithan ior iequal ito i(<=): iChecks iif ithe ileft ioperand iis iless ithan ior iequal ito
ithe iright ioperand
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii boolean iresult i= i(5 i<= i3); i// iresult iis ifalse
5. iLogical iOperators
These ioperators iare iused ito iperform ilogical ioperations ion iboolean ivalues.
Logical iAND i(&&): iReturns itrue iif iboth ioperands iare itrue
iiiiiiiiiiiiiiiiiiiiiiiiiiiiii boolean iresult i= i(true i&& ifalse); i// iresult iis ifalse
Logical iOR i(||): iReturns itrue iif iat ileast ione iof ithe ioperands iis itrue
iiiiiiiiiiiiiiiiiiiiiiiiii boolean iresult i= i(true i|| ifalse); i// iresult iis itrue
Logical iNOT i(!): iInverts ithe ivalue iof ithe ioperand
iiiiiiiiiiiiiiiiiiiiiiiiiii boolean iresult i= i!true; i// iresult iis ifalse
Q.NO i3 iWhat ido iyou i imean iby ian iArray i? iExplain iwith ian i iexample.
Ans i iAn iarray iin iJava iis ia idata istructure ithat iallows iyou ito istore imultiple ivalues
iof ithe isame itype iin ia isingle ivariable. iIt iis ia icollection iof ielements, ieach
iidentified iby ian iarray iindex. iArrays iin iJava iare ifixed iin isize, imeaning ionce ian
iarray iis icreated, iits isize icannot ibe ichanged.
Key iFeatures iof iArrays:
1. Homogeneous iElements: iAll ielements iin ian iarray iare iof ithe isame itype.
2. Fixed iSize: iThe isize iof ithe iarray iis ispecified iwhen iit iis icreated iand icannot
ibe ichanged idynamically.
3. Indexed iAccess: iElements iin ithe iarray ican ibe iaccessed iusing ian iindex,
istarting ifrom i0 ifor ithe ifirst ielement iup ito ilength-1 ifor ithe ilast ielement.
4. Efficient iMemory iAllocation: iArrays iallow iefficient iaccess iand
imanipulation iof idata istored iin icontiguous imemory ilocations.
Declaring, iCreating, iand iInitializing ian iArray
Declaration
To ideclare ian iarray, iyou ispecify ithe itype iof iits ielements ifollowed iby isquare
ibrackets i[] iand ithe iarray iname.
int[] imyArray;
Creation
To icreate ian iarray, iyou iuse ithe inew ikeyword ifollowed iby ithe itype iand ithe isize
iof ithe iarray.
myArray i= inew iint[5];
Initialization
You ican iinitialize ian iarray iwhen iyou ideclare iit iby iproviding ithe ielements iin
icurly ibraces i{}.
int[] imyArray i= i{10, i20, i30, i40, i50};
Example: iWorking iwith iArrays
Here iis ia icomplete iexample ithat idemonstrates ideclaring, icreating, iinitializing,
iand iaccessing ielements iof ian iarray iin iJava.
Input i:
public iclass iArrayExample i{
iiii public istatic ivoid imain(String[] iargs) i{
iiiiiiii // iDeclaration iand icreation iof ian iarray
iiiiiiii int[] inumbers i= inew iint[5];
iiiiiiii
iiiiiiii // iInitialization iof ithe iarray
iiiiiiii numbers[0] i= i10;
iiiiiiii numbers[1] i= i20;
iiiiiiii numbers[2] i= i30;
iiiiiiii numbers[3] i= i40;
iiiiiiii numbers[4] i= i50;
iiiiiiii
iiiiiiii // iAccessing iand iprinting ielements iof ithe iarray
iiiiiiii System.out.println("Array ielements:");
iiiiiiii for i(int ii i= i0; ii i< inumbers.length; ii++) i{
iiiiiiiiiiii System.out.println("Element iat iindex i" i+ ii i+ i": i" i+ inumbers[i]);
iiiiiiii }
iiiiiiii
iiiiiiii // iDeclaration, icreation, iand iinitialization iof ian iarray iin ia isingle iline
iiiiiiii int[] imoreNumbers i= i{60, i70, i80, i90, i100};
iiiiiiii
iiiiiiii // iAccessing iand iprinting ielements iof ithe iarray
iiiiiiii System.out.println("More iarray ielements:");
iiiiiiii for i(int ii i= i0; ii i< imoreNumbers.length; ii++) i{
iiiiiiiiiiii System.out.println("Element iat iindex i" i+ ii i+ i": i" i+ imoreNumbers[i]);
iiiiiiii }
iiii }
}
Output i:
Array ielements:
Element iat iindex i0: i10
Element iat iindex i1: i20
Element iat iindex i2: i30
Element iat iindex i3: i40
Element iat iindex i4: i50
More iarray ielements:
Element iat iindex i0: i60
Element iat iindex i1: i70
Element iat iindex i2: i80
Element iat iindex i3: i90
Element iat iindex i4: i100
In ithis iexample:
• An iarray inumbers iis ideclared, icreated, iand ieach ielement iis iinitialized
iindividually.
• The ifor iloop iis iused ito iaccess iand iprint ieach ielement iin ithe iarray.
• Another iarray imoreNumbers iis ideclared, icreated, iand iinitialized iin ia
isingle iline, iand iits ielements iare iaccessed iand iprinted isimilarly.
SET- i2
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
Q.No i4 i iWhat iis i ithe idifference ibetween ierror iand iexceptions i?
Ans i iIn iJava, iboth ierrors iand iexceptions iare itypes iof iproblems ithat ican ioccur
iduring ithe iexecution iof ia iprogram, ibut ithey irepresent idifferent itypes iof iissues
iand iare ihandled idifferently. iHere iare ithe ikey idifferences ibetween ierrors iand
iexceptions:
1. iNature iof ithe iProblem
• Errors: iErrors irepresent iserious iproblems ithat iare itypically inot iexpected
ito ibe icaught iby iapplications. iThey iare igenerally iexternal ito ithe
iapplication iand iindicate iissues iwith ithe ienvironment iin iwhich ithe
iapplication iis irunning i(e.g., ihardware ifailure, iJVM iissues).
• Exceptions: iExceptions iare iproblems ithat iarise iwithin ithe iapplication
iitself. iThey iare iusually iconditions ithat ithe iapplication ican ianticipate iand
ihandle, isuch ias iinvalid iuser iinput, ifile inot ifound, ior inetwork iissues.
2. iHierarchy iin iJava
• Errors: iErrors iare irepresented iby ithe iError iclass, iwhich iis ia isubclass iof
iThrowable. iCommon isubclasses iof iError iinclude iOutOfMemoryError,
i StackOverflowError, iand iVirtualMachineError.
• Exceptions: iExceptions iare irepresented iby ithe iException iclass, iwhich iis
ialso ia isubclass iof iThrowable. iThere iare itwo imain icategories iof
iexceptions:
• Checked iExceptions: iThese iare iexceptions ithat iare ichecked iat
icompile-time. iThe icompiler iensures ithat ithese iexceptions iare
ieither icaught ior ideclared iin ithe imethod isignature iusing ithe
i throws ikeyword. iExamples iinclude iIOException, iSQLException,
iand iClassNotFoundException.
• Unchecked iExceptions: iThese iare iexceptions ithat iare inot ichecked
iat icompile-time ibut irather iat iruntime. iThey iare isubclasses iof
i RuntimeException. iExamples iinclude iNullPointerException,
i ArrayIndexOutOfBoundsException, iand iIllegalArgumentException.
3. iHandling
• Errors: iErrors iare igenerally inot imeant ito ibe icaught ior ihandled iby ithe
iapplication. iThey iusually iindicate isevere iissues ithat ia itypical iapplication
icannot irecover ifrom. iAttempting ito ihandle ierrors ican ilead ito
iunpredictable ibehavior.
• Exceptions: iExceptions, iespecially ichecked iexceptions, iare iintended ito ibe
icaught iand ihandled iby ithe iapplication. iProper ihandling iof iexceptions
ican iallow ithe iapplication ito irecover igracefully ior iprovide imeaningful
ierror imessages ito ithe iuser.
4. iExamples
Error iExample
A icommon iexample iof ian ierror iis iOutOfMemoryError, iwhich ioccurs iwhen ithe
iJVM iruns iout iof imemory. iThis iis iusually ia isign iof ia iserious iissue, isuch ias ia
imemory ileak ior iinsufficient imemory iallocation ifor ithe iJVM.
public iclass iErrorExample i{
i i i ipublic istatic ivoid imain(String[] iargs) i{
i i i i i i i itry i{
i i i i i i i i i i i iint[] ilargeArray i= inew iint[Integer.MAX_VALUE];
i i i i i i i i} icatch i(OutOfMemoryError ie) i{
i i i i i i i i i i i iSystem.err.println("Caught iOutOfMemoryError: i" i+ ie.getMessage());
i i i i i i i i}
i i i i}
Exception iExample
A icommon iexample iof ian iexception iis iFileNotFoundException, iwhich ioccurs
iwhen ian iapplication itries ito iaccess ia ifile ithat idoes inot iexist. iThis ican ibe
ianticipated iand ihandled iby ithe iapplication.
import ijava.io.File;
import ijava.io.FileNotFoundException;
import ijava.io.FileReader;
public iclass iExceptionExample i{
iiii public istatic ivoid imain(String[] iargs) i{
iiiiiiii try i{
iiiiiiiiiiii File ifile i= inew iFile("nonexistentfile.txt");
iiiiiiiiiiii FileReader ireader i= inew iFileReader(file);
iiiiiiii i } catch i(FileNotFoundException ie) i{
iiiiiiiiiiii System.err.println("Caught iFileNotFoundException: i" i+ ie.getMessage());
iiiiiiii }
iiii }
Q.No i5 iExplain i ithe i iSynchronization i iof i iThreads i?
Ans i iSynchronization iin iJava iis ia imechanism ithat iensures ithat itwo ior imore
iconcurrent ithreads ido inot isimultaneously iexecute ia iparticular isegment iof ia
iprogram, iwhich ican ilead ito ithread iinterference iand iinconsistent iresults.
iSynchronization iis iparticularly iimportant iwhen imultiple ithreads ineed iaccess ito
ishared iresources isuch ias ivariables, idata istructures, ior ifiles.
Key iConcepts iof iSynchronization
1. Synchronized iMethods:
• When ia imethod iis ideclared iwith ithe isynchronized ikeyword, ionly
ione ithread ican iexecute ithis imethod iat ia itime ifor ia igiven iobject
iinstance.
Syntax i:
public isynchronized ivoid isynchronizedMethod() i{
iiii // isynchronized icode
}
Synchronized iBlocks:
• Instead iof isynchronizing ian ientire imethod, iyou ican isynchronize ia iblock
iof icode iwithin ia imethod. iThis ican ibe imore iefficient ibecause iit ireduces
ithe iscope iof isynchronization.
Syntax i:
public ivoid imethod() i{
iiii synchronized(this) i{
iiiiiiii // isynchronized icode
iiii }
}
Lock iObjects:
• Instead iof iusing ithis ias ithe ilock, iyou ican iuse iany iother iobject ias ia ilock
ito ihave ifiner icontrol iover ithe isynchronization.
Syntax i: i
private ifinal iObject ilock i= inew iObject();
public ivoid imethod() i{
iiii synchronized(lock) i{
iiiiiiii // isynchronized icode
iiii }
}
Example: iSynchronized iMethod
Here’s ian iexample idemonstrating ia isynchronized imethod iin ia imulti-threaded
ienvironment.
class iCounter i{
iiii private iint icount i= i0;
iiii public isynchronized ivoid iincrement() i{
iiiiiiii count++;
iiii }
iiii public iint igetCount() i{
iiiiiiii return icount;
iiii }
}
public iclass iSynchronizedExample i{
iiii public istatic ivoid imain(String[] iargs) ithrows iInterruptedException i{
iiiiiiii Counter icounter i= inew iCounter();
iiiiiiii Runnable itask i= i() i-> i{
iiiiiiiiiiii for i(int ii i= i0; ii i< i1000; ii++) i{
iiiiiiiiiiiiiiii counter.increment();
iiiiiiiiiiii }
iiiiiiii };
iiiiiiii Thread ithread1 i= inew iThread(task);
iiiiiiii Thread ithread2 i= inew iThread(task);
iiiiiiii thread1.start();
iiiiiiii thread2.start();
iiiiiiii thread1.join();
iiiiiiii thread2.join();
System.out.println("Final icount: i" i+ icounter.getCount()); i// iShould iprint
iiiiiiii
i2000
iiii }
}
Explanation:
• The iCounter iclass ihas ia isynchronized imethod iincrement iwhich iensures
ithat ionly ione ithread ican imodify ithe icount iat ia itime.
• Two ithreads iare icreated, iboth iexecuting ithe itask iwhich iincrements ithe
icount i1000 itimes.
• By iusing ithe isynchronized ikeyword, iwe iensure ithat ithe ifinal icount iis
i2000, ias ithe icritical isection iis iprotected ifrom iconcurrent iaccess.
Example: iSynchronized iBlock
Here’s ian iexample idemonstrating ia isynchronized iblock iwithin ia imethod.
class iCounter i{
i i i iprivate iint icount i= i0;
i i i iprivate ifinal iObject ilock i= inew iObject();
iiii public ivoid iincrement() i{
i i i i i i i isynchronized(lock) i{
i i i i i i i i i i i icount++;
i i i i i i i i}
i i i i}
iiii public iint igetCount() i{
i i i i i i i ireturn icount;
i i i i}
public iclass iSynchronizedBlockExample i{
i i i ipublic istatic ivoid imain(String[] iargs) ithrows iInterruptedException i{
i i i i i i i iCounter icounter i= inew iCounter();
iiiiiiii Runnable itask i= i() i-> i{
i i i i i i i i i i i ifor i(int ii i= i0; ii i< i1000; ii++) i{
i i i i i i i i i i i i i i i icounter.increment();
i i i i i i i i i i i i}
i i i i i i i i};
iiiiiiii Thread ithread1 i= inew iThread(task);
i i i i i i i iThread ithread2 i= inew iThread(task);
iiiiiiii thread1.start();
i i i i i i i ithread2.start();
iiiiiiii thread1.join();
i i i i i i i ithread2.join();
iiiiiiii System.out.println("Final icount: i" i+ icounter.getCount()); i// iShould iprint
i2000
i i i i}
Explanation:
• The iCounter iclass inow iuses ia isynchronized iblock iwithin ithe iincrement
imethod.
• An iexplicit ilock iobject ilock iis iused ito isynchronize ithe iblock iof icode ithat
imodifies ithe icount.
• The ibehavior iand iresult iare ithe isame ias iin ithe iprevious iexample,
iensuring ithat ithe icount iis iaccurately iincremented iby iboth ithreads
iwithout iinterference.
Summary:
• Synchronization iis icritical iin ia imulti-threaded ienvironment ito iprevent
iconcurrent ithreads ifrom iinterfering iwith ieach iother iwhen iaccessing
ishared iresources.
• Synchronized iMethods: iEnsure ithat ithe ientire imethod iis iaccessed iby
ionly ione ithread iat ia itime.
• Synchronized iBlocks: iAllow ifiner-grained icontrol iby ilimiting ithe iscope iof
isynchronization ito ia ispecific iblock iof icode.
• Proper iuse iof isynchronization iprevents ithread iinterference iand iensures
idata iconsistency iin iconcurrent iapplications.
Q.NO i6 iExplain ithe ilife icycle iof ia iServlet i?
Ans i iThe ilife icycle iof ia iServlet iin iJava idefines ithe istages ia iservlet igoes ithrough
ifrom iits icreation ito iits idestruction. iUnderstanding ithe iservlet ilife icycle iis
icrucial ifor imanaging iresources iefficiently iand iensuring ioptimal iperformance iof
iweb iapplications. iThe iservlet ilife icycle iis imanaged iby ithe iservlet icontainer
i(e.g., iTomcat, iJetty), iand iit iincludes ithe ifollowing istages:
1. iLoading iand iInstantiation
• Loading: iWhen ia iservlet iis ifirst irequested iby ia iclient ior iduring ithe iserver
istartup i(if iconfigured ito iload ion istartup), ithe iservlet icontainer iloads ithe
iservlet iclass.
• Instantiation: iAfter iloading ithe iservlet iclass, ithe icontainer icreates ian
iinstance iof ithe iservlet.
2. iInitialization i(init iMethod)
• The icontainer icalls ithe iinit imethod ionce iafter iinstantiating ithe iservlet.
iThis imethod iis iused ifor iservlet iinitialization iand iis icalled ionly ionce
iduring ithe iservlet's ilife icycle.
• In ithis imethod, ithe iservlet ican iperform iany iinitialization itasks, isuch ias
iestablishing idatabase iconnections ior ireading iconfiguration iparameters.
• The iinit imethod ireceives ia iServletConfig iobject, iwhich iprovides
iconfiguration iinformation ifrom ithe iweb.xml ifile.
public iclass iMyServlet iextends iHttpServlet i{
i i i ipublic ivoid iinit(ServletConfig iconfig) ithrows iServletException i{
i i i i i i i i// iInitialization icode, isuch ias idatabase iconnection isetup
i i i i}
3. iRequest iHandling i(service iMethod)
• Each itime ia iclient irequest iis imade ito ithe iservlet, ithe icontainer icalls ithe
i service imethod.
• The iservice imethod iis iresponsible ifor ihandling iclient irequests iand
igenerating iresponses. iIt idetermines ithe itype iof irequest i(GET, iPOST,
ietc.) iand idispatches iit ito ithe iappropriate ihandler imethod i(doGet,
idoPost, ietc.).
• This imethod ican ibe icalled imultiple itimes iduring ithe iservlet's ilife icycle,
ionce ifor ieach iclient irequest.
public ivoid iservice(ServletRequest ireq, iServletResponse ires) ithrows
iServletException, iIOException i{
i i i i// iRequest ihandling icode
For iHttpServlet, iit’s imore icommon ito ioverride idoGet, idoPost, ietc., irather ithan
i service
protected ivoid idoGet(HttpServletRequest ireq, iHttpServletResponse ires) ithrows
iServletException, iIOException i{
i i i i// iHandle iGET irequest
protected ivoid idoPost(HttpServletRequest ireq, iHttpServletResponse ires)
ithrows iServletException, iIOException i{
i i i i// iHandle iPOST irequest
4. iDestruction i(destroy iMethod)
• The idestroy imethod iis icalled iby ithe iservlet icontainer ito iindicate ithat ithe
iservlet iis ibeing itaken iout iof iservice.
• This imethod iis icalled ionly ionce iat ithe iend iof ithe iservlet’s ilife icycle iand
iallows ithe iservlet ito irelease iany iresources iit iholds i(e.g., iclosing
idatabase iconnections).
• After ithe idestroy imethod iis icalled, ithe iservlet iinstance iis ieligible ifor
igarbage icollection.
public ivoid idestroy() i{
i i i i// iCleanup icode, isuch ias iclosing idatabase iconnections
Summary iof iServlet iLife iCycle iMethods
1. init(ServletConfig iconfig):
• Called ionce iduring iservlet iinitialization.
• Used ifor ione-time isetup itasks.
2. service(ServletRequest ireq, iServletResponse ires):
• Called ifor ieach iclient irequest.
• Dispatches irequests ito iappropriate ihandler imethods i(doGet,
idoPost, ietc.).
3. destroy():
• Called ionce iwhen ithe iservlet iis ibeing idestroyed.
• Used ifor icleanup itasks.
Example iServlet iLife iCycle iImplementation
Here iis ia icomplete iexample ithat idemonstrates ithe iservlet ilife icycle imethods:
import ijava.io.IOException;
import ijavax.servlet.ServletException;
import ijavax.servlet.ServletConfig;
import ijavax.servlet.http.HttpServlet;
import ijavax.servlet.http.HttpServletRequest;
import ijavax.servlet.http.HttpServletResponse;
public iclass iMyServlet iextends iHttpServlet i{
i i i i@Override
i i i ipublic ivoid iinit(ServletConfig iconfig) ithrows iServletException i{
i i i i i i i isuper.init(config);
i i i i i i i i// iInitialization icode
i i i i i i i iSystem.out.println("Servlet iinitialized.");
i i i i}
iiii @Override
i i i iprotected ivoid idoGet(HttpServletRequest ireq, iHttpServletResponse ires)
ithrows iServletException, iIOException i{
i i i i i i i i// iHandle iGET irequest
i i i i i i i ires.getWriter().println("Hello, iWorld!");
i i i i}
iiii @Override
iiii protected ivoid idoPost(HttpServletRequest ireq, iHttpServletResponse ires)
ithrows iServletException, iIOException i{
i i i i i i i i// iHandle iPOST irequest
i i i i i i i ires.getWriter().println("Post irequest ihandled.");
i i i i}
iiii @Override
i i i ipublic ivoid idestroy() i{
i i i i i i i i// iCleanup icode
i i i i i i i iSystem.out.println("Servlet idestroyed.");
i i i i}