Nov Dec 19
Nov Dec 19
Nov Dec 19
2019]
CS8392 – OBJECT ORIENTED PROGRAMMING
Third/Fifth Semester
Part : A
1. What is access specifier?
The access specifiers in Java specify the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by
applying the access modifier on it. There are four access modifiers in java; they are private,
default, public and protected
2. What is Javadoc?
Javadoc is a tool which comes with JDK and it is used for generating Java code
documentation in HTML format from Java source code, which requires documentation in a
predefined format
3. What is object cloning?
Object cloning refers to creation of exact copy of an object. It creates a new instance of the
class of current object and initializes all its fields with exactly the contents of the
corresponding fields of this object.
4. Describe the uses of interfaces in java.
There are mainly three reasons to use interface. They are
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling
5. What is exception handling?
An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. The Exception Handling in Java is one of
the powerful mechanisms to handle the runtime errors so that normal flow of the application
can be maintained.
6. What is the use of assert key word?
Assert is a Java keyword used to define an assert statement. An assert statement is used to
declare an expected boolean condition in a program. If the program is running with assertions
enabled, then the condition is checked at runtime. If the condition is false, the Java runtime
system throws an AssertionError
7. Describe the various states of thread.
New
Runnable
Blocked
Waiting
Timed Waiting
Terminated
8. “Thread is a light weight process” – Comment.
We can say thread is a light weight process. A thread of execution is the smallest sequence
of programmed instructions that can be managed independently by scheduler. Threads reside
inside the process. Each thread belongs to exactly one process. No thread exists outside the
process
9. Write the code segment to handle two mouse events.
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
10. What are the purposes of JPanel?
The JPanel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the JComponents class. The main task of JPanel is to
organize components, various layouts can be set in JPanel which provide better organisation of
components, however it does not have a title bar.
Part : B
11. a. Explain the various features in java in details
The prime reason behind creation of Java was to bring portability and security feature into a
computer language. Beside these two major features, there were many other features that
played an important role in moulding out the final form of this outstanding language. Those
features are :
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to
understand.The confusing and ambiguous concepts of C++ are either left out in Java
or they have been re-implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important
part of C++.
2) Object Oriented
In java everything is Object which has some data and behaviour. Java can be easily
extended as it is based on Object Model.
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile
time error checking and runtime checking. But the main areas which Java improved
were Memory Management and mishandled Exceptions by introducing automatic
Garbage Collector and Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into
platform specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide
security. Any machine with Java Runtime Environment can run Java Programs.
5) Secure
When it comes to security, Java is always the first choice. With java secure features
it enable us to develop virus free, temper free system. Java program always runs in
Java runtime environment with almost null interaction with system OS, hence it is more
secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other
resources to execute multiple threads at the same time, like While typing, grammatical
errors are checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language
like C or C++. But, Java enables high performance with the use of just-in-time
compiler.
OR
b. What is JVM? Explain the internal architecture of JVM with neat sketch.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
It is:
1. A specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its implementation has
been provided by Oracle and other companies.
2. An implementationIts implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to
run the java class, an instance of JVM is created.
The JVM performs following operation:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
Class Loader Subsystem
It is mainly responsible for three activities.
• Loading
• Linking
• Initialization
Loading : The Class loader reads the .class file, generate the corresponding binary
data and save it in method area. For each .class file, JVM stores following information
in method area.
• Fully qualified name of the loaded class and its immediate parent class.
• Whether .class file is related to Class or Interface or Enum
• Modifier, Variables and Method information etc.
After loading .class file, JVM creates an object of type Class to represent this file in the heap
memory. Please note that this object is of type Class predefined in java.lang package. This
Class object can be used by the programmer for getting class level information like name of
class, parent name, methods and variable information etc. To get this object reference we can
use getClass() method of Object class.
12. a. Explain in detail about various types of inheritance in java with neat diagram
Inheritance can be defined as the procedure or mechanism of acquiring all the properties and
behavior of one class to another, i.e., acquiring the properties and behavior of child class from
the parent class. This concept was built to achieve the advantage of creating a new class that
gets built upon an already existing class(es). It is mainly used for code reusability within a
Java program
Java supports three types of inheritance
1. single inheritance
2. multilevel inheritance
3. hierarchical inheritance
Single Inheritance
When a single class gets derived from its base class, then this type of inheritance is
termed as single inheritance. The figure drawn above has class A as the base class,
and class B gets derived from that base class
classA {
publicString meth() {
return"A's Method";
}
}
classB extendsA {
publicString meth() {
return"B's Method";
}
publicString meth2() {
return"B's Method2";
}
}
publicclassSingleInheritanceDemo {
publicstaticvoidmain(String[] args) {
B b = newB();
System.out.println("B : "+ b.meth());
}
}
Multi-level Inheritance
In this type of inheritance, a derived class gets created from another derived class and
can have any number of levels
classA {
publicString meth() {
return"A's Method";
}
}
classB extendsA {
publicString meth() {
return"B's Method";
}
}
classC extendsB {
publicString meth1() {
return"C's Method";
}
}
publicclassMultiLevelInheritanceDemo {
publicstaticvoidmain(String[] args) {
A a = newC();
System.out.println("A: "+ a.meth());
}
}
Hierarchical Inheritance
In this type of inheritance, there are more than one derived classes which get created
from one single base class
classA {
publicString meth() {
return"A's Method";
}
}
classB extendsA {
publicString meth() {
return"B's Method";
}
}
classC extendsA {
publicString meth2() {
return"C's Method";
}
}
publicclassHierarchicallInheritanceDemo {
publicstaticvoidmain(String[] args) {
A a = newC();
System.out.println("C's A : "+ a.meth());
B b = newB();
System.out.println("B's B : "+ b.meth());
}
}
OR
b. What is an abstract class? Illustrate with an example to demonstrate abstract class
A class that is declared using “abstract” keyword is known as abstract class. It can have
abstract methods(methods without body) as well as concrete methods (regular methods with
body). A normal class(non-abstract class) cannot have abstract methods.
An abstract class can not be instantiated, which means you are not allowed to create an
object of it
// An example abstract class in Java
abstractclassShape {
intcolor;
classDerived extendsBase { }
classMain {
publicstaticvoidmain(String args[]) {
Derived d = newDerived();
d.fun();
}
}
Abstract classes can also have final methods (methods that cannot be overridden).
abstractclassBase {
finalvoidfun() { System.out.println("Derived fun() called"); }
}
classDerived extendsBase {}
classMain {
publicstaticvoidmain(String args[]) {
Base b = newDerived();
b.fun();
}
}
Multitasking is when a single CPU performs several tasks (program, process, task, threads) at
the same time. To perform multitasking, the CPU switches among theses tasks very frequently
so that user can interact with each program simultaneously.
The basic difference between multitasking and multithreading is that in multitasking, the system
allows executing multiple programs and tasks at the same time. In multitasking CPU has to
switch between multiple programs so that it appears that multiple programs are running
simultaneously. Multitasking allocates separate memory and resources for each process/program
whereas, in multithreading threads belonging to the same process shares the same memory
and resources as that of the process.
OR
b. What is synchronization? Explain the different types of synchronization in java
At times when more than one thread try to access a shared resource, we need to ensure
that resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization. Synchronized keyword in java create a critical section in
which a lock is associated with the object . To enter the critical section a thread need to
obtain the object lock. The general form of synchronized is as follows
synchronized(object){
statement;
}
There are basically two types of synchronization available. They are:
1. Process Synchronization: The simultaneous execution of multiple threads or
processes to reach a state such that they commit to a certain sequence of actions.
2. Thread Synchronization: At times when more than one thread tries to access a
shared resource, you need to ensure that resource will be used by only one thread
at a time.
In JAVA we have two types of synchronization techniques. They are synchronized methods and
synchronized blocks.
1. Synchronized methods:
If any method is sharable for 'n' number of threads then make the method as synchronized by using a
keyword synchronized.
In JAVA we have two types of synchronized methods. They are synchronized Instance methods and
synchronized static methods.
Synchronized Instance methods: If the ordinary instance method is made it as synchronized then the
object of the corresponding class will be locked.
class Account {
intbal = 0;
15. a. Describe in detail about the different layouts in java GUI. Which layout is the default
one?
Layouts tell Java where to put components in containers (JPanel, content pane, etc).
Every panel (and other container) has a default layout, but it's better to set the layout
explicitly for clarity. Create a new layout object (using one of its constructors) and use
the container's setLayout method to set the layout.
Flow Layout - left to right, top to bottom. Good for initial testing. FlowLayout does not
respect preferred size information, so it may make variable size elements (eg, a
graphics panel) extremely small.
Border Layout - north, east, south, west, and center areas. Has various rules for how
components are stretched to fit these areas. Both common and useful.
Grid Layout - equal sized grid elements.
Box Layout and Boxes - horizontal or vertical sequence of components.
Grid Bag Layout - unequal sized grid. Can produce excellent results, but can be
difficult to use.
SpringLayout was added in Java 1.4, but is difficult for humans. It is rumored to be
intended for authomatic layout programs..
CardLayout is good for something like a wizard interface which shows one of several
possible layouts (think about a stack of index cards). Tabbed panes are something like
a card layout with tabs.
OR
b. Discuss mouse listener and mouse motion listener. Give an example program
MouseListener and MouseMotionListener is an interface in java.awt.event package. MouseListener
handles the events when the mouse is not in motion. While MouseMotionListenerhandles the
events when mouse is in motion
There are five types of events that MouseListener can generate. There are five
abstract functions that represent these five events. The abstract functions are :
1. void mouseReleased(MouseEvent e) : Mouse key is released
2. void mouseClicked(MouseEvent e) : Mouse key is pressed/released
3. void mouseExited(MouseEvent e) : Mouse exited the component
4. void mouseEntered(MouseEvent e) : Mouse entered the component
5. void mousepressed(MouseEvent e) : Mouse key is pressed
There are two types of events that MouseMotionListener can generate. There are two
abstract functions that represent these five events. The abstract functions are :
1. voidmouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in
the component and dragged. Events are passed until the user releases the mouse
button.
2. voidmouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from
one point to another within the component, without pressing any mouse buttons.
importjava.awt.*;
importjava.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
newMouseListenerExample();
}
}
importjava.awt.*;
importjava.awt.event.*;
public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
importjava.util.*;
classTwoArray{
public static void main(String[] args){
int[][] array=new int[5][5];
Scanner scan=new Scanner(System.in);
int size=scan.nextInt();
for(inti=0;i<size;i++){
for(int j=0;j<size;j++){
array[i][j]=scan.nextInt();
}
}
System.out.println("Array Elements are");
for(inti=0;i<size;i++){
for(int j=0;j<size;j++){
System.out.println(array[i][j]+" ");
}
System.out.println();
}
int small=array[0][0];
for(inti=0;i<size;i++){
for(int j=0;j<size;j++){
if(array[i][j]<small){
small=array[i][j];
}
}
}
System.out.println("smallest is:"+small);
}
}
OR
b. Create a simple real life application program in java to illustrate the use of multithreads.
importjava.util.ArrayList;
public Bank(intaccountsCount) {
accounts = new ArrayList<Account>();
for (inti = 0; i<accountsCount; i++) {
accounts.add(new Account(i));
}
}
@Override
public String toString() {
return "Account " + number + " balance: " + balance;
}
}
@Override
public String toString() {
return name;
}
}
importjava.util.Random;
importjava.util.logging.Level;
importjava.util.logging.Logger;
privateintrandAmount() {
return (new Random()).nextInt((RAND_MAX_AMOUNT - RAND_MIN_AMOUNT) + 1)
+ RAND_MIN_AMOUNT;
}
privateintrandSleepTime() {
return (new Random()).nextInt((RAND_MAX - RAND_MIN) + 1) + RAND_MIN;
}
@Override
public void run() {
for (inti = 0; i< CLIENT_ITERATIONS; i++) {
Account acc = bank.getRandomAccount();
clientWork();
acc.withdraw(client, randAmount());
clientWork();
acc.deposit(client, randAmount());
}
System.out.println("#Account balance: " + Account.getBalance());
}
}