0% found this document useful (0 votes)
175 views21 pages

Opps Unit 1 Oops Unit 1 Notes

The document provides an overview of Object Oriented Programming (OOP) concepts, including objects, classes, abstraction, encapsulation, inheritance, and polymorphism. It explains key principles of OOP, such as how objects are instances of classes and how encapsulation helps protect data. Additionally, it discusses the importance of these concepts in creating modular and maintainable software systems.

Uploaded by

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

Opps Unit 1 Oops Unit 1 Notes

The document provides an overview of Object Oriented Programming (OOP) concepts, including objects, classes, abstraction, encapsulation, inheritance, and polymorphism. It explains key principles of OOP, such as how objects are instances of classes and how encapsulation helps protect data. Additionally, it discusses the importance of these concepts in creating modular and maintainable software systems.

Uploaded by

nayanshi mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

lOMoARcPSD|16655472

OPPS UNIT 1 - oops unit 1 notes

Master of computer application (Dr. A.P.J. Abdul Kalam Technical University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by nayanshi mishra ([email protected])
lOMoARcPSD|16655472

1-2 B (MCA-Sem-2) Introduction

PART· 1

Object Oriented Programming: Objects, Classes, Abstraction,

1
UNIT
Introdu ction
Encapsulation, Inheritance, Polymorphism.

Questions-Ans wers

Long Answer Type and Medium Answer Type Questions

Que 1.1. What do you understand by Object Oriented


Programming ?
CONTENTS Answer
1. Object Oriented Programming (OOP) is a programming paradigm that
Part-1 Object Oriented Programming: ..... .... .. l-2B to 1-l0B is based on the concept of objects.
Objects, Classes, Abstraction, 2. hi. OOP, objects are instances of classes, which are templates that define
Encapsulation, Inheritance, the properties and behavior of objects.
Polymorphism. 3. The key principles of OOP are enc apsulation, inheritance, and
polymorphism.
OOP in J ava , Characteristics ............. 1-lOB to l-l 7B
Part-2
of Java, The Java Environment, 4. '
OOP is often used to create complex, modular software systems that are
easier to maintain and extend. /
Java Source File Structure and
Compilation. 5. By breaking down a system into smaller, more manageable objects.
OOP allows developers to focus on individual components and their
Part-3 Fundamental Programming .......... .. ... 1-178 to 1-34B interactions, rather than the system as a whole.
Structures in Java: Defining classes 6. OOP is widely used in programming languages such as Java, C++,
in J ava, Constructors, Methods, Python, etc.
Access Specifiers, Static Members,
Comments, Data Types, Variables,
Operators, Control Flow, Arrays
Que 1.2. IExplain the concept of objects in OOP.
Answer /
1. Object means a real word entity such as pen, chair, table etc. Any entity
that has state and behavior is known as an object.
2. In Object Oriented Programming (OOP), an object is an instance of a
class.
3. A class is a blueprint or template that defines the properties and behavior
of objects.
4. When a class is instantiated, it creates an object with its own set of
properties and methods.
5. Objects have two main characteristics: state and behavior.

1-1 B (MCA-Sem-2)

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

Object Oriented Programming

6. . of
State refers to the properties
arrays, and other data structures.
1-3 B (MCA-Sem-2)

an ob.~ect , which can include variables,


.
7. Behavior refers to the methods or functions of an object, which define
what an object can do or how it can be interacted with.
1-4 B (MCA-Sem-2)

4.

5.
Introduction

An interface defines a set of methods that a class must implement, but


does not provide any implementation details.
An abstract class is similar to an interface, but can also provide some
7
implementation details.
8. Objects in OOP allow us t o model real-world entities and systems in a
modular, organized way. 6. Abstraction allows us to define the behavior of objects without specifying
how they achieve that behavior.
9. By breaking down a system into smaller, more manageable objects, we
can focus on individual components and their interactions, rather than 7. For example, let's say we have a "Vehicle" interface with a "drive" method.
the system as a whole. We can create classes such as "Car", "Truck", and "Motorcycle" that
implement the "Vehicle" interface and provide their own implementations
10. This makes it easier to write and maintain code, and a.1.-;o makes it easier
of the "drive" method. The user of these classes doesn't need to know
to scale and extend a software system over time. the specific implementation details of each class, as long as they know
Que l.S. IWrite a short note on classes in OOP.
8.
how to use the "drive" method.
Abstraction also allows us to change the implet¥Dtation of a system
Answer I 9.
without affecting the users of that system.
For example, if we were to change the way the "drive" method works in
1. In Object Oriented Programming (OOP), a class is a blueprint or template
our "Vehicle" interface, we could update the implementation in each of
for creating objects.
our implementing classes without affectiilg &IlJ'Code that uses those
2. A class defines the properties and behavior of objects, but dues not classes. ~
actually create any objects itself. Instead, objects are instant iat ed from
classes. Que 1.5. IWhat do you understand by encapsulation in OOP ?
3. A class can have data members (also called fields or properties) that OR
store the state of the ~bject, as well as member functions (also called Discuss the concept of encapsulation with suitable example.
methods) t hat define the behavior of the object .
4. The data members and member functions ar e encapsulated within the Answer
class , meaning they are only accessible within the dass unless specified 1. Encapsulation r efers to the practice of bundling data and- ~havior
otherwise. together and controlling access to them through a well-defined interface.
5. Classes in OOP allow us to model real-world entities and systems in a 2. Encapsulation allows us to hide implementation details and protect the
modular, organized way. data and behavior of an object from outside interference or misuse.
6. By breaking down a system into smaller, more manageable classes, we 3. In OOP, encapsulation is achieved through the~ of classes and access
can focus on individual components and their interactions, rather than modifiers . fl' ·
the system as a whole. ' 4. Classes define t he data and behavioroC an object, and access modifiers
7. This makes it easier to write and maintain code, and also makes it easier control the visibility of those members outside of the class.
t o scale and extend a software system over time . 5. For example, let's say we have a "Persqn" class with private data members
Que 1.4. IWhat do you understand by abstraction in OOP ?
such as "name" and "age", as well..!'8 public member functions such as
"getName" and "getAge".
Answer 6. By making the data members private and the member VJilCtions public,
we can control how users of the class interact with its data.
1. Abstraction refers to the practice of hiding implementation details while
showing only the necessary information to the user. 7. Users can only access the data through the public member functions,
which ensures that the data is protected from accidental modification or
2. Abstraction provides a way to manage complexity by breaking down a misuse.
system into smaller, more manageable parts.
8. Encapsulation also allows us to change the implementation of a system
3. In OOP, abstraction is achieved through the use of interfaces and abstract without affecting the users of that system.
classes.

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

1-5 B (MCA-Sem-2) 1-6 B (MCA-Sem-2) Introduction


Object Oriented Programming
. han e the data members or member 6. By hiding an object's internal details, OOP provides a level of abstraction
9. For example, 1f we were to c g uld d te the implementation in that allows the object to be used without the user needing to know the
functions ofour "Person" class, we co up a
the class without affecting any code th at uses th e c1ass. details of how the object works internally.
7. This improves the maintainability and flexibility of the code, as changes
Que 1.6. IHow does the object-oriented concept o~me~sage dp'.38si~g to the object's internal implementation do not affect the interface that is
help to encapsulate the implementation of an obJect, mclu mg its used by the rest of the program.
data? 8. Information hiding also helps to prevent errors and improve the
reliability of the code, as it reduces the chances of accidental or intentional
Answer I ' . modification of an object's data or behavior from outside the object.
1. The object-oriented concept of message passing helps to ~~capsulate
the implementation of an object, including its ~ata, by p~oVl~mg a well-
defined interface for accessing and manipulatmg the obJect s data.
Que 1.8. ICompare abstraction and encapsalation.
2. In OOP, an object's data is typically declared as private: which m~ans Answer
that it cannot be accessed or modified directly from outside the obJect.
3. Instead, other objects must send messages to the object to request S.No. Abstraction Enc:apswation
information or to perform an action. 1. Abstraction is the process Encapsulation is the process or
4. When an object receives a message, it determines how to respond based or method of gaining the method to contain the information.
on its internal state and the parameters of the message. information.
5. The object may perform an action, such ' as modifying its internal data, or 2. In abstraction, problems are In encapsulation, problems are
it may return information to the sender of the message. solved at the design .or solved at the implementation level.
6. By controlling access to an object's data through message passing, OOP interface level.
~ncapsulates the implementation of the object and provides a level of
3. Abstraction is the method Encapsulation is a method to hide
abstraction to the user of the object.
of hiding the unwanted the data in a single entity or unit
7. Message passing also allows objects to be decoupled from each other, information. along with a metliod to !)JOtect
which makes the system more modular and easier to maintaln.
" information fromoutside.
8. Changes to the implementation of one object do not necessarily affect
the implementation of other objects, as long as the message passing
4. We c.an im plement Encapsulation is impfemented using
interface remains the same. abstraction using abstract by acces• modifier i.e. private ,
class and interfaces. protected and public.
Que 1.7. IWrite short note on information hiding. 6. The objects that help t o Objects that result in encapsulation
perioJ'!Il abstraction are need notJe abstracted.
Answer encapsulated.
1. Information hiding is a fundamental principle of OOP that is closely -
related to encapsulation.
2. Information hiding refers to the practice of hiding the internal details of
Que 1.9. IWbai do you understand by inheriiaaee in OOP?
an object ftom the outside world, so that the object's data and behavior
cannot be accessed or modified directly. Answer
3. In ~OP, information hiding is achieved through the use of access 1. Inheritance allows us to create new classes from existing classes,
modifiers such as pnvate, protected, and public. inheriting their data and behavior.
4. 2. Inheritance provides a way to reuse code and create classes that are
~:O!e~~:~~ :::jc::i~ata as private, it cannot be accessed or modified
related to each other in a hierarchical structure.
5. Similarly, by declaring an obje t' 8 h d . 3. In OOP, inheritance is achieved through the use of parent and child
called from outside the object. c met O 8 as private, they cannot be classes.

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

