Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Semester:4th Semester

Programme:B.Tech
Branch/Specialization:CSE, CSCE

SPRING END SEMESTER EXAMINATION-2024


4th Semester, B.Tech
Object Oriented Programming Using Java
CS20004
(For 2022 Admitted Batches)
Time: 2 Hours 30 Minutes Full Marks: 50
Answer any FIVE questions.
Question paper consists of two SECTIONS i.e. A and B.
Section A is compulsory.
Attempt any Four question from Sections B.
The figures in the margin indicate full marks.
Candidates are required to give their answers in their own words as far as practicable
and all parts of a question should be answered at one place only.

Learning Course
levels as Outcomes
SECTION-A (Learning levels 1)
per (CO)
Bloom’s
taxonomy
1 Answer the following questions. [1 × 10]
.
(a) Find the output / error for the below code 1 1
with brief explanation.
class Test {
public static void main(String[] args) {
for(int i = 0; 1; i++) {
System.out.println("Hello");
break;
} }}
Ans: Compilation Error (Incompatible types:
int cannot be converted to boolean)
Evaluation Scheme: Award 0.5 for output and
0.5 for brief explanation.
(b) Find the output / error for the below code 1 1
with brief explanation.
class Point {
protected int x, y;
public Point(int _x, int _y)
{
x = _x;
y = _y;
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
} }
public class Main {
public static void main(String args[])
{
Point p = new Point();
System.out.println("x = " + p.x + ", y = " +
p.y);
}}
Ans: Compilation Error (Constructor Point in class Point
cannot be applied to given types)
Evaluation Scheme: Award 0.5 for output and
0.5 for brief explanation.
(c) Find output/Error for the below code with 1 3,4
brief explanation.
import java.io.*;
class Parent{
void msg()throws Exception {
System.out.println("parent class method");
} }
class TestExceptionChild extends Parent{
void msg()throws ArithmeticException {
System.out.println("child fclass method");
}
public static void main(String args[]){
Parent p = new TestExceptionChild4();
try {
p.msg();
}catch(Exception e) { }
} }
Ans: Compilation Error Or child fclass method
If constructor name is TestExceptionChild4()
Or If constructor name is TestExceptionChild( )
Evaluation Scheme: Award 1 mark for output
compilation error or output.
(d) Find the output / error for the below code 1 5
with brief explanation.
class Test {
public static void main(String args[ ]) {
System.out.println(10 + 20 + "KIIT");
System.out.println("KIIT" + 10 + 20);
} }
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
Ans: 30KIIT
KIIT1020
Evaluation Scheme: Award 0.5 mark for
“30KIIT” output and 0.5 for mark “KIIT1020”.
(e) Find the output/error for the below code 1 5
with brief explanation.
class STRING {
public static void main(String args[ ]) {
String s="DATA";
s.concat("SCIENCE");
System.out.println(s);
s=s.concat("ANALYTICS");
System.out.println(s);
StringBuffer x = new StringBuffer("KALINGA");
System.out.println("The capacity before
append is:"+x.capacity());
x.append("ODISHA");
System.out.println("The capacity after append
is:"+x.capacity());
}}
Ans: DATA
DATAANALYTICS
The capacity before append is: 23
The capacity after append is: 23

Evaluation Scheme: Award 1 mark for any two


outputs.
(f) Find the output/error for the below code 1 4
with brief explanation.
class Exception_Demo
{public static void main(String args[])
{try{
throw new ArrayIndexOutOfBoundsException("AIOBE"); }
catch(ArithmeticException e){
System.out.println("Exception Caught with
first catch block"); }
catch(Exception e) {
System.out.println("Exception Caught with
second catch block");}}}
Ans: Exception Caught with second catch
block
Evaluation Scheme: Award 1 mark for correct
output.
(g) Write any two differences between abstract 1 3
class and interface.
Ans:

Abstract Class Interface


KIIT-DU/2023/SOT/Spring End Semester Examination-2023
Can contain both abstract and non-abstract Can only contain abstract methods
methods

Abstract class is extended using “extends” Interface is implemented using “implements”


keyword. keyword.

Does not support multiple inheritance Supports multiple inheritance

Can extend another class and implement Can only extend another interface
interfaces

Evaluation Scheme: Award 1 mark for two correct difference.


(h) With suitable example, explain the difference 1 5
between equals( ) and == operation on String
objects.
Ans: “==” returns true only if both string
objects are pointing to the same string
instance. “equals()” returns true if both string
objects have the same value.

Output: true
false
true

Evaluation Scheme: Award 0.5 mark for


correct explanation and 0.5 mark for example.
(i) What is the purpose of using sleep() method 1 4
and join() method with Java threads? Give
syntax.
Ans: The sleep( ) method causes the currently
executing thread to sleep for the specified
number of milliseconds. This means that the
thread will not be able to execute any code
during this time.
public static void sleep(long millisec)

The join( ) method, on the other hand, causes


the currently executing thread to wait for
another thread to finish executing. This means
that the thread will not be able to execute any
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
code until the other thread has finished.
public final void join(long millisec)

Evaluation Scheme: Award 0.5 mark for sleep


method and 0.5 mark for join method.
(j) Which swing component is used to display 1 6
images and which method is used to add an
action listener to a button in Java Swing? Give
syntax.
Ans: JLabel is used to display a short string or
an image icon. JLabel can display text, image
or both. JLabel is only a display of text or
image and it cannot get focus.
Syntax: JLabel(Icon img)

component.addActionListener() method is used


to add an action listener.
Syntax: public abstract void
actionPerformed(ActionEvent e)
Evaluation Scheme: Award 1 mark for
addActionListener() method.
Learning Course
levels as Outcomes
SECTION-B (Learning levels 2, 3, 4, 5 and 6)
per (CO)
Bloom’s
taxonomy
2 (a) Draw and explain the components of java [5] 2 1
. architecture in detail. What is the significance of
byte code in achieving portability?
Ans: Java Architecture combines the process of
compilation and interpretation of a Java source
program. It explains each and every step of how
a Java program is compiled and executed. As a
whole, it is a collection of components, viz.,
JVM, JRE, and JDK. It integrates the process of
interpretation and compilation. The following
figure presents the Java Architecture where
each step is shown graphically.

KIIT-DU/2023/SOT/Spring End Semester Examination-2023


a) There is both a compilation and an
interpretation process in Java.
b) After a JAVA code is written, the JAVA
compiler comes into the picture that converts
this code into an intermediate format called byte
code.
c) After the creation of byte code, JAVA
virtual machine (JVM) converts it to the machine
code.
d) And finally, the machine (precisely, OS)
runs that machine code.

We now elaborate the components of Java


architecture one by one:
Java Virtual Machine (JVM): JVM is a Java
platform component that gives us an
environment to execute java programs. JVM's
main task is to convert byte code into machine
code. JVM, first, loads the code into memory
and verifies it. After that, it executes the code
and provides a runtime environment. Java
Virtual Machine (JVM) is a part of the Java
Runtime Environment and has its own
architecture.
Java Runtime Environment (JRE): JRE provides
an environment in which Java programs are
executed. JRE takes our Java code, integrates it
with the required libraries, and then starts the
JVM to execute it. JRE contains all of the
libraries and software required to run Java
programs. Although JRE is included in the JDK,
it is also available for download individually.
Java Development Kit (JDK): JDK is a Java
application (and applet) development
environment. Java Development Kit contains
JRE and several development tools, an
interpreter/loader (java), a compiler (javac), an
archiver (jar), a documentation generator
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
(javadoc) accompanied with another tools like
debugger (jdb), ClassLoader, appletviewer, etc.

The significance of Java bytecode in achieving


portability:
Java bytecode is platform-independent,
meaning it can be executed on any device that
has a Java Virtual Machine (JVM) installed.
When you compile a Java program, it is
compiled into bytecode rather than native
machine code.
The JVM, installed on the target platform,
interprets this bytecode and translates it into
machine code that the underlying hardware can
understand.
This allows Java programs to be developed and
compiled once and run on any device with a
compatible JVM, regardless of the underlying
hardware and operating system.
It simplifies the process of software
development and deployment by eliminating the
need to recompile the code for each specific
platform.

Evaluation Scheme: Award 3 + 2.


(b) Write a program in java to implement Queue [5] 2,3 2,3,4
data structure.
Create a class Queue having data members
Max_Size, an integer array, front, rear and size.
Initialize default values for data members in
default constructor. The functions enqueue(),
dequeue(), isEmpty(), isFull(), size() and display()
of Queue class has to be implemented and
tested to make your Queue class follows First In
First Out principle. The queue must check for
overflow and underflow conditions, and handle
it as a user defined exceptions.
Ans:
class QueueException extends Exception {
public QueueException(String message) {
super(message);
}
}

class Queue {
private int maxSize;
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
private int[] queueArray;
private int front;
private int rear;
private int size;

public Queue(int maxSize) {


this.maxSize = maxSize;
this.queueArray = new int[maxSize];
this.front = 0;
this.rear = -1;
this.size = 0;
}

public void enqueue(int data) throws


QueueException {
if (isFull()) {
throw new QueueException("Queue is
full. Cannot enqueue.");
}
rear = (rear + 1) % maxSize;
queueArray[rear] = data;
size++;
}

public int dequeue() throws QueueException {


if (isEmpty()) {
throw new QueueException("Queue is
empty. Cannot dequeue.");
}
int removedItem = queueArray[front];
front = (front + 1) % maxSize;
size--;
return removedItem;
}

public boolean isEmpty() {


return size == 0;
}

KIIT-DU/2023/SOT/Spring End Semester Examination-2023


public boolean isFull() {
return size == maxSize;
}

public int size() {


return size;
}

public void display() {


if (isEmpty()) {
System.out.println("Queue is empty.");
return;
}
System.out.print("Queue: ");
int i = front;
while (true) {
System.out.print(queueArray[i] + " ");
i = (i + 1) % maxSize;
if (i == (rear + 1) % maxSize) {
break;
}
}
System.out.println();
}
}

public class Main {


public static void main(String[] args) {
Queue queue = new Queue(5);

try {
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);

queue.display();

KIIT-DU/2023/SOT/Spring End Semester Examination-2023


System.out.println("Dequeued item: " +
queue.dequeue());
System.out.println("Dequeued item: " +
queue.dequeue());

queue.display();

queue.enqueue(60);
queue.enqueue(70);

queue.display();

} catch (QueueException e) {
System.out.println("Queue Exception: "
+ e.getMessage());
}
}
}
Evaluation Scheme: Award 2.5 marks if the
student has attempted to implement Queue.
Evaluator discretion to award more marks for
mostly correct answers and 5 marks for a fully
correct answer.
3 (a) Draw the thread life cycle and explain the [5] 2,3,4 4
. different states of a thread. What are the
different techniques available in Java for
achieving synchronization of threads? Discuss
with suitable examples.

Ans: Threads in Java go through various states


during their lifetime. The typical thread life cycle
includes the following states:

New: When a thread is created but not yet


started, it is in the new state.
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
Runnable: Once the thread starts execution, it
moves to the runnable state. In this state, the
thread is ready to run and waiting for the CPU
to execute it.

Blocked or Waiting: A thread enters this state


when it is waiting for a resource or another
thread to perform a certain action. For example,
it might be waiting for user input, I/O
operations, or for another thread to release a
lock.

Timed Waiting: Similar to the blocked state, but


with a specified time limit. Threads can enter
this state when they are waiting for a certain
amount of time before proceeding.

Terminated: When a thread completes its


execution or is explicitly terminated, it enters
the terminated state and cannot be restarted.

Synchronization Techniques in Java:


Java provides several techniques to synchronize
access to shared resources and avoid data races
in multi-threaded applications:

Synchronized Methods: By using the


synchronized keyword, you can ensure that only
one thread can execute a synchronized method
at a time. This prevents multiple threads from
accessing shared resources concurrently.

class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public synchronized int getCount() {


return count;
}
}

Synchronized Blocks: Instead of synchronizing


entire methods, you can synchronize specific
blocks of code using the synchronized keyword
on an object.

class Counter {
private int count = 0;
private Object lock = new Object();

public void increment() {


KIIT-DU/2023/SOT/Spring End Semester Examination-2023
synchronized(lock) {
count++;
}
}

public int getCount() {


synchronized(lock) {
return count;
}
}
}

Evaluation Scheme: [2 + 3]
(b) What are the differences between function [5] 2,3 3
overriding and function overloading. Write a java
program to create an abstract class Bank having
an abstract method getRateofInterest(). Derive
three classes SBI, ICICI and HDFC from Bank
class. Now use dynamic method dispatch
concept and function overriding concept to
override getRateofInterest() of bank class with
derived class methods to display rate of interest
of different banks.
Function overloading Function overriding
1 It is performed within a class. It occurs in two classes -one inherits from another.
2 It is the example of compile time It is the example of run time polymorphism.
polymorphism.
3 In this case parameters must be different. In this case parameters must be same in both the classes.
abstract class Bank{
abstract void getRateofInterest();
}

class SBI extends Bank{


void getRateofInterest()
{ System.out.println("SBI rate is 7.5");
}
}

class ICICI extends Bank{


void getRateofInterest()
{ System.out.println("ICICI rate is 8.0");
}
}

class HDFC extends Bank{


void getRateofInterest()
{ System.out.println("HDFC rate is 8.2");
}
}

class driver{
public static void main (String ar[]){
Bank ob;
ob= new SBI();
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
ob.getRateofInterest();
ob= new ICICI();
ob.getRateofInterest();
ob= new HDFC();
ob.getRateofInterest();
}
}

Evaluation scheme: [2 + 3]
4 (a) Draw picture of multiple inheritance through [5] 2,3,4 3
. interface. Explain with example program how
multiple inheritance is supported in java
through interfaces and not by classes. Explain
the rules for ambiguity resolution while
implementing multiple inheritance using
interfaces with suitable example.

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void
show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
In this example, two interfaces the Printable and
Showable has implemented by class A7. In
Printable interface print() method and in
Showable interface show() method is present. Its
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
implementation is provided by A7 class.
Multiple inheritance is not supported in the case
of class because of ambiguity. However, it is
supported in case of an interface because there
is no ambiguity. It is because its implementation
is provided by the implementation class. For
example:
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestInterface3 implements Printable,
Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
In the above example, Printable and Showable
interface have same methods but its
implementation is provided by class
TestTnterface1, so there is no ambiguity.
Evaluation scheme: [1 + 2 + 2]
(b) State the differences between String and [5] 2,3,4 5
StringBuffer class. Write a program in java to
perform the following operations on string
objects.
1. To reverse two strings without using any
third variable.
2. To check if two strings are anagrams of
each other or not. (Two strings are said to
be anagram of each other if they contain
the same characters but in different
orders: e.g. state & taste)
Ans: There are many differences between String
and StringBuffer. A list of differences between
String and StringBuffer are given below:

No. String StringBuffer

1) The String class is immutable. The StringBuffer class is mutable.


2) String is slow and consumes more memory StringBuffer is fast and consumes less memory when we
when we concatenate too many strings concatenate t strings.
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
because every time it creates new instance.
3) String class overrides the equals() method of StringBuffer class doesn't override the equals() method
Object class. So you can compare the of Object class.
contents of two strings by equals() method.
4) String class is slower while performing StringBuffer class is faster while performing
concatenation operation. concatenation operation.
5) String class uses String constant pool. StringBuffer uses Heap memory
4(b)1. // Java program to swap two strings without using a temporary variable
Input: a = "Hello"
b = "World"
Output:
Strings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello

import java.util.*;
class Swap
{
public static void main(String args[])
{
// Declare two strings
String a = "Hello";
String b = "World";

// Print String before swapping


System.out.println("Strings before swap: a = " + a + " and b = "+b);

// append 2nd string to 1st


a = a + b;

// store initial string a in string b


b = a.substring(0,a.length()-b.length());

// store initial string b in string a


a = a.substring(b.length());

// print String after swapping


System.out.println("Strings after swap: a = " + a + " and b = " + b);
}
}

4(b)2.
Input: str1 = “listen” str2 = “silent”
Output: “Anagram”
Explanation: All characters of “listen” and “silent” are the same.
Input: str1 = “gram” str2 = “arm”
Output: “Not Anagram”

import java.util.Arrays;

class ANAGRM {
public static void main(String[] args) {
String str1 = "Race";
String str2 = "Care";
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();

// check if length is same


if(str1.length() == str2.length()) {

// convert strings to char array


char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();

// sort the char array


Arrays.sort(charArray1);
Arrays.sort(charArray2);

// if sorted char arrays are same


// then the string is anagram
boolean result = Arrays.equals(charArray1, charArray2);

if(result) {
System.out.println(str1 + " and " + str2 + " are anagram.");
}
else {
System.out.println(str1 + " and " + str2 + " are not anagram.");
}
}
else {
System.out.println(str1 + " and " + str2 + " are not anagram.");
}
}
}
Evaluation scheme: Award 1 mark for one point comparison and 4(b)1. award 2 marks for reverse of two
strings or exchange of two strings, award 2 for 4(b)2. program.
5 (a) What are the different ways to create a user [5] 2,4,5 4,5
. defined thread? Write a program in Java to
create two user defined threads which performs
the following task respectively:

