Java Programming Question Bank
Java Programming Question Bank
QUESTION BANK
CS2210401 JAVA PROGRAMMING
PART-A (ONE MARK QUESTIONS)
I. Choose the correct answer
1) Which package contains the Random class?
a) java.utilpackage
b) java.langpackage
c) java.awt package
d) java.iopackage
2) What do you mean by nameless objects?
a) Anobjectcreatedbyusingthenewkeyword.
b) Anobjectofasuperclasscreatedinthesubclass.
c) Anobjectwithouthavinganynamebuthavingareference.
d) Anobjectthathasnoreference.
3) Whichofthefollowingexceptionisthrownwhendividedbyzerostatementisexecuted?
a) NullPointerException
b) NumberFormatException
c) ArithmeticExpression
4) What do you meanbychainedexceptionsinJava?
a) Exceptionsoccurred bytheVirtualMachine Error
b) Anexceptioncausedbyotherexceptions
c) Exceptions occur in chainswithdiscardingthedebugginginformation
d) Noneoftheabove
5) WhichofthefollowingoptionleadstotheportabilityandsecurityofJava?
a) BytecodeisexecutedbyJVM
b) TheappletmakestheJavacodesecureandportable
c) Useofexceptionhandling
d) Dynamicbindingbetweenobjects
6) WhichofthefollowingisnotaJavafeatures?
a) Dynamic
b) ArchitectureNeutral
c) Useofpointers
d) Object-oriented
7) isusedtofindandfixbugsintheJavaprograms.
a) JVM
b) JRE
c) JDK
d) JDB
8) What doestheexpressionfloata=35/0return?
a) 0
b) NotaNumber
c) Infinity
d) Runtimeexception
9) EvaluatethefollowingJavaexpression,ifx=3,y=5,andz=10:
++z+y-y+z+x++
a) 24
b) 23
c) 20
d) 25
10) Whichofthefollowingforloopdeclarationisnotvalid?
a) for(inti=99;i>=0;i/9)
b) for(inti=7;i<=77;i+=7)
c) for(inti=20;i>=2;--i)
d) for(inti=2;i<=20;i=2*i)
11) Whichoptionisfalseaboutthefinalkeyword?
a) Afinalmethodcannotbeoverriddeninitssubclasses.
b) Afinalclasscannotbeextended.
c) Afinalclasscannotextendotherclasses.
d) Afinalmethodcanbeinherited.
12) Whichof thefollowingis a mutableclassin java?
a) java.lang.String
b) java.lang.Byte
c) java.lang.Short
d) java.lang.StringBuilder
13) NumberofprimitivedatatypesinJavaare?
a) 6
b) 8
c) 9
d) 10
14)Whatisthesizeoffloatanddoubleinjava?
a) 32and64
b) 32and32
c) 64and64
d) 64and32
2 Mark
1. WhatisintroductiontoOOPs?
2. WhataretheprinciplesofOOPs?
Abstraction, encapsulation, polymorphism, and inheritance are the four main theoretical
principles of object-oriented programming
3. Whatisthedifferencebetweenprocedureorientedandobject-orientedprogramming?
The Procedural Programming follows a Top-Down approach. The Object Oriented Programming
follows a Bottom-Up approach. This programming model does not give importance to data. It prioritizes
the functions along with the sequence of actions that needs to follow.
4. WhataretheapplicationsofJava?
By using Java, we can develop a variety of applications such as enterprise applications, network
applications, desktop applications, web applications, games, android app, and many more.
5. WhatisJavaprogrammingstructure?
We have discussed about 8 Elements of the Structure of the Java Program below. These are
Section Documentation, Package Disclosure, Import Declarations, Connector Section, Category
Definition, Class constants and variables, Method Class Main and Techniques and conduct.
6. WhatistheneedofobjectinJava?
Objects are instances or references of a class. So we can call the methods and variables present in
this class with the help of their objects.
7. WhatisthehistoryofJava?
Java was originally developed by James Gosling at Sun Microsystems. It was released in May
1995asacorecomponentofSunMicrosystems'Javaplatform.Theoriginalandreference
implementationJavacompilers,virtualmachines,andclasslibrarieswereoriginallyreleasedbySun under
proprietary licenses.
8. WhataretheadvantagesofJVM?
The two most important benefits of the JVM are the possibility to write a code once and run
everywhere, and automatic memory management.
9. WhatisthepurposeofJDK?
The JDK isa development environment for building applications, applets, andcomponents using
the Java programming language.
10. WhatarefeaturesofJava?
ThemajorfeaturesinJava are:
● Simple.
● Object-Oriented.
● Portable.
● PlatformIndependent.
● Secured.
● Robust.
Unit-2 1
2 Mark
1. WhatareconstructsinJava?
Constructor in java is used to create the instance of the class. Constructors are almost similar to
methods except for two things - its name is the same as the class name and it has no return type.
2. WhatareprimitivedatatypesinJava?
Primitive Data Types. The eight primitives defined inJava are int, byte, short, long, float, double,
Boolean and char. These aren't considered objects and represent raw values.
3. WhatisidentifierinJavaprogramming?
Identifiers in Java are a sequence of characters to identify something in a program. They are
names given to a class, variable, package, method, or interface and allow the programmer to refer tothe
specific item from any place in the program.
4. WhatisthenamingconventionofaJavaprogram?
For variables, the Java naming convention is to always start with a lowercase letter and then
capitalize the first letter of every subsequent word.
5. Whatareoperatorsinprogramming?
6. HowmanyexpressionsarethereinJava?
InJava,there arefourkindsofexpressionstatements:assignmentexpressions,suchasa+=5,b
*=7,orc=3.Prefixandpostfixincrementanddecrement,suchas++a,--b,c++,d--
7. WhatisthedifferencebetweenunaryandternaryoperatorinJava?
An operator is called a unary, binary, or ternary operator based on the number of operands. Ifan
operator takes one operand, it is called a unary operator; if it takes two operands, it is called a binary
operator; if it takes three operands, it is called a ternary operator.
8. Whatisconversionofprimitivedatatypesin Java?
Specificconversionsonprimitivetypesarecalledthewideningprimitiveconversions:
9. Whatisflowofcontrolin Java?
Control flow statements let you control the flow of the execution of the code in your
program.InJava programming language, you can control theflow ofexecution ofthe codeby placing the
decision making, branching, looping, and adding conditional blocks.
10. Whichconstructisusedtodefineanarray?
An array constructor can be used to define only an ordinary array with elements that are not a row
type. An array constructor cannot be used to define an associative array or an ordinary array with
elements that are a row type.
Unit-3 1
2 Mark
1. WhatisthedifferencebetweenexceptionanderrorinJava?
Both exceptions and errors are the subclasses of a throw able class. The error implies a problem
that mostly arises due to the shortage of system resources. On the other hand, the exceptions occur during
runtime and compile time.
2. WhatisaabstractclassinJavaandinterface?
The Abstract class and Interface both are used to have abstraction. Anabstract class contains an
abstract keyword on the declaration whereas an Interface is a sketch that is used to implement a class.
3. WhichpackageisusedforexceptioninJava?
Java.langpackage
The top three classes in this hierarchy (the Throw able, Error, and Exception classes) are all defined
inthe java. Lang package (which is automatically imported into every class file)
4. WhatistheaccessspecifiesinJavaforinterface?
The access specifies used with classes are private, protected and public. While in Interface only
one specified is used- Public.
5. Whatisexceptionandexceptionhandlingin Java?
6. Whataretheuser-definedexceptionsin Java?
User-defined exceptions are also referred to as custom exceptions. The exceptions created per our
use case and thrown using the throw keyword are user-defined exceptions, and such exceptions are
derived classes of the Exception class from the java.
7. Whatarethedifferenttypesofencapsulationin Java?
There are three types of encapsulation, namely Member variable encapsulation, Function
encapsulation and Class encapsulation.
8. WhatisenrichmentinJava?
The process of replacing objects to refs and refs to objects is called "Enrichment" and can be
done in two different ways.
9. Whenshouldyouuseanassertionoveranexception?
Meanwhile, exceptions indicate exceptional conditions - problems for which the developer may
not have accounted. You can use assertions for internal logic checks within your code, unchecked
exceptions for error conditions outside your immediate code's control, and checked exceptions for
business and recoverable errors.
10. HowtocreateanexceptioninterfaceinJava?
In order to create a custom exception, we need to extend the Exception class that belongs to
java.Lang package.Example:Wepassthestringto the constructorof the superclass- Exceptionwhichis
obtained using the “get Message ()” function on the object created.
Unit-4 1
2 Mark
1. WhatismultitaskinginJava?
2. WhatiscalledthreadinJava?
AthreadinJavaisthedirectionorpaththatistakenwhileaprogramisbeingexecuted.
Generally,alltheprogramshaveatleastonethread,knownasthemainthread,
3. HowtocreateanewthreadinJava?
JavaThreadExamplebyextendingThreadclass
{ System.out.println("thread is running
")
}
publicstaticvoidmain(Stringargs[])
t1.start();
4. Whataretheprioritylevelsof threads?
Threads are scheduled to run based on their scheduling priority. Each thread is assigned a
scheduling priority. The priority levels range from zero (lowest priority) to 31 (highest priority). Only the
zero-page thread can have a priority of zero.
5. Whatisthedifferencebetweenjoin()andalive()?
isAlive () just returns a Boolean that indicates whether the thread is alive, the status of the thread
- it returns true or false, indicating whether the thread is "done". . join() makes the currentthread you are
in wait until the thread that you're calling . join() on has completed.
6. Whatistheuseofalive()methodinJava?
This method is used to find out if a threadhas actually been started and has yet not terminated.
Note: While returning this function returns true if the thread upon which it is called is still running. It
returns false otherwise
7. Whatistheprocesssynchronizationinthread?
Process Synchronization means sharing system resources by processes in a such a way that,
Concurrent access to shared data is handled thereby minimizing the chance of inconsistent data.
8. Whatarethreemethodsofsynchronization?
DifferentTechniquesforSynchronization
● ThreeDarkLampsMethod.
● TwoBright,OneDark Method.
● SynchroscopeMethod.
9. HowtoreadandwritemultiplefilesinJava?
Create a file object by passing the required file path as a parameter. Read the contents of each file
using Scanner or any other reader. Append the read contents into a StringBuffer. Write the StringBuffer
contents into the required output file.
10. Whatisarealexampleofmultithreadingin Java?
A very good example of thread-based multithreading is a word processing program that checks
the spelling of words in a document while writing the document. This is possible only if each action is
performed by a separate thread.
Unit-5 1
2 Mark
1. WhatisnetworkprogramminginJava?
Network programming is the procedure of writing programs that run on multiple devices (computers)
that are linked together via a network. To allow for low-level communication details, Java encapsulates
classes and interfaces.
2. Whatisconcurrentprogramin Java?
Concurrency is the ability to run several or multi programs or applications in parallel. The
backbone of Java concurrency is threads (a lightweight process, which has its own files and stacks and
can access the shared data from other threads in the same process)
3. Whatarethreadsinconcurrentprogramming?
A thread is a unit of control within a process: when a thread runs, it executes a function in the
program - the “main thread” executes the “main” function and other threads execute other functions.
4. Whatareinterruptingthreadsin Java?
An interrupt is an indication to a thread that it should stop what it is doing and do something else.
It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common
for the thread to terminate.
5. Whatisthreadcommunicationin Java?
Overview. Inter Thread Communication, as the name implies, is a method that allows many
synchronized threads to communicate or interact with one another. In Java, there are two ways to
implement inter-thread communication: using wait () and notify() methods and using the higher-level
constructs of the java.
6. Whatiscommunicationbetweenthreads?
Inter-threadCommunication
All the threads in the same program share the same memory space. If an object is accessible tovarious
threads then these threads share access to that object's data member and thus communicate each other.
The second way for threads to communicate is by using thread control methods.
7. WhatistheuseofJavanetpackageinJava?
Provides the classes necessary to create an applet and the classes an applet uses to communicate
with its applet context. Contains all of the classes for creating user interfaces and for painting graphics
and images.
8. WhichclassisusedtocreateTCPserver?
9. WhatisTCPinJava networking?
TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to asTCP/IP.
10. Whatareclientandserverinjava?
Part –B
10 Mark
Unit-1
1. ExplaintheJVM(JavaVirtualMachine)Architecture.
● JavaVirtualMachine
● InternalArchitectureofJVM
JVM(JavaVirtualMachine)isanabstractmachine.Itisaspecificationthatprovidesruntime environment in
which java bytecode can be executed.
JVMsareavailableformanyhardwareandsoftwareplatforms(i.e.JVMisplatformdependent).
WhatisJVM?
It is:
Whatitdoes
TheJVMperformsfollowingoperation:
o Loadscode
o Verifiescode
o Executescode
o Providesruntimeenvironment
o Memoryarea
o Classfile format
o Registerset
o Garbage-collectedheap
o Fatalerrorreportingetc.
JVMArchitecture
ClassloaderisasubsystemofJVMwhichisusedtoloadclassfiles.Wheneverwerunthejavaprogram,it is loaded
first by the classloader. There are three built-in classloaders in Java.
1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension
classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like
java.lang package classes, java.net package classes, java.util package classes, java.io package
classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader ofSystem
classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It
loadsthe classfilesfromclasspath. By default,classpath is set tocurrentdirectory. Youcan changethe
classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.
1. //Let'sseeanexampletoprinttheclassloadername
2. publicclassClassLoaderExample
3. {
4. publicstaticvoidmain(String[]args)
5. {
6. //Let'sprinttheclassloadernameofcurrentclass.
7. //Application/Systemclassloaderwillloadthisclass
8. Classc=ClassLoaderExample.class;
9. System.out.println(c.getClassLoader());
10. //IfweprinttheclassloadernameofString,itwillprintnullbecauseitisan
11. //in-builtclasswhichisfoundinrt.jar,soitisloadedbyBootstrapclassloader
12. System.out.println(String.class.getClassLoader());
13. }
14.}
TestitNow
Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null
ThesearetheinternalclassloadersprovidedbyJava.Ifyouwanttocreateyourownclassloader,you need to extend
the ClassLoader class.
2) Class(Method)Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and methoddata,
the code for methods.
3) Heap
Itistheruntimedataareainwhichobjectsare allocated.
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in methodinvocation
and return.
EachthreadhasaprivateJVMstack,createdatthesametimeasthread.
Anewframeiscreatedeachtimeamethodisinvoked.Aframeisdestroyedwhenitsmethodinvocation completes.
5) ProgramCounterRegister
PC (program counter) register contains the address of the Java virtual machine instruction currently being
executed.
6) NativeMethodStack
Itcontainsallthenativemethodsusedintheapplication.
7) ExecutionEngine
It contains:
1. Avirtual processor
2. Interpreter:Readbytecodestreamthenexecutetheinstructions.
3. Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte
code that have similar functionality at the same time, and hence reduces the amount of time
neededforcompilation.Here, theterm"compiler" refers to atranslatorfrom theinstructionset of a
Java virtual machine (JVM) to the instruction set of a specific CPU.
8) JavaNativeInterface
Java Native Interface (JNI) is a framework which provides an interface to communicate with another
application written in another language like C, C++, Assembly etc. Java uses JNI framework to send
output to the Console or interact with OS libraries.
12.ExplaintheInstallationoftheJDKonMicrosoftWindowsPlatforms?
SystemRequirementsforInstallingtheJDKon64-BitWindowsPlatform
Forsupportedprocessorsandbrowsers,seeOracleJDKCertifiedSystemsConfigurations.
JDKInstallationInstructionNotationforWindows
JDKinstallersnowsupportonlyoneversionofanyJavafeaturerelease.Youcan'tinstallmultiple versions
of the same feature release.
Forexample,youcan'tinstalljdk-20andjdk-20.0.1simultaneously.Ifyouattempttoinstalljdk-
20.0.1afterjdk-20isinstalled,theinstalleruninstallsjdk-20andinstallsjdk-20.0.1.
JDKInstallationInstructionsforWindows
Yourunaself-installingexecutablefiletounpackandinstalltheJDKonWindowscomputers.
InstallJDKonWindowscomputersbyperformingtheactionsdescribedinthefollowingtopics:
● DownloadingtheJDKInstaller
● InstallingtheJDKfromtheJDK.exe Installer
● InstallingtheJDKfromtheMSIEnterprise Installer
● InstallingtheJDKSilently
DownloadingtheJDKInstaller
AccesstheJavaSEDownloadspageandclickAcceptLicenseAgreement.Under
theDownloadmenu,clicktheDownloadlinkthatcorrespondstothe.exeforyourversionofWindows. Download
the file jdk-20.interim.update.patch_windows-x64_bin.exe.
InstallingtheJDKfromtheJDK.exeInstaller
YoumusthaveadministratorprivilegestoinstalltheJDKonMicrosoftWindows. To
1. StarttheJDK20installerbydouble-clickingtheinstaller'siconorfilenameinthedownload
location.
2. Followtheinstructionsprovidedbytheinstaller.
3. Aftertheinstallationiscomplete,deletethedownloadedfiletorecoverdiskspace.
Unit-2
11. ExplaintheArraysinJava.
● InJava,allarraysaredynamicallyallocated.(discussedbelow)
● Arraysmaybestoredincontiguousmemory[consecutivememorylocations].
● SincearraysareobjectsinJava,wecanfindtheirlengthusingtheobjectproperty length.Thisisdifferent from C/C++,
where we find length using sizeof.
● AJavaarrayvariablecanalsobedeclaredlikeothervariableswith[]afterthedatatype.
● Thevariablesinthearrayareordered,andeachhasanindexbeginningwith0.
● Javaarraycanalsobeusedasastaticfield,alocalvariable,oramethodparameter.
● Thesizeofanarraymustbespecifiedbyintorshortvalueandnotlong.
● ThedirectsuperclassofanarraytypeisObject.
● EveryarraytypeimplementstheinterfacesCloneableandjava.io.Serializable.
● Thisstorageofarrayshelpsusrandomlyaccesstheelementsofanarray[SupportRandomAccess].
● Thesizeofthearraycannotbealtered(onceinitialized).However,anarrayreferencecanbemadetopoint to another array.
●
An array can contain primitives(int, char, etc.) and object (or non-primitive) referencesof a class depending onthe
definition of the array. In the case of primitive data types, the actual values might be stored in contiguous memory
locations(JVM
12. ExplainJavaExpressionswithExamples
JavaExpression
Variables, operators, literals, and method calls make up a Java expression. Operands and operatorsare
usedtobuildexpressions.Anexpression’soperatorsspecifywhichoperationsshouldbeappliedtotheoperands.
Theprecedenceandassociativityoftheoperatorsgoverntheorderinwhichtheyareevaluatedinanexpression.
Takeanexample:
int
marks;
marks=
95;
Here,marks=90isanexpressionthatreturnsan intvalue.
result=a+b-3.4;
Here,num1==num2isanexpressionthatreturnsaBooleanvalue.Similarly,“num1islargerthannum2”isa
stringexpression.
HowtoEvaluateJavaExpressions?
Even though Java has its method for evaluating expressions behind the scenes, a Java expression’s
outcomeanditscorrespondingarithmeticexpressionareidentical.Asaresult,youcanusethearithmeticruleto evaluate a
Java expression confidently.
TypesofExpressions
Whileanexpressiontypicallyyieldsaresult,thisisnotalwaysthecase.InJava,thereareafewtypesof expressions:
Thosethatgenerateavalue,i.e.
(1 + 1) result
Those who, for example, assign a variable
(i=10)
Becauseanexpressioncancompriseawiderangeofelementssuchasmethodinvocationsorincrementoperators
thataffectthestate(i.e.,memory),thosethathavenoresultbutmayhavea“sideeffect.”
Unit-3
11. ExplaintheJavaExceptions.
WhatareJavaExceptions?
InJava,Exception isanunwantedorunexpectedevent,whichoccursduringtheexecutionofa program, i.e. at run
time, that disrupts the normal flow of the program’s instructions. Exceptions can be
caughtandhandledbytheprogram.Whenanexceptionoccurswithinamethod,itcreatesanobject.Thisobjectis
calledtheexceptionobject.Itcontainsinformationabouttheexception,suchasthenameanddescriptionof the exception and
the state of the program when the exception occurred.
MajorreasonswhyanexceptionOccurs
● Invaliduserinput
● Devicefailure
● Lossofnetworkconnection
● Physicallimitations(out-of-diskmemory)
● Codeerrors
● Openinganunavailablefile
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory
leaks,stackoverflowerrors,libraryincompatibility,infiniterecursion,etc.Errorsareusuallybeyondthecontrol of the
programmer, and we should not try to handle errors.
DifferencebetweenErrorandException
LetusdiscussthemostimportantpartwhichisthedifferencesbetweenErrorandExceptionthatisasfollows:
● Error:AnErrorindicatesaseriousproblemthatareasonableapplicationshouldnottrytocatch.
● Exception:Exceptionindicatesconditionsthatareasonableapplicationmighttrytocatch.
ExceptionHierarchy
Allexceptionanderrortypesaresubclassesoftheclass Throwable,whichisthebaseclassofthehierarchy.
Onebranchisheadedby Exception.Thisclassisusedforexceptionalconditionsthatuserprogramsshould catch.
NullPointerExceptionis an example of such an exception. Another branch, Error is used by the Java run-
timesystem(JVM)toindicateerrorshavingtodowiththerun-timeenvironmentitself(JRE).StackOverflowError is an
example of such an error.
12. ExplaintheExceptionHandlinginJava.
Exception handling in java is one of the powerful mechanisms to handle runtime errors caused by
exceptions.Exceptionhandlingplaysanimportantroleinsoftwaredevelopment. Thisarticlehelpsyou understand java
exception, exception in java, java exception handling, java exception hierarchy, types of exception in java, and many
more.
WhatisExceptionHandlinginJava?
Exception handling in java helps in minimizing exceptions and helps in recovering from exceptions. It
isone of the powerful mechanisms to handle runtime exceptions and makes it bug-free. Exception handling helps in
maintaining the flow of the program. An exception handling is defined as an abnormal condition that may happen at
runtime and disturb the normal flow of the program.
AlsoRead:JavaTutorialforbeginners
WhatisanException?
An expectation is an unexpectedevent that occurs while executing the program, that disturbs the normal flow of the
code.
Exceptionhandlinginjavawithanexample:
Let’s say,
statement
statement
statement
exception anexceptionoccurred,thenJVMwillhandleitandwillexittheprog.
statement
statement
statement
Forhandlingexceptions,thereare2possibleapproaches
1. JVM
If an exception is not handled explicitly, then JVM takes the responsibility of handling the exception.
Oncetheexceptionishandled,JVMwillhalttheprogramandnomoreexecutionofcodewilltakeplace
● Example
importjava.util.*;
classMain{
{ System.out.println(5/0);
System.out.println("Endofprogram!");
RuntimeError:
Exceptioninthread"main"java.lang.ArithmeticException:/byzero at
Main.main(File.java:5)
Unit-4
11. ExplaintheMultithreadinginJava.
MultithreadinginJavaisaprocessofexecutingmultiplethreadssimultaneously.
Athreadisalightweightsub-process,thesmallestunitofprocessing.Multiprocessingandmultithreading,bothare used to
achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area. They don't
allocate separate memory area so saves memory, and context-switching between the threads takes less time than
process.
JavaMultithreadingismostlyusedingames,animation,etc.
AdvantagesofJavaMultithreading
2) Youcanperformmanyoperationstogether,soitsavestime.
3) Threadsareindependent,soitdoesn'taffectotherthreadsifanexceptionoccursinasinglethread.
Multitasking
o Process-basedMultitasking(Multiprocessing)
o Thread-basedMultitasking(Multithreading)
1) Process-basedMultitasking(Multiprocessing)
o Eachprocesshasanaddressinmemory.Inotherwords,eachprocessallocatesaseparatememoryarea.
o Aprocessis heavyweight.
o Costofcommunicationbetweentheprocessishigh.
o Switchingfromoneprocesstoanotherrequiressometimeforsavingandloading registers,memory maps, updating
lists, etc.
2) Thread-basedMultitasking(Multithreading)
o Threadssharethesameaddressspace.
o Athreadis lightweight.
o Costofcommunicationbetweenthethreadislow.
12. ExplaintheSynchronizationinJava.
Synchronization in Java is the capability to control the access of multiple threads to any sharedresource.
WhyuseSynchronization?
Thesynchronizationismainlyusedto
1. Topreventthreadinterference.
2. Topreventconsistencyproblem.
TypesofSynchronization
Therearetwotypesofsynchronization
1. ProcessSynchronization
2. ThreadSynchronization
Here,wewilldiscussonlythreadsynchronization.
ThreadSynchronization
Therearetwotypesofthreadsynchronizationmutualexclusiveandinter-threadcommunication.
1. MutualExclusive
1. Synchronizedmethod.
2. Synchronizedblock.
3. Staticsynchronization.
2. Cooperation(Inter-threadcommunicationinjava)
MutualExclusive
1. ByUsingSynchronizedMethod
2. ByUsingSynchronizedBlock
3. ByUsingStaticSynchronization
ConceptofLockinJava
Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock
associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's
lock before accessing them, and then release the lock when it's done with them.
FromJava5thepackagejava.util.concurrent.lockscontainsseverallockimplementations.
Unit-5
11. ExplainSocketProgramminginJava.
This article describes a very basic one-way Client and Server setup where a Client connects, sends
messagestotheserverandtheservershowsthemusingasocketconnection.There’salotoflow-levelstuff that needs to
happen for these things to work but the Java API networking package (java.net) takes care of all of that, making
network programming very easy for programmers.
Client-SideProgramming
EstablishaSocketConnection
To connect to another machine we need a socket connection. A socket connectionmeans the two machines
have information about each other’s network location (IP Address) and TCP port. The java.net.Socket class
represents a Socket. To open a socket:
Socketsocket=newSocket(“127.0.0.1”,5000)
● Thefirstargument– IPaddressofServer.(127.0.0.1istheIPaddressoflocalhost,wherecodewillrunon the single
stand-alone machine).
● Thesecondargument– TCPPort.(Justanumberrepresentingwhichapplicationtorunonaserver.For example, HTTP
runs on port 80. Port numbercan be from 0 to 65535)
Communication
Tocommunicateoverasocketconnection,streamsareusedtobothinputandoutputthedata.
Closingtheconnection
Thesocketconnectionisclosedexplicitlyoncethemessagetotheserverissent.
Intheprogram,theClientkeepsreadinginputfromauserandsendsittotheserveruntil“Over”istyped
JavaImplementation
1. Java
//AJavaprogramforaClient
import java.io.*;
import java.net.*;
//initializesocketandinputoutputstreams
privateDataInputStreaminput=null;
privateDataOutputStreamout=null;
//constructortoputipaddressandport public
//establishaconnection try
socket=newSocket(address,port);
System.out.println("Connected");
//takesinputfromterminal
input=newDataInputStream(System.in);
out=newDataOutputStream( s
ocket.getOutputStream());
catch(UnknownHostExceptionu)
{ System.out.println(u);
return;
catch (IOException i)
{ System.out.println(i);
return;
//stringtoreadmessagefrominput String
line = "";
//keepreadinguntil"Over"isinput while
(!line.equals("Over")) {
try{
line=input.readLine();
out.writeUTF(line);
catch (IOException i)
{ System.out.println(i);
//closetheconnection try
input.close();
out.close();
socket.close();
catch (IOException i) {
System.out.println(i);
publicstaticvoidmain(Stringargs[])
Clientclient=newClient("127.0.0.1",5000);
ServerProgramming
EstablishaSocketConnection
Towriteaserverapplicationtwosocketsareneeded.
● AServerSocketwhichwaitsfortheclientrequests(whenaclientmakesanewSocket())
● AplainoldSockettouseforcommunicationwiththeclient.
Communication
getOutputStream()methodisusedtosendtheoutputthroughthesocket.
ClosetheConnection
Afterfinishing,itisimportanttoclosetheconnectionbyclosingthesocketaswellasinput/outputstreams
12. ExplaintheTCP/IPwithexample.
First,let’sunderstandabouttheworkflowandtheAPI.
1. ServerSocketAPI
TheServerSocketclassisusedtoimplementaserverprogram.Herearethetypicalstepsinvolveindevelopinga server
program:
1. Createaserversocketandbindittoaspecificportnumber
2. Listenforaconnectionfromtheclientandacceptit.Thisresultsinaclientsocketiscreatedforthe connection.
3. ReaddatafromtheclientviaanInputStreamobtainedfromtheclientsocket.
4. Senddatatotheclientviatheclientsocket’s OutputStream.
5. Closetheconnectionwiththeclient.
Thesteps3and4canberepeatedmanytimesdependingontheprotocolagreedbetweentheserverandthe client.
Let’sdiveintoeachstepindetails.
CreateaServerSocket:
CreateanewobjectoftheServerSocketclassbyusingoneofthefollowingconstructors:
- ServerSocket(intport):createsaserversocketthatisboundtothespecifiedportnumber.Themaximum number of
queued incoming connections is set to 50 (when the queue is full, new connections are refused).
- ServerSocket(intport,intbacklog):createsaserversocketthatisboundtothespecifiedportnumber and with
the maximum number of queued connections is specified by the backlog parameter.
- ServerSocket(intport,intbacklog,InetAddressbindAddr):createsaserversocketandbindsittothe specified
port number and a local IP address.
Sowhentousewhich?
Usethefirstconstructorforasmallnumberofqueuedconnections(lessthan50)andanylocalIPaddress available.
Usethesecondconstructorifyouwanttoexplicitlyspecifythemaximumnumberofqueuedrequests.
1 ServerSocketserverSocket=newServerSocket(6868);
Notethattheseconstructorscanthrow IOExceptionifanI/Oerroroccurswhenopeningthesocket,soyouhaveto catch or re-
throw it.
Listenforaconnection:
OnceaServerSocketinstanceiscreated,callaccept()tostartlisteningforincomingclientrequests:
1 Socketsocket=serverSocket.accept();