0 ratings 0% found this document useful (0 votes) 97 views 91 pages OOPS With Java Quantum (2023-24)
The document is a comprehensive guide on Object Oriented Programming with Java, covering topics such as Java fundamentals, exception handling, Java new features, collections framework, and the Spring framework. It includes detailed explanations of concepts like classes, inheritance, multithreading, and the Java Virtual Machine. Additionally, it provides a structured approach to learning through question-answer formats and short questions for each unit.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save OOPS with Java Quantum (2023-24) For Later QUANTUM cseries
Object Oriented Programming with Java
® 7
Sestak
2023-208
“even Semh™
* Topic-wise coverage of entire syllabus 9 =* )
aap
in Question-Answer form.
* Short Questions (2 Marks)
& scanned with OKEN ScannerBCS 40: ct Oriented Programming with Java
UNIT-1 : INTRODUCTION (1-1 F to 1-50 F)
Introduction: Why Java, History of Java, JVM, JRE, Java
Environment, Java Source File Structure, and Compilation.
Fundamental.
Programming Structures in Java: Defining Classes in Java,
Constructors, Methods, Access Specifies, Static Members,
Final Members, Comments, Data types, Variables,
Operators, Control Flow, Arrays & String.
Object Oriented Programming: Class, Object, Inheritance
Super Class, Sub Class, Overriding, Overloading,
Encapsulation, Polymorphism, Abstraction, Interfaces,
and Abstract Class.
Packages: Defining Package, CLASSPATH Setting for
Packages, Making JAR Files for Library Packages, Import
and Static Import Naming Convention For Packages.
UNIT-2 : EXCEPTION HANDLING (2-1 F to 2-29 F)
Exception Handling: The Idea behind Exception,
Exceptions & Errors, Types of Exception, Control Flow in
Exceptions, JVM Reaction to Exceptions, Use of try, catch,
finally, throw, throws in Exception Handling, In-built and
User Defined Exceptions, Checked and Un-Checked
Exceptions.
Input/Output Basics: Byte Streams and Character Streams,
Reading and Writing File in Java.
Multithreading: Thread, Thread Life Cycle, Creating
Threads, Thread Priorities, Synchronizing Threads, Inter-
thread Communication.
& scanned with OKEN ScannerUNIT:3 ; JAVA NEW FEATURES (Gap
Functional Interfaces, Lambda Express, ett,
rences, Stream API, Default Methods, Sr Mthey
References, Stream API, Default V Stati
Base6 Encode and Decode, Forkach Meth, Try. he,
resources, Type Annotations, Repeating. Annotations
Module System, Diamond Syntax with Inner Ang.
Class, Local Variable Type Inference, Switch
Moy,
Yield Keyword, Text Blocks, Records, Seale,
Expres
d Clase”
UNIT-4 : JAVA COLLECTIONS FRAMEWORK
1 t 4.9
Collection in Java, Collection Framework inj,
Hierarchy of Collection Framework, leratorgiyg
Colleton interface List Interface ArrayList Lin
Vector, Stack, Queue Interface, Set Int
terface, Hashge,
LinkedHashSet, SortedSet Interface, TreeSet, Map
Interface, HashMap Class, LinkedHashMap Class
TreeMap Class, Hashtable Class, Sorting, Compatable
Interface, Comparator Interface, Properties Clas inj
UNIT-5 : SPRING FRAMEWORK & SPRING BOOT
(5-1 Fto5.t0F
Spring Framework: Spring Core Basics-Spring
Dependency Injection concepts, Spring Inversion of
Control, AOP, Bean Scopes- Singleton, Prototype,
Request, Session, Application, Web Socket, Auto witng,
Annotations, Life Cycle Call backs, Bean Configuration
styles.
Spring Boot: Spring Boot Build Systems, Spring Boot Code
Structure, Spring Boot Runners, Logger, BUILDING
RESTFUL WEB SERVICES, Rest Controller, Request
Mapping, Request Body, Path Variable, Request
Parameter, GET, POST, PUT, DELETE APIs, Build Web
Applications,
Sf
SHORT QUESTIONS (SQ-1 Ft so
& scanned with OKEN ScannerPart-1
Part-2 +
Part-3 :
Part-4 :
Part-5
Part-6 +
Part-7
Part-8 :
Part-9 +
Part-10 :
CONTENTS
Why Java, History of Jav
JVM, JRE, Java Environment
Java Source File
Structure and Compilation
Programming Structures in Java :
Defining Classes in Java,
Constructors, Methods
Access Specifiers, Static Members, .....
Final Members, Comments
Data types, Variables, Operators,
Control Flow, Arrays & String
Object Oriented Programminj
Class, Object
Inheritance, Superclass, Subclass
Overriding, Overloading
Encapsulation, Polymorphism
1-1F (CS/IT-Sem-4)
1-10F to 1-12F
.1-80F to 1-32F
.1-82F to 1-35F
..1-85F to 1-38F
Introduction
1-8F to 1-5F
1-5F to 1-10F
1-12F to 1-16F
1-16F to 1-24F
-24F to 1-29F
-29F to 1-30F
& scanned with OKEN Scanner1-2 F (CBT. Sem-A)
(Part-11 2 Abotrnction, Interface,
and Abutraet Chane
PartelZ + Packayon
Port-13 ¢ Import and Static Import,
Convention For Packages
Dofining Package, sooo
CLASSPATH Setting for,
Packages, Making JAR
Filew for Library Packages
dq
Untradetig
1-B8K to ToAap
J-ARF bo toagp
oAABE to 150%
& scanned with OKEN ScannerObject Oriented Programming with Java 1-9 F (CSIT-Sem-4)
| PART-1,
Why
Java, History of Java.
Que 1. | What is Java and why is it used ? What are some of the
key characteristics and features that distinguish Java from other
programming language ?
Answer
A Java:
1. Java is a versatile, high-level, object-oriented programming
language developed by Sun Microsystems.
2. Itisa general-purpose programming language made for developers
to “write once, run anywhere” Java codes.
3. Javacode can run on all platforms that support Java,
B. Why Javais used: Javais used in wide range of applications because :
1, Javahas rich API.
2. Javais platform independent.
3, Java has great collection of open source libraries,
4, Javais robust because it utilizes strong memory management.
C. Key characteristics and features that distinguish Java :
L Platform independence : Java programs are‘compiled into
bytecode, which is a platform-independent intermediate
representation.
2. Object-oriented : Java is a pure object-oriented programming
language, which promotes modular and reusable code through
classes and objects.
3. Robust and secure: Java has features like strong type checking,
automatie memory management, and built-in security mechanisms.
‘This makes Java applications less prone to programming errors
and security vulnerabilities.
4. Rich standard library : Java includes a comprehensive standard
library with classes and APIs.
5. Multithreading :Java provides built-in support for multithreading,
allowing developers to write concurrent and scalable applications,
6 Exception handling : Java has a robust exception-handling
mechanism that simplifies the management of errors and
unexpected situations in code.
& scanned with OKEN ScannerIntroduction
IAF (CSITSem-t)
GaeTE] Mow does:Java achieve platform independence and why,
is this a significant feature ?
amr |
1 pe cee plato indepen
Noche ME
Joes SM to exeateitcoe
sere apres come ti compiled int bytecode
PEER cs asated yee M, which platform spect
ee pentane JV wh understands
ogra nahin cle that on run om hat pee
oon
Seva platform independence
sSrantagess
Cre patarm comp
Reduced development ine nde
Snlied manera and pate,
Exhaned ear and portblt
QueiS. ] What is the historical background and origin of the
Java programming language ?
Answer
Following is « brief overview ofits development and origins
1. San Microsystems : The origin of Java‘ean be traced back to Sun
‘Microsystems, Sua recognized the need fora programming language
thst could provide platform independence and be used in a networked
dence through the use of Java Virtual
4
5
significant because of following
2 ake Tx promt ra cleOn was dy dames Going and
4 Reaaming to Java In 1965, Oak wat renamed to “Java” de
‘trademark issues. cident)
44 Ineduction of Applets: Jv apts were aay bringin
{ste early web early 1085) lt aawed decnyrstoereate mall
interception applet that old embeded eb page.
5 Java10:I0 1995 Jena LO war released anditincded
tera andieature or Geveopingapctng
& Sun's Open Approach Sun Microuytem ok an open approach to
doen, The approach helped
sen Th pra Java fain widepresd adoption and
ibuted toits “Write Once, Run Anywhere” capability, a
sve
Object Oriented Progamming wit
‘Acquisition by Oracle : In 2010, Oracle Corporation sequired Sun
Microsystems, including the rights to Java. Oracle has continued to
‘maintain and develop the Java platform since then
PART-2
AVM, JRE, Java Environment.
QueTA, | What is Java virtual machine (JVM) ? Deseribe its
architecture. What is ts primary role inthe execution of programs ?
“Answer
A. JVM: JVM is an abstract machine. Ibis a software-based, virtual
‘Computer that provides runtime environment in which java bytecode
‘can be executed.
B. Architecture Fig. 14.1 shows the internal architecture of VM.
Jove Cinna? ]
a Hono ar
onen sia
Farr
at || ay || sce || Sue fee
aren stack
Becution aatro
=>} method
= interface
Pipa
LM contains the flowin
1. Classloader :Classloader isa subsystem of JVM which is used to
load elas files. Whenever werun the ava program its loade first
by the classloader.
2 Class aren : Class area stores per-lass structures such as the
runtime constant pool, eld and method data.
© scanned with OKEN ScannerIntroduction
1-6F (CSITSem-t) —_—__——= Object Oriented! Progen
ing with Juve
nt for Java
executed,
: lek: 1¢ containsall the native methods used,
6 Native method stack a 8. Libraries and APIs:"The JDK inelues the Java Standard Library
the application i and APIs (Application Programming Interfaces for building various
|ypesof applications
Java Virtual Machine (JVM) : The JDK ineludes the JVM,
‘which is required for running Java applications
Execution engine :It contains
i. Avirtual processor
* Read bytecode stream then execute the
: & Compatibility : The JDK ensures compatiblity withthe Java
iii, Just-In-Time(JIT) compiler : It is used to improve the lang ‘and platform specifications,
2ECIesEes OT complies parts ofthe bytecode that have vag
rnin name tin adc rds Gaels | What ix Java Runtime Environment (JRE) and what i=
nun of time needed for compilation Beis ee
& Java Native Interface :JavaNative Interface (IND isa framework iene ee
2B peesaninteric communicate with another appliation Taswor
“written in another language like C, C++, Assembly ote. A. Java Runtime Environment (JRE):
©. Rote of V3: The primary ol ofthe Java Virtual Machine (JVMD in Lava Bur deces cage (ORE) is tho pet of asian
{he carton af programe isto ect aban intermediary boteen the ete
‘Spe Jove code and the host operating systems and hardware, ee ay ae eee
je15, | What isaJavaDevelopment Kit (JDK) ?Whydowemeed Seen Ee
by = us | 2. Iiva ely aval stare ditrbtin which Java Class
i ! Lira, speci tools, and a stand-aloneJV3L
Tawwer] 1B, Primary purpose of JRE:
A dava Development Ri (JDI0 1 Tho primary purpose RR stollon Jv raat aon
1 JDKisacrossplatformed software development environment that Raver ptpter or devi regasdingggs ie enderiying hardware
offers a collection of tools and libraries necessary for developing, ae
iam masteae sar pea aaa 2 Teprvides the envionment needed to interpret and exceute java
2 Itis a core package used in Java, along with the JVM and the JRE Ce
(va Rontine Environment) WwoTA | Mow docs IRE work with JVM?
GRE eel
‘The IRE and the JVM work closely together to enable the execution of Sava,
+ Development Tools applications, Here'show they interact and cooperate:
1. When you write «Java program, you have to saveit with java extension,
+ Library
VM | esses
2. After saving the program you compile your program. The output of the
DK ‘Java compiler is byte-code which is platform independent.
3. Aftor compiling, the compilor generates a .class file which has the
Fig 181, bytecode
© scanned with OKEN ScannerIntroductio
1-SF(CSTTSem-t) troduction
“The traecode is platform independent and runs on any device having
the JRE,
From here the work of JRE begins. Torun any Java program, y
IRE
The ow ofthe bytecode to run is as follows:
Fig. 171,
7. Thefollowing steps take place at runtime :
Step I : Class Loader : At this step, the class loader loads various
classes which are essential for running the program:
Step 2: Bytecode verifier : The code is allowed tobe interpreted only
‘hunt pase he eto verfer vik chek an
and checks for illegal code. ee
Step: Interpreter One hcl aed adh oe
Vere, thenntrpeter ede sembly cle linen sd es
‘the following two functions: - o
i. Execute the bytecode,
i Make appropriate calls to the underlying hardware.
In this way, the program runs in JRE.
QueTS. Differentiate between JDK, JRE and JVM.
‘Object Oriented Progeamming with Java
“Answer
B.No] Aspect WK RE, TM
1. | PullForm — [Java [Java Runtime [Java Virtual |
Development Kit [Environment [Machine
% [Purpose |Fordava |For running [Por executing
laplication (Java [ava bytecode.
ldevelopment, applications. |
including |
Jcompilation |
and debuexing. t
3. [Component [fava [Java Virtual |Jast-n-Time
Compiler Gavae) [Machine (VM | JIT) Compiler
4 |Platirm [No [yes Platform [Yes (Platform
Independence|(Platform-specif)|independent) independent) |
5 [Usedby [Yes INo INo
Developers?
6 [Used by Bnd [No [ve Iso,
Users?
7. | Needed for’ |Yes Ino INe
Compilation
‘Que 19. | What is Java development environment ? Give some of
its features. Also name
environments.
‘An
A. Java development environmer
1. A dava development environment, also known as Integrated
Development Environment (IDE), is asoftware suite that provides
tools and features to facilitate the development, testing, and
‘debugging of Java applications.
2. It isa comprehensive platform that helps Java developers create,
dit, build, and manage Java cade efficiently.
B, Features of Java development environment :
1. Code editor + A code editor is a central component of the
development environment, providing atext editor for writing and
‘editing Java sourcecode
yme of the popular Java development
© scanned with OKEN Scanner1-10 F CSTTSem4 Introduction
Compiler: Tee development environment integrates the Jy
2 Comper: Tr to comple dava sourcecode into bytecode,
Debugger A debugger allows developers to step through their
aoe alpeints impos variables, ane track program execution
geeniy and fx ivoes i the ode
44. Integrated build tools : Many development environments
tool for managing dependencies and building ava
c. Popuiar Java development environments : Examples of
environments include : ene
3 NetBeans. and
Oracle Developer
PARTS
Java Source Structure and Compilation,
(GeeLIG | What is Java source file? Explain the structure of Java
source file
‘newer
A dava source file:
1. Adevasource ile, also known a8 adava sure code file, contains
Regine teJea remramminghnsas. "
fsracture ofa Jevasource i
Tesrocurecfad file follows specificconventions and
B, Surcture of Jevasoure fe: 7
Sratre of Searels Flog aa they tre
Package declaration (Optional) Thi
This declaration species
shag ouch theclastn fl belong For example pockape
com example myapp; nm
2 Import struments (Optional: Aer the package delaration
cr tbe nein of le yon ean inde opin ert
Sits wen ous aces Boa ena
7 ‘exemple impor: java.util ArrayList; a sl
Class detartion Tain rial
The main by of Java source typilly
‘contains one or more class declarations. For example : °
Object Oriented Programming with Java 1-11 F(CSIT-Sem-t)
Object Oriented Pree sree
public clase MyClass
Clas members and methods go bere
1 isintended tobe an entry point
in method Options hcl
4 Mateo ate ‘method with the following
fora Java application, it contains 9 mai
signature
public stati oid main’ String args)
{Main program logic
1
|b. Fields and methods: Inside the clas declaration, youean define elie
caentbles) and methods (functions) Fields represent the data tbe class
thal, hile methods define the behavior and fanctionalty ofthe clase.
Forexample:
publieelass MyClass
private int myField// Feld
publie void myMethod0) {Method
‘Method logic here
1
1
‘Comments: Java source files commonly include comments to document
ole. Java eupports both single-line and malt-line comments
‘M'Thisisa singleline comment
y
This isa multiline comment
”
Que LAT, [Explain the steps involved in the compilation process of
Java source file.
Tome |
Following are the key steps in the compilation process of aJava source file
1. Writing Java source code : The frst step i to create or write Java
source code using atext editor.
2 Baiting and saving : After writing the source code, it's essential to
review and edit it for correctness and maintainability.
Compiling source code : Once the Java source code is ready, you
fompileit using the Java compiler (iavae)
4 Bytecode generation : The Java compiler generates bytecode
Instructions forthe JVM from the source code.
© scanned with OKEN Scanner1g (CSITSem-4) Introdetion
seco Verification + The JVM Batecd
Bescceerode ar cnetnve a ei
eo eeeeis ews clstner ods the come elses int
nny ats ae ned i 7
eae asst nesta sos are aed nt memory.
Execution oe re imeretethe ese comp ina
nein ee or encuin
ee
ramming Statues in Joe : Defining
Pe ove, Comtracar Methods
le verifier cheeks the
&
Que TAD | What do you understand by ‘object’ in Java?
‘Answer
1 InJava, an obec isa fundamental runtime entity that represents an
instance af a class.
2. Objects ares key contept in object-oriented programming (OOP),
13 Objects are central tothe principles of OOP, including éncapsulation,
{nhertance, and polymorphism.
4. They enable the modeling of real-world entities and the organization of
«ode into manageable and reusable components
In.Jave, jects are the building blocks of programs, anda well-designed
program izoftea composed of numerous interacting objects.
‘Que 115: ] What do you understand by ‘class'in Java?
oR
Define class in Java.
“newer
{tas ha Sant Sgat ooo Sr ont
objects. “
2 Sears a mel for dfn th atiuts (at) and behaviors
(catty da wi nib
2. Here are some key pits to undertnd about ae ind
Defnition:A clin Jv defined wingthe la eywor, we
‘by the class name, For example : St 7
obi caurMyCas
1 Css member ld and meth) phere
1-19 F(CST-Sem-4)
roucan declare attributes. These
dn abject ofthe class. Felds can
1. For example
fi, Attribntos Fields) : Within a cas
fare used to sore data ascociated wil
have differentdata types, such as integers, strings,
public clas Person (
String name; //Astrig attribute to store the name
int age; //Anintoger attribute to store the age
,
iti, Methods A class contains methods that define the behavior of objects
rented from that class, Methods are functions that emn perform actions
‘in manipulate the data stored inthe fields, Methods are defined within
‘the class and can take parameters and retura values. For example
publi class Calculator
publicint addfint a, int b)
returna +b;
1
iv. Access modifiers :Java provides access modifiers ike publisprivate’,
‘and protected’. Access modifies determine whether a class member is
‘ccessibe from other classes or not. For example:
publicelass MyClass
private int privateFeld Private feld
‘public void publicMethod®
‘MPvblic method
1
,
QueLis] Define constructor. What are various types of
constructor available in Java?
iGeaal
A. Constructor +
1. Aconstructoris a special method ina class that is automatically
‘alled when an object of that classi created.
2. Constructors are called when an object ofa clas is created,
8. ‘They are responsible for setting the initial state ofthe object.
4. Constructors have the same name as the elass and do not have a
return type.
© scanned with OKEN Scanner1-14 F(CSIT-Sem-t) Introductiog
B. Types of constructors in Java
1. Default constructor =
“tdefault constructor is automatically provided by Jas
Aixetlecenot define any constructors explicitly.
i its
fi Ttakes no arguments.
Itiniialize fields with defoult values (e.g, 0 for numeric types,
null for reference types).
Example:
pubiclse MSCs
Deteieontractrie provided by Java
:
2 Parameterized constructor
1 Ryan constr dfedithone or ore parantn
4 allows ooo prove inal ales when resting tect
S Peumetrnd conrersaruseflwhen 00 wants ps
Pine oranojectssitee daring eget creation.
Beample
pobidas Perton
ite Sg
tne
+ oe
‘ii PerssSting name, ina
tiles Sane
‘hs age = age;
,
1
3. Peat ematrnto: ta er is dsaed
is elared es private, then
Rovatairmtaitentmunucteietsaa™ tm
Private eveatructor
private MyClasstint value)
this.myValue = value;
1
public static MyClass ereatelnstancelint value)
return new MyClass(value); |
a ———
onjct Oriented Programming with Inve
ic int get My Value!
retarn myVal
1
’
Copy constructor +
abject by copying the
‘4
ce” Kcopy constroctor is sed ta ereate 8 2%
tisibates of an existing object
‘This constructor typically takes an o
parameter and initializes the new object
existing object.
Example:
publi lass Point (
private int x;
privateiat y:
11 Cops constructor
public Point(Point other) {
this.x = other:
thisy = others:
cio the sme ass 342
= ith the values of the
)
’
Gas dt | What is'method’ in Java ? How doyou define a method
in Java?
‘Answer
“A method is block of code which only runs when itis called.
‘Methods are used to perform certain actions, and they are also known,
as functions
44, Amothod must be declared within aclass. It is defined with the name of
the method, followed by parentheses 0.
Example Create a method inside Main:
‘public lass Main (
stati void myMethodi) [
Meode to be executed
1
)
Que 116: | Differentiate between constructors and methods in Java.
© scanned with OKEN Scanner~_ =
Introdbetig
17 F (CSAT-Sem-)
csrnsent) —
Object Oriented Programming with Java
a mie public’ are secessibe from any class
wublie: Members marked az"public’ are ace ya
ioe | i Pel package They have the widest visibility. For example. ifa class
ran et ean teal frm anyother eae
= |
Taitine obosts en
only accesibe within
er they are created.
rma re
Tle rome clr, ite ubclanee, and other castes within the mae
Cr fess aicanioe peo
rot race
Perform operations
provide behavior.
[Has the same name as|Can have any name,
the las. Tong as it follows Java'
| naming rules,
SS
7 Bevare Tape [Ne return type, not even
: access specifi ecified.
= 4 default (no: specifier) : Ifno access specifier fs =pes
J} ——____—___f the member has package-level visibility. This means it can be
7 Egisr [Constructors are aol ereosed only ty canes inthe same package.
Taheritance [therteliy mba Que LAG, | What are the different types of operators used in Java?
| Defsale A defaalt constroctor is] No default methods
Constructor |utomaticellyprovided by provided: they must
Metod [Java if no constructors| defined explicitly.
‘Answer
Following are the main types of operators used in Java:
SO ‘A. Arithmetic operators +
tte opera a Ua rondo per teil
PARTS aa nes ctngiogrs desta
‘numbers.
2. Arithmetic operators follow the usual rules of mathematics.
3." Whea using these operators, you should consider data types and
potential division by zero errors
“4. Also mixed-type operations may result in type sting or promotion,
Access Spevifiers, Static Members, Final Members, Comments.
‘Que 1.7, | What is an access specifier in Java ? List and explain
types of access specifier in Java.
‘depending on the operands involved.
“newer _] 5. Following are the common arithmetic operators used in Java.
AL Access specifier: Operator Meaning
1. In Javea, access specifiers (modifiers) are keywords used to control Si wen
‘the visibility and accessibility of classes, methods, variables, and - Subtraction
other members within a Java clas, . ‘Mulkiplicaton
2 They define the level of aces that other ase ouside the uret 1 Division
2 Sihmnetenstieden ania . Modulus, remainder after division
The acess specifiers help in encapsulation and provide a way remen
bide the internal implementation details oa class, s ened 7
4 They are important for maintaining the integrity and security of 7 Pe
satearen or nd 1B. Relational operators
B. Types of acess specifier: There are four main aces pein in 1. Relational operators in Java are used to compare two values and
determine the relationship between them.
© scanned with OKEN Scannerak Sean) Intreaetion
“Thea operators tum aotea toe rwear fale) Based on thy
monly sed in control struct
oops, to ake decisions or
3, Relational operators are com
as conditional statements and
conditions
44 Following are the relational operators used in Java
Operator Meaning
- qual to
Not oqual to
Less than,
Greater tha
< Les than or equal {0
> Greater than or equal to
C. Logical operators :
1. Logical operators inJava are us
boolean values
2 These operators allow you to combine or modify boolean values
sand make decisions based on the results.
5. Logical operators are frequently used in conditional statements
Srey, for) to control program flow and make decisions
to perform logical operations on
44. Following ae the logieal operators usedin Java
Operator Meaning
bE ‘Logical AND.
i Logical OR
1 ‘Logie NOT
D. Assignment operators :
| Assignment operators in Java are used to assign values to variables.
2 These operators combine the assignment of a value with an
arithmetic or bitwise operation.
8. They make it more consis and efficient to update the value of @
variable bared on ts eurrent value.
4. Following are some common assignment operators used in Ja
Operator Meaning
. Assignment
“ ‘Add and assign
Subtratand sign
Muliplyand assign
4. Oriented Programming with Java
fn Divide and sasign
Modale ad assign
be Bitwine AND and assign
I Bitwian OR and assign
Bitwioe XOR and sore
« Left shi ad aosign
bon ight bia assign
boos Unsignedight hit ard assign
Hitwise operators
1. Bitwine oporators in Java aro wed to perform operations 08
idualbtaofinger pertis te tog?
2. Thescoprators ret the values as soqueees of ary isis it)
and manipulate them the bit evel
{iwi operators are often needa lw level programming
4A Javaprovides the following bitwive operator
Operator Meaning
®
\
Conditional operator :
1. The conditional operator in Java, often referred to asthe “ternary
‘operator,”is a shorthand way of writing an ‘if-else’ statement ina
single line.
2. It provides a compact way to make a decision and assign values
bated on a condition.
‘The conditional eperator has the fllowing syntax:
condition ? expression}: expression?
4. ‘conditon'is a boolean expression that i evaluated first
5. Ifthe ‘ondition'is "true, expression’ is executed, and its vale is
returned.
alse’ ‘expression? is executed, andits value is
6. Ifthe ‘condition’
returned
© scanned with OKEN ScannerIny
dance om i Object Oriented Programing ith Java Lal F(CSMTSem)
so nts PT Ias rsterfie On ,
“anecof parte Hore are some of the commn unary operators in Java
instance ‘enother an obit Belong to
pee emanates eet Operator — Meaning
aloe ar Oeste, om ‘ inary pus ose tides a positive va
exw earns aoolean valve try’
pt ‘flee others nary minus, ued to negate a
2 Theta pe apecticd Ea alse’ otherwiga ; :
semester vy posal
si te ! Logie NOT aso uted for Boolean negation
rere, cost UATE : a
eels crite YOUNHRRL ir, Ge TAD,| What are static members in Java
Wiis instanceo —
1. Typecast operator! tanto ertico, 1. Variables and methods declared using keyword statienre called satic
Pindar the typecast OPT city covert ay tar
4 12. Whena memberis declared static, it an be acsasned before any objects
fom one data Pe f° “
This operation it known a5 Be cASENG OF Te conversion”
Sage casting canbe lpi in etations where you ned
Ofita clas are created, and without reference to any object
InJava, static members belong to theclass itself rather than to instances
ofthe class.
‘Tape Strront data types or need to perform arithmetic o,
‘operations involving mixed data types. Ce 4. Statie members are used for various purposes, such as maintaining
«¢_ espurofa typecast nas allows oF) Snes as msn
cage Type) va {9 Rarer ett zae mentor ae
re targeTypis the datatype to which you want fc variables (Class variables):
‘ae tonto wie eos 1 State yale are declared uring the eae’ Rapword within a
class.
Slit esprenon or variable youant gener, fo. niananrn et RE tren
1 String concatenation operator Tea fe ae eg linea
‘3. )Statie variables are typically used to stare dats that should be
‘onimon to all instances of the elas
4. Stati variables are accessed using the class name, followed by the
{dot (operator.
B, Static methods:
1 aaa thing contention peta denoted he's
‘is used to combine or join strings together a
2 Teante mda concatenate combine) two or more ti
vaaltyelicdboreeeseglestg a
2. Harte rng conan
emeataton operator wks
Suing rete srng see ate methods are cared sing the ‘tat keyword and canbe
a armas tthe taney 7 ahs matte os ntanee eo dae.
Heth pir i ed oobi te wo ating 2. They areoften used for utility methods that dont require acess to
A ava, aa acetate
Spertors: 4 move methde ernest sa etree ns on
members) directly because they do not have access to "this
‘They can only acceas other statie members.
Static methods are invoked using the class name, followed by the
dot ()operater.
1 nary
‘sary peratorsin Java are operators that perform operates
Tage Bra wich canbe avaiable or an express.
day ately sedi incrementing or deerementing si
values, ign of a number, and negating ‘boolean or bitvi#
2
© scanned with OKEN ScannerIntrod
segercemtsem)
FTA ie ah character a talon in Jog
ewer |
Static members ha
1. Theyarelond
we following characteristics :
ont memory me the ass ded and thr,
They ae ep ofeach static member Per class, regardless of hoy,
Sina instances of the class ar created
‘Thos ean be accessed even if no instances of the class have ben
created
3. They are often used for const
.
ot)
sso F (CAT Set
inheritance
vaheritance,asubelass derives from another subel
inheritance a,
“By which, in turn, extendsclass “A=
Introduetiog
Multilevel
Inter
Rinsing a chain of
_Adtacs"C" extends class
jeal inheritance:
4 Hierarchi
re jerarchical inheritance, multiple subclasses inherit from a single
superclass
Ths creates a branching structure where multiple classes sharg
common Features.
Geeiaa.| What is a superciass and subclass ?
Answer
Inobject-oriented programming and inheritance, the terms “superclass?
‘anicubelace” are sed to describe the relationship between two clases,
A. Superelass
1. Asuperclass, also known as a base class or parent class is a class
from which other classes (cubelastes) inherit properties and
bebaviors.
2 The superclass defines common attributes and mothods that are
shared by its cubelasses.
3, Trserves as template or blueprint for ereating derived classes,
4 Inaclasshierarehy, a superclass is typically higher inthe hierarchy
‘andis more general or abstract,
Subclass:
L.A subelass, also known as a derived class oF child clas, is class
that inherite properties and behaviors from a superclass.
2. Subclasses extend or specialize the functionality ofthe superclass
3. They ean add additional attributes, methods, or override inherited
methods to customize their behavior.
& Subel
asses are more specific and detailed compared to
superclass. rared to Oe
a
PARTS
Overriding, Overloading.
Que 1.34. ] What is method overriding in Java, and why is it used?
_-
Object Oriented Programming i
Tawer |
1. Method overriding in Java allows a subclass to pre
implementation ofa method that i already defined in its supercls
it redefines the method with the
the superclans method.
vide a specific
2, When a nubelaas overrides a method,
same name, return type, and parameters at
lows the subclass to customize the behavior of the inherited
ether overriding is used for following
Why method overriding is used
|. Customization :Itallows asubelass to provide itsoon implementation
fof method inherited from the superctass.
2 Polymorphism : Method overriding enables polymorpha
fllows objects of different classes to be treated ax objects of a common
superclass.
8, Extensibility : It allows for the extension of class behavior without
‘changing the existing code.
4. Consistency: Method overriding enstres that when a method is called
fon an object of a eubelasa, it behaves consistently with themethod's
tontraet defined in the superclass.
5. Specialization : Subclasses can specialize the behavior of fsherited
methods.
Que IAS. | Provide an éxample of method overriding in Java.
‘Answer
Following is an example of method overriding in Java:
class Animal (
public void makeSound0 (
System .out printla("Some generic sound”)
’
,
‘lass Dog extends Animal (
@Override
public void makeSound0){
System.out println "Bark";
’
,
1. Inthisexample, the Animal’ class has a method ‘makeSound’
© scanned with OKEN ScannerLotro
overrides this metagy
SSS Soeens send” demonstrating method overriding, "*€&
SS TRE] Deere method overloading and
Beswer |
peed evel sows yon fon mips cathe
sane name in class but with different parameter lists, the
Fae pescetr yin the mer of pecan hi yp
Wr you cll an evconded metod, the Goya obi de
Es ematical enon bad geen
‘arguments provided in the method call” “onal
fic cf eth vetoing in Jas Metedorradag flor
annie
1 Improved code readabileyiOverbdedmethodscan hav thane
mame ating tc co gee ae
Flesibiliy: Method veining provides Nesbit by ang
dete methods that cou teale ieren tes oftca ale hace
maine citing Scgetioee, “
3 Default values : Overloaded methods can provide default'values for
aie
4 Consistency #Waliow oats maintain consency inetd naming
tcmvenoay making cae or derapoes Gerad ae
foodie andes
& Polymorphiom : Method oGloding hed combined ith mtd
over contrite to th conageefpfncronaar stone
‘GeeTRT | Give an example of method overloading in Java.
aaa
Follovingisanexample of method overloading in Java:
bles Caleatr
obi aditftb
ara
:
pbc debl ad double, doable
—
role in Java,
Object Oriented Progeamming with Java 1-35 F (C/T-Sem-4)
’
Inth
2. One takes two int para
peramoters.
‘This allows the class to perform addition with both integer and float
point numbers.
example, the'Calculator’ classe two‘adl' methods.
ers, and the other takes two double
PART-10
Encepsulation, Polymorphism.
Que 1s: | Explain the concept of encapsulation in Java. Give its
advantages.
Answer
1. Encapsulation refersto the bundling of data and the methods that operate
on that data into single unit called aelass.
2 Bacapsulation helps to hide the internal implementation details of a
clas.
‘3, Ieprovides controlled accessto the data by using acceasedifers such
‘private ‘proteted’ and ‘public.
Advantages of encapsulation :
1L. Data security Encapeulation provides alevlef security by preventing
‘unauthorized access and modification of data.
2 Controlled access : It allows controlled accesso the data throuzh
well-defined methods.
Code flexibility :By encapsulating data and providing public methods,
youcan change the internal implementation ofa class without affecting
other parts of the program that use the class.
4. Simplified maintenance :Encapeulation makesit easier to debug and
‘maintain code.
5 Improved testing Encapsulation allows for easier unit testing.
6 Enhanced readability Code that uses encapsulated classes is often
more readable and understandable.
7. Reusability : Encapsulation promotes code reusability
QueTS9] Provide an example of a el
‘eneapsulation in Java.
demonstrating
© scanned with OKEN Scannerpevateint age:
pubic String getNamet)
pbc void setNamelString name) |
thiszname = name:
,
public int getge0 (
return age;
1
ppoblicwoidsetAgeint age)
(age >= 0.&& age <= 120) |
thisage= age
EER h ateteteel pd,
See
Heed canine
Jan mtesoel
Seon et print ent geome
Syren ryt hg isdntgttgeor
oie antag 10; Ostatnio ee”
'
1
‘This code demonstrates encapsulation epi ‘name’
Eels pets ta roving Coteaed oo a eae
pened
It enforces data validation rules for age and hides the internal
meee ato se fos
Quen
Define polymorphism and gi
NINN Tree eee ener eee EEE
jct Oriented Programming with Java 1-A7F (C8AT-Sem-)
Answer
A. Polymorphism +
1. Pelymorphism refers tothe ability different objects to respond 80
the same method callin away that is appropriate for their specific
types
2, In Java, polymorphism allows objects of different classes to be
treated at objects of common superclass.
1B. ‘Types of polymorphism in Java : There are two main types of |
polymorphisen in Java:
1. Compile-time polymorphism (static binding):
i. Also known as method overloading.
i Occurs when multiple methods have the same naze but different
‘parameter ists within the same cassor between a ube and its
superclass.
‘The Java compiler determines which method to call based on the
‘number and types of arguments passed during compile time
fv. ‘The decison on which method to execute is made at compile time,
and it's often referred to as early binding
vy. Exampl
class Caleulator |
int adatinta,int BU)
double add(double'a, double b) |.)
Y
2 Runtime Polymorphism (dynamic binding)
1. Also known as method overriding.
i -Osedre when a subclas provides a specific implementation for a
‘method that is already defined nits superclass.
‘The decision on which method to eallis made at runtime, based on
the actual type ofthe object.
fe. This allows diferent subclasses to customize the behavior ofthe
method, and i's often referred to as late binding.
v. Exampl
class Animal
void makeSound0 (.)
,
lass Dog extends Animal (
void makeSound0{..)
’
© scanned with OKEN ScannerIntroduction
1-38 F(CSATSem-t)
‘polymorphism ang
Object Oriented Programming with Java 1.29 F (CSAT-Sem-4)
Key axpeets of abstraction :
1, Abstract classes and interface
using abstract clases and interfaces
2 Hiding implementation details: Abstraction allows you
internal details of how an object works, expening only
se between compitestime
Que TAL | Ditferent
runtime polymorphism.
Taser |
Abstract
implemented
to ide the
piterenses parts to the outside world
cae : 4 Modeling real-world concepts : Abstraction enables you to modell
‘SNo]__Complletime, real-world concepts as objects in sour software
"Tas isnot resolved bythe compiler 4. Reusability and extensibility: Abstraction promotes code reusability
by defining common interfaces or abstract clacoes
5. Reducing complexity: Abstraction simplifies the development process
TL [This is resolved by the |
compiler
sale Known ag ne | Ta ale Kor 2 anit
2 [Riera Ror oveioadig. | binding overriding by breaking down complex systems into smaller, Sanagesbie
Int wach components.
| Th methodiame is samme witht]
The methed name is ae ieee :
|S [Rec gst perameters |sameparaneersandsameretan ‘GaeTAS. | How is abstraction implemented in Java using abstract
and return SF re classes and interfaces ?
Provide fast execution cine | Provides slow execution since the|
{he mnethod tobe executed ig | method to be executed isknownat|
ies
Peer ccurpliedime. runtime Abstraction implementation in Java using an abstract class :
& | ex fenibe sine all things | More flexible since all things abstract class Animal ”
| & \Gexietrcompletime. | execute st runtimes String name;
‘ ‘public Animal(Strig name)
ant ‘this.name =/name:
PART-11 1
‘Abstract method (no implementation)
ppablic abstract void makeSoundi);
y
“Abstraction, Interfacesjand Abstract Class.
‘Que 142:] What is abstraction in object-oriented programming?
‘lass Dog extends Animal {
ea public DogiString name) {
aoe ssuper(name) .
‘isco ste o he proses of sinplivng complex ptems by
ng them down at smaller, nore manageable part whieh
Aheunnecesary deta “ “
12s one ofthe fur main principles of object-oriented
le ofabject-orented programming,
along with encapalation, inheritance, and polpessphieee 4
3 Asracton allows you tofrut onthe essential characteristics and
Icha meeting the eran ra
1
‘Concrete implementation ofthe abstract method
Override
public void makeSound()
System.out println'name + "harks";
1
’
lass Cat extends Ania (
‘ublie CatString name) |
allows you to define com
deta ag ie mmo8 interfaces and hide implementation
Seis B-msing it easier to work with and reason about objects ia OUT
© scanned with OKEN Scanner1-40 F (CSAT-Sem-4) a
superinamel
,
‘Concrete implementat
Override
public void makeSound0 |
‘System.out.printnname +" mows"
1
ion ofthe abstract method
,
public lass Main (
public static vid main(String] ars) {
‘Animal dog = new Dog("Buddy")
Animal ext = new Cat("Tom");
{og:makeSoundl); / Output: Buddy barks
‘eat. makeSounel);// Output: Tom meows
1
1. In this example, the ‘Animal’ abstract class defines the ‘milkeSound?
abstract method.
2 Concrotesuelsses Dog and Cat provide their specffiplementons
for the ‘makeSound’ method. i
8. Thisallows for the abstraction of common animal Behaviors while allowing
‘orepecitic implementations in subelasses,
‘Que 144] Explain the concept of interfaces in Java.
‘Answer
1. Aninterfce is like a contract that defines a set of methods that a class
"ust implementift claims to implement that interface,
only contains method signatures without implementations.
{In Java, class can implement multiple interfaces.
‘Todeclare an interface, you use th
Bxample
interface Drawable {
‘void draw; / Method signature
’
‘Que 1.46, | Differentiate between abstract class and interface.
interface’ keyword,
|
!
ted Programming with Java
Tower |
1-41 F (CSAT-Sem-4)
Difference _
‘Absiieat hs P| Se Eee
“Abstract class can have | Interface can have only abstract
Aintrnet_and noneabsteaet | methods
tnothods. (eee |
Abstract caandoesntsupport [Interface supports multiple
fnultiple inheritance inheritance.
“Abstract clas ean have final, | Interface has only static and inal
Son-fnalstaieand nonstate | variables.
variables.
‘tract daascanbave atic [Interface can't have static
‘Rethods, main method and | methods,” main method or
fonstrciar. fonstructor.
‘Ainroctcasscanprovdetbe |Taterface can't provide the
{Implementation of interface. | implementation of abstract class
‘Tho abstract keywords used | The interface keyword Is used #0
fodeclareabstractlass. | delare interface.
Example: ‘Example:
public les Shape publietntertce Drawablet |
‘oid draws
Public abstract void draw0: |
, ,
1 J
a ee
quote]
1, Following an example ofa Java interface that defines a simple “Draveable”
interface witha single abstract method, “draw”
interface Drawable (
void drav()// Abstract method declaration
,
2 Inabove example, the“Dravable" interface has only one abstract method,
pea
Any class that implements this interface must provide a concrete
{implementation fr the “draw” method.
4. Let'scroate a claas that implements tl
lass Circe implements Drawable |
© scanned with OKEN ScannerIntroduction
privatetat
public Cree adv
thin radio = radios
‘eoverride
publi woid dra
System. pint
radius” + radius);
ey*Draveing a circle with rad i
score’ dacsimplementsthe*Drawable” interface
5 thier te Cr a thd
to provider ape
re ca dw sl
Ce ed aed nae
QueTaT] Describe an abstract class and its purpose.
Answer
AL Abstract class
1 In Seve, an abstract elate isa class that cannot be instantiated
directly bateervs ais bluepriat for other clases.
2 Ins used to define common methods and fields that should be
Suared emong ite eubclases, while allowing those subclasses to
provide specific implementations for some or all of the abstract
nethads
Abstract elisss are away to implement abstraction in Java, and
they play s central rle in creating a hierarchy of classes with
shane charscrisiee,
B, Purposes ofan abstract class:
1 Abstract methods: Abstrtclassos can include abstract methods
The purpose of abstract methods isto ensure that all subclasses
provide their pectic functionality
2 Partial implementation : Partial implementation helps avoid
redundant code and enforces
‘edundant code and enforces consistency across the hierarchy of
Inheritance : Sub
lasses of an abstract class inherit both the
foverete methods, This allows you to
Abstract classes enable polymorphism, which
ie se
ates dan
strat methods and the
reste hierarchical struct
4 Polymorphism :
means that you e
work with
ming with Save 1-44 F (C8ITT-Bem-4)
onject 0
Que TAR, | How inn abstract las different trom a regula
Fawwer |
No] Feature
| Abstract Clana Regular
Concrete) Class
Initantiation [Cannot be Can be instantiated
instantiated diretly | new.
srith new,
‘Abstract (Caneontain abstract| Contains only. evn
Methods |mothods thes,
Concrete | Cancontain eneree| Contains only concrete
Methods |methods. ethos
Unagein | Often used az Base| Geed as bath base clase
Hierarchy class in clase and leaf (final clases i
Method hierarchies.
Implementation] Contains methods| Contains methods»
with erwithout | concrete implementations
implementations
elas hierarchies
PART-12
Packages: Defining Package, CLASSPATH Setting for
Packages, Making JAR Files for Library Packages.
QueIA9. | What is a package ia Java ? Explain the process of
defining a package in a Java program.
a package is away to organize related classes interfaces,
and sub-packages.
1 provides amechanism for grouping related types together, making
iteasir to manage and maintain a large codebase
‘A package ia essentially a directory that contains a collection of
Javafiles
B. Defining a package : Here's the process of defining a package io
Java program:
© scanned with OKEN Scannercpoore m package name
choose a packns® rand unique name fOF YOUF Package,
pacha Tor eae YP
2 Package decaration
re top af em?
Adie pockace decarati
rhage com example APP:
= fremethe Java compiler about the package
Ba he clas or interface belongs
reture
| Onganize your directory st¥M
nie etrectory ireture that mirrors the package name,
example above (com.exampleaiyapP) You would create
recor erctare ike this
example
mee
4 Compile your cod
{Compile your Jere aourc les using the javaceofpiler.
When compiling, make sure sour eurrent working directory is
the cimetory that contains the root of your package structure,
‘ ion statement. Example
WeeTSr] Whar are the benefits of using packages ?
‘Answer
Follng ae sane ef the ey advantages using packages
1 Nameyyormanagement:Fakaes provide away create din
-peces for classes. This helps prevent naming conflicts between
4, tiers raze rane om dierent package
c onganization: Cue related toa specific functionality canbe
yep tether in a package, making it easier to locate and mansge
2 Modularity:
Modularity: Psckges promote modularity This makes the codebase
4 Access contr:
ipa Eee ort ace cena and visibility mies
a eile: pees prt
rec eve ee kei easier to reuse code across different
uly eases and use them in multiple
Eseowshies end intrusion
eae tin is of classes by using package-private acces
rer nang ca usage ate
Intro
tscally in reverse domain nae
My source file that belongs to the package,
ret Oriented Programming with avn 1-45 F (C8/T-Som-t)
oni
GueTAT | What tn the CLASSPATH in Java ? Describe the steps
involved in setting the CLASSPATH for Java pack
Tnawer
A. CLASSPATH:
1. The CLASSPATH in Java is a configuration that specifies where
tho JVM and compiler should look for classes and resources.
12 It’s crucial for enabling the JVM to locate and lond classes and
Iibraries when running Java applications
Proper CLASSPATH management is edzential for Java
development, ensuring that the necessary dependencies aro
‘available to your programs.
1B. Sotting the CLASSPATH: Following aé the stp involved in setting
the CLASSPATH for Java packages:
1. Determine dependencies: Identify the directories and JAR files
that contain the classes and resourees you need for your Java
packages.
Define the CLASSPATH : Determine how you want to set the
CLASSPATH. You have following options:
i. Environment variable # You can set the CLASSPATH as a2
‘environment variable in your operating system.
set CLASSPATH=C.\path\to\directory
si Command-line option : You can specify the CLASSPATH using
or “¢lasepath’ option when running the ava’ or avac’
3
java -p path to/directory L/path/ta/myLibrary jar YourMainClass
Manifest file Ifyou are working with JAR files, you can specity
‘the CLASSPATH in the manifest file of your JAR fle using the
‘Clase-Path’ attribute,
(Class-Path:libvmyLibrary jar
Order and delimiters : If you use multiple paths in the
CLASSPATH, separate them with the appropriate delimiter for
your operating system (semicolon ‘on Windows)
4. Verify the setting : Double-check that the CLASSPATH is set
correelly by running the ‘echo CLASSPATH’ (for Windows) to
display the current value.
5 Compile or run your
CLASSPATH, you can comp
"The JVM will use the CLASS
classes and resources.
Java program : After setting the
ile und run your Java program as usual.
SPATH to locate and load the required
© scanned with OKEN Scanner1-46 F (CSAT-Sem-4) Jotrodactig
GaeTHE]] What is the purpore of setting the CLASSPATH ? Wy,
tappens if you don't st the CLASSPATH correctly £0" Ur Packagyy
newer
1h purpose of setting the CLASSPATH : The purposes of se
CLASSPATH are as follows: a
{Locating classes nd resources.
andlng dependencies.
Supporting modular development.
“Avoiding clase name conics
Case oading and resolution.
Managing dependencies for thir. part bras.
1B. Consequences of not setting the CLASSPATH correctly:
L_ClassNotFoundException :If the CLASSPATH i not set correct,
SSeS nt be ble so Sind theelassosit needs to run sour ogra
{Ths willevat ine ClassNotFoundEsception.
2. NoClassDefFoundError : This eror occurs when th clas is found
Scouple tine but not st runtime Iusually happens wher you rena
roman that depend om brary that isnot nthe CLASS,
4 Resouroeloaing fpueef sour proaran depends erie
roperies Gls or XML, configurations, they wont be found
CLASSPATH is set incorrectly. aed pie
4. Library/and dependency problems: 1f sof using external ibrar
fr depecdencies, they need to be included in the CLASSPATH, Ifa
Peqavedllreryor dependent inchdd, team rel icompatin|
Gee TSS | How do you create JAR files for libraries in Java?
on
What do you understand by JAR (Java Archive) filesin Java? Explain
the seps involved in creating a JAR file.
Tarwer
JAR Java Archive) files: In Java, a JAR file is a compressed file format
Se stn Sa ln ned metadata oor
ee. JAG fen are onmennnly wood or ing Java
segs Be Ua fe iy ributing Jv Hbraves
Greating JAR files To crests 2 JAR fil fllow thee steps
1 Comite and pnerate lane len
Open your command prompt or terminal
err eee
i
i
1
Oriented Programming with Java 1-ATF (CSAT-Sem-4)
irectory containing your Java source files
files using the javac command. For example, if
famed MyLibrary java, you would run
Navigate tothe
Compile your Java
your main class
javae MyLibrary java
‘This will generate corresponding lass files.
Create a manifest file:
7 ts for specifying
rer yunifestleisno lays necessary but its wef fox
Amani point of your aplication fis an exeeutable JAR.
4 Createa text lenamed Manifst.xt and nciode ine ike this:
Main-Clase:com.example-MainClass :
i. Replace com example MainClass withthe fully qualified name of
Tense containing the main method. .
ste theJAR file: Use the ar command to create the JAR fle. You
3 Create ie ihe Manifest st fle if needed using the m option. For
sample
jar ein MyLibrary jar Manifest. txt class
4. Verify theJAR file:
1 You can verify the contents ofthe JAR file using the following
command: =
JjartfMyLibeary jar
This will list the files contained within the JAR.
| Test the JAR file: You can test your JARby running using the jav=
jar command. For example :
java jar MyLibrary jor
Que 154 | Whats the role of JAR files in Java?
“Answer e
Following are the key roles of JAR files in Jva.
1. Packaging classes and resources : JAR files allow you to package
‘multiple class files, resource files, and other assets into a single,
compressed archive.
2 Classpath management : JAR files are a standard way to manage
dependencies in Java.
3. Modularity : JAR files facilitate modularity in Java by organizing code
into reusable and manageable units.
4. Reduced filesize: JAR files are compressed, which reduces their size.
5. Socurity :JAR files support digital signatures and can include a manifest
file to specify security attributes,
© scanned with OKEN Scannerea_"—_—_—i—s—S=—
ntrodetion
148 F (CSTESemt)
JAR files re platorm-independeny,
romsplatform compatibitts 1 aplications.on various ope
ean without medication
jon control: JAR ies
pelude version information, allo
1
nin contol JAR eet verso bare oF apie
Import and State Import, Naming Convention For Packages, |
S—_—_—e—"——- es?
GucTEE] Explain the process ofimporting packages i Java, What
is the purpose ofthe import statement 2
‘Answer
1 Importing packages in J
interfaces fom other ped
2 The-import atement ie used to specify which classes or packages you
rant te eco in your cade. .
5. Here's how the proceso importing packages in Java works,
AL Import statement syntax
The import'satemen ie fllowed by the Fully qualified siame ofthe
ass or package Sou want to import. The syntax is as follows:
‘import package name ClassName;
4% You can wwe the “wildcard chardeer to iniport all classes and
{tevin from a specific package, making them available for use
{in your cde, For example
{mort packagename.*
'B. Importing single clases: To import a single class or interface, specif
= single class or interface, specly
‘he package name andthe class name separated by adot. For example
impor java util ArrayList;
©: Imprint packages
to grt aes nitro
package, you can use the "wildcard character. For example: ke
Sopot
D. Multiple import statements
cess
‘ sleet emits er Sera wre
tap page nce ar
They shoulda
ould appear t the top ofthe file, after the ‘packeg?
java fe the process of including classes and
ages in your Java source code.
3
rnted Programming with Java
declaration’ (if present) and before the clas declaeation
-ample.myay
package com
{import java.itil ArrayList;
{import java.util-HashMap,
{import com.example.otherpackage.*;
Purpose of the import statement :
‘The purpose ofthe import statement isto simplify and elarify your Java
code.
allows you to reference classes and interfaces from ather packages
‘using thet simple names, making your ende more readable and reducing
‘the need for fully qualified class names,
Iealso promotes code reusability by allowing you ts integrate external
‘lasses and libraries seamlessly into your projets.
‘GaSTEET] Beplatn the concept of talc nports in Java, What are
the benefits of static imports?
==
A. Static imports
1 Static imports in Java are a feature introduced in Java 6(J2SE 5.0)
that allows you to import and vse statie members (fields and
‘methods) ofa clase directly without having to prefix them withthe
classname.
2 thie feature simplifies code Feadabiiy and canbe particularly usfl
‘when working with classes that providetility methods or constants,
B. Benefits of static imports:
1. Improved code readability : State imports make the code more
‘Conse and easier to read by avoiding repetitive classname prefixes
fortatie members.
2 Convenient access It provides a convenient way to access utility
methods, constants, and other static members, which can lead €0
cleaner and more expressive code.
8, Enhancing maintainability : When working with Ubraries or
‘external APIs that expose many’statiemethods or constants, static
{Imports can simplify code maintenance and updates,
QueiS7] What is the difference between a regular import and a
statie import in Java ?
© scanned with OKEN Scannerfe
Soy enttsemd) letroductn
i
SS
TL [Punwe | Usedtoinpertcamesor| Used 10 import
tat
packages. members (fields. a!
methods) from a elasa,
import import stati
package ClassName;
~ Enables you to use the
class name without the| members without the daa]
package prefix
java import java.util. List
java” import
Java lang Math.”
‘Que BBS] What are naming conventions for Java packages?
Sinn cottons dare kage help maintain cSt a
nied argu oour depen ange eae
Sister trdewip wren ani te
stone cana te coronene
1" onerous Posage names ul pei cere ten
2 Uniqueness Fcings mer shuld ta eigen pein
ollnanagenticasihctne usetrns
2 Reverse damn name: Ung arcu me a he poe
fou yc namer bps ones rl eee
«elem
Wo sng wor Ba Jr yrds pcg ae
(e.., package int is not allowed). —o eel
ive names Kee package mumes sort at
sestpveForenmpi tape are re
‘noon tteacamdbeca ae
& Aes undercorer: Avoid ningun ia pchage aes
7. No special characters : Package names should not contain special
Skiers once
wold acronyma void sing acronyms unless they ae widely seeped
* newer ate
rig hen sang covets reve pane eheah ee
cwdeate crane maintainable seal unetendie
00
UNIT
Exception Handling
CONTENTS ~
[1 + Exception Honing : The Ide
Perel" jehiad Exception, Exception
Errors, Types of Exception
Gontrol Flow in Exceptions, JVM.
Reaction to Exceptions
‘Use of Try, Catch, Finally, Throw,
‘Throws ia Exception Handling
InBuilt and User Defined
xeeptions, Checked and
Unchecked Exception:
InpalOatpat Basics : Br
‘Seema, and Character Streams
_2IF to 218F
‘Reading and Writing File in Javan. 2-18F to 2-19F
‘Multithreading : Thread, Throod .....2-19F to 2-22
Life Cycle, Creating Threads
‘Thread Priorities, Synchronizing .....2-22F to 2-297
2-1 F (CSMT-Sem-4)
© scanned with OKEN ScannerYr
—_ = itn
PARTI
enti Honing : The Idea Behind Beep, Sage
ond Bore Typex of Eeception,
—————E—E—E—E—
QeeET. | What do you mean by exception in Java ? What isthe
fundamental idea behind exception handling in Jaya ? How docs
Java handle exceptions ?
Taswer |
A. Exception in Jawa:
Exception Handing
et Oriented Programming with Java 24K (CSNT-Sem-4)
11 Code that always exe
‘exception occurred
(08, regardless of whether an
1
GEERT] What do you mean hy errors in Java?
Tawer |
In dava, errors represent srious, unrecoverable problems that occur
dhving the execition ofa progr
Unlike exceptions, which can bo caught and handled programmatically,
errors generally are beyond the control ofthe application.
‘usually requires intervention at ahigher love, such asthe JVM or the
1, InJava, an exception is an event that disrupts the normal fow of
program execution,
2 Itreprecents an unexpected eandition or error that occurs during
‘3. Exceptions can arise due to Yarious reasons, such as invalid user
‘input, fle not found, or programming errors.
B, Fundamental idea behind exception handling :
1. Thefundamental dea behind exception handling i Java isto provide
‘2 mechanism for dealing with runtime errors ina structured and
‘eracefal manner.
2 Exception handling allows you to anticipate and haridle exceptional
situations that may arise during program exec
operating system,
Errorsin Java are instances of classes that extend the javalang. Error’
lass.
‘Some common errors include:
i. OutOfMemoryError : This error oceurs when the Java Virtual
‘Machine (JVM) runs out of memory and is unable to allocate more
‘memory tothe application
fi. StackOverflowEeror! This errr occurs when the execution stack
grows beyond its maximum size
i, VirtualMachineError : This isthe superclass ofallerrors thrown
by the JVM
iv. LinkageError: This error occurs when there isa problem with
the classloading mechanism,
‘AssertionError : This error occurs when an assertion made by
the ‘assort’statement fails.
Ae Que 23. | Explain the difference between exceptions and errors in
Java handles exceptions through a combination of try, eateh, an lava. f
senses sh try, eateh, and. as
2 Statements that you want to monitor for exceptions are contained (Aneweel 7
‘within a try block. Ifan exception occurs within the try bloc, itis Enon
thrown, SiNe: [Aspect Exceptions
3
‘Your code ean catch this exception using catch and handle it
‘4. Anycode that absolutely must be exeeuted before a method returns
Parent class |javalang.Exception. | java.lang Error.
[Nature of _|Usually recoverable | Severe, often
{s putin finaly block. loceurrence |and handled, unrecoverable,
5 Following ss basic structure of exception handling in Java: [Cause | Generally caused by | Typically caused by
tt the application logicor | external factors such as
7 ‘Code that might throw an exception environment. the JVM or hardware.
J eatch (Exception ype e) ( [Handling [Can be caught and | Usvally not caught or
‘Handle the exception handled using ty-catch | handled,
1 finaly | blocks.
5. [Example [FieNotFoundBsception. | OutOfMemoryBrror
© scanned with OKEN Scanner2-4 F(CSTT-Sem-4) Excepti
GaET] vin or the teres p68 of eeD ton a
Provide examples for each type. “a
new]
eae explana coegried no tro mala type ches
eecked exceptions,
A Checked exceptions:
1” Checked xcepins areeption that are ches yt
Sonpleine, 1 the com
The compiler ensures that thes excep fe etc
redo tetzora br the mend wing the Wer
RIvukckebtet semi ade 0taeag
4 Thee cxrptins ually represent onions thata wel ek
application should anticipate and recover from, | ml
5. Example
import java.io FilelapetStream “
{import java io BléNotF oundException;
public class Main
Publi static wid main(String!) args)
wy!
‘Waszenipt to open a file 4
FilelnputStream file «new FleInputStream(“fle.txt”);
| ate (FileNotFoundException e) |
‘Handle the exception
Syetemout printin(File not found:" +e. getMessage();
1
"excepting
risen Te
,
bo
B. Unchecked exceptions:
L Sao
a
checked by the compiler at compile-time,
2 Instead, they occur at runti
Programming errors
9% Exampesofmchecedecptins ice Walid
‘ArandexO uO icundsBecpa ea
1¢ and are typically caused by
vith Java
2-5 ¥ (CHIT Sem-4)
5. Example
publicctass Main |
public static void main(String args) |
nt arr = (1, 2,31;
ty!
Attempt to access an index out of bounds
int value = are;
J atch (ArraylndexOutOfBoundsException’6 |
Handle the exception
System.out.printin(“Array indéx out of bounds: * +
egetMessagel);
'
= PART-2
Control Flow in Exceptions, JVM Reaction to Exceptions.
‘Que25. | Describe the control flow in exception handling when
an exception occurs. y
: on
How does Java manage control flow when an exception occurs?
Answer |
‘When an exception occurs in Java, the eoutrol low changes to handle the
exception. Here's a step-by-step description ofthe control flow in exception
‘handling’
1. Exception occurs : An exceptional condition occurs due to various
‘reasons suchas invalid input, arithmeticerrors, file VO errors, or other
unexpected conditions.
2 Exception thrown : The code that detects the exceptional condition
creates an object representing the exception and throvts it using the
‘throw statement,
'& Search for matching catch blocks : The Java runtime searches for
‘a matching catch block to handle the thrown exception.
4 Control transfers to matching eatch block : If « matching catch
block is found, the control flow transfers to the corresponding eatch
block, skipping the remaining code in the try block.
5. Exception handling : The code inside the matching catch block is
‘executed to handle the exception,
© scanned with OKEN ScannerS-8F(CSIT-Sem-)
& Program continues exec
contro flow continues from the end of the eatch block,
Gee] How does the JVM rent to exceptions dating progry
execution
oR
Describe how the JVM reacts to an unhandled exception iy
program. ‘
Virtual Machine (JVM) encounters an uihandl 6d excep
follows these steps a
1. Exception propagation : The exceptionis propagated up through the
callstack It look fora catch block that matches the type ofthe exases
2 Stack unwinding : If a matching Watch Blick is found, the aq
“unwinds” the call stack. This means it starts popping of thecal stack
‘frames until t finds a matching eateh block.
3 Exception handling : Once a'matching catch block is found, the
‘exception is caught, and the code inside the eateh block is executed Itsy
‘matching eatch block is found, che program terminates, nd an emer
message is displayed. -
4 Finally block (Optional): I'ther's a finally block asociatd withthe
try-catch structure it wil be executed after the eatch loc, Fegardass
of whether an exception was thrown or not.
& Exiting the program (Optional): After ll relevant atch and finally
blocks are executed, the program continues its execution. Ifno stele
catch bloc is found, the JVM may terminate the program.
PARTS ig
Use of Try, Catch, Finally, Throw, Throws in Exception Handling.
Que27. | Explain the purpose and usage of the try, eateh, and
finally blocks in exception handling.
“Answer
Following is an explanation ofeach block and its purpose :
A try block:
1, ‘The try block encloses the code that might throw an exception.
2 Tis used to define a block of code where excoptions might oeeut-
3. Theeyntaxis
try!
2-7 F (CSNT-Sem-A)
sed Programming with Java
“7 Coals that might throw an exception
1
‘the try block must be followed by either a eatch block, a finally
tock oF bot
1p, enteh block:
tae Mie catch block follows try block and specifies the type of exception
jean handle.
2, In wed to catch and handle exceptions that occur withie the
‘associated try block.
‘4, fan exception occurs inthe try block, Java arches for’ matching
catch block.
4. Thesyntax
cateh (Exception Type e) |
‘1/Handle the exception
,
15. Multiple catch blocks ead follow asingle try block tohandle different,
types of exceptions.
©. finally block:
1. The finally bloc follows & try block and contains code that always
Cxocutes, regardless of whether an exception oceurred or not.
2, Tis used for releasing resources, performing cleanup operations,
‘or finalizing tasks. .
4 The finally block executes even ifan exceptionis thrown and caught,
allowing for essential cleanup actions.
1/ Code that always executes, regardless of whether an
‘exception occurred
’
5, The finally block is optional, but if used, it must follow the last cate
block (ifany).
‘Que2ZS_ | What is the role of the throw keyword in exception
handling ? Provide an example.
‘Answer
1 In Java, the throw keyword is used to explicitly throw an exception
within a method.
2 Itallowa developers to create and throw their own exceptions or to re-
throw exeeptions that were caught earlier.
© scanned with OKEN ScannerException
throw throwabloOect:
& Baample
pois ease ThrowEcample {
publc static woid main(String ang) (
yt
Call a method that throws an exéeption
AivideByZer00;
J catch (ArithmoticExeeption e){
W Handle the exception,
System.cut printlaCException eaught:"
+ eget Message)
public staticvold divideByZero0 { Me >
int dividend = 10; , N
intdivisor=0, a
if(divisor== 0)
‘Maivisoris0, throw an AvithmeticBxception
‘throw stew ArithmeticException(*Cannot divide by ero"
Helse (
1 Otherwise, perfarm the division
int result = dividend/ divisor;
‘System out printin(“Resilt of division: "+ result);
,
’
‘Que29. | How does the throws keyword contribute to exception
handling in Java?
“Answer
1. In Java, the throws keyword is used to indicate that the method may
‘throw certain types of exceptions during its execution,
‘Que 240. | What are inbuilt exceptions ?
zal
with Jove 2.9 F (CSATSem-4)
is part of the method signature and provides information to the ealler
bout the types af exceptions that the method might chess,
{in informing the aller abort
he potential exceptions that
ore’ how the throws keyword contributes to exception handling in
nwa.
i, Informing callers : It informs the caller about the potent
ceptions that might occur during the method's eaneuton, That
allows tho caller to be aware of the exceptions thas nea t bo
handle.
i, Propagation of exceptions : If « méthod enéelinters aa
‘exceptional condition that it eannot handle itself ie can chosen to
propagate the exception. This allows the exception tobe propmeatod
further up the call stack,
fii, Compile-time checking :The throws keyword enables compile-
time checking of exception handling. This helps in ensuring shat
cexcoptions are handled appropriately at compile time.
PART-4
In-Built and User Defined Exceptions, Checked and
Unchecked Exceptions.
ve an example.
Tava inti acptions rf the bps that are provided by
thodnvastandard itary
Those exceptions are predeRd and are walle Or use in Jaen
os
3. _Inbuilt exceptions are typically organized inte a hierarchy of exception,
classes, with the base elass being Java lang Exception’
4. Examples ofinbuilt exceptions include:
i. NallPointerException : This exception thrown when aprogram
attempts to nocess or manipulate an object reference that bas a aull
value.
String str = null;
‘System_out.prntin(str lengthi) Throws NullPointerException
ii, AvithmeticException : This exception is thrown when an
‘arithmetic operation suchas division by zero occurs,
int result = 10/0 /‘Throws ArithmeticException
‘QueRAT,] What are user-defined exceptions ?
© scanned with OKEN Scanner