0% found this document useful (0 votes)
4 views32 pages

Java Programming Question Bank

The document is a question bank for a Java Programming course, containing multiple-choice questions, fill-in-the-blank questions, true/false questions, and short answer questions. It covers various topics such as object-oriented programming principles, Java features, exception handling, and data types. The document serves as a study guide for students preparing for assessments in Java programming.

Uploaded by

anusanu162
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views32 pages

Java Programming Question Bank

The document is a question bank for a Java Programming course, containing multiple-choice questions, fill-in-the-blank questions, true/false questions, and short answer questions. It covers various topics such as object-oriented programming principles, Java features, exception handling, and data types. The document serves as a study guide for students preparing for assessments in Java programming.

Uploaded by

anusanu162
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

MAHENDRA INSTITUTE OF TECHNOLOGY(AUTONOMOUS)

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

15) Find the output of the following code.int


Integer = 24;
char String= ‘I’; System.out.print(Integer);
System.out.print(String);
a) Compileerror
b) Throwsexception
c) I
d) 24I
16) Selectthevalidstatement.
a) char[]ch=newchar(5)
b) char[]ch=newchar[5]
c) char[]ch=newchar()
d) char[]ch=newchar[]
17) Selectthevalidstatementtodeclareandinitializeanarray.
a) int[]A={}
b) int[]A={1,2,3}
c) int[]A=(1,2,3)
d) int[][]A = {1,2,3}
18) Whenistheobjectcreatedwithnewkeyword?
a) AtRuntime
b) Atcompiletime
c) Dependsonthecode
d) None
19) Identifythecorrecteddefinitionofapackage.
a) Apackageisacollectionofeditingtools
b) Apackageisacollectionofclasses
c) Apackageisacollectionofclassesandinterfaces
d) Apackageisacollectionofinterfaces
20) InwhichofthefollowingistoString()methoddefined?
a) Java.lang.object
b) java.lang.String
c) java.lang.util
d) None
21) CompareTo()returns
a) True
b) False
c) Anintvalue
d) None
22) Identify the output of the following program. Public
class Test{
Public static void main(String argos[]){ String
str1 = “one”;
String str2 = “two”;
System.out.println(str1.concat(str2));
}}
a) one
b) two
c) onetwo
d) twoone
23) Identifythereturntypeofamethodthatdoesnotreturnanyvalue.
a) int
b) void
c) double
d) None
24)Identifythemodifierwhichcannotbeusedforconstructor.
a) public
b) protected
c) private
d) static
25) Whatisthevariablesdeclaredinaclassfortheuseofallmethodsoftheclasscalled?
a) Object
b) InstanceVariable
c) Referencevariable
d) None
26) Identifythecorrectwayofdeclaringconstructor.PublicclassSolution{}
a) Solution()
b) publicSolution()
c) Solution(void){}
d) Both(A)and(B)
27) How many times will “Interviewbit” be printed. Int
count = 0;
do{ System.out.println(“Interviewbit”);
count++;
}while(count<10);
a) 8
b) 9
c) 10
d) 11
28) Whichstatement istrueaboutJava?
a) Javaisasequence-dependentprogramminglanguage
b) Javaisacodedependentprogramminglanguage
c) Javaisaplatform-dependentprogramminglanguage
d) Javaisaplatform-independentprogramminglanguage
29) Which of thesecannotbeusedfor a variablenameinJava?
a) identifier&keyword
b) identifier
c) keyword
d) noneofthementioned
30) Whatistheextensionofjavacodefiles?
a) .js
b) .txt
c) .class
d) .java
II. Fillingtheblanks
1. keywordusedtoimplementsinheritance
2. Mentionthekeywordusingwhileinterface
3. Onebase onederivedclassis known as
4. String in Java is
5.
6. methodofStringclasscanbeusedtotesttostringsforequality
7. Arraysareusedtostore valuesina variable
8. The statementisusedtoincludeanotherJavapackageinaJavasourcefile.
9. TheoutputoftheJavacompilerisexecutedbythe----------
10. A isacollectionofclassesandinterfaces
11. TheoutputoftheJavacompilerisknownas --.
12. Father of Java Programming Language is
13
is the java compiler.
14.URLstandsfor --.
15 commandisusedastheJavainterpreter.
16.Javasupports --_programming.
17 declares aclassvariablethatistobesharedamongallinstances.
18. Methodsdefinedinaninterface mustbe --.
19. Javaisa generationlanguage.
20. Manyobjectsandtheircode formauserdefineddatatypecalled --.
21 meansdatahiding.
22 symbolofStringclasscanbeusedtotestthestringcomparison.
23. Javasupports programming.
24. Itispossibletothrowanexceptionexplicitlyusingthe statement.
25. Javacompilerproducesanobjectfilethatcontains----------
26. JavabytecodeoutputfromtheJDKcompilerwillbeplacedintoafilewith---------- extension.
27. An isanobjectthatisgeneratedwhenaruntimeerroroccurs.
28 isnotsupportedbyjava.
III. (True/False)
1. Thecompilerconvertssourcecodefilesintobytecodefile.
2. Methodsdefinedinaninterface mustbe private.
3. Instancevariablesaredeclaredoutsideaclass.
4. Itisnotpossibletodefine,amethodinthesubclassthathasthesamename,same arguments and the same return type.
5. Aconstructormusthavethesamenameastheclassitisdeclaredwithin.
6. Javaisaplatformindependentlanguage.
7. Javaiscasesensitivelanguage.
8. MultipleInheritancenotsupportedbyjava.
9. SyntaxofaJavaPackageispackage;
10. Apackageisacollectionofclassesandinterfaces.
11. Anexceptionisanobjectthatisgeneratedwhenaruntimeerroroccurs.
12. Aclassdeclarationcanincludebothabstractandfinalmodifiers.
13. Javasupportsoperatoroverloading.
14. Ifaclasscontainsanabstractmethod,thatclassitselfmustalsobedeclaredabstract.
15. Ifaclassimplementsaninterface,itmustimplementallthemethodsdeclaredbythat interface.
16. Ifaclassdefinitiondoesnotexplicitlyputaclassintoapackage,theclassbelongstothe default package.
17. Javasupportsmultithreadedprogramming.
18. Javahasakeywordcalledfinally.
19. Catchkeywordisnotapartofexceptionhandling.
20. Theobjectcreatedbythestringclasscanbemodified.
21. Javahasakeywordcalledsuper.
Unit-1 1