1. Prints all possible substrings of a given string


starting from the first character of the string.
After printing each substring, it sleeps for 500
milliseconds (Task-1)

N.B.: If the string is KIIT, it will print K, KI, and


KII.
2. Prints the reverse of each strings present in
the string array. After printing reverse of each
string in the array, it sleeps for 1000
milliseconds (Task-2).

N.B.: Input: {KIIT, SCE, CSE, IT, CSSE, CSCE}


Output: {TIIK, ECS, ESC, TI, ESSC, ECSC}
Ans:
Different ways to create user defined thread are-
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
(1 Mark)
a) By implementing Runnable interface
b) By extending Thread class

import java.util.*;
class T1 extends Thread
{
String str;
Scanner sc=new Scanner(System.in);
T1()
{
System.out.println("Task-1: Enter a
String");
str=sc.next();
}
public void run()
{
try
{
for(int i=0;i<(str.length()-
1);i++)
{
System.out.println("Task-
1:"+str.substring(0,i+1));
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("Task-1
interrupted");
}
}
}
class T2 extends Thread
{

String[] str;
StringBuilder sb;
int n;
T2()
{
Scanner sc=new
Scanner(System.in);
System.out.println("Task-2: Enter
no of strings");
n=sc.nextInt();
str=new String[n];
for(int i=0; i<n; i++)
{
System.out.print("Enter String
"+(i+1)+":");
str[i]=sc.next();
}
}
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
public void run()
{
try
{
for(int i=0;i<n;i++)
{
sb=new StringBuilder(str[i]);
System.out.println("Task-
2:"+sb.reverse());
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Task-2
interrupted");
}
}
}
class Main
{
public static void main(String[] args)
{
T1 t1 = new T1();
T2 t2 = new T2();
t1.start();
t2.start();
}
}

Output:
Task-1: Enter a String
KIIT
Task-2: Enter no of strings
6
Enter String 1:KIIT
Enter String 2:SCE
Enter String 3:CSE
Enter String 4:IT
Enter String 5:CSSE
Enter String 6:CSCE
Task-2:TIIK
Task-1:K
Task-1:KI
Task-2:ECS
Task-1:KII
Task-2:ESC
Task-2:TI
Task-2:ESSC
Task-2:ECSC

Evaluation scheme: [1 + 2 + 2]
(b) Draw the Throwable class hierarchy. State the [5] 3,4,5 4
differences between checked and unchecked
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
exceptions. Write a Java Program to create an
user defined exception called
IllegalArgsException and throw the exception if
we pass the negative timeout value in
Thread.sleep() method otherwise sleep for given
time and display “KIIT University” five times.

Checked Exception Unchecked Exception


Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.
The compiler checks a checked exception. The compiler does not check these types of
exceptions.
These types of exceptions can be handled at the time of These types of exceptions cannot be a catch or handle
compilation. at the time of compilation, because they get generated
by the mistakes in the program.
They are the sub-class of the exception class. They are runtime exceptions and hence are not a part
of the Exception class.
Here, the JVM needs the exception to catch and handle. Here, the JVM does not require the exception to catch
and handle.
Examples of Checked exceptions: Examples of Unchecked Exceptions:

• File Not Found Exception • No Such Element Exception


• No Such Field Exception • Undeclared Throwable Exception
• Interrupted Exception • Empty Stack Exception
• No Such Method Exception • Arithmetic Exception
• Class Not Found Exception • Null Pointer Exception
• Array Index Out of Bounds Exception
• Security Exception
Write a java program, to create an user defined exception called IllegalArgsException and throw the Exception and
throw the exception if we pass the negative timeout value in Thread.sleep(). Otherwise, sleep for given time and
display “KIIT University” five times.
class IllegalArgsException extends Exception{

KIIT-DU/2023/SOT/Spring End Semester Examination-2023


IllegalArgsException (String str){
super (str);
}
}
public class display{

public static void main (String Args []) throws IllegalArgsException{


int sleeptime = Integer.parseInt(Args[0]);
if (sleeptime <0)
{

throw new IllegalArgsException ("Value should be greater than or equal to zero");

}
else{
for (int i=0;i<5;i++){
try{
Thread.sleep (sleeptime);
}catch (InterruptedException e){}
System.out.println ("KIIT University");
}
}
}
}

Evaluation scheme: [1 + 1 + 3]
6 (a) Create a swing application in Java to create a [5] 4,5,6 6
. student’s registration page to participate in a
University event. The registration entities have
to be displayed on a label and corresponding
textbox must be available to enter the relevant
data. Buttons must be placed on the frame to
carry out different operations. The details of the
components to be present on the frame are:
Component List:
1. Name(Label & Text Box) :String
2. Roll No (Label & Text Box): Integer
3. CGPA (Label & Text Box): Float
4. Branch : Dropdown Menu (CSE, IT,
CSCE, CSSE)
5. Email Id(Label & Text Box): String
6. SUBMIT (Button): To submit the data
entered and display the data in the frame
on the labels.
7. RESET (Button): To clear all the entered
data from the textboxes.
8. CHANGE COLOR (Button): To change the
color from GREEN(default) to PINK
Validation Rule:
1. The length of the Roll No must be in the
range 7 to 8.
2. The CGPA can’t be greater than 10.0 and
KIIT-DU/2023/SOT/Spring End Semester Examination-2023
less than 6.0
3. The Email ID must be in the format
<string>@<string>.<string>
An exception must be thrown if any of the
validation rules are not satisfied.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// Custom Exception class for invalid data entry
// Extending RuntimeException class to make a
unchecked exception
class InvalidData extends RuntimeException{
InvalidData(String message){
super(message);
}
}
// I have used anonymous inner class to
implement ActionListener to reduce the size of
code
// I have also used GridLayout to arrange
components, which was not part of syllabus,
// but I have taught in the class since layouts
make arrangements easier.
class RegistrationPage{
RegistrationPage(){
JFrame frame = new JFrame("Registration
Page");
frame.setSize(500, 500); // Size of frame in
pixels
frame.setVisible(true);

frame.getContentPane().setBackground(Color.GR
EEN);

frame.setDefaultCloseOperation(JFrame.EXIT_O
N_CLOSE);

JLabel nlabel = new JLabel("Name: ");


JTextField name = new JTextField();
JPanel npanel = new JPanel(new
GridLayout(1, 2));
npanel.add(nlabel);
npanel.add(name);

JLabel rlabel = new JLabel("Roll No: ");


JTextField roll = new JTextField();
JPanel rpanel = new JPanel(new

KIIT-DU/2023/SOT/Spring End Semester Examination-2023


GridLayout(1, 2));
rpanel.add(rlabel);
rpanel.add(roll);

JLabel clabel = new JLabel("CGPA: ");


JTextField cgpa = new JTextField();
JPanel cpanel = new JPanel(new
GridLayout(1, 2));
cpanel.add(clabel);
cpanel.add(cgpa);

JLabel blabel = new JLabel("Branch: ");


String[] choices = {"CSE", "IT", "CSCE",
"CSSE"};
JComboBox<String> branch = new
JComboBox<String>(choices);
JPanel bpanel = new JPanel(new
GridLayout(1, 2));
bpanel.add(blabel);
bpanel.add(branch);

JLabel elabel = new JLabel("Email ID: ");


JTextField email = new JTextField();
JPanel epanel = new JPanel(new
GridLayout(1, 2));
epanel.add(elabel);
epanel.add(email);

JButton submit = new JButton("SUBMIT");


JButton reset = new JButton("RESET");
JButton ccolor = new JButton("CHANGE
COLOR");
JPanel buttons = new JPanel(new
GridLayout(1, 3));
buttons.add(submit);
buttons.add(reset);
buttons.add(ccolor);

JTextArea tarea = new JTextArea(8, 8);


// Adding all components to the frame
frame.setLayout(new GridLayout(7, 1));
frame.add(npanel);
frame.add(rpanel);
frame.add(cpanel);
frame.add(bpanel);
frame.add(epanel);
frame.add(buttons);

KIIT-DU/2023/SOT/Spring End Semester Examination-2023


frame.add(tarea);

// Adding event handling


submit.addActionListener(new
ActionListener(){
public void actionPerformed(ActionEvent
e){
tarea.setText("");
String studentName = name.getText();
int studentRollNo =
Integer.parseInt(roll.getText());
float studentCGPA =
Float.parseFloat(cgpa.getText());
String studentBranch =
branch.getSelectedItem().toString();
String studentEmail = email.getText();

// Validations
if(roll.getText().length() <= 6 ||
roll.getText().length() >= 9)
throw new InvalidData("Roll
Number should have 7-8 digits.");

if(studentCGPA < 6.0 || studentCGPA


> 10.0)
throw new InvalidData("CGPA
should be in range 6.0 to 10.0");

if(!studentEmail.matches("^[A-Za-z0-
9+_.-]+@(.+)$"))
throw new InvalidData("Email
should be in valid format.");

tarea.append("name: " + studentName


+ "\n");
tarea.append("Roll No.: " +
String.valueOf(studentRollNo) + "\n");
tarea.append("CGPA: " +
String.valueOf(studentCGPA) + "\n");
tarea.append("Branch: " +
studentBranch + "\n");
tarea.append("Email: " +
studentEmail + "\n");
}
});
reset.addActionListener(new
ActionListener(){

KIIT-DU/2023/SOT/Spring End Semester Examination-2023


public void actionPerformed(ActionEvent
e){
tarea.setText("");
name.setText("");
roll.setText("");
cgpa.setText("");
email.setText("");
}
});
ccolor.addActionListener(new
ActionListener(){
public void actionPerformed(ActionEvent
e){

frame.getContentPane().setBackground(Color.PI
NK);
}
});
}
}
class Driver{
public static void main(String[] args){
new RegistrationPage();
}
}

Evaluation scheme: Award 4 marks for first four


components and 1 marks for actionListener( )
method. [4 + 1]
(b) Briefly discuss about the components and [5] 4,5,6 6
containers available in swing. Write a java
program to design a calculator in swing frame to
perform arithmetic operations addition and
subtraction. Design the frame with any
background color, three text boxes and two
buttons (ADD and SUB). When you place values
in two text boxes and press ADD or SUB button,
the result of addition and subtraction of two
numbers should be displayed in third text box.
Ans:
import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements
ActionListener{
JTextField tf1,tf2,tf3;

KIIT-DU/2023/SOT/Spring End Semester Examination-2023


JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
f.getContentPane().setBackground(Color.BLUE);

tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);

f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}

KIIT-DU/2023/SOT/Spring End Semester Examination-2023


String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}}

Evaluation scheme: [2 + 3]
*****

KIIT-DU/2023/SOT/Spring End Semester Examination-2023

You might also like