. 1-7 B (MCA·Sein. 2
Object Oriented Progranuning --J 1-8 B (MCA-Sem-2) Introductfo~
derived class, inherits properties a d
4. A child class, also known! as aalso known as a base class or superclan When we write code that works with objects of the "Shape" interface,
behavior from its parent c ass, . . ss. we can call the "draw" method on any object that implements the
d 1•ts own properties and behavior, or overrid interface, regardless of its specific type.
5 The child class canthen a d e
. rt· d behavior of its parent c1ass . 10. Polymorphism allows us to write code that can work with objects of
~~pe~an • . .
, ve have a "Vehicle class with properties such •• different types, without knowing their specific type at compile time.
6 ForexampI e, Ie t ssay, h · h "dri ve ■ and
""
· d •
"make", "mo e1 , an
d "year" as well as be av10r sue as
, 11. This makes the code more flexible, generic, and reusable, and allows us
to write more efficient and maintainable code.
"stop". \
7
_ We can then create child classes such as "Car", "Truck", and "Motorcycle•
that inherit these properties and behavior from ~he "Vehicle" class, but
I
Que 1.11. Is the concept of polymorphism only applicable to object-
also add their own specific properties and behavior. oriented systems ? Explain.
8. Inheritance allows us to reuse code and avoid duplicating code in multiple Answer
classes. 1. Polymorphism is a concept that refers to the ~eloi?jects to take on
It also allows us to create classes that are related to each other in a different forms or behaviors. '),,
9.
hierarchical structure, making the code more organized and easier to 2. It allows different objects to respond to the same meaage or method call
maintain. " . in different ways. ,
3. While polymorphism is most co=only associatl!d with object--0riented
Que 1.10. , What do you mean by polymorphism ? Explain it with
programming languages such as J•Pyfcfioii. and C++, w concept
an example. itself is not limited to these languages ~to:object--0riented systems.
4. Polymorphism can be achieved in. oilier programming paradigms as
Answer
well, such as functional programming or procedural programming.
L Polymorphism refers to the ability of objects to take on different forms
or exhibit different behaviors in different contexts. -,' 5. For example, in functional pl'ogramming, higher--0rder functions can be
use d to achieve polymorphism by allowing functions to-fake other
2. Polymorphism allows us to write code that can work with objects of functions as arlr1J'.llents and return functions as results. ..,
multiple types, without knowing their specific type at compile(time.
6. Therefore, while polymorphism is commomy associated with object-
3. In OOP, polymorphism is achieved through the u se of inheritance and oriented systems, it is not limited to them, and can be adrieved in other
interfaces. programming paradigms as well.
4. When a subclass inherits from a superclass, it can override the methods
of the superclass with its own implementation. Que 1.12.1 Discuss the three OOP principles.in detail.
5. This allows objects of the subclass to behave differently from objects of Answer
the superclass when the same method is called.
The three main OOP prin~' are:
6. Interfaces provide another way to achieve polymorphism.
I. Encapsulation: Refer Q. l .5~P ~ l-4B, Unit-1.
7. An interface ~efines_a set of methods that a class must implement, but 2. Inheritance: Refer Q. 1.9, Page"1-6B, Unit-1.
doe_s not proVIde any 1IDplementation details. This allows multiple classes
· e their own spec1'fi1c
· t erf ace, but provid 3. Polymorphism: Refer Q. 1.10, Page l-7B, Unit-1.
. implement
to . the same m
imp1ementat10n details.
Que i.1s.1 Differentiate between structured approach and object
8.
:::: : : l e i ' considehr a "Shape" interface with a "draw" method. We
c asses sue as "Circle" d "Re h oriented approach.
"Shape" interface and . . an ctangle" that implement t ~
method. th
provide eir own implementations of the "draw

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

1-9 B (MCA-Sem-2)
Object Oriented Programming
1-lOB (MCA-Sem-2)
Introduction
An ■wer

S. No. Structured approach Object oriented approach Answer


1. It works with Top-down It work s with Bottom -up S. No. Procedural Oriented Objeet-Oriented
I
I 2.
approach. approach.
Program is divided into number Program is organized by having
Programming I Prosnunmin1
1. In proced~ral . progr a mming _! In object-oriented programming,
I of sub-modules or function s. number of classes and obj ects.
program 1s d1v1d_ed into small! program is divided into small
3. Function call is used. Message passing is used. parts called funct10ns . parts called objects.

4. Software reuse is not possible. Reusability is possible. 2. Procedural programming follows! Object-oriented programming
top down approach. follows bottom up approach.
5. Structured de sig n Object or ie nt e d d es ign
programming usually left until programming done 3. There is no access specifier in Object -oriented programming
end phases. concurrently with other phases. procedural programmmg. has access specifiers like private,
public. protectedietc.
6. Structured Design is more It is s ui table for in-house
development. 4. Adding new data and function isl Addin1rnew data and function is
suitable for off-shoring.
not easy. easy.
7. It. shows clear transition from N ot so clear transition from
design to implementation. 5. Procedural programming doesl Object-oriented programming
design to
implementation. not have any proper way for provides data hiding so it is more
I hiding data so it is less secure. I secure.
It is suitable for re a l time It is suitable for most business
I 8.
system, embedded system and applications, game development 6. In pr oc~dural programm ing,! Overloading is possible in object-
projects where objects are not projects, which are expected to ove rloading 1s not possible. oriented program.ming.
t h e most u s efu l lev e l of customize or extended. 7. In procedural In object-oriented
abstraction . programming, function is mo re programming, data is more
9. DFD & E-R diagram model the Class diagr a m , s e qu ence important than data. important than function.
data. diagram, state chart diagram, 8. Pr ocedur a l ~ogramming is Object-orientedprogram.mi.ng is
and use cases all contribute. based on unreal world. based on real world.
10. In this, projects can be ma naged In thi s approach , project s can be 9, Examples : C. FORTRAL'-1 . Pa.scat ! Examples : C++. Java, Python,
easily due to clearly identifi able diffi c ul t to manage due to Basic etc . ( C# etc.
phases. uncertain transitions between
p hases.
P A R T-2
OOP i11 Ja va, Characteristics of Jaua, Tire Java Environment,
Que LJ.C.1 What i1 the difference between Procedure Based J aua Source File Strwcture and CompilatiorL
programming language and Object-Oriented progra01min1
language?

Lone Anawer Type . . . Medium Answer Type Questions

Q.a• t.11, j Explain OOP in Java.


Downloaded by nayanshi mishra ([email protected])
lOMoARcPSD|16655472

1- 11 B (MCA •Sem-2) 1-12 B (MCA-Sem-2) . Introducti~


Object Oriented Programming
1. Single Inheritance :

1.
Answer I
OOP is a programming paradigm that organizes code around objects
i. Single inheritance is the most basic type of inheritance in Java
where a child class inherits properties and methods from a sing!;
parent class.
that encapsulate data and behavior.
2. Java is a popular object-oriented programming language that supports ii. In single inheritance only one class extends another class.
the OOP paradigm.
Class A
3. In Java, everything is an object, including primitive data types such as
integers and floating-point numbers.
4. Objects are instances of classes, which define the properties and behaviors
of the objects.
5. Following are the main concepts in OOP in Java :
i. Classes and Objects : A class is a blueprint or template for creating
objects. It defines the properties and behaviors that objects of that 2. Multilevel Inheritance :
class will have. An object is an instance of a class.
i. Multilevel inheritance is when a child ciass inherits from a parent
ii. Encapsulation : Encapsulation is the process of hiding the internal class, and that parent class is also a child of another class.
details of an object and providing a public interface for interacting
ep'!:thi code organized and ii. In Multilevel Inheritance, one cias[can inherit from a derived class.
with the object . This helps t -<, k-R Hence, the derived class becomes the base class for the new class.
maintainable. jf'
iii. As shown in Fig. 1.16.2, Class C is subclass of B and B is a of
iii. Inheritance: Inheritance is the ability of a class to inherit properties
subclass Class A.
and behaviors from another class. This allows for code reuse and
makes it easier to manage comP,lex codes.
iv. Polymorphism : Polymorphism is the ability of objec~to take on
multiple form~. InJava, ~ ymorphism is achieved throu!cl'J :{~thod
overloading and method'overriding. ·• · ,,#
~ ~ ~
v. Abstraction: Abstraction is the process,of creatj.ng,abstract classes
?r interfac:s that defi~e a set of propertiJ~ ~.~ bEiha~ or s without
=plementing them. This allows for greater flexibility and modularity
in t he code. kJ•· ·. ,/
6.
·" ,,.
In Java, these concepts are implem~ ted thr9,V,gh various language
Fig.1.16.2.
feat ures such as classes, objects, S:c9ess modifiers, constructors, 8. Hierarchical Inheritance :
inheritance, interfaces, andp.bstract .cl~ s. \ i single parent class has multiple
i. Hierarchical inheritance is w.hen
7. By using these features! d~vvl}lopers can create well-organized, child classes that inherit from it •.
, maintainable, ~d.extensi~le cov . ii. In Hierarchical Inheritance., one class is inherited by many sub
1
j
;91iJI 1.18. Explam m detail about vanous types of inheritance in
classes.
iii. In Fig. 1.16.3, Class B, C, and D inherit the same class A.
Java with neat sketch.
OR
~ith diagrammatfc illustration and Java programs illustrate the
different types ofmheritance.
ClassD
~ -~ J
In Java, there are five types of inheritance:
Class B

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

1-13 B (MCA-Sem-2)
Object Oriented Programming l-14B (MCA-Sem-2) Introduction

4. Multiple Inheritance: 'nh •t from more than 3. Simple and easy to learn : Java is designed to be simple and easy to
i. Multiple inheritance is when a child class J en s learn, with a syntax that is similar to other popular programming
one parent class. languages like C++ and C#.
t d more than one class. 4. Secore : Java has built-in security features that make it a secure
ii. In Multiple Inheritance one class ex en s
programming language. For example, Java programs run inside a
iii. In Fig. 1.16.4, Class C extends Class A and ClassB both.
sandbox environment, which prevents them from accessing resources
Class B on the host system without permission.
Class A
5. Robust: Java is designed to be robust and reliable, with features like
automatic memory management (garbage collection) and exception
handling that help to prevent crashes and errors.
Class C
6. Multi-threaded : Java supports multi-threading, which allows
Fig.1.16.4. developers to create programs that can execute multiple tasks
simultaneously. -•
5. Hybrid Inheritance : ,. 7. Rich API: Java has a rich API (Application Programming Interface)
i. Hybrid inheritance is a combination of two or more types of that includes a wide range of pre-built libraries and too!s that make it
inheritance. "' easy to develop complex applications.
ii. For example, it can be a combipation of single inheritance and 8. Scalable: Java is designed to be scalable, whiclifueans that it can be
multiple inheritances, or a compination.ofhierarchical inheritance used to develop applications of any s&.. fromimlllll applications to large-
and multilevel inheritance. ' .' , · scale enterprise applications.
iii. In Fig. 1.16.5, all the public and.protected members of.Class A are
inherited into Class D, first via Class Band secondly vrn Class C. Que 1.18.1 Write a short noie'on tJie.J ava Environment.

Class A Answ:er I ,'


1. The Java Environment, also ~ wn as the Java Development.Kit.(JDIO,
is a set of software too& and libraries used for developing Java
applications. ,J I
2. It includes the Jan Virtual Machine (JVM), tli~a Runtime
Environment tJRf:), and the Java compile:i:, as well as other tools and
Class D libraries.
Fig.1.18.15. 3. The JVM is)a key component of the J ava Environment. It is respoll.5ible
for ~xecuting,Java bytecode, which is the compiled form of Java code.
Qu.e 1,17.1 Explain the characteriatics/features of Java in detail. 4. The UVM is platform-independent, which means that it can run on any
platform that has a JVM installed'.

Auwer I
Following are the most important characteristics/features of Java:
5. The JRE is another important ~omp,onent of the Java Environment. It
includes the JVM, as well as the libraries and other resources needed to
run Java applications. 6. The JRE is required to run any J ava application
1. Object-oriented : Java is an object-oriented programming language, on a user's machine.
which means that it is designed to organize code around objects that
7. The Java compiler is used to compile Java code into bytecode that can be
encapsulate data and behavior. executed by the JVM.
2. Platform-independent: Java code can be run on any platform that 8. The compiler is included in the JDK and can be used to compile Java
has a Java Virtual Machine (JVM) installed, including Windows, Linux, code from the command line or from an integrated development
and MacOS. This is because Java code is compiled into bytecodr , which environment (IDE).
can be run on any platform that has a JVM.

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

1-15 B (MCA-Sem-2) 1-18 B (MCA-Sem-2) Introduction


Object Oriented Programming
. d d • th J va Environment include the 6. Native Method Stack: It contains all the native methods used in the
9. Other tools and librarie~ mclu e m e a hich rovides detailed application.
Java Development Kit documentation, w p 11 t 001 f;
information about the Java language an? APls, as we as s or 7. Execution Engine: Contains a virtual processor, Interpreter to read
testing, debugging, and profiling Java apphcations. bytecode stream then execute the instructions and Just-In-Time (JIT)
compiler is used to improve the performance. JIT compiles parts of the
I
Que 1.19, Give the internal architecture of Java Virtual Machine byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation.
(JVM).
OR
JAVA Memory Areas
What is JVM ? Explain the internal architecture of JVM with neat
Runtime Allocated by
sketch. JVM
System
Answer
Java Virtual Machine: ,------------------ ---- -----------,
assl □ eap utack ~Register
A
1. JVM is an abstract
machine that provides a runtime environment for
executing Java bytecode.
iB
1 Area
c Native l,
2. When a Java program is
compiled, the source code is translated into
bytecode, which is a set of instructions that can be executed by the JVM.
I
I i.'!ii:a• ·
I
I

3. The JVM is responsible for interpreting the bytecode and executing it on


~---------- ------------ ----------- I
the underlying hardware.
4. The JVM provides following important features : execution k::=~:)I native method Java Native
engine Interface Libraries
i. Platform independence: The JVM provides a consistent runtime
environment that is the same across different platforms, such as
Windows, Mac, and Linux. This means that Java programs can be Fig. 1.19.1. Internal architecture of JVM.
run on any platform that has a JVM installed, without the need for
recompilation. I
Que 1.20, Explain Java source file structure an.ii comp:ililtion.
ii. Memory management : The JVM manages memory allocation
and deallocation for Java programs, which makes it easier for Answer
developers to write code that is free from memory leaks and other A Java source file structure:
memory-related errors. 1. In Java, a source file is a text file that contains Java code.
iii Security: The JVM provides a security sandbox that isolates Java 2. Java source files have a specific structure and naming convention, and
programs from the underlying system, preventing them from
they must be compiled before they can be executed.
accessing resources that they are not authorized to access.
3. A Java source file has the following basic structure :
B. Internal architecture of JVM :
i. Package declaration (optional) : The package declaration is the
L Classloader: It is a subsystem of JVM that is used to load class files . first line of a J ava source file and is used to specify the package that
2. Class (Method) Area: It stores per-class structures such as the runtime the file belongs to. If the file does not belong to any package, this
constant pool, field and method data, the code for methods. line can be omitted.
3. Heap: It is the runtime data area in which objects are allocated. ii. Import statements (optional) : Import statements are used to
4. Stack: Java Stack stores frames. It holds local variables and partial import classes and puckages that are used in the source code.
results, and plays a part in method invocation and return. iii. Class declaration: The class declaration is the main body of the
5. Program Counter (PC) Register: It contains the address of the Java Java sow·ce file and contains the code that defines the class. A Java
virtual machine instruction currently being executed. source file ran contain only one public class, and the name of the
public class must match the name of the source file.

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

