Ans Key ND20
Ans Key ND20
PART-A
1 Define Encapsulation in Java.
The wrapping up of data and functions into a single unit is known as data encapsulation.
Here the data is not accessible to the outside the class. The data inside that class is accessible
by the function in the same class. It is normally not accessible from the outside of the
component
2 What is Constructors in Java?
A constructor is a special method that is used to initialize an object. The name of the
constructor and the name of the class must be the same. A constructor does not have any
return type.
There are two types of Constructor
Default Constructor – constructor without argument
Parameterized constructor – constructor with arguments
3 What is the use of super keyword?
This is used to initialize constructor of base class from the derived class and also access the
variables of base class like super.i = 10.
4 Difference between class and interface.
Class and Interface both are used to create new reference types. A class is a collection of fields
and methods that operate on fields. An interface has fully abstract methods i.e. methods with
nobody. An interface is syntactically similar to the class but there is a major difference
between class and interface that is a class can be instantiated, but an interface can never be
instantiated.
5 What is the purpose of finally clause? Give example.
The finally clause is used to provide the capability to execute code no matter whether or not
an exception is thrown or caught.
class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute even if there is no exception in try block */
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
6 What are the uses of streams? What are the two types of streams?
Java provides I/O Streams to read and write data where, a Stream represents an input source
or an output destination which could be a file, i/o devise, other program etc.
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 1 of 17
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
In general, a Stream will be an input stream or, an output stream.
InputStream − This is used to read data from a source.
OutputStream − This is used to write data to a destination.
The Stream API is used to process collections of objects. A stream is a sequence of objects that
supports various methods which can be pipelined to produce the desired result.
7 What is the need for synchronization? How it can be implemented?
Synchronization is a process of handling resource accessibility by multiple thread requests.
The main purpose of synchronization is to avoid thread interference. 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. If we do not use synchronization, and let two or more threads access a
shared resource at the same time, it will lead to distorted results.
Consider an example, Suppose we have two different threads T1 and T2, T1 starts execution
and save certain values in a file temporary.txt which will be used to calculate some result
when T1 returns. Meanwhile, T2 starts and before T1 returns, T2 change the values saved by
T1 in the file temporary.txt (temporary.txt is the shared resource). Now obviously T1 will
return wrong result. To prevent such problems, synchronization was introduced.
8 How to create a single class, which automatically works with different types of data? Give
example. (Nov/Dec 2020)(Apr/May 2021)
A Wrapper class is a class whose object wraps or contains primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store primitive
data types. In other words, we can wrap a primitive value into a wrapper class object. They
convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method.
Example:
1. //Autoboxing example of int to Integer
2. public class WrapperExample1{
3. public static void main(String args[]){
4. //Converting int into Integer
5. int a=20;
6. Integer i=Integer.valueOf(a);//converting int into Integer explicitly
7. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
8. System.out.println(a+" "+i+" "+j);
9. }}
10. Output:
20 20 20
9 Write the sequence in which method calls takes place when an applet is terminated?
Define those methods.
When an applet is terminated, the following sequence of method calls takes place :
stop()
destroy()
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
stop( ) method is called when a web browser leaves the HTML document containing the
applet—when it goes to another page, for example. When stop( ) is called, the applet is
probably running. You should use stop( ) to suspend threads that don't need to run when the
applet is not visible.
destroy() method is called by the browser just before an applet is terminated. Your applet will
override this method if it needs to perform any cleanup prior to its destruction. A subclass of
Applet should override this method if it has any operation that it wants to perform before it
is destroyed.
10 What are the two key features of swing?
Swing offers two key features:
Swing components are lightweight and don't rely on peers.
Swing supports a pluggable look and feel.
PART B –(5*13=65 marks)
11 a How Java changed the internet? ii) If semicolons are needed at the end of each statement, why
does the comment line not end with a semicolon ?
The Internet helped catapult Java to the forefront of programming, and Java, in turn, had a profound
effect on the Internet. In addition to simplifying web programming in general, Java innovated a new
type of networked program called the applet that changed the way the online world thought about
content. Java also addressed some of the thorniest issues associated with the Internet: portability and
security.
Semicolon is a punctuation mark (;) indicating a pause, typically between two main clauses, that is ore
pronounced than that indicated by a comma. In programming, Semicolon symbol plays a vital role. It
is used to show the termination of instruction in various programming languages as well, like C, C++,
Java, JavaScript and Python.
Role of Semicolon in Java:
1. Java uses Semicolon similar to C.
2. Semicolon is a part of syntax in Java.
3. It shows the compiler where an instruction ends and where the next instruction begins.
4. Semicolon allows the java program to be written in one line or multiple lines, by letting the
compiler know where to end the instructions.
Comments are used in a programming language to document the program and remind programmers
of what tricky things they just did with the code, or to warn later generations of programmers stuck
with maintaining some spaghetti code. While comments may seem to be a minor issue in a language,
an awkward comment format in a language is a nuisance and can be a source of nasty errors. The
content of a comment is handled as if it were not there by the compiler. Examples of modern-day
comments are:
11 b What are the three categories of control statements used in Java? Explain each category with
example.
Control Statements in Java
Java provides us control structures, statements that can alter the flow of a sequence of instructions.
Compound statements
Compound statements or block is a group of statements which are separated by semicolons (;) and
grouped together in a block enclosed in braces { and } is called a compound statement.
Example:
{
temp = a;
a = b;
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
b = temp;
}
Types of control statements
Java supports two basic control statements.
Selection statements
Iteration statements
Selection statements
This statement allows us to select a statement or set of statements for execution based on some
condition.
The different selection statements are:
if statement
if-else statement
nested statement
switch statement
if statement
This is the simplest form of if statement. This statement is also called as one-way branching. This
statement is used to decide whether a statement or a set
of statements should be executed or not. The decision is based on a condition which can be evaluated
to TRUE or FALSE.
Syntax:
if(expression)
Statement;
if–else statement
This statement is also called as two-way branching. It is used when there are alternative statements
need to be executed based on the condition. It executes some set of statements when the given
condition is TRUE and if the condition is FALSE then other set of statements to be executed.
Syntax:
if(expression)
Statement;
else
Statement;
Nested-if statement
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
An if statement may contain another if statement within it. Such an if statement is called as nested if
statement.
Syntax:
if(condition1)
Statement
If(condition2)
Statement
if-else-if statement
This structure is also called as else-if ladder. This structure will be used to verify a range of values. This
statement allows a choice to be made between different possible alternatives.
Syntax:
if(condition)
Statement;
else if (condition)
Statement;
.
.
else
Statement;
Switch statement
Java has a built-in multiple-branch selection statement, switch. This successively tests the value of an
expression against a list of integer or character constants. When a match is found, the statements
associated with that code is executed.
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
12 a Write a Java program to calculate electricity bill using inheritance. The program should get the
inputs of watts per hour and unit rate. Check your program for the following case : Assume a
consumer consumes 5000 watts per hour daily for one month. Calculate the total energy bill of
that consumer if per unit rate is 7 [1 unit = 1k Wh].
import java.util.*;
class ComputeElectricityBill {
// Driver Code
public static void main(String args[])
{
int units = 250;
System.out.println(
calculateBill(units));
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
}
}
12 b What is interface? With an example explain how to define and implement interface.
An interface in java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and multiple
inheritance in Java. Java Interface also represents the IS-A relationship. It cannot be
instantiated just like the abstract class
There are mainly three reasons to use interface. They are
An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax :
interface <interface_name> {
// declare constant fields
// declare methods that abstract
// by default.
}
Example
interface MyInterface{
public void method1();
public void method2();
}
class Demo implements MyInterface{
public void method1() {
System.out.println("implementation of method1");
}
public void method2() {
System.out.println("implementation of method2");
}
public static void main(String arg[]) {
MyInterface obj = new Demo();
obj.method1();
}
}
Output:
implementation of method1
An interface declared within another interface or class is known as nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred by the outer interface or class. It can't be accessed directly.
Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class. Nested interfaces are declared static implicitely.
Example
interface MyInterfaceA{
void display();
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
interface MyInterfaceB{
void myMethod();
}
}
class NestedInterfaceDemo1 implements MyInterfaceA.MyInterfaceB{
public void myMethod(){
System.out.println("Nested interface method");
}
public static void main(String args[]){
MyInterfaceA.MyInterfaceB obj= new NestedInterfaceDemo1();
obj.myMethod();
}
}
Output:
Nested interface method
13 a Write a short note on the following topics :
a) Uncaught exceptions.
b) Difference between throw and throws. Give example for both.
c) Chained exceptions. Give example
13 b How to perform reading and writing files? Explain with example.
i. reading from a file
Java FileWriter and FileReader classes are used to write and read data from text files (they are
Character Stream classes). It is recommended not to use the FileInputStream and
FileOutputStream classes if you have to read and write any textual information as these are
Byte stream classes.
FileReader is useful to read data in the form of characters from a ‗text‘ file.
• This class inherit from the InputStreamReader Class.
• The constructors of this class assume that the default character encoding and the
default byte-buffer size are appropriate. To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
• FileReader is meant for reading streams of characters. For reading streams of raw
bytes, consider using a FileInputStream.
importjava.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReaderfr=new FileReader("D:\\testout.txt");
inti;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
ii. writing in a file
FileWriter is useful to create a file writing characters into it. This class inherits from the
OutputStream class. The constructors of this class assume that the default character encoding
and the default byte-buffer size are acceptable. To specify these values yourself, construct an
OutputStreamWriter on a FileOutputStream.FileWriter is meant for writing streams of
characters. For writing streams of raw bytes, consider using a FileOutputStream. FileWriter
creates the output file , if it is not present already
importjava.io.FileWriter;
public class FileWriterExample {
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
public static void main(String args[]){
try{
FileWriterfw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
14 a Discuss the different states of thread in detail.
The following figure shows the states that a thread can be in during its life and illustrates
which method calls cause a transition to another state.
14 b i) What is the purpose of thread priorities? What are the different thread priorities that exist?
What are bounded types? Why it is used? Give example.
In a Multi threading environment, thread scheduler assigns processor to a thread based on
priority of thread. Whenever we create a thread in Java, it always has some priority assigned
to it. Priority can either be given by JVM while creating the thread or it can be given by
programmer explicitly.
Accepted value of priority for a thread is in range of 1 to 10. There are 3 static variables
defined in Thread class for priority.
public static int MIN_PRIORITY: This is minimum priority that a thread can have. Value for
this is 1.
public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly
define it. Value for this is 5.
public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this is 10.
Get and Set Thread Priority:
1. public final int getPriority(): java.lang.Thread.getPriority() method returns priority of
given thread.
2. public final void setPriority(int newPriority): java.lang.Thread.setPriority() method
changes the priority of thread to the value newPriority. This method throws
IllegalArgumentException if value of parameter newPriority goes beyond minimum(1)
and maximum(10) limit.
Bounded Type Parameters
There may be times when you want to restrict the types that can be used as type arguments in
a parameterized type. For example, a method that operates on numbers might only want to
accept instances of Number or its subclasses. This is what bounded type parameters are for.
Sometimes we don‘t want whole class to be parameterized, in that case we can create
java generics method. Since constructor is a special kind of method, we can use generics
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
type in constructors too.
Suppose we want to restrict the type of objects that can be used in the parameterized type.
For example in a method that compares two objects and we want to make sure that the
accepted objects are Comparables.
The invocation of these methods is similar to unbounded method except that if we will try
to use any class that is not Comparable, it will throw compile time error.
15 a List any five different user interface components that can generate the events. Demonstrate
any four mouse event handlers with example.
Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page are the activities that causes
an event to happen.
Types of Event
The events can be broadly classified into two categories:
Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in Graphical
User Interface. For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires,
an operation completion are the example of background events.
Event Handling is the mechanism that controls the event and decides what should happen if n
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events. Let's have a brief
introduction to this model.
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provides classes for source object.
Listener - It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener waits
until it receives an event. Once the event is received , the listener process the event an then
returns.
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 11 of 17
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
setSize(250, 100); // "super" Frame sets initial size
setTitle("AWT Counter"); // "super" Frame sets title
setVisible(true); // show "super" Frame
}
/Person Class
public class Person {
// Attributes
private int id;
private String firstName;
private String lastName;
// Constructor
public Person(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
// Getters
public int getId() {
return id;
}
// Setters
public void setId(int id) {
this.id = id;
}
import java.util.List;
System.out.println("Results: ");
if (results.size() != 0) {
for (Person p : results) {
System.out.println(p);
}
} else {
System.out.println("No person matched");
}
System.out.println("Results: ");
if (results.size() != 0) {
for (Person p : results) {
System.out.println(p);
}
} else {
System.out.println("No person matched");
}
System.out.println("Results: ");
if (results.size() != 0) {
for (Person p : results) {
System.out.println(p);
}
} else {
System.out.println("No person matched");
}
}
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
}
Output Of Code: