0% found this document useful (0 votes)
71 views15 pages

OOPS JAVA M1 Solved Ktunotes - in

note
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)
71 views15 pages

OOPS JAVA M1 Solved Ktunotes - in

note
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
You are on page 1/ 15

ST.

THOMAS INSTITUTE FOR SCIENCE AND TECHNOLOGY,


TRIVANDRUM
CST 205 OBJECT ORIENTED PROGRAMMING IN JAVA
MODULE 1 IMPORTANT QUESTIONS AND ANSWERS

1. Explain different approaches in software designing.


2. Compare approaches in software designing.
3. Compare Function (Procedure) Oriented Approach (POP) with Object Oriented Approach (OOP)
Answer
Procedure Oriented Approach: Importance is for functions rather than data.
• Top-Down Decomposition: POP starts at high level view of a system which refines high level
function to low level functions. Consider an example of a Student Management System which
consist of a high level function enrollStudent(). For enrolling a student some other internal
activities are carried out which includes, student record creation, course selection and fee
payement. These activities can be identified as low level functions of the high level function
enrollStudent(). Thus enrollStudent() can be further divided into low level functions such as
createStudent(), selectCourse(), payFees().
• Centralized State System: In POP various functions share data, so that the system state is
centralized. For example, in Student Management System, the data “StudentRecord” will be
shared by various functions such as a createStudent(), deleteStudent(), updateStudent() for
making updation regarding Students.
• Free Data Flow: Since POP follows Centralized State System, data flows freely between the
functions. The changes made by function on a data will affect other functions too.
• Less Secure: POP doesn’t have any access control mechanisms which makes data less secure.
Object Oriented Programming: Importance is for data rather than functions
• Bottom-Up Approach: OOPs first identifies classes then identifies the required high level
member functions. For example in a Student Management System, using OOPs we can identify
Student and Teacher classes. Student class may consist of functions like enrollCourse(),
viewAttendance(), viewMarks() etc.. Whereas, Teacher class may consist of functions like
uploadNotes(), enterAttendance(), enterMarks()…
• Decentralized State System: In OOPs every class have its own member data and methods. So,
the variables(data) aren’t shared globally.
• Restricted Data Flow: In OOPs objects of a class holds the data regarding that class which
can’t be directly accessed by any other classes. Data of a class can be only accessed from
another class by invoking methods.
• Highly Secure: Since OOPs provides access control mechanisms, data can be created as private
or protected in a class which makes it inaccessible from other classes.
4. Explain an example case Study of Procedure Oriented Programming and Object-Oriented
Programming
5. Explain case Study of an Automated Fire Alarm System
Answer
Procedure Oriented Design
• First identify and list global data (normal or array variables with data type)

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


• The identify and list different functions (needs your imagination, if given read the
requirement para carefully and identify functions) that share the global data.
• In case of an Automated Fire Alarm System using POP, following are the
1. GLOBAL DATA
BOOL detector_status[Max_Rooms]; // an array variable which stores the
status(ON/OFF) of fire detector installed at all rooms(Max Rooms) in the hotel.
int detector_locs[Max_Rooms]; // an array variable to store the locations of activated
fire detectors (Max Rooms) in the hotel.
BOOL alarm_status[Max_Rooms]; //an array variable which stores the status(ON/OFF)
of fire alarms installed at all rooms(Max Rooms) in the hotel.
int alarm_locs[Max_Rooms]; // an array variable to store the locations of activated fire
alarms at all rooms(Max Rooms) in the hotel.
int neighbor_alarms[Max_Rooms][10] ; // a multi-dimensional array variable to store
neighbouring alarms of a fire detector. Each detector have 10 neighboring alarms.
int sprinkler[Max_Rooms]; // an array variable to store information of sprinklers
installed at all rooms.

*note: Since there are many rooms, fire detectors, alarms, sprinklers, corresponding data needs
to store in array variables.

2. HIGH LEVEL FUNCTIONS


