CST 205 - OOP Using Java
CST 205 - OOP Using Java
PART A
Answer all questions. Each question carries 3 marks
Marks
Byte code implementation makes java a platform independent language.Byte code is a machine
code for JVM.Byte code is a machine independent language.It is an intermediate code that is not
completely compiled. The Java compiler generate byte code for JVM rather than different machine
code for each type of machine. JVM executes the byte code generated by compiler and produce
output.JVM is the one that makes java platform independent. Java language and Java Virtual
Machine helped in achieving the goal of “write once; run anywhere, any time, forever.” Changes
and upgrades in operating systems, processors and system resources will not force any changes in
Java programs. Java compiler (javac) compiles *.java files to obtain *.class files that contain the
byte codes understood by the JVM.Thus platform independence is achieved.
• When JVM starts up, it creates a heap area which is known as runtime data area. This is where
all the objects (instances of class) are stored.
• Since this area is limited, it is required to manage this area efficiently by removing the objects
that are no longer in use.
• The process of removing unused objects from heap memory is known as Garbage collection and
this is a part of memory management in Java.
• Languages like C/C++ don’t support automatic garbage collection, however in java, the garbage
collection is automatic.
• In java, garbage means unreferenced objects.
• Main objective of Garbage Collector is to free heap memory by destroying unreachable objects.
• Unreachable objects : An object is said to be unreachable iff it doesn’t contain any reference to
it.
• Eligibility for garbage collection : An object is said to be eligible for GC(garbage collection) iff
it is unreachable.
• finalize() method – This method is invoked each time before the object is garbage collected and
it perform cleanup processing.
• The Garbage collector of JVM collects only those objects that are created by new keyword. So
if we have created any object without new, we can use finalize method to perform cleanup
processing.
Request for Garbage Collection
• We can request to JVM for garbage collection however, it is upto the JVM when to start the
garbage collector.
• Java gc() method is used to call garbage collector explicitly.
• However gc() method does not guarantee that JVM will perform the garbage collection.
• It only request the JVM for garbage collection. This method is present in System and Runtime
class.
3) Explain the use of static variable with the help of an example. (3)
When a variable is declared as static, then a single copy of the variable is created and shared among
all objects at the class level. Static variables are, essentially, global variables. All instances of the
class share the same static variable.
Example:
public class StaticKeywordExample {
private static int count = 0; // static variable
public static void printCount() { // static method
System.out.println("Number of Example objects created so far: " + count);
}
}
As you can see above, we declared the count variable as a static variable, while we declared the
printCount method as a static method.
When a variable is declared static in Java programming, it means that the variable belongs to the
class itself rather than to any specific instance of the class. This means that there is only one copy
of the variable in memory, regardless of how many instances of the class are created.
4) Can final modifier be used with an abstract class.?Justify your answer. (3)
No, you cannot make an abstract class or method final in Java because the abstract and final are
mutually exclusive concepts. An abstract class is incomplete and can only be instantiated by
extending a concrete class and implementing all abstract methods, while a final class is considered
complete and cannot be extended further. This means when you make an abstract class final, it
cannot be extended hence it cannot be used and that's why the Java compiler throws a compile-
time error when you try to make an abstract class final in Java. In short, an abstract class cannot
be final in Java, using both abstract and final modifiers with a class is illegal in Java.
5) Differentiate between the usage of keywords throw and throws. (3)
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword.
Example:
Java program to demonstrate the working of throw keyword in exception handling
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions.
If there occurs any unchecked exception such as NullPointerException, it is programmers fault
that he is not performing check up before the code being used.
CLASSPATH is an environment variable (i.e., global variables of the operating system available
to all the processes) needed for the Java compiler and runtime to locate the Java packages/classes
used in a Java program.
7) List any three event sources and their corresponding event types and listeners used.
(3)
An event is an object that describes a state change in a source.The components in user interface
that can generate the events are the sources of the event. A listener is an object that is notified
when an event occurs.
i)Button - Generates action events when the button is pressed.
The ActionListener Interface is invoked when an action event is generated.
This interface defines the actionPerformed( ) method that is invoked when an action event occurs.
Its general form is shown here:
void actionPerformed(ActionEvent ae )
ii)Check box - Generates item events when the check box is selected or deselected.
The ItemListener Interface is invoked when an item event is generated.
This interface defines the itemStateChanged( ) method that is invoked when the state of an item
changes. Its general form is shown here:
void itemStateChanged(ItemEvent ie )
iii)Text components - Generates text events when the user enters a character.
The TextListener Interface is invoked when a text event is generated.
This interface defines the textChanged( ) method that is invoked when a change occurs in a text
area or text field. Its general form is shown here:
void textChanged(TextEvent te )
8) Illustrate the creation of arraylist with the help of a sample program. (3)
Program
import java.util.*;
class JavaExample
{
public static void main(String args[])
{
ArrayList<String> alist=new ArrayList<String>();
alist.add("Steve");
alist.add("Tim");
alist.add("Lucy");
alist.add("Pat");
alist.add("Angela");
alist.add("Tom");
//displaying elements
System.out.println(alist);
//Adding "Steve" at the fourth position
alist.add(3, "Steve");
//displaying elements
System.out.println(alist);
}
}
Output:
[Steve,Tim,Lucy,Pat,Angela,Tom]
[Steve,Tim,Lucy,Steve,Pat,Angela,Tom]
10) What are layout managers? List any two layout managers. (3)
• A layout manager automatically arranges our controls within a window by using some type of
algorithm.
• Each Container object has a layout manager associated with it.
• A layout manager is an instance of any class that implements the LayoutManager interface.
• The layout manager is set by the setLayout( ) method.If no call to setLayout( ) is made, then the
default layout manager is used.
• The setLayout( ) method has the following general form:
void setLayout(LayoutManager layoutObj)
• The layout manager is notified each time we add a component to a container.
• Each layout manager keeps track of a list of components that are stored by their names.
• Whenever the container needs to be resized, the layout manager is consulted via its
minimumLayoutSize( ) and preferredLayoutSize( ) methods.
– Each component that is being managed by a layout manager contains the getPreferredSize() and
getMinimumSize( ) methods.
• Java has several predefined LayoutManager classes,
– FlowLayout
– BorderLayout
– GridLayout
– CardLayout
– GridBagLayout
PART B
Answer any one full question from each module. Each question carries 14 marks
MODULE 1
11) a)Consider the problem of a Service Station which provides three types of services to its
customers: refuelling, vehicle maintenance and parking. Customer can pay using cash, card
or cheque. The pricing for vehicle maintenance depends on the cost of parts and labour.
Parking areas are rented according to weekly and monthly rates. Construct an UML class
diagram for the above problem by identifying atleast six entities in the system which can be
represented using classes and show the relationship between them.
(10)
b) Describe programming structure of Java that deals with the organization of Java
code. (4)
Documentation section
• You can write a comment in this section. It helps to understand the code. These are optional
• It is used to improve the readability of the program.
Package declaration
• It is an optional part of the program, i.e., if you do not want to declare any package, then there
will be no problem with it, and you will not get any errors.
• Package is declared as: package package_name;
Eg: package mypackage;
Import Statement
• If you want to use a class of another package, then you can do this by importing it directly into
your program.
• Many predefined classes are stored in packages in Java
• We can import a specific class or classes in an import statement.
Interface section
• This section is used to specify an interface in Java
• Interfaces are like a class that includes a group of method declarations
• It's an optional section and can be used when programmers want to implement multiple
inheritances within a program.
Class Definition
• A Java program may contain several class definitions.
• Classes are the main and essential elements of any Java program.
• A class is a collection of variables and methods
Software design is a process to transform user requirements into some suitable form, which helps
the programmer in software coding and implementation.
The design process for software systems often has two levels. At the first level the focus is on
deciding which modules are needed for the system on the basis of SRS (Software Requirement
Specification) and how the modules should be interconnected.
Software design is the first step in SDLC (Software Design Life Cycle).It tries to specify how to
fulfill the requirements mentioned in SRS document.
MODULE 2
13)
(a)Write a Java program by creating a ‘Student’ class having the following data
members: rollNumber, name, mathMarks, phyMarks, chemMarks and methods
getRequiredDetails() – to get required input and displayAverage() – to calculate average
marks and display it. In class ‘Implement’ create an object of the Student class and get the
required details from user and display the average marks of that student. (7)
import java.util.Scanner;
class Student{
int rollNumber;
double mathMarks, phyMarks, chemMarks, avg;
String name;
void getRequiredDetails(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter Roll No. of Student");
rollNumber = sc.nextInt();
System.out.println("Enter Name of Student: ");
name = sc.next();
System.out.println("Input marks in Mathematics: ");
mathMarks = sc.nextDouble();
System.out.println("Input marks in Physics: ");
phyMarks = sc.nextDouble();
System.out.println("Input marks in Chemistry: ");
chemMarks = sc.nextDouble();
}
void displayAverage(){
avg=(mathMarks+phyMarks+chemMarks)/3;
System.out.println("Average Mark is : " + avg);
}
}
class Implement{
public static void main(String [] args){
Student st = new Student();
st.getRequiredDetails();
st.displayAverage();
}
}
(b)Write a java program that illustrates how ‘this’ keyword can be used to resolve the
ambiguity between formal parameters and instance variables. (7)
14)
(a) Explain the concept of method overloading with the help of a program. (7)
With method overloading, multiple methods can have the same name with different parameters
● Method overloading is one of the ways that Java supports polymorphism.
● There are two ways to overload the method in java
○ By changing number of arguments
○ By changing the data type
Example:
● Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
● The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.
● When you inherit from an existing class, you can reuse methods and attributes of the parent
class. Moreover, you can add new methods and attributes in your current class also
● Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
● Syntax: The extends keyword indicates that you are making a new class that derives from
an existing class.
○ The meaning of "extends" is to increase the functionality.
○ In the terminology of Java, a class which is inherited is called a parent or superclass,
and the new class is called child or subclass.
Hierarchical Inheritance Example:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
}}
MODULE 3
15)
(a)Write a program to read the first n characters in a file, where n is given by the user. The
characters read from file has to be reversed and displayed on screen. Built in methods can
be used in the program. (7)
import java.io.*;
import java.util.Scanner;
class FileReverse{
public static void main(String [] args) throws IOException{
char [] rev = new char[200];
int k=0,i, n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of Characters: ");
n = sc.nextInt();
FileReader fr = new FileReader("text.txt");
while (( i = fr.read()) != -1 && k!=n){
rev[k] = (char)i;
k++;
}
for(int p=n; p>=0; p--){
System.out.print(rev[p]);
}
}
}
(b)Explain the role of access modifiers when packages are used in Java. (7)
There are four types of Java access modifiers:
● Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
● Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
● Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
● Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
16)
(a)Create a user defined exception ‘InvalidAgeException’. Write a Java program that takes
age as a Command Line Argument. Raise the Exception ‘InvalidAgeException’ if age is less
than 18.
import java.util.Scanner;
try {
if(age < 18)
throw new InvalidAgeException("Invalid age");
else
System.out.println("Valid age");
}
catch (InvalidAgeException a) {
System.out.println(a);
}
}
}
(b)Explain the concept of Serialization and demonstrate how an object can be serialized with
a sample program.
● Serialization in Java is the process of converting the Java code Object into a Byte Stream,
to transfer the Object Code from one Java Virtual machine to another and recreate it using
the process of Deserialization.
● Most impressive is that the entire process is JVM independent, meaning an object can be
serialized on one platform and deserialized on an entirely different platform.
● For serializing the object, we call the
writeObject() method of ObjectOutputStream,
and for deserialization we call the readObject()
method of ObjectInputStream class.
● We must have to implement the Serializable
interface for serializing the object.
● Advantages of Java Serialization
○ It is mainly used to travel object's state
on the network (which is known as
marshaling).
MODULE 4
17)
(a) Illustrate the event handling mechanism in Java using the Delegation Event Model with
the help of a diagram. (8)
(b) Illustrate the usage of the following methods related to String with appropriate sample
code. (6)
(i) find() (ii)substring() (iii) replace() (ii)substring( )
(iii) replace( )
1. The first form replaces all occurrences of one character in the invoking string with another
character. String replace(char original, char replacement)
◦ Here, original specifies the character that will be replaced by the character specified by
replacement.The resulting string is returned.
String s = "Hello".replace('l', 'w');
◦ Here letter l is replaced by w. So “Hewwo” is put into String object s.
2. The second form of replace( ) replaces one character sequence with another. String
replace(CharSequence original, CharSequence replacement)
18)
(a) What is multithreading? Write a multithreaded Java program that demonstrates the
working of wait() and notify() methods. (7)
Variables
o FOCUS_FIRST: Marks the first integer id for the range of focus event ids.
o FOCUS_LAST: Marks the last integer id for the range of focus event ids.
o FOCUS_GAINED: The focus gained event type.
o FOCUS_LOST: The focus lost event type.
Methods
o isTemporary: Returns whether or not this focus change event is a temporary change.
o paramString: Overrides paramString in class ComponentEvent
MODULE 5
19)
(a)Write a Java program that uses two textfields and a button. The first textfield accepts
temperature in Celsius. When the ‘Convert’ button is clicked the second textfield displays
the temperature in Fahrenheit. Use appropriate Swing components and event handling
techniques. F=(C*9/5)+32 (9)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public TemperatureConverter() {
jfrm.add(celsiusLabel);
jfrm.add(celsiusTextField);
jfrm.add(convertButton);
jfrm.add(fahrenheitLabel);
jfrm.setVisible(true);
}
(b) Describe the two different ways to create frames using Swing package with appropriate
examples. (7)
import javax.swing.*;
In the main() method, we create an instance of the MyFrame class, which creates and displays the
frame.
import javax.swing.*;
In this example, we create an instance of the JFrame class and set its title, size, and default close
operation. We also make the frame visible.
In both approaches, we use the setSize() method to set the size of the frame, the
setDefaultCloseOperation() method to set the default close operation of the frame, and the
setVisible() method to make the frame visible.
Note: It is generally recommended to create a class that extends JFrame when you want to create
a custom frame with more complex functionality, and to create an instance of JFrame when you
want to create a simple frame with basic functionality.
20)
(a) Discuss the Model View Controller (MVC) Architecture using a diagram. Also list out
the advantages of writing programs based on MVC Architecture. (7)
1. Establish a Connection
import java.sql.*;
Load the vendor specificdriver
◦ Class.forName("oracle.jdbc.driver.OracleDriver");
Dynamically loads a driver class, for Oracledatabase
Make the connection
◦ Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@oracle-prod:1521:OPROD",
username, passwd);
4. Get ResultSet
5. Close Connection
stmt.close();
con.close();
rs.close()