1-18 B (MCA-Sem-2) Introduction


1-17 B (MCA-Sem-2)
Object Oriented Programming 1
Syntax:
i Methods and var1a . bl es ·. The class declaration can contain
class classname I
v. methods and variables that are used by the c1ass.
type instance-variable!;
B. Java compilation : ·1 d · to type instance-variable2;
1. Once a Java source file has been written, it must be comp1 e m
II ...
bytecode before it can be executed.
type instance-variableN;
2. The Java compiler (javac) is used to compile Java source files.
type methodnamel(parameter-list) I
3. The basic syntax for compiling a Java source file is : // body of method
javac MySourceFile.java I
4. This command will compile the Java sourc~ file MySourceFile.java and
generate a bytecode file called MySourceF1le.class. type methodnameN(parameter-list) I
5. During the c~mpilation process, the Java compiler che,cks the sr:i~if II body of method
the source code and generates bytecode that can'l>e execute Y e
Java Virtual Machine (JVM).
I
. · ,.#
4. The data, or variables, defined within a class are called"instance variables.
6. If there are any errors in the s_o urce code, the cp~piler will report them
5. The code is contained within methods.
and the code will not be compiled. . "• .
7. Once a Java source file has been compiled, i~ ciµi ~ executed by runnmg 6. The methods and variables defined within a class are called members of
the bytecode file with the Java Virtµal'-Machine'(JVM) : the class.
· java MySourceFile 7. In most classes, the instance variables are acted upon and accessed by
the methods defined for that class.
8. This co=and will run the,bytecode file MySourceFile.class using the
JVM, , ' . 8. Variables defined within a class,are called instance variables because
each instance of the class {that is, each object of the class,)' contains its
9. If the bytecode file contains a main method, the code in the p'tafo method
own copy of these variabl,es.
will be executed.
9. Thus, the data for o~ o~ t is separate and unique ~ tll,a,;d"ata for
another.
I PART-3 I 10. Example: A simple.crass called Box that defuws-tluee illllCance variables:
Fundamental Programming Structures in Java : Defining classes width, height, and depth.
in Java, Constructors, Methods, Access Specifiers, Static Members, . cl~Box{
Comments, Data Types, Variables, Operators, Control Flow, Arrays j
doubl8'width;
double h~ight;
Questions-Answers double depth;
)
Long Answer Type and Medium Answer Type ~uestion.s /
The new data type is called Box. 'niis name is used to declare objects of
type Box. The class declaration only creates a template. It does not
create an actual object.
Qu,el.21.1 Explain how we define classes in Java.
Quel~.-1 Explain constructors in Java with examples.
Anawer
1. The class is at the core of Java. ~,w~.- I
1. In Java, a constructor is a special type of method that is used to initialize
2. A class is a template for an object, and an object is an instance of a class.
the pFoperties of an object when it is created.
3. A class-is declared by use of the class keyword.

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

l-19B (MCA -Sem- 2) 1-20 B (MCA -Sem- 2) Introd uction


Object Orient ed Progra mming
.
. . . . tance variab les of the obJect s.
2. It is used to give uut1al values to ms
. An.wer'
3. It is automa tically called at the time of object
creat10 n.
4. Following is an examp le of a constr uctor 1. In Java, a constr uctor is a specia l metho d ~e~
in J ava : to initial ize o~ject s of a
class. It is called autom aticall y when an obJect
public class Person I 1s create d, and 1t has the
same name as the class itself. The constr uctor
can take param eters or
private String name; have no param eters at all.
private int age; 2. The 'this' keywo rd is used to refer to the
curren t object instan ce in
public Person(String name, int age) I which the code is being execu ted. It is often
used inside a constr uctor to
this.na me = name; refer to the instan ce variab les of the object
being create d.
this.age = age; 3. Here's an examp le of a constr uctor that takes
two param eters :
public class Person I
privat e String name;
5. In above examp le, we have a class called Person
with two privat e privat e int age;
proper ties (name and age). • ·. public Person (Strin g name , int age) I
6. We also have a constr uctor for the class, which
takes two argum e_n ts
(name and age) and sets the corres pondin g this.na me= name;
proper ties of the obJect
using the 'this' keywo rd. ~- ./': . 'v" this.ag e = age;
7. When a new Person object is cre att d u~iri$.t his
constr uctor, th_e name
and age proper ties will be initial ized,w ith
the values provid ed as
argum ents. 0
"'
8. For examp le : 4. In the above examp le, the 'Perso n"dass has
a constr uctor that takes two
Person person l = new Person ("Ram", 21); param eters, 'name ' and 'age":
In this case, a new Person ol;>ject is create d wit~ 5. The 'this' keywo rd is used to refer to the instan
a narne""o!p• ce variab les.of the 'Perso n'
age of 21. object being create d, so that they can be,set
;J to the varues of the
constr uctor param eters.
Rules :
1. A constr uctor has the same name as the class.
j
Que 1.24. Expla in const ructo r overlo ading
_in Ja~ Illust rate with
2. A class can have more than one constr uctor.
, , an exam ple.
3. A constr uctor can take zero, one or more' param
eters.
4. A constr uctor has no return value. Answ er
5. A constr uctor is always called with the new L Constr uctor overlo ading is the practic e of:defi
operat or. ning multip le constr uctors
for a class, each with a diffete nt signat ure.
6. The constr uctor cannot be abstra ct, static, final
or synchr onized . 2.
Types of constr uctors : There are two types This allows object s of the class to be initial
of constr uctors : ized with differe nt sets of
param eters, makin g it more flexibl e and versat
1. Defau lt constr uctor (no-ar g constr uctor) ile.
: A constr uctor h aving 3. Follow ing is an examp le of constr uctor overlo
no param eter is known as defaul t constr uctor ading in Java :
and no-arg constr uctor.
2. Param eteriz ed constr uctor : A constr uctor public class Emplo yee I
which h as a specific
numbe r of parame ters is called param eterizt·d constru privat e String name;
ctor. Param eterize d
cons tructo r is used to provid e differe nt values
to the distinc t object s. privat e int age;
Que 1.23. j Outlin e the use of const ructo rs and this keyw
ord in
privat e double salarv ;
,iava. public Emplo yee() t

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

1-21 B (MCA-Sem-2) t-22 B (MCA-Sem-2)


Object Oriented Programm ing

name="";
age= O;
!
IQae 1.21, What i• method? Bow method i• defined? Give Example.

salary= 0.0; tAn_-wer J


1. In Java, a method is a block of code that performs a specific task.
public Employee(String name) l 2. Methods are used to organize code into reusable and modular units,
this.name = name; which make code easier to read, write, and maintain.
age= O; 3. A method is defined inside a class, and it can take parameter s and
return a value.
salary= 0.0;
4. Here's an example of a method in Java :
public class MathUtils l
public Employee(String name, int age) l
public static int add(int a, int b) l
this.name = name;
return a+ b;
this.age = age;
salary= 0.0;

5. In this example, we define a class call81¾..'MathU'tils'. Inside the class, we


public, Employee (String name, irit age, double salary) l
define a method called 'add' that takes two integer parameters 'a' and 'b'.
this.name = name; The method returns the sum.. of 'a' an~ 'b".°"
this.age= age; ~ \_ · 6. The breakdow n of the method-.d'efinitfon is as follow :
this.salary =. saJ~y.;f~ ... i. public : this is an access modifier that means the metl!od can be
t ,•,;;'iry~ called from a.xi'' '
ii. static : this a !
in the program.
er that means the method l,el~ to the
// Other m~tti,ods li~ r!3~-~
class, nof-to-~ i!P'ticular illlltance-or'ttie-class; /
4.
)
"'·~
fiit,
Iii the above exa~
;.
.,,e, we have a class called 'E iii. int: -t ~ is t~turn type ofthe meth ~~ ease, the method
returns a@teger value.
constructo rs. . ,. ,. iv. add : this is the 11ame of the meth~
5. The first coru;t z:uctor takes no argumefft s'and se_ti~ll member variables
to their default'va lues. v. (int -. int b) : these ~ th~param eters ¥the method. In this case,
"'-' /!
the method takes two integer ~eter s called a and_b.
6. The second constructo r t akes a single ·•~ame' argument and sets the
'name' variable, leaving the other variables at their default values. vi. (return a+ b;} : this idhe oodyof tbe method. h contains the code
that performs the task of the method, which in this case is to add
7. The third constructo r takes a 'natµe' and 'age' argument , and sets those the two paramete rs and re\,urn the result.
variables, leaving 'salary' at its default value.
8.

9.
The fourth constructo r takes all three argument s and sets all three
variables.
By defining multiple constructo rs with different paramete rs, we have
made the 'Employee ' class more flexible and easier to use .
e:xample explain how finaliae() method

Aa~· .I
c-
.9!e·~.11,I State the p ~ offinalia e() method in Java. With an
be uaed in Java program.

1.The finalize( ) method in Java is a method that gets called by the garbage
collector before an object is destroyed .

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

1- 23 B (MCA -Sem-2)
Objec t Orient ed Programming 1-24 B (MCA-Sem-2) Introduction
to perfor m some ver&atile and flexible
2. Its purpos e is to provide a way for the progra mmer 3- By using method overloading, we can create more
cleanu p operat ions before the object is garbage
collected.
ds that can handle differe nt types and numbe rs of parameters,
metho
file handles, closing g our code more efficie nt and easier to use.
3. This can be useful for releas ing resour ces like makin
Java :
databa se connections, or freeing up memo ry. 4. Following is an example of method overloading in
on finalize () to perform
4. However it is impor tant to note that relying solely public class Calcul ator (
no guaran tee that
cleanu p operat ions can be unreliable becaus e there's public int add(in t a, int b) (
it will be called in a timely manne r, or even at all.
try-wi th-reso urces or a return a+ b;
5. It's better to explicitly releas e resour ces using
finally block.
can be used in a Java public double add(double a, double b) {
Exam ple: Following example show how finalize()
progra m : return a+ b;
public class MyCiass [
privat e File file; public int add(in t a, int b, int c) (
public MyClass(Stri ng filenam e) ( return a+ b + c;
file = new File(filename );
~ public static void main(String0 args) (
}
protec ted void finalize() ( , Calcul ator calc = new Calculator(};
try( ~"- · int suml = calc.add(t 32;
if (file != mill) ( ,~
file.i:tose(); y .,,
'
double sum2 = qa.leadd(2.5\"3.5);
int sum3 = c!J}c.ad d(2,~3; 4);
'\, p System .out.println(i'Sum 1:" + suml);
} ~ ,/
] catc~ OEx~ P,tion e) [ System~ t.print ln("Su m 2:" + sum2>?

/. II ~ 411 the exception System .out.pr intln(" Sum 3:" + sum3


~
:

}
Que 1.27.
r. .;
j Expla in metho d overlo ading in Java ? Illust rate with
Que 1.28. j Expla in metho d overr iding in .Tava
example.
? Illusir aie with an

OR
an exam ple. Outlin e metho d overr iding wiih an example.

Answ er I allows a class to have


Answer I a subclass to r -ovi_:
I. Metho d overlo ading is a featur e of Java that 1. Method overrid ing is a feature of Java that allows
with the same name, but with differe nt param et ers . entatio n of a metho d that is already define m ,
multip le metho ds its ow~ implem
d name to be used for superclass.
2. This is useful becaus e it allows the same metho I h th type signatu
e name andsubclas re as
on the type or numbe r of param et er s passed d . th s is said to
differ ent operat ions based 2. When a metho d in a subc ass as thee samtho
me m e
to the metho d. a method in its superclass, then
overri de the method in the superclass.

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

1-25 B (MCA-Sem-2)
Object Oriented Programming
l-26B (MCA-Sem-2) · lntroductioili
3. When an overridden method is called from within its subclass, it will
always refer to the version of that method defined by the subclass. ii. protected : The 'protected' access specifier allows access from the
Following is an example of method overriding in Java : same class, as well as any subclasses and classes in the same package.
4. Protected methods and variables can be accessed within the class
public class Animal ( as well as by any subclass or class in the same package. '
public void makeSound() { iii. default (no keyword) : The 'default' access specifier allows access
System.out.println("The animal makes a sound"); from within the same package only. Methods and variables with no
access specifier are considered to have default access.
iv. private: The 'private' access specifier is the most restrictive, and
allows access only from the same class. Private methods and
public class Dog extends Animal { variables cannot be accessed from any other class, even subclasses.
@Override 4, By using access specifiers, we can control the level of access that different
classes, methods, and variables have within our program, making it
public void makeSoundO {
more secure and easier to manage. -~
System.out.println("The dog barks");
5. It's important to choose the appropriate accessspecifier fij'each element
of our program to ensure that it's accessible to the right classes and
methods, and not accessible to others that' should net have access.

public class Main ( I


Que 1.30. Explain in detail static members~ Java.
public static void main(Str ingO args) (
Animal animal = ne,' i'~ mal();' Answer
animal.makeso&<fo; II Output: The animal makes•·a ,s ound L In Java, a 'static' member is a member of a class that belongs to the class
~}'- ·•"'/)' itself, rather than to any ~
·cular instance of the class. A
Dog dog = ~ew D?gO; · d!t· ·"
2, This means that tliere is onl one copy of the 'static' ~ that is
dog.makeSol.llldO; //'Output: The dogL~ar shared by all instanc$, o_(thll class, ~ . , , '1
J' 1.. ·2 ':;:};
" '¼ , v ,,,,,,,
3. There are three ~ it <!f''static' members in Java : \ ·
a. 'static' variables•;,'
;p"
i, These are variables that are shared hy all instances of a class,
Que 1.29.1 Explain in detail access sp_e cifiers in Java.
They are declared using the 'static' keyword and can be accessed
Answer I (' •1
~ f"
,using the class name, fi ll~ ed by-the variable name. For example :
public cl~ss MyClass {
1. Access specifiers in Java are used ·to define the level of access that
different classes, methods, and'varia~les have within a program. static int x = O;
2. How a member can be accesseci"is determined by the access specifier public void increment() {
that modifies its declaration, x++;
3. There are four different access specifier s in J ava :
i. public : The 'public' access specifier is the most permissive, and
allows access from any class or package. Public methods and
iii. In this example, 'x' is a 'static' variable tha! is shared_by all instances
variables can be accessed from anywhere in the program. of the 'MyClass' class, The 'increment() method mcrements the
value of'x'.

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

1- 27 B (MCA-Sem-2)
Object Oriented Programming 1- 28 B (MCA-Sem-2) Introduction

'static' methods : The comments can be used to provide information or explanation about
to the class itself, rath er t h an to any
b. bel
2.
i. These are methods that ong the variable, method, class or any statement.
particular instance of the class. 3. It can also be used to hide program code for specific time.
d . the 'static' keyword and can be called using
ii. They are declare usmg th d me For example · 4. There are 3 types of comments in Java :
the class name, followed by th e me O na · ·
i. Single-line comments : These comments start with two forward slashes
public class MyClass I (If)and continue to the end of the line. Single-line comments are used
static int x = O; for short comments or to explain specific lines of code. For example :
public static void increment() I II This is a single-line comment

x++; int x = 10; II This line initializes the variable x to the value 10
ii. Multi-line comments : These comments start with a forward slash
and an asterisk (/) and end with an asterisk and a forward slash (/).
'\?• Multi-line comments are used for longer comments that span multiple
iii. In this example, 'increment()' is a 'static' metbo d th~9ielo~gs to ~he lines. For example : ~
'MyClass' class. It increments the value ofthe 1static vanable 'x . r ~

c. 'static' blocks : This is a multi-line comment that can spanmultip)e lines.


i These are blocks of code that are exe.cuted only once when the
It is typically used to provide detailed explanations of code.
class is loaded into memofi;. ..,..1~0r~~.,,,.
*I
ii They are declared using thJ;;static',ke~ ord and are typically used
to initialize 'static' variables. For e:Miample : int x = 10; II This line initializes,_the variable x to the value 10
public class MyClass { ' " ~ iii. Documentation comments :, The documentation comment begins
with a I** and ends with a */. .They are usually used to wri~ large
static int x; programs for a pxyject"O( sqftware application as it helpa to. create
static { documentation,~!. ~or ti-xample :
I**
Thisis
documentation comment.
iii In this example, the 'static' block initializes the\ tatic' variable 'x' to *I
the value '10'. 4Y 7
4. Que 1.32. 1· Explain different data iyp4:ls in J ava.
The ~e of static ~embers in Java provides a way to share data and
be~vior across all instances of a class, without having to create separate
copies of the data and behavior for each instance. Answer
5. This can help to reduce memory usage and make your code more efficient. In Java, there are two categories of data types: primitive and reference
types.
Que lJU.1 Write a short note on : Java comments. A Primitive Data Types:
1. Primitive data types are the most basic data types in Java.
Answer
2. They represent simple values and are not objects.
1. The Java comments are state t th .
• t t men s at are not executed by the compiler 3. There are eight primitive data types in Java, which are :
and m erpre er.

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

1-29B (MCA-Sem-2) 1--30 B (MCA-Se m-2) Introduction


Object Oriented Programm ing

i. byte . used to represent who1e num be r s from -128 to 127.


2. Floating- point literals: Floating-p oint literals are used to represent
• fractional numbers. They can be specified using a decimal point or in
ii. short: used to represent whole num be rs from -32 ' 768 to 32,767. scientific notation. For example, 3.14 and 2.0E-5 are floating-point literals.
iii. int : used to represent w h o1e n umbers from -2,147,48 3,648 to 3. Characte r literals: Character literals are used to represent individual
2,147,483,647. characters. They are enclosed in single quotes. For example, 'A', '5', and
iv. long: used to represent whole numbers from -9,223,372,036,854,775,808 '& ' are all character literals .
to 9 223,372,036,854,775,807. 4. String literalll : String literals are used to represent a sequence of
' . al
v. Ooat: used to represent fraction num be rs W1"th up to 7 decimal digits characters . They are enclosed in double quotes. For example, "Hello,
of precision. world!" is a string literal.
vi. double : used to represent fractional numbers with up to 15 decimal 5. Boolean lit,,,ralll : Boolean literals are used to represent boolean values,
digits of precision. whlch are either true or false . For example, true and false are boolean
vii. char: used to represent a single character, such as a letter or symbol. literals.

viii. booiean: used to represent true/false values. 6. Null literal : The null literal is used to represent a reference that does
not refer to any object. It is typically used to indicate the absence of a
B. Referenc e Data Types : value.
1. Reference data types are used to store references to objects .
2. Que 1.34. , Explain in detail about variaWe in Java.
Unlike primitive data types, they are objects themselve s and can be
assigned null.
Answer
3. Some of the reference data types in Java are :
1. A variable is a container which holds the value and that can be changed
i. String: used to represent a sequence of characters . during the execution of the program.
ii. Array: used to store a collection of elements of the same data type. 2. A variable is assigned with a datatyoe.
iii. Class : used to represent a class definition. 3. All the variables must be declared before they can be used.
iv. Interface : used to represent an interface definition. 4. There are three types of variables in Java :
v. Enumera tion : used to represent a set of constants. A Local Variable :
Que 1.33. , What are literals? Explain the types of literals supporte 1. A variable defined within a block or method or constnx:ro r is called local
d variable .
by Java.
2. These variables are created when the bloclt in eutered,or the function is
Answer called and destroyed after exiting from the block or when the call returns
from the function.
A Literals :
3. The scope of these variables exists only within the bloc.k in whlch the
1. In Java, a literal is a constant value that is explicitly defined in the
variable is declared i.e ., we can accll6S these variable only within that
source code of a program. block.
2. Liter.als are used to represent values such as numbers, character s, and B. Instance Variable :
boolean values in a program.
1. Instance variables are non-static variables and are declared in a class
B. Types of literals supporte d by Java are :
outside any method, constructo r or block.
1. Integer literals: Integer literals are used to represent whole numbers. 2. AB instance variables are declared in a class, these variables are created
They can be specified in decimal, octal, or hexadecim al format . For when an object of the class is created and destroyed when the object is
example, 42, 052, and 0x2A are all integer literals. destroyed .

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

1-31 B (MCA-Sem-2)
Object Or iented Program ming 1-32 B (MCA-Sem-2) Introduc tion
variables.
3. Unlike local variables we may use access specifiers for instance 7. ~nstanc eof operato r : This operator is used to check if an object
is an
~y access specifier then the default access specifier as
Ifwe do not specify m~tance of a particul ar class or a subclass of that class. It's written
will be used. obJect mstance of class.
C. Static Variab le:
Que 1.36., Explain differen t control stateme nts in Java.
1. Static variable s are also known as Class variable s.
difference OR
2. These variable s are declared similar to instance variables; the in Java ?
variable s are declared using the static keyword within a What are the three categor ies of control stateme nts used
is that static OR
class outside any method construc tor or block.
Explain the selectio n stateme nt in Java.
variable
3. Unlike instance variable s, we can only have one copy of a static
Answe r
per class irrespec tive of how many objects we create.
program
4. Static variable s are created at start of program executio n and
destroyed Contrnl stateme nts in J ava are used to control the flow of
n. They allow the program to make decision s,. loop over a block
automat ically when executio n ends. execut10
of control
of code, and _break out of loops. Following are the main types
stateme nts m J ava :
Que 1.35. j Explain differen t operato rs in Java. used to
A Conditi on_a l/Select ion stateme nts : These st atement s are
ma ke dec1s10ns based on a condition.
Answe r
nt. It is
Java has severa l types of operator s, each of which perform
s a specific 1. if stateme ~t : It is the most simple decision making stateme
nts will
functi on on one or more operand s. Following are some of
the main used to decide whether a ce rtain st atement or block of stateme
executed or not i.e. , if a certain conditio n is true then a block of
categori es of oper ators in J ava : be
stateme nt 1s executed otherwis e not.
1. Arithm etic operato rs : These operator s are used
for mathem atical
ition.
calculat ions and include + (addition ), - (subtrac tion),* (multiplication), / 2. if-else stateme nt: The J ava if-else stateme nt also tests the.cond
block
(division ), % (modulus or remainder), ++ (increme nt), and -- (decrem
ent). It executes the 'if' block if condition is true else if it is false the 'else'
1s executed .
operato rs a re used for compari ng values
2. Relatio nal operato rs: These nt inside
to ), >= 3. Nested if-else stateme nt : It is using one if or else-if stateme
and include< (less than),> (greater than ), <= (less than or equal another if or else-if stateme nt(s).
(greater t han or equal to), == (equal to), and!= (not equal to).
from the
rati ons 4. if-else-i f ladder stateme nt: The 'if' state ments are executed
3. Logical operato rs : These oper ators ar e used for logical ope conditio ns controlli ng the if are true, the stateme nt
NOT). top d_own. T_h e
and include && (logica l AND), 11 (logical OR), a nd! (logical bypassed .
assoc iated with that ifis executed , and the r est of the ladder is
values to
4. Assignm ent operato rs: These operato rs are used to ass ign If none of the conditions is true, then the fin al else stateme
nt will be
ass ign), -=
variable s and include = (simple assignm ent), += (add and executed.
nd assign), 5.
(subtrac t and assign ), *= (multipl y and assign ), I= (divide a Switch statem ent: The switch stateme nt is J ava's multi-wa
y branch
a nd %= (modulu s and assign). st atement . It provides till easy way to dispa tch executio n to different
5. Bitwise operato rs : These oper a tors are used to perform
bitwise parts of your code based on the val ue of an expression .
operatio ns on integers and include & (bitwise AND), I (bitwise
OR), " B. execute
(left shift),» (signed Iteratio n stateme nt (Loops) : Iteration statements are used to
complem ent or NOT),« ts
(bitwise XOR), - (bitwise a bloc k of code repeatedly. There are three types of iteration statemen
right shift), and >» (unsigne d right shift). in J ava :
ons I.
6. Conditi onal operato r: This operator is used for conditional expressi for : The fo r loo p is used when the number of it erations is known
in
s the
and is written as conditio n? expressi onl : expression2. lt evaluate advance.
otherwi se
conditio n and if it's true, it returns the value of express ion 1,
it returns the value of expression2.

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

Int r oduc tion


1-SS B (MC A-Se m-2) 1- 84 B (MCA -Sem -2 )
Obje ct Orien ted Prog ramm ing of the
s of arra ys with each elem ent
when the numb er of itera tions
is not ii. Mult idime nsion al array s are array r arra y.
2. whil e : The while loop is used array holdi ng the refer ence of othe
know n in adva nce. Arra ys.
is simil ar to the while loop, but it
executes iii. Thes e are also know n as Jagg ed
3. do-w hile: The do-while loop is false. A multi dime nsion al =:i~.s creat e
d b re
the block of code at least once, even if the cond ition iv. Y appe ndin g one set of squa
jump to a brackets( □ ) per dim
state ment s allow the prog ram to
C. Jum p state men ts : Jump three types of jump state ment s in
.
Synt ax : type var-n am I I I I - new type[ row- Size) [col- size) ;
t in the code. Ther e are v. e -
speci fic poin
Java :
loop or
state ment is used to t ermi nate a
1. Brea k state men t : The break tion at the next state ment after t he
switc h state ment and resum e execu
loop or switc h.
th e
nue state ment is used to skip to
2. Con tinu e state men t : The conti
next itera tion of a loop.
meth od and
3. Retu rn state men t: The
retur n state ment is used to exit a
retur n a value to the calle r. .cl ...
y.
Java ? Give the type s of arra
Que 1.37.1 Wha t is arra y in

Ans wer
A Arra y in Java :
s
that holds a fixed numb er of value
1. In Java , an array is a data struc ture ;>
of the same data type. . ·
array
mean ing the first elem ent ofan
2. Arra ys in Java are zero- index ed;
has an index of 0.
alloc ated.
3. In Java all a1Tays are dyna mica lly
B. Typ es of arra y :
1. One -Dimensi onal Arra ys :
er of value s of the same data t ype
i. It's an array that holds a fixed numb
onen ts: the type and the name .
ii. An array decla ratio n has two comp
ent type of the array .
iii. Type decla res the elem
deter mine s the data type of each elem
iv. The elem ent type ent t ha
comp rises the array .

V. Syn tax: type var-n ame[ ];


2. Mul tidim ensi onal Arra ys :
er of a¥ray s, wher e each
i. It's an array that holds a fixed numb dat a type_ array hol
same
a fixed num ber of value s of the

Downloaded by nayanshi mishra ([email protected])


-
lOMoARcPSD|16655472

'l
l
(_}bject Ori~nte d Program ming SQ-2 B (MCA-Sem-2)
SQ-1 B (MCA-Sem-2) 2 Marks Questions
user. In other words, it is the process of creating abstract data types

1
that provide a high-level interface to the user, while hiding
the
impleme ntation details.

1.6. When a clus must be declared as abtltnct ?

UNI T
Intr odu ctio n .,_ A class must be declared as abstract in Java ifwe want to
define a
common interface or behavior for a set of related classes, but
we
(2 Marks Que stion s) don't want to provide a concrete implementation for all of
the
methods or attribute s.

What is Object Oriente d Progra mming ?


Obje~t Oriente d Program ming (OOP) is a pro/taiii lhing paradigm
that IS based on the concept of objects. In OOP, opjectsl! ie instance
of classes, which are templat es that de~ne ·tile p;operti
behavio r of objects. The key principl e/ ofC>OP ~ri encapsu
es and
lation
s
-1.7. What is encapsulation in OOP?
Encapsu lation refers to the practice ofbundling data and behavior
together and controlling access to them thnllli1 a well-defi
interfac e. In OOP; encapsul ation is a c h i e v ~ the use
classes and access modifiers.
'>-
ned
of

1.8. What is information biding in OOP ?' ,


inherita nce, and polymor phism. f"~'t). -- ~%1' ' Informa tion hiding refers to the practice ,Chiding th~ -in~rnal
ms details
. iA~, ~'~,' -~'; of an object from the outside world; so that the objects data
1.2. Define Objects and clas~s -i n OOP. ,-.,
,,, ' and behavior cannot be accessec lormodif ied directly. In ?OP,
D1i: Object : In Object Oriented '.lo-ogra-,mming
, I
(OOP) an object is an informa tion hiding is achieved through the use of access modifier
instance ofa class. - "- - -,{x ff_ s
' such as private, protecte d. and public.
Class : In Object Oriented ~~min ing (OOP), a class is a blueprin
t #
or templat e for creating objects'.

,al:
~ '.i'"'

1.3. Disting uish betwee n class and object.


,;-$\
~

....
1.9. What do you mean~ inherita nce in OOP?
' -
Inherita nce allows us to-create new cl~ fro existing classes
inheritin g their data.and behavior - lnhentan cem~.des a wa! ~
' d ..:...,..e classes that are related \0 each other m
_,__"an
''1 " <)' reuse couo,-
. q -•
chi al ................
a
- --,."~ d through
S.No. .. In OOP inheritaI!,1:11,-lS ~ve
Aspect Class '" Object " hierar c ---~~ - ' '-
the use of parent and child classes.
1. Definitio n A blueprin t for creating, An instance of a class. y
objects.
1.10. Defin& po]ymo rphi~-. . . take ~n multiple forms or
2. 'd
Keyw.or 'class' keyword . l' ':}
Instanti ated using the
~ Polymor phism is t~e abili~ of oh\e~ : which they are used.
1n
~
beh~viors depending on . e conl orphism is ~cally achieved
'new' keyword .
object-or iented progr&;[llDllllC, po ym .ding
3. Memory Does not occupy me~ory Occupie s memory when thr~ugh inheritan ce an,dmethod ovem .
allocation until an object is cre,ted . instantia ted. , -~ i....igae e in Java?
... 111 What are various types u,µuaa-• •
1.4. What is abstrac tion in Java? • · ti types of inheri'8n ce :
Jl8 In Java, ther_e are ve
aa: Abstract ion refers to the practice of hiding impleme ntation
details 1. Single Inbentan ~e
while showing only the necessa ry informa tion to the user. In 2. Multilevel lnhen ~
OOP,
abstract ion is achieved through the use of interfac es and abstract 3. Hierarchical ~entan ce
classes. 4. Multiple lnh~ntan ee
1.15. Define data abstraction. 5_ Hybrid Inbentan ce
ri ucslfeaturell of Java.
Mil Da~ lU>f:ltr!lCtion is a program ming concept that refers to the process 1.12. Give the ch&raCWh s cteristicslfeatures of Java:
of simplifying complex data structur es by hiding unneces sary Ulli Follo~ are the c ara
details
and exposing only the essentia l features that are relevant l . Object-onented
to the

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

~b.ieot Oriented J?rogr.anuning sQ-4 B (MCA-Sem-2)


, SQ-SB (MCA-Sem-2) 2 Marks Questio'ru:

2. Platform-independent class. A class is declared by use of the 'class' keyword.


3. Simple and easy to learn Syntax :
4. Secure class classname I
5. Robust type instance-variable!;
6. Multi-threaded type methodnamel(parameter-list) I
7. RichAPI // body of method
)
8. Scalable .
)
1.18. Java is robust. Comment.
1.19. What is an abstract clan in Java ?
- . Java is often considered a robust programming language due~ its :ur&: In Java, an abstract class is a class that cannot be instantiated
many features like memory management, strong type checking, directly, and must be subclassed to be Wied.
exception handling, platform independence, etc., which enhance
its reliability, stability, and secµrity . These features contribute to
making Java a robust and reliable language that'iswel\-suited for 1.20. What is a constructor ?
In Java, a constru~r is · as~·al ~of-method tbat is used to
·t . created It is used to
large-scale enterprise applications, we~, devefo~ment, and many
initialize the properties of an obJect w
other use cases. "- '\,> · I IS ;,:. • .
give initial values to instance v~able~ >the ob1ects. It is

....
1.14. What is Java Environment? '
,, F
'

The Java Environment also known as the Java Development Kit


(JDK), is a set of softw~e' tools anq libraries used for developing
automatically called at the time ofobject er on.

1.21. Outline the use of 'this"iefwordia Java.


Di: The 'this' keyword is use O I
. . .
d ti ref1 to the current object instance m
i's fte used inside a constructor
Java applications. It includes the JavaVirtual Machine (JVM), the
which the code is being executed. t o n . . created
Java Runtime Environment (JRE), and the Java compiler, as well to refer to the instance_variables of the object bemg r ._ .
as other tools and libraries.

-
loading in Java? nJ.ti 1
1.15. What is bytecode ? 1h 1.22. What is c o ~ over
, r ~= ·
the practice of defining- ~ P e
Constructor over10&9"mg 15 .th diff•t sign&ture. This allows
Bytecode is a binary representation_of Java code_that c ·. be.executed constructors for a: class, _e ~ ~ ~th diffeftllli 11ets-ofparameters,
on any pl~tform that:has a Java Virtual Mac~ne (~ ) Bytec~de
41 objects of the class to be rm . ' •
is a low-level code.that is not specific to anylfardwa.reor'operatmg making it more flexible and versatile. Y
system. When you run a Java program, the ~,l'~~ps the bytecode
and interprets it into machine code that can b!f,executed by the
1.23, What is method '. e l:Iiat.J)erforms a specific tas~.
underlying hardware. ·
Ans. In Java, a jnethod is a bl~o~ into reusable and.modular umt,
Aft 0
Methods are used to ~ ~write', and maintain.
1.16. What is Java Virt~al Machine (JVM},? which makes code easJer t<r
mac JVM is an abstract machine that provides a runtime environment · . medlodinJava.
for executing Java bytecode. When a Java program is compiled, the
1.24, State the purpose o f ~ ."' thod that gets called b~ the
source code is translated into bytecode, which is a set of instructions e finalize() method in J au 1:5 a ~destroyed. Its purpose is to
that can be executed by tlie .JVM. The JVM is responsible for US Th bage collector before an ob1ect t perform some cleanup
interpreting the bytecode and executing it on the underlying gar £ th programmer o
provide a way or ~ - tis garbage collected.
hardware. operations before the o ~ec

1.17. Discuss Java source file structure. loadinl in Java ? have


1.25. What is meih~~:v:ra feature of Java that ~:r:.:t~tdi;erent
al: In Java a source file is a text file that contains Java code . Java ~ Methodoverloa1.UU6 ·th the same name, _
source files have a specific structure and naming convention, and multiple methods w1
they must be compiled before they can be executed. parameters.
'dinl in Java?
1.18. Explain how we define classes in Java. 1.26. What is method overn .
21'1111: A class is a template for an object, and an object is an instance of a

Downloaded by nayanshi mishra ([email protected])


lOMoARcPSD|16655472

Object Oriented Programming SQ-ff B (MCA-Sem-2)


SQ-6 B (MCA-Sem-2) 2 Marks Questions
bi: Met~od _overriding is a feature of Java that allows a subclass to
provide its own implementation of 8 method that is already defined For example, let's say we have a Java class named 'MyClass' which
in its superclass. is declared as public. We can save this class in a source file named
'MyClass.java'. However, we can also save this class in a file named
1.27. State the conditions for method overriding in Java. 'MyOtherClass.java' as long as the public class declared in the file is
DI: Following are the conditions that must be met for method overriding named 'MyClass' .
to work correctly in Java :
1. The method in the subclass must have the same name, return type, 1.,'32. What are literals?
and paran1eters as the method in the superclass.
AD: In Java, a literal is a constant value that is explicitly defined in the
2. The method in the subclass must have the same or higher access so urce code of a program. Literals are used to represent values
level than the method in the superclass. such as numbers, characters, and boolean values in a program.
3. The method in the subclass must not throw a checked exception
that is not declared in the throws clause of the method in the 1.33. Explain about variable in Java.
superclass.
Ans; A variable is a container _which holds the value ~d t~t C'.1fi ~
4. a
The method in the subclass must not have more restrictive access changed during the execution ofthe pr ogram. A variable JS assigne
level than the method in the superclass. with a datatype. All the variables must be declared before they can
5. The method in the subclass must be marked with the "override" be used.
keyword, although this is not strictly required.
l.34. What are control statements m · J ava
· _1'What
·. are
., the three
1.28. What is access specifier ? categories of control statements used' m Java .
am. Access specifiers in Java are used to define the level of access that . J sedfo control the flow of program
~ Control statements m ava are u t make decisions loop over a
different classes, methods, and variables have within a program. execution. They allow the program o . th; main types
How a tnember can be accessed is determined by the access specifier block of code, and break out ofloops. Following are
that modifies its declaration. / of control statements in Java :
1. Conditional/Selection statements
1.29. Explain 'static' member in Java. ~.. flfi' 2. Iteration statement (Llops)
am. In Java, a 'static' member is a member ofa class t:ha e ong~ to the 3. Jump statements
class itself, rather than to any particular ins~nce of the class ...This
means t.Qat there is only one copy of t}le· 'stl\\!C:.!}1ember that is 1.35, What is. array in Java? h ..,. fixed number of
shared by all instances of the class. ; ·,:;- · d ta structure that O1wra d
A'ii'.'iC In Java, an array 1s a a Arra . ill Java. are zero-indexe ;
values of the same data type. ~ an index ofO. In Java all
1.30. Discuss Java comments. What Bfe'its types? meaning the first element of an aqay as
ffiia. The Java comments are statements that are not executed by the arrays are dynamically allocated.
compiler and interpreter. The comments can be used to provide
information or explanation about the variable, method, class or any
statement. There are 3 types of comments in Java :
1. Single-line comments
1.36, What is J avadoc ?
as: J avadoc is a tool in J_ava. th~;
Java source code. It is a pat
:r:;~::;
t
i\PI documentation from
Development Kit (JDK)
. . HTML format from the
2. Multi-line comments and is used to create documentation m
3. Documentation comments comments in the source code.

1.31. Can a Java source file be saved using a name other than
the clus name ? Justify.
. _ Yes, a Java source file can be saved using a name other than the
class name. In Java, the source file name and the class name can be
different. This is because Java follows a convention that requires
the file name to match the name of the public class declared in the
file only ifit exists.

Downloaded by nayanshi mishra ([email protected])

You might also like