interrogate_detectors() // a function to check the status of detectors
get_detectorLocatation() // a function to get location of currently activated fire detectors
determine_neighbour_alarm() // a function to identify neighboring alarms of currently
activated detectors
determine_neighbour_sprinklers() // a functions to identify sprinklers near activated fire
detector
ring_alarm() // function to activate alarms near activated fire detectors.
activate_Sprinkler() //function to activate identified sprinklers neighboring to activated fire
detectors
reset_alarm() //function to reset alarms after fire has been handled
reset_sprinkler() //function to reset sprinklers

Object Oriented Programming


• First identify the classes required in the system.
• Then for each class, identify member variables(attributes) and member functions(operations)
• In case of an Automated Fire Alarm System using OOP, following are the
• Classes: detector, alarm, sprinkler
• List Members of each class
1. class Detector
attributes(variables): status, location, neighbors
operations(functions): create, senseStatus, getLocation, findNeighbors
2. class Alarm
attributes(variables): location, status
operations(functions): create, ringAlarm, getLocation, findNeighbor, resetAlarm
3. class Sprinkler
attributes(variables): status, location

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


operations(functions): create, activateSprinkler, getLocation resetSprinkler

6. Explain the need of UML. What are the advantages?


Answer
• UML stands for Unified Modeling Language.
• It is a general-purpose modeling language used for developing object oriented softwares.
• Includes several graphical notations that drives the software development task and can be
through out the software development lifecycle.
• Following are the advantages of using UML:
1. Enhances communication and collaboration between Project team members: It contains
standard design information which can be shared among developers.
2. Provides a Better understanding of the system requirements, relation between various
entities, operations, data and workflow.
3. Unifies design by providing a standard way to design software and systems.
4. Saves time since during development and testing UML Diagrams acts as a reference.
7. How classes are represented in a class diagram. Show the representation of Student class.
Answer
• Foremost, a class consist of member variables and member functions.
• UML class representation must include the list of these members inside a Rectangle box as
shown:
ClassName

Member Variables

Member Functions

• A Student class can be represented as follows:


Student

+name : String
+rn : int
+rank : int
- fees : long
+ displayDetails(n:String, r: int) : void
+displayRank( ra:int): void
• Inside the box First row represents class name
• Second row represents member variables listed as
access_specifier var_name : datatype
• Third row represents member functions
access_specifier function_name(para1:type, para2:type…): returntype
• Access specifier + (public), -(private), *(protected)

8. Draw a use case diagram for Online Music Player

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


Answer
• For drawing an use case diagram first and foremost identify the actors (users)who are going
to interact with the system:
In the case of Online Music Player, following are the actors: Listeners, Admin
• Now Identify various usecases (operations) associated with each user
Listeners: Login, SearchMusic, PlayMusic, Stop, ChangeSettings
Admin: Login, ManageUser, ManageSongs

LOGIN

SEARCH

MANAGE
USER
PLAY

MANAGE
SONGS
STOP

CHANGE

9. Explain Java Runtime Environment and Programming Environment


Answer
• Java runtime environment (JRE) is a set of components used to create and run Java
Applications.
• JRE is a part of Java Development Kit (JDK).
• JRE consists of 3 components: Class Loader, Java Class Libraries and JVM.
• JRE runs on top of OS to provide additional Java Specific resources.
• The components of JRE works together to provide an environment for Java application
development and deployment.

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


• JRE acts as a translator and facilitator, so that Java programs are portable from one system to
another without modifications.
• Java Class libraries contains predefined functions that can be called whenever required.
• Class Loader connects Class Libraries and JVM by loading the required libraries to JVM.
• JVM is the part that executes the code.
• Java Programming Environment consist of a programming language, API Specification and a
Virtual Machine.
10. Explain ByteCodes and JVM.
11. Why java is Platform Independent? Give reasons.
12. Why Java programs are called WORA (Write Once Run Anywhere)
Answer
• Bytecode and JVM in Java is the reason java is platform-independent.
• Bytecodes are generated in .class format when a program is successfully compiled for the first
time.
• It is the instruction set for Java Virtual Machine (JVM).
• When a Java program is executed, the compiler compiles
that piece of code and a Bytecode is generated for each
method in that program in the form of a .class file.
• We can run this bytecode on any other platform as well.
But the bytecode is a non-runnable code that requires or
relies on an interpreter. This is where JVM plays an
important part.
• The bytecode generated after the compilation is run by the
Java virtual machine. Resources required for the execution
are made available by the Java virtual machine for smooth
execution which calls the processor to allocate the
resources.
• JVM (Java Virtual Machine) acts as a run time engine to run Java based applications. It is the
part that invokes main function of a Java Program.
• Java applications are called WORA (Write Once Run Anywhere). This means a programmer
can develop Java code on one system and can expect it to run on any other Java-enabled
system without any adjustment. This is all possible because of JVM.
• When we compile a .java file, .class files (contains byte-code) with the same class names
present in .java file are generated by the Java compiler.

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


13. Explain different Java Development Platforms
Answer

There are three platforms of the Java programming language:


• Java Platform, Standard Edition (Java SE)
• Java Platform, Enterprise Edition (Java EE)
• Java Platform, Micro Edition (Java ME)
• All Java platforms consist of a Java Virtual Machine (VM) and an application programming
interface (API). The Java Virtual Machine is a program, for a particular hardware and
software platform, that runs Java applications. An API is a collection of software
components that you can use to create other software components or applications.
• Standard Edition (Java SE): Java SE’s API offers the Java programming language’s core
functionality. It defines all the basis of type and object to high-level classes. It is used for
networking, security, database access, graphical user interface (GUI) development, and
XML parsing.
• Enterprise Edition (Java EE): The Java EE platform offers an API and runtime
environment for developing and running highly scalable, large-scale, multi-tiered, reliable,
and secure network applications.
• Micro Edition (Java ME): The Java ME platform offers an API and a small-footprint
virtual machine running Java programming language applications on small devices, like
mobile phones.

14. Explain Java Applets


15. Compare Java Applets and Standalone Java Applications
Answer
Java Applications
• They are normal java programs that require a main () function.
• Have full access to local storage.
• Trusted by OS.
• For execution a web browser isn’t required
Example:
class Sample
{
public static void main(String args[])
{

}
}
Java Applets
• Applets are programs that can be embedded in an HTML website.
• It runs inside a web browser and requires an extension of JDK to be installed in the browser
for execution.
• Doesn’t have full access to local storage, can’t read and write without permission.
• It doesn’t require a main() method for its execution.
• A java applet program consist of following functions: init(), start() and paint().

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


Example:

import java.applet.Applet;
import java.awt.Graphics;
// importing necessary packages
public class SampleApplet extends Applet //class must extend Applet class in java
{
public void paint(Graphics g) // paint function includes all graphics related operations
{
// printing the message using drawString() method
// other parameters are of the position
g.drawString("Java Applet", 250, 250);
}
}
16. Explain Java Buzzwords. (Properties of Java Programming Language)
Answer
• Object oriented - Java provides the basic object technology of C++ with some enhancements
and some deletions.
• Architecture neutral - Java source code is compiled into architecture-independent object code.
The object code is interpreted by a Java Virtual Machine (JVM) on the target architecture.
• Portable - Java implements additional portability standards. For example, ints are always 32-
bit, 2's-complemented integers. User interfaces are built through an abstract window system
that is readily implemented in Solaris and other operating environments.
• Distributed - Java contains extensive TCP/IP networking facilities. Library routines support
protocols such as HyperText Transfer Protocol (HTTP) and file transfer protocol (FTP).
• Robust - Both the Java compiler and the Java interpreter provide extensive error checking. Java
manages all dynamic memory, checks array bounds, and other exceptions.
• Secure - Features of C and C++ that often result in illegal memory accesses are not in the Java
language. The interpreter also applies several tests to the compiled code to check for illegal
code. After these tests, the compiled code causes no operand stack over- or underflows,
performs no illegal data conversions, performs only legal object field accesses, and all opcode
parameter types are verified as legal.
• High performance - Compilation of programs to an architecture independent machine-like
language, results in a small efficient interpreter of Java programs. The Java environment also
compiles the Java bytecode into native machine code at runtime.
• Multithreaded - Multithreading is built into the Java language. It can improve interactive
performance by allowing operations, such as loading an image, to be performed while
continuing to process user actions.
• Dynamic - Java does not link invoked modules until runtime.
• Simple - Java is similar to C++, but with most of the more complex features of C and C++
removed.

17. Explain Object Oriented Concepts.


Answer

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


1. Classes: Class is a collection of objects that share common traits. It can be used as a template for
creating the objects. Class consists of member variables and methods that are common to all objects of
that class. Member variables represents data associated with the objects and methods corresponds to
operations that can be carried out by the objects.

Eg: Consider a Student class.

- Member variables associated with Student class are: name, rollno, marks, rank, fees…
- Methods associated with Student class are: displayDetails(), payFees() etc…

2. Objects: Instance of a class. All objects belonging to a class share common variables and methods.
However the values of variables differ across objects.
Eg: In a Student class, objects will be different students say stud1, stud2, stud3…..All these objects
have name, rollno, marks, rank and fees that may contain different values. In addition all these objects
can perform the operations displayDetails(), payFees() defined in class Student.
3. Encapsulation: Wrapping up of data and methods into a single entity. The only way to access data
is through methods.
DATA
METHODS

Teachers Employee
int tid displayDetails()
String name, designation
void displayDetsils()

In the above example Employee class is trying to access the Teachers data through the member method
displayDetails() of class Teachers. It is possible because the data and methods of classes are wrapped
as a single entity by means of encapsulation.

4. Inheritance: It is a process by which object of one class inherit the properties of objects of another
class. It is the capability to define a new class in terms of an existing class. The existing class or Parent
class is known as a base class or super class and the new class or child class is known as derived class
or sub class. Inheritance supports code reusability.

Example : Consider a parent class named Vehicle and its members as given in the figure.

• Vehicle is a class having member variables String reg_no, model, color, int
fuel_capacity and member functions void vehicleDetails(), void fillfuel() and void
calculateSpeed().

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


• Two subclasses of the class Vehicle are created Car and Bus. The subclasses will inherit
the member variables and functions of Vehicle class. Car and Bus can have their own
member variables as shown in the figure.

5. Abstraction: Abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or interfaces. Its main
goal is to handle complexity by hiding unnecessary details from the user. That enables the user to
implement more complex logic on top of the provided abstraction without understanding or even
thinking about all the hidden complexity.

Two types of Abstraction:

When the object data is not visible to the outer world, it creates
data abstraction. If needed, access to the Objects’ data is
provided through some methods. In the example member
variables of the class are private members limiting the access
of data within the class.

When we hide the internal implementation of the different


functions involved in a user operation, it creates process
abstraction. In the example, several functions are private
members, thus hiding the implementation details from outside
world.

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


6. Polymorphism: An object or reference basically can take multiple forms in different instances. As
the word suggests, ‘poly’ means ‘many’ and ‘morph’ points at ‘forms’; thus, polymorphism as a whole
would mean ‘a property of having many forms.’

There are two types of polymorphism

• Dynamic Polymorphism
• Static Polymorphism

In Dynamic polymorphism, the object creation is done at run-time the form of method which should
be executed (the method in the object) can be only decided at run-time. Method Overriding is a type of
Dynamic polymorphism or Run Time Polymorphism. In method overriding, when functions of same
signature is used in both parent and child, the function of superclass will be overridden by the subclass
method.

In Static Polymorphism, method overloading happens. Method overloading is having more than one
method with the same method name but with different arguments (return type may or may not be same).
Here when calling the methods compiler compiler choose which method to call depending on the
parameters passed when calling. This happens at compile-time

18. Explain comments in Java.