2 Mark

1. WhatisintroductiontoOOPs?

Object-oriented programming (OOP) is a computer programming model that organizes software


design around data, or objects, rather than functions and logic. An object can be defined as a data field
that has unique attributes and behavior.

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?

In mathematics and computer programming, an operator is a character that represents aspecific


mathematical or logical action or process.

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:

● bytetoshort, int,long, float,ordouble.


● shortto int,long, float,ordouble.
● chartoint ,long, float,or double.
● inttolong,float,ordouble.
● longtofloatordouble.
● floatto double.

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?

Exception handling is the process of responding to unwanted or unexpected events when a


computer program runs. Exception handling deals with these events to avoid the program or system
crashing, and without this process, exceptions would disrupt the normal operation of a program.

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?

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved in two ways: Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)

2. WhatiscalledthreadinJava?

AthreadinJavaisthedirectionorpaththatistakenwhileaprogramisbeingexecuted.
Generally,alltheprogramshaveatleastonethread,knownasthemainthread,

3. HowtocreateanewthreadinJava?

JavaThreadExamplebyextendingThreadclass

class Multi extends Thread{

public void run()

{ System.out.println("thread is running

")

}
publicstaticvoidmain(Stringargs[])

{ Multi t1=new Multi();

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?

To create a TCP server, it is necessary to understand a new class, ServerSocket. ServerSocket


allows you to bind a port and wait for clients to connect, setting up a complete Socket object at thattime

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?

A morereliable distinctionis that aclientinitiates aconversation,while aserverwaits forclients to


start conversations with it. In some cases, the same program may be both a client and a server.

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:

1. A specificationwhere working of Java Virtual Machine is specified. But implementation provider


is independent to choose the algorithm. Its implementation has been provided by Oracle and other
companies.
2. AnimplementationItsimplementationisknownasJRE(JavaRuntimeEnvironment).
3. Runtime InstanceWhenever you write java command on the command prompt to run the java
class, an instance of JVM is created.

Whatitdoes

TheJVMperformsfollowingoperation:

o Loadscode
o Verifiescode
o Executescode
o Providesruntimeenvironment

JVM provides definitions for the:

o Memoryarea
o Classfile format
o Registerset
o Garbage-collectedheap
o Fatalerrorreportingetc.

JVMArchitecture

Let'sunderstandtheinternalarchitectureofJVM.Itcontainsclassloader,memoryarea,execution engine etc.


1) Classloader

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

run the JDK installer:

1. StarttheJDK20installerbydouble-clickingtheinstaller'siconorfilenameinthedownload
location.
2. Followtheinstructionsprovidedbytheinstaller.
3. Aftertheinstallationiscomplete,deletethedownloadedfiletorecoverdiskspace.
Unit-2

11. ExplaintheArraysinJava.

ArrayinJava isagroupoflike-typedvariablesreferredtobyacommonname.ArraysinJavaworkdifferently than they do in


C/C++. Following are some important points about Java arrays.

● 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.

double a = 3.2, b = 3.4, result;

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.

ExceptionHandling inJavaisoneof the effectivemeanstohandle runtimeerrorssothatthe regular flow of the


applicationcan be preserved. JavaException Handlingisamechanismto handleruntimeerrors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

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{

public static void main (String[] args)

{ 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

1) Itdoesn'tblocktheuserbecausethreadsareindependentandyoucanperformmultipleoperationsatthe same time.

2) Youcanperformmanyoperationstogether,soitsavestime.

3) Threadsareindependent,soitdoesn'taffectotherthreadsifanexceptionoccursinasinglethread.

Multitasking

Multitaskingisaprocessofexecutingmultipletaskssimultaneously.WeusemultitaskingtoutilizetheCPU. Multitasking can


be achieved in two ways:

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.

JavaSynchronizationisbetteroptionwherewewanttoallowonlyonethreadtoaccessthe shared resource.

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

MutualExclusivehelpskeepthreadsfrominterferingwithoneanotherwhilesharingdata.Itcanbe achieved by using the


following three ways:

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.*;

public class Client {

//initializesocketandinputoutputstreams

private Socket socket = null;

privateDataInputStreaminput=null;

privateDataOutputStreamout=null;

//constructortoputipaddressandport public

Client(String address, int port)

//establishaconnection try

socket=newSocket(address,port);

System.out.println("Connected");

//takesinputfromterminal

input=newDataInputStream(System.in);

// sends output to thesocket

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.

InthisJavanetworkprogrammingtutorial,youwilllearnhowtodevelopasocketserverprogramtoimplementfully functional network


client/server application. You will also learn how to create a multi-threaded server.

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.

Thesteps1to5canberepeatedforeachnewclient.Andeachnew connectionshouldbehandledbyaseparate thread.

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.

AndusethethirdconstructorifyouwanttoexplicitlyspecifyalocalIPaddresstobebound(incasethecomputer has multiple


IP addresses).

Andofcourse,thefirstconstructorispreferredforsimpleusage.Forexample,thefollowinglineofcodecreatesa server socket


and binds it to the port number 6868:

1 ServerSocketserverSocket=newServerSocket(6868);
Notethattheseconstructorscanthrow IOExceptionifanI/Oerroroccurswhenopeningthesocket,soyouhaveto catch or re-
throw it.

Listenforaconnection:

OnceaServerSocketinstanceiscreated,callaccept()tostartlisteningforincomingclientrequests:

1 Socketsocket=serverSocket.accept();

Notethattheaccept()methodblocksthecurrentthreaduntilaconnectionismade.Andtheconnectionis represented by the


returned Socket object.

You might also like