19. What are the uses of comments? Explain different types of comments.
Answer
Comments can be used to explain Java code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.

Types: Single Line, Multi Line Comments & Documentation Comments

A Single-line comment starts and ends in the same line. To write a single-line comment, we can use
the // symbol. For example,

// "Hello, World!" program example

class Main
{
public static void main(String[] args)
{
// prints "Hello, World!"
System.out.println("Hello, World!");
}
}

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


The Java compiler ignores everything from // to the end of line. Hence, it is also known as End of
Line comment.

Multi Line Comments: When we want to write comments in multiple lines, we can use the multi-
line comment. To write multi-line comments, we can use the /*....*/ symbol. For example,

/* This is an example of multi-line comment.

* The program prints "Hello, World!" to the standard output.

*/

class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

This type of comment is also known as Traditional Comment. In this type of comment, the Java
compiler ignores everything from /* to */.

Documentation Comments: This type of comment is used to produce an HTML file that documents
your program. The documentation comment begins with a /** and ends with a */ .

20. Explain various lexical issues in Java Programming Language.


Answer
• These are the atomic elements in a java program.
• Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
• Whitespace : Java is a free-form language. This means that you do not need to follow any
special indentation rules. In Java, whitespace is a space, tab, or newline. A program could be
written all on one line or in any other way, as long as there was at least one whitespace character
between each token that was not already delineated by an operator or separator.
• Identifiers: Identifiers are used to name things, such as classes, variables, and methods. An
identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters. They must not begin with a number. Again, Java is case-
sensitive, so VALUE is a different identifier than Value. Some examples of valid identifiers are

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


• Literals: A constant value in Java is created by using a literal representation of it. For example,
here are some literals:

• Comments: Comments can be used to explain Java code, and to make it more readable. It can
also be used to prevent execution when testing alternative code.

/* This is an example of multi-line comment and Single Line Comment.

* The program prints "Hello, World!" to the standard output.

*/

class HelloWorld {

public static void main(String[] args)

{ // Printing Hello World

System.out.println("Hello, World!");

• Separators: In Java, there are a few characters that are used as separators. The most commonly
used separator in Java is the semicolon.

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


• Keywords: There are 50 keywords currently defined in the Java language. These keywords,
combined with the syntax of the operators and separators, form the foundation of the Java
language. These keywords cannot be used as identifiers. Thus, they cannot be used as names
for a variable, class, or method. The keywords const and goto are reserved but not used. In the
early days of Java, several other keywords were reserved for possible future use.

21. Explain Java Program Structure with example.


Answer
import packages; // import the required packages

public class ClassName

public static void main ( String args[ ] )

// program body

• All java programs are enclosed within a class.


• We can define multiple classes in a single program.
• class is the keyword used to create a class.
• Syntax: class ClassName

…………….

- ClassName of class must begin with uppercase alphabet.

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in


• Save the program in the name of the class which contains the void main( ) function with .java
extension.

eg: ClassName.java

• Program starts execution from void main() function which is represented as

public static void main( String args[] )

….

- public : It has to be public so that java runtime can execute this method. If you make any
method non-public then it’s not allowed to be executed by any program, there are some access
restrictions applied.
- static : java runtime starts, there is no object of the class present. That’s why the main method
has to be static so that JVM can load the class into memory and call the main method. If the
main method won’t be static, JVM would not be able to call it because there is no object of the
class is present.
- void : Java programming mandates that every method provide the return type. Java main
method doesn’t return anything, that’s why it’s return type is void. This has been done to keep
things simple because once the main method is finished executing, java program terminates. So
there is no point in returning anything, there is nothing that can be done for the returned object
by JVM.
- main : This is the name of java main method. It’s fixed and when we start a java program, it
looks for the main method.
- String args[] : Java main method accepts a single argument of type String array. This is also
called as java command line arguments.

Example:

OOPS-2019 SCHEME DEPARTMENT OF CSE, STIST

Downloaded from Ktunotes.in

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy