0% found this document useful (0 votes)
67 views48 pages

Java Programming

This document contains a question bank and answer key for a Java Programming exam for semester 4 students. It includes 11 multiple choice questions about Java concepts like OOP, procedural vs object-oriented programming, advantages of OOP, Java buzzwords, method overloading vs overriding, type conversion and casting, the final keyword, Java byte code, contexts for using final and finalize, and garbage collection. The document was created by a student named Md Riyan Nazeer for self-study purposes and comes with a disclaimer that it should not be used for cheating.

Uploaded by

Abhishek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
67 views48 pages

Java Programming

This document contains a question bank and answer key for a Java Programming exam for semester 4 students. It includes 11 multiple choice questions about Java concepts like OOP, procedural vs object-oriented programming, advantages of OOP, Java buzzwords, method overloading vs overriding, type conversion and casting, the final keyword, Java byte code, contexts for using final and finalize, and garbage collection. The document was created by a student named Md Riyan Nazeer for self-study purposes and comes with a disclaimer that it should not be used for cheating.

Uploaded by

Abhishek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 48

QUESTION BANK WITH ANSWER KEY FOR

B.E SEM-IV SEMENTER END EXAMS

SUBJECT: JAVA Programming

Disclaimer:
I am not responsible for any errors, inaccuracies, or mistakes
in this PDF. There is no guarantee of achieving a good score by
following the contents of this PDF. Use it at your own risk.

IMPORTANT: This PDF is NOT made for the purpose of


cheating in exams, copying, or creating unauthorized mini
copies. Use of this material for such purposes is strictly
prohibited and may lead to serious consequences.

Made By:
Name: Md Riyan Nazeer
Roll No: 160921748036
Branch: CSM-2A
MD Riyan Nazeer CSM-2A 160921748036

JAVA PROGRAMMING SEE Answer key


UNIT 1
SAQ’s
1 Define OOP?
A OOP stands for Object-Oriented Programming. It is a computer programming model that organizes software
design around data, or objects, rather than functions and logic. An object can be defined as a data field that
has unique attributes and behavior. OOP focuses on the objects that developers want to manipulate rather
than the logic required to manipulate them.
2 Distinguish between procedural language and OOPs?
A
Procedural Programming Object-Oriented Programming
(OOP)
Data and Behavior Separated Encapsulated together in objects
Reusability Less reusable Objects can be reused in different
programs or projects
Inheritance Not supported Allows creation of new classes
based on existing ones
Polymorphism Not supported Allows objects to take on different
forms depending on context
3 List advantages of OOP?
A a) Re-usability: It means reusing some facilities rather than building them again and again. This is done
with the use of a class. We can use it ‘n’ number of times as per our need.
b) Data Redundancy: This is a condition created at the place of data storage where the same piece of data
is held in two separate places. So, the data redundancy is one of the greatest advantages of OOP.
c) Code Maintenance: This feature is more of a necessity for any programming languages; it helps users
from doing re-work in many ways. It is always easy and timesaving to maintain and modify the existing
codes by incorporating new changes into them.
d) Security: With the use of data hiding and abstraction mechanism, we are filtering out limited data to
exposure, which means we are maintaining security and providing necessary data to view.
e) Design Benefits: If you are practicing on OOPs, the design benefits a user will get is in terms of designing
and fixing things easily and eliminating the risks (if any).

4 a) List down Java Buzzwords. Or


b) why is java architectural neutral? Or
c) why is java called as “robust”? or
d) Discuss: Java programs are Portable.
A a) JAVA BUZZWORDS
• Platform independent.
• Portable.
• Dynamic.
• Distributed.
• Secure.
• Robust.
• Compiled and interpreted.
• Multithreaded.
• Architecture-Neutral

b) A central issue for the Java designers was that of code longevity and portability. One of the main
problems facing programmers is that no guarantee exists that if you write a program today, it will run
tomorrow even on the same machine. Operating system upgrades, processor upgrades, and changes in
core system resources can all combine to make a program malfunction. Java Virtual Machine solves this
problem. The goal is written once run anywhere, anytime, forever.

1
MD Riyan Nazeer CSM-2A 160921748036

c) Robust:

Robust

powerful exception
Strong memory automatic garbage handling type checking
allocation collection [try, throw, catch, mechanism
throws, finally]

1. Java has strong memory allocation and automatic garbage collection; it also provides powerful
exception handling and type checking mechanism.
2. Compiler checks the program for finding the finding the compile time error and interpreter checks the
program for runtime error and makes the system secure from crash.
3. All the above feature makes the java language strong (Robust)
d) Portable:
1. The feature “write once and run anywhere ” make the java language portable.
2. Java also have the standard data size irrespective of operating systems or the processor.
3. This feature makes the java as a portable language

5 What is the difference between method overloading and method overriding?


A Method overloading and method overriding are two concepts in Java programming language that allow the
use of methods with the same name but with different behaviour’s.

Method overloading is used to increase the readability of the program. It is performed within a class and
allows multiple methods with the same name but with different parameters. This means that you can have
multiple methods with the same name, but they must have a different number of parameters or parameters
of different types.

Method overriding, on the other hand, is used to provide a specific implementation of a method that is
already provided by its superclass. It occurs in two classes that have an IS-A (inheritance) relationship. This
means that a subclass can provide its own implementation of a method that is already defined in its
superclass.
6 Define type conversion?
A Type conversion, also known as type casting, is the process of assigning a value of one data type to a
variable of another data type. If the two types are compatible, then Java will perform the conversion
automatically. However, if the two types are incompatible, an explicit cast must be used to perform the
conversion between the two types.
7 Define type casting?
A Type casting is the process of assigning a value of one data type to a variable of another data type. If the two
types are compatible, then Java will perform the conversion automatically. However, if the two types are
incompatible, an explicit cast must be used to perform the conversion between the two types.
8 What is the use of final keyword in java?
A Final Keyword: The final keyword in java is used to restrict the user. The java final keyword can be used in
many contexts.

Final can be:


1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank final
variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can
be static also which will be initialized in the static block only. We will have detailed learning of these. Let's
first learn the basics of final keyword

2
MD Riyan Nazeer CSM-2A 160921748036

9 What is byte code? Or What is a “Java byte code”?


A Bytecode is a low-level, compact, platform-independent representation of compiled code that can be
executed by a virtual machine (VM) or further compiled into machine code. It is generated by compiling
source code written in a high-level programming language such as Java. The virtual machine then converts
the bytecode into machine code that can be executed by the computer’s hardware processor.

Bytecode is designed to be portable and efficient, allowing the same code to run on multiple platforms
without the need for recompilation. This makes it easier to develop and distribute software that can run on
a wide range of devices and operating systems.
10 Under which contexts do you use “final” and “finalize”
A In Java programming language, final and finalize are two distinct keywords that serve different purposes.

The final keyword is an access modifier that can be used with variables, methods, and classes. When used
with a variable, it makes the variable a constant, meaning its value cannot be changed once initialized.
When used with a method, it prevents the method from being overridden by a subclass. When used with a
class, it prevents the class from being subclassed.

On the other hand, finalize is a method of the Object class that is called by the garbage collector before an
object is garbage collected. It is used to perform clean-up processing on an object before it is destroyed.
11 Define garbage collection?
A Garbage collection in Java is the process of automatically managing memory by reclaiming memory
occupied by objects that are no longer used by the running application. The Java Virtual Machine (JVM) runs
a low-priority background thread, called the Garbage Collector, to free up this unused memory.

The garbage collector identifies objects that are no longer being used by the application and deletes them to
free up memory. This process helps to prevent memory leaks and ensures that the application has enough
memory available to continue running smoothly.
12 Explain the significance of each word in public static void main(String args [ ])
A public static void main(String args[]) is the signature of the main method in a Java program. Each word in this
signature has a specific meaning:

public: This keyword specifies that the main method is accessible from anywhere, including outside of the
class in which it is defined. This is necessary because the main method must be called by the Java Virtual
Machine (JVM) when the program is executed.

static: This keyword indicates that the main method is a class-level method, meaning that it can be called
without creating an instance of the class. This is necessary because the main method must be called before
any objects are created.

void: This keyword specifies that the main method does not return any value.

main: This is the name of the method. The main method is the entry point of a Java program and is where
the execution of the program begins.

String args[]: This specifies that the main method takes an array of String objects as a parameter. These
String objects represent the command-line arguments passed to the program when it is executed.
13 Define method. Write method’s signature?
A in Java programming language, a method is a block of code that performs a specific task and can be called by
other code. A method can take input in the form of parameters and can return a value.

Here is an example of a method in Java:


public int add(int x, int y) {
int sum = x + y;
return sum;
}
14 What is the use of super keyword? Or What is the use of ‘super’ keyword?

3
MD Riyan Nazeer CSM-2A 160921748036

A The super keyword in Java is a reference variable that is used to refer to the immediate parent class object.
It is used when we want to acquire a superclass member and use it in a derived class. When an instance of
the child class is created, an instance of the superclass is also created.

The super keyword can be used in several contexts:


1. To refer to the immediate parent class instance variable: If a subclass and its superclass have instance
variables with the same name, the super keyword can be used to refer to the instance variable of the
superclass.
2. To invoke the immediate parent class method: If a subclass and its superclass have methods with the
same name, the super keyword can be used to call the method of the superclass.
3. To invoke the immediate parent class constructor: The super keyword can be used to call a constructor
of the superclass from a subclass constructor.

15 Define object in java. Or What is an object and class in Java? Give an example for each.
A Class is a blueprint for creating objects. It defines a set of attributes and methods that will be common to all
objects of that class.

An Object is a real time entity. An object is an instance of a class. Instance means physically happening. An
object will have some properties and it can perform some actions

Example:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
LAQ’s
1 Discuss the various characteristics of object-oriented programming concepts?
A OOP CONCEPTS: Object-Oriented Programming (OOP) is a programming paradigm that focuses on
organizing code into objects that have data and methods.

The characteristics of OOP concepts are:


1. Class: In object-oriented programming, a class is a programming language construct that is used as a
blueprint to create objects. This blueprint includes attributes and methods that the created objects all
share. Usually, a class represents a person, place, or thing - it is an abstraction of a concept within a
computer program. Fundamentally, it encapsulates the state and behavior of that which it conceptually
represents. It encapsulates state through data placeholders called member variables; it encapsulates
behavior through reusable code called methods.

2. Object: An Object is a real time entity. An object is an instance of a class. Instance means physically
happening. An object will have some properties and it can perform some actions. Object contains
variables and methods. The objects which exhibit similar properties and actions are grouped under one
class. To give a real-world analogy, a house is constructed according to a specification. Here, the
specification is a blueprint that represents a class, and the constructed house represents the object‖.
• To access the properties and methods of a class, we must declare a variable of that class type. This
variable does not define an object. Instead, it is simply a variable that can refer to an object.
• We must acquire an actual, physical copy of the object and assign it to that variable. We can do this
using new operator. The new operator dynamically allocates memory for an object and returns a
reference to it. This reference is, more or less, the address in memory of the object allocated by
new. This reference is then stored in the variable. Thus, in Java, all class objects must be
dynamically allocated.

3. Encapsulation: Wrapping up of data (variables) and methods into single unit is called Encapsulation.
Class is an example for encapsulation. Encapsulation can be described as a protective barrier that

4
MD Riyan Nazeer CSM-2A 160921748036

prevents the code and data being randomly accessed by other code defined outside the class.
Encapsulation is the technique of making the fields in a class private and providing access to the fields
via methods. If a field is declared private, it cannot be accessed by anyone outside the class.

4. Abstraction: Providing the essential features without its inner details is called abstraction (or) hiding
internal implementation is called Abstraction. We can enhance the internal implementation without
effecting outside world. Abstraction provides security. A class contains lot of data, and the user does not
need the entire data. The advantage of abstraction is that every user will get his own view of the data
according to his requirements and will not get confused with unnecessary data. A bank clerk should see
the customer details like account number, name and balance amount in the account. He should not be
entitled to see the sensitive data like the staff salaries, profit or loss of the bank etc. So, such data can be
abstracted from the clerks view.

5. Inheritance: Acquiring the properties from one class to another class is called inheritance (or) producing
new class from already existing class is called inheritance. Reusability of code is main advantage of
inheritance. In Java inheritance is achieved by using extends keyword. The properties with access
specifier private cannot be inherited.

6. Polymorphism: The word polymorphism came from two Greek words poly‘ means many‘ and morphos‘
means forms‘. Thus, polymorphism represents the ability to assume several different forms. The ability
to define more than one function with the same name is called Polymorphism.
e.g.: int add (int a, int b)
float add (float a, int b)
float add (int a , float b)
void add (float a)
int add (int a)
2 Explain briefly about the features (buzzwords) of Java.
A a. platform independent:
• The concept of “write once and run anywhere”(knowns as platform independent) is one of the
important features of java language that makes java language that makes java as most powerful
language.
• The program written on one platform can run on any platform provided the platform must have
JVM(java virtual machine)

2. Portable:
• The feature “write once and run anywhere ” make the java language portable.
• Java also have the standard data size irrespective of operating systems or the processor.
• This feature makes the java as a portable language.

3. Dynamic:
• while executing the java program the user can get the required files dynamically from a location drive or
from a computer thousands of miles away from the user just by connection with the internet

4. Distributed:
• the widely used protocol like “http” (hypertext transfer protocol )and “ftp” (file transfer protocol) are
developed in java.
• Internet programmers can call functions on this protocols sand con get access the files from any remote
machine on the internet rather than writing codes on their local system.

5. Secure:

5
MD Riyan Nazeer CSM-2A 160921748036

• Security is an important issue for a language that is used for programming on internet.
• Threats for several viruses will be present always.
• Java programs not only verify all memory access but also ensures that there are no viruses
communicated with applet.
• A program that uses GUI(graphical user interface) for interacting with the user is known as “event driven
program”.
• Applets are event driven because it uses GUI for interacting with the user.
• The absence of pointers in java ensures that programs connot gain access to the memory location.

6. Robust:

Robust

powerful exception
Strong memory automatic garbage handling type checking
allocation collection [try, throw, catch, mechanism
throws, finally]

• Java has strong memory allocation and automatic garbage collection; it also provides powerful exception
handling and type checking mechanism.
• Compiler checks the program for finding the finding the compile time error and interpreter checks the
program for runtime error and makes the system secure from crash.
• All the above feature makes the java language strong (Robust).

7.Compiled and interpreted:


• Any computer languages is either compiled or interpreted but java is both compiled and interpreted.
• First java converts source code into bytecode, this is done by compiler.
• Second java interpreter(JVM) generates machine code that can be executes machine code that can be
executed by the machine.
• Thus, java is both compiled and interpreted.

8. Muti-threaded:
• Multi-threaded means handing multiple tasks simultaneously.
• Multithreaded programs are supported by java.
• It means there is no need to wait for the application to finish one task before beginning the other task.
3 Differentiate Method Overloading and Method Overriding with example
A In Java programming language, both method overloading and method overriding are used to provide
polymorphism, which allows different behavior based on the context of the code. However, they differ in
their approach and usage.

Method Overloading:

Method overloading is a feature in Java that allows creating multiple methods with the same name in a
single class. The methods must have different parameters, either in their number, type, or order. The
compiler uses the number and types of the parameters to differentiate between the methods during
compilation and selects the appropriate method during runtime based on the arguments passed.

For example, let's consider a class called `Calculator` that contains two methods with the same name
`addition`, but with different parameters:

6
MD Riyan Nazeer CSM-2A 160921748036

public class Calculator {


public int addition(int x, int y) {
return x + y;
}
public float addition(float x, float y) {
return x + y;
}
}

In this example, we have defined two methods with the same name, `addition`, but with different
parameter types (`int` and `float`). During compilation, the compiler will differentiate the methods based on
their parameter types, and select the appropriate method based on the argument passed during runtime.
Method Overriding:

Method overriding is a feature in Java that allows a subclass to provide its own implementation of a method
that is already defined in its superclass. The method in the subclass must have the same name, return type,
and parameters as the method in the superclass. This is achieved by using the `@Override` annotation.

For example, let's consider a superclass called `Animal` that contains a method called `speak()`:

public class Animal {


public void speak() {
System.out.println("The animal speaks");
}
}

In this example, the `Dog` class overrides the `speak()` method of the `Animal` class with its own
implementation. During runtime, if we create an instance of the `Dog` class and call the `speak()` method, it
will execute the `speak()` method of the `Dog` class instead of the `Animal` class.

In conclusion, method overloading and method overriding are two different features in Java that allow
polymorphism in a different way. Method overloading allows creating multiple methods with the same
name but different parameters, while method overriding allows a subclass to provide its own
implementation of a method that is already defined in its superclass with the same name, return type, and
parameters.
4 Differentiate different types of constructors with an example.
A Constructors are special methods in Java that are used to create and initialize objects. There are several
types of constructors in Java, each with its own purpose.

different types of constructors in Java programming language with examples.


1. Default Constructor
A default constructor is a constructor that is provided by the Java compiler if a class does not define any
constructor. The default constructor takes no arguments and does nothing. Its purpose is to initialize the
object's instance variables to their default values. For example:
public class Person {
String name;
int age;

// Default Constructor
public Person() {
}
}

Person p = new Person(); // Invokes default constructor


2. Parameterized Constructor
A parameterized constructor is a constructor that takes one or more arguments. It is used to initialize the
object's instance variables with the values provided by the user. For example:

7
MD Riyan Nazeer CSM-2A 160921748036

public class Person {


String name;
int age;

// Parameterized Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}

Person p = new Person("John Doe", 30); // Invokes parameterized


constructor

3. Copy Constructor
A copy constructor is a constructor that takes an object of the same class as a parameter and creates a new
object with the same values as the parameter object. It is used to create a new object that is a copy of an
existing object. For example:

public class Person {


String name;
int age;

// Copy Constructor
public Person(Person p) {
this.name = p.name;
this.age = p.age;
}
}

Person p1 = new Person("John Doe", 30);


Person p2 = new Person(p1); // Invokes copy constructor

4. Private Constructor
A private constructor is a constructor that is only accessible within the class in which it is defined. It is used
to prevent the creation of objects of the class from outside the class. For example:

public class Singleton {


private static Singleton instance;

// Private Constructor
private Singleton() {
}

public static Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

Singleton s = Singleton.getInstance(); // Invokes public method to get


the singleton instance

5 What is method overloading? Explain with an example.


A • In Java it is possible to define two or more methods within the same class that share the same name, as
long as their parameter declarations are different.

8
MD Riyan Nazeer CSM-2A 160921748036

• When this is the case, the methods are said to be overloaded, and the process is referred to as method
overloading.
• Method overloading is one of the ways that Java implements polymorphism.
• When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to
determine which version of the overloaded method to actually call.
• Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded
methods may have different return types, the return type alone is insufficient to distinguish two versions
of a method.
• When Java encounters a call to an overloaded method, it simply executes the version of the method
whose parameters match the arguments used in the call.

class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a * a;
}
}

class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;

ob.test();
ob.test(10);
ob.test(10, 20);

result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}

OUTPUT:

No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625

6 Discuss about the constructor overloading with an example program.


A Constructor overloading is a technique in Java that allows a class to have multiple constructors with different
parameter lists. The constructors are distinguished by the number and types of parameters they take, just
like method overloading.

Here's an example program that demonstrates constructor overloading:

import java.io.*;

class Box {

9
MD Riyan Nazeer CSM-2A 160921748036

double height, width, depth;

Box() {
height = 10;
width = 20;
depth = 30;
}

Box(double h, double w, double d) {


height = h;
width = w;
depth = d;
}
}

class ConstructorOverload {
public static void main(String args[]) {
Box b1 = new Box();
Box b2 = new Box(100, 200, 300);
System.out.println("Volume is " + b1.height * b1.width * b1.depth);
System.out.println("Volume is " + b2.height * b2.width * b2.depth);
}
}
Output
Volume is 6000.0
Volume is 6000000.0

7 Explain briefly about String class and discuss various methods in String class with an example.
A The String class in Java is used to represent a sequence of characters. It is one of the most commonly used
classes in Java and provides many useful methods for working with strings. Here are some of the methods in
the String class:

• length(): This method returns the length of the string.


• charAt(int index): This method returns the character at the specified index.
• concat(String str): This method concatenates the specified string to the end of the existing string.
• equals(Object obj): This method compares this string to the specified object.
• equalsIgnoreCase(String anotherString): This method compares this String to another String, ignoring
case considerations.
• indexOf(int ch): This method returns the index within this string of the first occurrence of the specified
character.
• lastIndexOf(int ch): This method returns the index within this string of the last occurrence of the
specified character.
• replace(char oldChar, char newChar): This method returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.
• substring(int beginIndex): This method returns a new string that is a substring of this string.
• toLowerCase(): This method converts all of the characters in this String to lower case using the rules of
the default locale.
• toUpperCase(): This method converts all of the characters in this String to upper case using the rules of
the default locale.

Here’s an example that demonstrates some of these methods:

public class StringDemo {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";

10
MD Riyan Nazeer CSM-2A 160921748036

String str3 = str1.concat(str2);


System.out.println("str1: " + str1);
System.out.println("str2: " + str2);
System.out.println("str3: " + str3);
System.out.println("str3 length: " + str3.length());
System.out.println("str3 char at index 0: " + str3.charAt(0));
System.out.println("str3 index of 'o': " + str3.indexOf('o'));
System.out.println("str3 last index of 'o': " +
str3.lastIndexOf('o'));
System.out.println("str3 substring from index 2: " +
str3.substring(2));
System.out.println("str3 substring from index 2 to 5: " +
str3.substring(2, 5));
}
}

Output:

str1: Hello
str2: World
str3: HelloWorld
str3 length: 10
str3 char at index 0: H
str3 index of 'o': 4
str3 last index of 'o': 7
str3 substring from index 2: lloworld
str3 substring from index 2 to 5: llo
8 Explain Dynamic Method Dispatch (Runtime Polymorphism )with example.
A Dynamic Method Dispatch in Java
Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at run time,
rather than compile time. This is how Java implements run-time polymorphism.

When an overridden method is called through a superclass reference, Java determines which version of that
method to execute based on the type of the object being referred to at the time of the call. Thus, this
determination is made at run time.
Dynamic method dispatch allows a class to specify methods that will be common to all of its subclasses,
while allowing subclasses to define the specific implementation of some or all of those methods.

Dynamic Method Dispatch Program:


class A {
void show() {
System.out.println("class A");
}
}

class B extends A {
void show() {
System.out.println("class B");
}
}

class C extends A {
void show() {
System.out.println("class C");
}
}

class DynamicMethod {
public static void main(String[] args) {

11
MD Riyan Nazeer CSM-2A 160921748036

A a;
B b = new B();
a = b;
a.show();
}
}
Output:
class B
9 Define Inheritance? List different types of inheritances in java? Explain each of them in detail with an
example program
A a. Java Inheritance Types
Below are the different types of inheritance which are supported by Java.

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

1. Single Inheritance:
In single inheritance, subclasses inherit the features of one superclass. In the image below, class A
serves as a base class for the derived class B.
import java.io.*;
import java.lang.*;
import java.util.*;

class one {
public void print_geek()
{
System.out.println("Geeks");
}
}
class two extends one {
public void print_for() { System.out.println("for"); }
}
public class Main {
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output
Geeks
for
Geeks

2. Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also
acts as the base class for other classes. In the below image, class A serves as a base class for the derived
class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the
grandparent’s members.

import java.lang.*;
class A {
void display A() {
System.out.println("Class A");

12
MD Riyan Nazeer CSM-2A 160921748036

}
}

class B extends A {
void display B() {
System.out.println("Class B");
}
}

class C extends B {
void display C() {
System.out.println("Class C");
}
}

class Multilevel {
public static void main(String[] args) {
C obj = new C();
obj.displayA();
obj.displayB();
obj.displayC();
}
}
}
output:
Class A
Class B
Class C

3. Hierarchical Inheritance:
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the
below image, class A serves as a base class for the derived classes B, C, and D.
class A {
public void print_A() { System.out.println("Class A"); }
}

class B extends A {
public void print_B() { System.out.println("Class B"); }
}

class C extends A {
public void print_C() { System.out.println("Class C"); }
}

class D extends A {
public void print_D() { System.out.println("Class D"); }
}

// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
C obj_C = new C();
obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();

13
MD Riyan Nazeer CSM-2A 160921748036

obj_D.print_D();
}
}

Output
Class A
Class B
Class A
Class C
Class A
Class D

4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can have more than one
superclass and inherit features from all parent classes. Please note that Java does not support multiple
inheritances with classes. In Java, we can achieve multiple inheritances only through Interfaces. In the image
below, Class C is derived from interfaces A and B.

import java.io.*;
import java.lang.*;
import java.util.*;

interface one {
public void print_geek();
}

interface two {
public void print_for();
}

interface three extends one, two {


public void print_geek();
}
class child implements three {
@Override public void print_geek()
{
System.out.println("Geeks");
}

public void print_for() { System.out.println("for"); }


}

// Drived class
public class Main {
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}

Output
Geeks
for
Geeks

5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types of inheritance.
Since Java doesn’t support multiple inheritances with classes, hybrid inheritance is also not possible with
classes. In Java, we can achieve hybrid inheritance only through Interfaces.

14
MD Riyan Nazeer CSM-2A 160921748036

class HumanBody
{
public void displayHuman()
{
System.out.println("Method defined inside HumanBody class");
}
}
interface Male
{
public void show();
}
interface Female
{
public void show();
}

// Single Inheritance is the relationship between Child // class and


HumanBody class.
// Implementing Male and Female interface is Multiple // Inheritance
public class Child extends HumanBody implements Male, Female
{
public void show()
{
System.out.println("Implementation of show() method defined in
interfaces Male and Female");
}

public void displayChild()


{
System.out.println("Method defined inside Child class");
}

public static void main(String[]args)


{
Child obj = new Child();
System.out.println("Implementation of Hybrid Inheritance in Java");
obj.show();
obj.displayChild();
}
}
10 Write a java program to read ‘n’ numbers from console and print their sum and Average.
A import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the value of n: ");


int n = scanner.nextInt();

int sum = 0;

for (int i = 0; i < n; i++) {


System.out.print("Enter number " + (i + 1) + ": ");
int number = scanner.nextInt();
sum += number;
}

double average = (double) sum / n;

15
MD Riyan Nazeer CSM-2A 160921748036

System.out.println("Sum: " + sum);


System.out.println("Average: " + average);
}
}
OUTPUT:
Enter the value of n: 2
Enter number 1: 1
Enter number 2: 2
Sum: 3
Average: 1.5

UNIT 2
SAQ’s

16
MD Riyan Nazeer CSM-2A 160921748036

1 Compare and Contrast differences between interfaces vs. Abstract class


A Feature Interface Abstract Class
Definition Collection of abstract methods and constants Class that cannot be instantiated
Method Can have both abstract and concrete
All methods are public and abstract
Implementation methods
Inheritance Supports multiple inheritance Supports single inheritance
Methods are public, variables are public, Methods and variables can have various
Accessibility
static, and final access modifiers
Constructor Cannot have constructors Can have constructors
Implementation
Allows implementing multiple interfaces Allows extending only one abstract class
Flexibility
Purpose and Defines contracts and API for unrelated Provides a common base for related
Design classes classes
Multiple
Supports multiple inheritance Does not support multiple inheritance
Inheritance
2 What are interfaces? What is the use of interface?
A In Java, an interface 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

Here are some uses of interfaces in Java:


1. An interface can be used to achieve abstraction.
2. We can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling
3 Define a package?
A To create a package in Java, simply include a package command as the first statement in a Java source file.
Any classes declared within that file will belong to the specified package. The package statement defines a
name space in which classes are stored. If you omit the package statement, the class names are put into the
default package, which has no name.

his is the general form of the package statement:


package pkg;
4 What are the advantages of using the packages?
A Packages in Java have several advantages. Some of them are:
1. Name Collision: Packaging helps to avoid class name collision.
2. Provide Control Access: The access specifiers have ingress control on package level and protected.
3. Reuse of Code: The most useful advantage of packages is reusability.
4. Information Hiding: With the help of packages, the class information will conceal.
5. Organization of Project: Packages play a significant role in organizing the structure of data that contains
several enumerations, interfaces, and classes.

5 Define various steps for creating and importing packages.


A Here are the steps for creating and importing packages in Java:
1. Choose a package name: Choose a package name according to the naming convention.
2. Write the package name: Write the package name at the top of every source file (classes, interface,
enumeration, and annotations).
3. Compile to create the Java packages: Compile to create the Java packages.
4. Importing a Package: If you want to use a package in a Java program, it is necessary to import that
package at the top of the program by using the import keyword before the package name.

6 Define an abstract class? Give an example.


A An abstract class in Java is a class that cannot be instantiated and can contain both abstract and non-
abstract methods. We use the abstract keyword to declare an abstract class.

17
MD Riyan Nazeer CSM-2A 160921748036

Here is a short example:


abstract class Shape {
abstract void draw();
}

class Circle extends Shape {


void draw() {
System.out.println("drawing circle");
}
}

class TestAbstraction1 {
public static void main(String args[]) {
Shape s = new Circle();
s.draw();
}
}
7 Define Exception?
A An abnormal event in a program is called an exception. Exceptions may occur at compile time or at runtime.
Exceptions which occur at compile time are called checked exceptions, such as Class Not Found Exception,
No Such Method Exception, No Such Field Exception etc. Exceptions which occur at runtime are called
unchecked exceptions, such as Array Index Out Of Bounds Exception, Arithmetic Exception, etc.
8 Distinguish between exception and error?
A
Feature Exceptions Errors
Categorization Checked exceptions and unchecked exceptions Errors
Handling Checked exceptions must be caught or Errors should not be caught or
Requirement declared handled
Recoverability Exceptions represent recoverable errors Errors indicate severe,
unrecoverable problems
Superclass Derived from java.lang.Exception Derived from java.lang.Error
Program Impact Exceptions can be handled programmatically Errors typically lead to program
termination
Examples File Not Found Exception, Parse Exception Out Of Memory Error, Stack Over
flow Error

9 What are the benefits of exception handling


A BENEFITS OF EXCEPTION HANDLING
Exception handling provides the following advantages over ``traditional'' error Management techniques:

Separating Error Handling Code from ``regular'' one


It separates the working/functional code from the error-handling code by way of try-catch clauses.

Propagating Errors Up the Call Stack


It allows a clean path for error propagation. If the called method encounters a situation it can't manage, it
can throw an exception and let the calling method deal with it.

Error Types and Error Differentiation


By enlisting the compiler to ensure that "exceptional" situations are anticipated and accounted for, it
enforces powerful coding.

18
MD Riyan Nazeer CSM-2A 160921748036

10 Difference between checked and unchecked exceptions?


A
Property Checked Exception Unchecked Exception
Exceptions that are checked at compile
Definition Exceptions that are not checked at compile time
time
Occurrenc
Occur at compile time Occur at runtime
e
Must be handled or specified using the
Handling Not required to be handled
throws keyword
Used to indicate exceptional conditions
Indication Used to indicate programming errors
that are out of the program’s control
IO Exception, Class Not Found
Examples Run time Exception, Error
Exception
11 What is the difference between throw and throws clause? Or
What is the difference between throw and throws keyword?
A
Property throw throws
Used to throw an exception Used in the method signature to declare an exception which
Definition explicitly from a method or might be thrown by the function while the execution of the
a block of code code
Number of Can throw only one Can declare multiple exceptions that can be thrown by the
exceptions exception at a time method
Followed by an instance of
Syntax Followed by class names of Exceptions to be thrown
Exception to be thrown
Declaration Used within the method Used with the method signature

12 What is the use of String Tokenizer?


A The StringTokenizer class in Java is used to break a string into tokens. It is a simple way to break a string into
smaller parts called tokens. A StringTokenizer object internally maintains a current position within the string
to be tokenized. Some operations advance this current position past the characters processed.

For example, if you have a string "Hello World", you can use StringTokenizer to split it into two tokens:
"Hello" and "World". You can specify the delimiters (characters that separate tokens) when creating a
StringTokenizer object
13 Define Serialization. OR What is serialization? Which type variables cannot be serialized?
A Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in
Hibernate, RMI, JPA, EJB and JMS technologies. Static variables cannot be serialized because they belong to
the class, not the instance.
14 What is serialization and deserialization?
A Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in
Hibernate, RMI, JPA, EJB and JMS technologies. Static variables cannot be serialized because they belong to
the class, not the instance.

The reverse operation of serialization is called deserialization where byte-stream is converted into an object.
The serialization and deserialization process is platform-independent, it means you can serialize an object on
one platform and deserialize it on a different platform.
15 Define byte stream?
A Byte streams in Java are used to perform input and output operations of 8-bit bytes. All byte stream classes
are descended from InputStream and OutputStream1. Byte streams are useful for reading or writing binary
files, such as images or audio files
16 Define character stream?
A Character streams in Java are used to perform input and output operations for 16-bit Unicode characters.
They can perform operations on characters, char arrays, and Strings. Character streams are useful for
reading or writing text files, which are processed character by character.

19
MD Riyan Nazeer CSM-2A 160921748036

The Reader and Writer classes are the superclasses of all character stream classes
17 What is the use of Print Writer Class.
A The PrintWriter class in Java is part of the java.io package and provides a way to write formatted text output
to a file or other output stream. It is often used to write text data to files, sockets, or other data streams.
The PrintWriter class extends the abstract class Writer
18 List the methods in Input stream and list the methods in Output stream
A InputStream and OutputStream are two abstract classes in Java that describe stream input and output,
respectively. They are part of the java.io package and provide a way to read and write data to a file or other
output stream.

Here are some commonly used methods of the InputStream class:


• read(): reads one byte of data from the input stream.
• read(byte[] array): reads bytes from the stream and stores them in the specified array.
• available(): returns the number of bytes available in the input stream.
• close(): closes the input stream.

Here are some commonly used methods of the OutputStream class:


• write(int): writes a byte to the current output stream.
• write(byte[]): writes an array of bytes to the current output stream.
• flush(): flushes the current output stream.
• close(): closes the output stream.

LAQ’s
1 What are packages? How do you create and use packages. Illustrate with an example. Or
Explain how to create a package and import a package with suitable example.
A In Java, a package is a mechanism to encapsulate a group of classes, sub-packages and interfaces. Packages
are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and
usage of classes, interfaces, enumerations and annotations easier.

To create a package in Java, simply include a package command as the first statement in a Java source file.
Any classes declared within that file will belong to the specified package. The package statement defines a
name space in which classes are stored. If you omit the package statement, the class names are put into the
default package, which has no name

Here’s an example of how to create a package in Java:


package MyPackage;
public class MyClass {
// Class code goes here
}

To import a package in Java, use the import keyword followed by the fully qualified name of the package.
Here’s an example:
import java.util.ArrayList;

In Java, file system directories are used to store packages. More than one file can include the same package
statement. The package statement simply specifies to which package the classes defined in a file belong. It
does not exclude other classes in other files from being part of that same package. Most real-world
packages are spread across many files. You can create a hierarchy of packages by separating each package
name from the one above it by use of a period.

The general form of a multileveled package statement is shown here:


package pkg1.pkg2.pkg3;

A package hierarchy must be reflected in the file system of your Java development system. For example:
package java.awt.image;

20
MD Riyan Nazeer CSM-2A 160921748036

2 Define interface? Write with an example?


A An interface in Java is a collection of abstract methods (methods without a body) and constants. It specifies
a contract that implementing classes must follow. A class that implements an interface must provide an
implementation for all of its methods.
Here’s an example that demonstrates the use of an interface:
interface Drawable {
void draw();
}

class Rectangle implements Drawable {


public void draw() {
System.out.println("Drawing rectangle");
}
}

class Circle implements Drawable {


public void draw() {
System.out.println("Drawing circle");
}
}

class TestInterface {
public static void main(String args[]) {
Drawable d = new Circle();
d.draw();
}
}
Output
Drawing circle
3 What is the difference between Interface and abstract classes?
A In Java, both interfaces and abstract classes are used to define a set of methods that subclasses must
implement. However, there are some key differences between them. Let's put these differences in a table
for better clarity:
Aspect Interface Abstract Class
Declaration Declared using the interface keyword. Declared using the abstract keyword.
Supports multiple inheritance (interfaces Supports single inheritance (abstract classes
Inheritance
can extend other interfaces). can extend one class only).
Cannot contain method Can contain both abstract and concrete
Implementatio implementations, only method methods. Subclasses must implement
n signatures. abstract methods and can optionally
override concrete methods.
Cannot have constructors. Can have constructors, which are called
Constructor
when a subclass object is created.
Can only have public static final Can have various types of variables,
Variables (constant) variables. including instance variables, class variables,
and constants.
Methods are implicitly public. Variables Can have different access modifiers for
Access
are implicitly public static final. methods and variables, providing more
Modifiers
control over visibility.
Used when a class wants to provide a Used when a base class wants to provide
Usage contract for multiple unrelated classes to common functionality and leave specific
implement. implementation details to its subclasses.
Implementatio More flexible, as a class can implement Less flexible, as a class can extend only one
n Flexibility multiple interfaces. abstract class.
Adding new methods to an interface is Adding new abstract methods to an abstract
Extensibility
less disruptive, as all implementing class can be more disruptive, as all

21
MD Riyan Nazeer CSM-2A 160921748036

classes will need to provide subclasses must implement these new


implementations. methods.
4 What is Exception? Explain about user defined exceptions
A An abnormal event in a program is called an exception. Exceptions may occur at compile time or at runtime.
Exceptions which occur at compile time are called checked exceptions, such as Class Not Found Exception,
No Such Method Exception, No Such Field Exception etc. Exceptions which occur at runtime are called
unchecked exceptions, such as Array Index Out Of Bounds Exception, Arithmetic Exception, etc.

In Java, you can create your own exceptions that are derived classes of the Exception class. Creating your
own exception is known as a custom exception or user-defined exception. Java custom exceptions are used
to customize the exception according to user needs
class OwnException extends Exception {
OwnException(String msg) {
super(msg);
}
}

class MyException {
public static void main(String[] args) {
int marks = Integer.parseInt(args[0]);
try {
if (marks < 0 || marks > 100) {
throw new OwnException("Marks should be between 0 to 100");
} else {
System.out.println("Entered marks are " + marks);
}
} catch (OwnException e) {
System.out.println(e.getMessage());
}
}
}
output:
java MyException 75
5 a) Write a program for example of multiple catch statements occurring in a program.
b) Write a java program that demonstrates user defined exceptions.
A a)
package exceptionHandling;

public class MultiCatchEx2 {


public static void main(String[] args) {
String s = "Scientech Easy";
int a[] = {0, 1, 2, 3, 4, 5};
try {
s = null;
int sLength = s.length();
System.out.println("String length: " + sLength);
int b = 6;
System.out.println(a[b]);
} catch (NullPointerException npe) {
System.out.println("NullPointerException is caught");
System.out.println(npe.toString());
} catch (ArrayIndexOutOfBoundsException aie) {
System.out.println("ArrayIndexOutOfBoundsException is
caught");
System.out.println(aie.toString());
}
}
}
Output:
Exception is caught java.lang.NullPointerException

22
MD Riyan Nazeer CSM-2A 160921748036

b)
class OwnException extends Exception {
OwnException(String msg) {
super(msg);
}
}

class MyException {
public static void main(String[] args) {
int marks = Integer.parseInt(args[0]);
try {
if (marks < 0 || marks > 100) {
throw new OwnException("Marks should be between 0 to 100");
} else {
System.out.println("Entered marks are " + marks);
}
} catch (OwnException e) {
System.out.println(e.getMessage());
}
}
}
output:
java MyException 75
6 What is an Exception? How does a java program handle the Exception,
write about all exception handling keywords used in java. OR
What is an Exception? Explain how exceptions are handled in JAVA with suitable example.
A An abnormal event in a program is called an exception. Exceptions may occur at compile time or at runtime.
Exceptions which occur at compile time are called checked exceptions, such as Class Not Found Exception,
No Such Method Exception, No Such Field Exception etc. Exceptions which occur at runtime are called
unchecked exceptions, such as Array Index Out Of Bounds Exception, Arithmetic Exception, etc.

A java program handle exceptions are handled using the try-catch block. The code that may throw an
exception is enclosed in the try block. The catch block contains code that handles the exception if it is
thrown by the code in the try block.

Java provides several keywords for handling exceptions: `try`, `catch`, `finally`, `throw`, and `throws`.
• try: The `try` keyword is used to define a block of code that might throw an exception. If an exception is
thrown within the `try` block, it is caught by a `catch` block that can handle that type of exception.
• catch: The `catch` keyword is used to define a block of code that handles a specific type of exception
thrown within the corresponding `try` block. A `catch` block must be associated with a `try` block and
must specify the type of exception it can handle.
• finally: The `finally` keyword is used to define a block of code that is always executed after the `try` and
`catch` blocks, regardless of whether an exception was thrown or not. The `finally` block is typically used
to release resources or perform cleanup operations.
• throw: The `throw` keyword is used to explicitly throw an exception. It takes an instance of an exception
class as its argument and transfers control to the nearest `catch` block that can handle that type of
exception.

Example program for exception handling


Same as above program
7 Differentiate between checked and unchecked exceptions?
A In Java, exceptions are divided into two categories: checked and unchecked.

Checked exceptions are exceptions that are checked at compile-time. This means that the compiler checks if
a method that might throw a checked exception either handles it using a try-catch block or declares it using

23
MD Riyan Nazeer CSM-2A 160921748036

the throws keyword. If neither of these conditions is met, the code will not compile. Checked exceptions are
used to represent exceptional conditions that a well-written application should anticipate and recover from.
Examples of checked exceptions include IOException, ClassNotFoundException, and SQLException.

Unchecked exceptions, on the other hand, are exceptions that are not checked at compile-time. This means
that the compiler does not enforce any handling or declaration requirements for these exceptions.
Unchecked exceptions are used to represent exceptional conditions that are usually caused by programming
errors and cannot be reasonably anticipated or recovered from. Examples of unchecked exceptions include
RuntimeException, NullPointerException, and IndexOutOfBoundsException.

The main difference between checked and unchecked exceptions is that checked exceptions must be
explicitly handled or declared, while unchecked exceptions do not have this requirement. This means that
checked exceptions provide a way to enforce error handling at compile-time, while unchecked exceptions do
not.

Checked Exceptions Unchecked Exceptions


Must be handled by the code that calls the method Do not have to be handled or declared in the
that throws the exception method signature
Examples include IOException, Examples include NullPointerException,
ClassNotFoundException, SQLException ArrayIndexOutOfBoundsException,
ArithmeticException
Typically represent anticipated exceptional Usually caused by programming errors or mistakes
conditions that cannot be easily recovered from
Extends Exception (excluding RuntimeException and Extends RuntimeException or its subclasses
its subclasses)
8 Define Serialization. Write a program to demonstrate it. OR
What is serialization? Write a program to demonstrate the concept of Serialization?
A Serialization is a process of writing the state of an object to a byte stream. This is useful when you want to
save the state of your program to a persistent storage area such as a file. At a later time, you may restore
these objects by using the process of deserialization. Serialization is also needed to implement remote
method invocation.

import java.io.*;

public class SerializationDemo {


public static void main(String args[]) {
try {
MyClass object1 = new MyClass("hello", 8, 8.5);
System.out.println("object = " + object1);

FileOutputStream fos = new FileOutputStream("serial");


ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
} catch (IOException e) {
System.out.println("Exception during serialization");
System.exit(0);
}

try {
MyClass object2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass) ois.readObject();
ois.close();
System.out.println("object2: " + object2);
} catch (Exception e) {

24
MD Riyan Nazeer CSM-2A 160921748036

System.out.println("Exception during deserialization");


System.exit(0);
}
}
}

class MyClass implements Serializable {


String s;
int i;
double d;

public MyClass(String s, int i, double d) {


this.s = s;
this.i = i;
this.d = d;
}

public String toString() {


return "s=" + s + ", i=" + i + ", d=" + d;
}
}

Output:
object = s=hello, i=8, d=8.5
object2: s=hello, i=8, d=8.5

9 What is the purpose of Sting Tokenizer class. Explain with example program. OR
Write a java program to illustrate the use of string tokenizer.
A The StringTokenizer class in Java is used to break a string into tokens. A StringTokenizer object internally
maintains a current position within the string to be tokenized. Some operations advance this current
position past the characters processed. A token is returned by taking a substring of the string that was used
to create the StringTokenizer object.

This class provides the first step in the parsing process often called lexer or scanner. It allows an application
to break a string into tokens. However, it is a legacy class that is retained for compatibility reasons although
its use is discouraged in new code3. Its methods do not distinguish among identifiers, numbers, and quoted
strings.
Program:
import java.util.*;

public class Tokenizer {


public static void main(String[] args) {
int sum = 0;
Scanner scan = new Scanner(System.in);
String s = scan.next();
StringTokenizer st = new StringTokenizer(s, ",");
while (st.hasMoreTokens()) {
String s2 = st.nextToken();
System.out.println(s2);
int x = Integer.parseInt(s2);
sum = sum + x;
}
System.out.println(sum);
}
}
Enter a string: 10,20,30,40,50.
10
20
30

25
MD Riyan Nazeer CSM-2A 160921748036

40
50
150
10 What is character stream in java? Explain any three-character streams with examples. OR
How do you use character streams, show with example?
A CHARACTER STREAM:
The character stream is used for inputting or outputting the characters. There are two super classes in
character stream and those are Reader and Writer from which most of the other classes are derived.
FileReader FileWriter
PipeReader PipeWriter
FilterReader FilterWriter
BufferedReader BufferedWriter
DataReader DataWriter
LineNumberReader LineNumberWriter
PushbackReader PushbackWriter
ByteArrayReader ByteArrayWriter
SequenceReader SequenceWriter
StringBufferReader StringBufferWriter

1. FileReader and FileWriter:


• FileReader: This class is used to read character data from a file. It reads characters from a file in a stream
and converts them to Unicode characters.
• FileWriter: This class is used to write character data to a file. It takes Unicode characters as input and
writes them to a file in a stream.

2. PipeReader and PipeWriter:


• PipeReader: It is used to read data from a piped output stream. It is typically used in a multi-threaded
environment where one thread writes data to the output stream, and another thread reads data from
the corresponding PipeReader.
• PipeWriter: It is used to write data to a piped input stream. It connects to a PipeReader to form a
communication pipe between threads.

3. FilterReader and FilterWriter:


• FilterReader: It provides additional functionality to an existing Reader by filtering the data being read. It
wraps around another Reader and can modify the data before it is read.
• FilterWriter: It provides additional functionality to an existing Writer by filtering the data being written.
It wraps around another Writer and can modify the data before it is written.

import java.io.*;
public class TextFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}

26
MD Riyan Nazeer CSM-2A 160921748036

}
}
}

11 Write a java program illustrate the use of I/0 streams.


A import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyExample {


public static void main(String[] args) {
String sourceFile = "path/to/source/file.txt";
String destinationFile = "path/to/destination/file.txt";

try {
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destinationFile);

byte[] buffer = new byte[1024];


int length;

while ((length = fis.read(buffer)) > 0) {


fos.write(buffer, 0, length);
}

fis.close();
fos.close();

System.out.println("File copied successfully.");


} catch (IOException e) {
e.printStackTrace();
}
}
}

UNIT 3
SAQ’s
1 Distinguish between process and thread?
A
S.NO Thread Process
1 Light weight process Heavy weight process
2 Do not require separate address space for Each process requires separate address space for
its execution. its execution.

2 What are the different ways to create a thread? Or


Discuss various methods used to create threads.
A There are 3 ways to create a thread in Java:
1. Extending the Thread class: You can create a thread by extending the Thread class and overriding its
run() method. Then, you can create an instance of the custom thread class and call the start() method to
start the thread's execution.

2. Implementing the Runnable interface: Another way to create a thread is by implementing the Runnable
interface and providing the implementation for the run() method. Then, you can create a Thread
instance, passing the Runnable object as an argument, and call the start() method.

3. Using the ExecutorService framework (Java 5 and later): The ExecutorService framework provides a
higher-level approach to manage thread execution. You can use the ExecutorService and related classes
to create and manage threads easily

27
MD Riyan Nazeer CSM-2A 160921748036

3 Define inter-thread communication?


A Inter-thread communication is a mechanism that allows threads to communicate with each other. In Java,
this can be achieved using methods such as wait(), notify(), and notifyAll().

4 What is synchronization?
A Synchronization is the process by which two or more threads ensure that a shared resource will be used by
only one thread at a time. The process by which this is achieved is called synchronization.
5 How many ways can thread be Created?
A Same as 2
6 Explain about the alive () and join() method
A isAlive() method: Checks if a thread is currently running (true) or terminated/not started (false).
join() method: Waits for a thread to complete its execution before proceeding with the current thread's
execution
7 Explain about thread priorities.
A In Java, the thread scheduler selects the threads using their priorities. The thread priority is a simple integer
value that can be assigned to a particular thread. These priorities can range from 1 (low priority) to 10
(highest priority).
Two commonly used methods are
1. setPriority()
2. getPriority()
8 Write short note on multithreaded programming.
A Multithreading is a process of executing multiple threads simultaneously. In Java, multithreading can be
achieved by extending the Thread class or implementing the Runnable interface.
Two commonly used methods are setPriority() and getPriority().
The thread priority is an integer value that can range from 1 (low priority) to 10 (highest priority).
9 Define collections?
A Collection represents a group of objects known as its elements. The Java Collections Framework provides a
well-designed set of interfaces and classes for storing and manipulating groups of data as a single unit, a
collection. The framework provides several core interfaces, including Collection, List, Set, Queue, and Deque,
as well as their various implementations such as ArrayList, LinkedList, HashSet, LinkedHashSet, and TreeSet
10 List different collection classes and collection interfaces.
A List different collection classes

1. ArrayList
2. ArrayDeque
3. HashSet
4. HashMap
5. LinkedList
6. LinkedHashSet
7. LinkedHashMap
8. PriorityQueue
9. TreeSet
10. TreeMap

11 Draw the hierarchy of collection interface.

28
MD Riyan Nazeer CSM-2A 160921748036

12 Give the difference between vector and array list classes. Or


Differentiate between vector and array list?
A Vector ArrayList
Vector is synchronized. ArrayList is not synchronized.
Vector increments 100% means doubles the array ArrayList increments 50% of current array size if the
size if the total number of elements exceeds than its number of elements exceeds from its capacity.
capacity.
Vector is a legacy class. ArrayList is not a legacy class.
Vector is slow because it is synchronized ArrayList is fast because it is non-synchronized.
A Vector can use the Iterator interface or ArrayList uses the Iterator interface to traverse the
Enumeration interface to traverse the elements. elements.
13 What is Iterator?
A In Java, iterators are used to traverse and access elements in various data structures like lists, sets, and
maps. The main advantage of using iterators is that they provide a consistent way to access elements
regardless of the underlying data structure's implementation. Java provides several types of iterators,
including:
1. Iterator
2. ListIterator
3. Enumeration

14 What is the difference between HashSet and Linked HashSet classes?


A
HashSet LinkedHashSet
HashSet is an unordered & unsorted collection of LinkedHashSet is an ordered and sorted collection
the data set. of HashSet.
HashSet does not provide any method to maintain LinkedHashSet maintains the insertion order of
the insertion order. elements.
HashSet uses a mechanism called “Hashing” to store LinkedHashSet uses a hashtable & a doubly-linked
the elements. list to store & maintain the elements.

15 What are legacy classes?


A Legacy classes in Java are the classes and interfaces that formed the collections framework in the earlier
versions of Java. They were reengineered to support the Collection interfaces and Generics in later versions.
They are fully compatible with the framework and are not deprecated. Some examples of legacy classes are
Vector, Hashtable, and Stack
LAQ’s
1 Compare the various ways of creation of thread with an example.
A In Java, there are two main ways to create threads: using the Thread class and implementing the Runnable
interface. Both approaches allow you to create and manage threads, but they differ in how they are
implemented.

29
MD Riyan Nazeer CSM-2A 160921748036

1. Extending the Thread class: In this approach, you create a new class that extends the Thread class and
overrides the run() method with the code that will be executed in the new thread.
Example:
public class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread using Thread class: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); }}

2. Implementing the Runnable interface: In this approach, you create a class that implements the
Runnable interface and provides the implementation for the run() method. Then, you create a Thread
object and pass an instance of your Runnable class to its constructor.
Example:
public class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread using Runnable interface: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {


MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
2 Explain with an example how java performs thread synchronization? Or
Explain the concept of thread synchronization with the help of a program.
A class Reserve implements Runnable {
int available = 1;
int wanted;

Reserve(int i) {
wanted = i;
}

public void run() {


synchronized (this) {
System.out.println("Available berths = " + available);
if (available >= wanted) {
String name = Thread.currentThread().getName();
System.out.println(wanted + " berth reserved for " +
name);
try {
Thread.sleep(2000);
available = available - wanted;

30
MD Riyan Nazeer CSM-2A 160921748036

} catch (InterruptedException ie) {


System.out.println(ie);
}
} else {
System.out.println("Sorry, no berths available.");
}
}
}
}

public class ThreadSynchronization {


public static void main(String[] args) {
Reserve obj = new Reserve(1);
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
t1.setName("First person");
t2.setName("Second person");
t1.start();
t2.start();
}
}
Output:
Available berths = 1
1 berth reserved for First person
Available berths = 0
Sorry, no berths available.
3 Explain briefly about the life cycle of a thread with an example.
A The life cycle of a thread in Java refers to the different states that a thread goes through during its existence.
A thread can be in one of several states at any given time, and its behavior and actions vary depending on its
current state. The life cycle of a thread can be summarized by the following states:

New (Born) State: When a thread object is created, it is in the "New" state. The thread has not yet started
its execution.

Ready State: After calling the start() method on the thread, it enters the "Ready" state. The thread is now
eligible to run and is waiting for the CPU time.

Running State: When the thread scheduler selects the thread from the "Ready" state, it enters the
"Running" state and starts executing its run() method.

Blocked State: A thread may enter the "Blocked" state when it is waiting for a certain condition to be
satisfied, such as waiting for a resource, waiting for a lock, or waiting for a notification using wait().

Sleeping State (Suspended State): A thread can enter the "Sleeping" state by calling the sleep() method. In
this state, the thread is not using the CPU, and it will resume after the specified sleep time or when
interrupted.

Waiting State: Threads can enter the "Waiting" state when they call the wait() method, waiting for a
notification from another thread using notify() or notifyAll().

Terminated (Dead) State: A thread enters the "Terminated" state when its run() method completes its
execution or when it is forcefully terminated using the stop() method (which is deprecated and not
recommended).
4 How to set priorities to thread in java. Specify various examples.
A n Java, you can set the priority of a thread using the setPriority() method, and you can retrieve the priority
of a thread using the getPriority() method. As mentioned in your context, thread priorities range from 1
(lowest priority) to 10 (highest priority).
Here's an explanation of the provided example code:

31
MD Riyan Nazeer CSM-2A 160921748036

class A extends Thread {


public void run() {
System.out.println("Thread #1");
for (int i = 1; i <= 5; i++) {
System.out.println("\tA: " + i);
}
System.out.println("End of Thread #1");
}
}

class B extends Thread {


public void run() {
System.out.println("Thread #2");
for (int k = 1; k <= 5; k++) {
System.out.println("\tB: " + k);
}
System.out.println("End of Thread #2");
}
}
public class ThreadPriority {
public static void main(String args[]) {
A a = new A();
B b = new B();

a.setPriority(1); // Set priority of Thread A to the lowest


(MIN_PRIORITY)
b.setPriority(10); // Set priority of Thread B to the highest
(MAX_PRIORITY)

System.out.println("Starting Thread #1");


a.start();

System.out.println("Starting Thread #2");


b.start();
}
}

OUTPUT
Thread #1
Thread #2
B: 1
B: 2
B: 3
B: 4
B: 5
End of Thread #2 A: 1
A: 2
A: 3
A: 4
A: 5
End of Thread #1
5 Explain the Java Collection framework with an example.
A The Java Collection framework provides a set of interfaces, implementations, and algorithms to manage and
manipulate groups of objects. It is designed to provide a unified and efficient way to work with collections of
data in Java.

At the core of the Java Collection framework are several key interfaces:

1. List: An ordered collection that allows duplicate elements. Lists can be accessed by their index.

32
MD Riyan Nazeer CSM-2A 160921748036

2. Set: A collection that does not allow duplicate elements. Sets do not have a specific order.
3. Map: A collection that maps keys to values. Each key is unique, and it is used to retrieve its
corresponding value.
4. Queue: A collection designed for holding elements prior to processing. Elements are typically processed
in a FIFO (First-In, First-Out) order.

Here’s an example of how to use the Java Collections Framework to create a list of cities:
import java.util.ArrayList;
import java.util.List;

public class Main {


public static void main(String[] args) {
List<String> city = new ArrayList<String>();
city.add("New York");
city.add("Dhanbad");
city.add("Mumbai");
System.out.println(city);
}
}

6 Explain the different iterators used for accessing the elements with example
A There are three types of iterators in Java:
1. Iterator: An Iterator is an object that allows iterating over elements of a collection. It is used to traverse
a collection object’s elements one by one. It is a universal iterator as we can apply it to any Collection
object. By using Iterator, we can perform both read and remove operations. It is an improved version of
Enumeration with the additional functionality of removing an element.

2. ListIterator: A ListIterator is an object that allows iterating over elements of a List in both directions
(forward and backward). It is used to traverse a List object’s elements one by one. It provides more
functionality than Iterator like adding an element, replacing an element, etc.

3. Enumeration: An Enumeration is an object that allows iterating over elements of a collection. It is used
to traverse a collection object’s elements one by one. It provides only read access to the collection’s
data and does not have any methods for modifying the collection

import java.util.ArrayList;
import java.util.Iterator;

public class Main {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

Iterator<String> itr = list.iterator();


while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}
7 Define map. How to store data using Map interface? Explain with an example.
A In Java, a Map is a way to store data using key-value pairs. It's like a dictionary where you can look up a word
(key) and find its definition (value). There are three common classes that implement the Map interface:

1. Hashtable: Think of it as a synchronized dictionary. It's safe to use in multiple threads but can be slower.

33
MD Riyan Nazeer CSM-2A 160921748036

2. HashMap: Think of it as a dictionary that's not synchronized. It's faster but not thread-safe. It allows null
keys and null values.
3. TreeMap: Think of it as a dictionary that keeps the words sorted. It's not synchronized but provides
sorted order based on keys.

To store data using the Map interface in Java, follow these steps:

1. Choose a Map implementation: There are different classes that implement the Map interface, such as
Hashtable, HashMap, and TreeMap. Select the appropriate implementation based on your needs.

2. Create a Map object: Instantiate the chosen Map class using the appropriate syntax. For example:
Map<String, Integer> map = new HashMap<>(); // Using HashMap
implementation

3. Add data: Use the `put(key, value)` method to add key-value pairs to the map. The key should be unique,
and the value can be any data type.
map.put("apple", 10);
map.put("banana", 5);

4. Retrieve data: Access values from the map using the `get(key)` method, providing the corresponding key.
int appleCount = map.get("apple"); // Retrieves the value associated
with the "apple" key

5. Update data: If needed, you can update the value associated with a specific key by using the `put(key,
value)` method again.
map.put("apple", 15); // Updates the value for the "apple" key to 15

6. Remove data: To remove a key-value pair from the map, use the `remove(key)` method, providing the key
to be removed.
map.remove("banana"); // Removes the key-value pair with the key
"banana"
8 Write a Java program to copy the content of one file to other OR
Write a program to copy one file into another.
A import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyExample {


public static void main(String[] args) {
String sourceFile = "path/to/source/file.txt";
String destinationFile = "path/to/destination/file.txt";

try {
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destinationFile);

byte[] buffer = new byte[1024];


int length;

while ((length = fis.read(buffer)) > 0) {


fos.write(buffer, 0, length);
}

fis.close();
fos.close();

System.out.println("File copied successfully.");


} catch (IOException e) {

34
MD Riyan Nazeer CSM-2A 160921748036

e.printStackTrace();
}
}
}

UNIT 4
SAQ’s
1 Define JDBC?
A JDBC (Java Database Connectivity) is a Java API that provides a standard way to connect and interact with
relational databases. A JDBC driver is a software component that enables Java applications to connect and
communicate with a specific type of database. There are four types of JDBC drivers based on how they
interact with the database:
1. JDBC-ODBC Bridge Driver
2. Native API/Partly Java Driver
3. Network Protocol Driver
4. Thin Driver

2 Define adapter class? Or What is the use of adapter classes? Or Define adapter class. Why is it used?
A Adapter classes: Adapter classes in Java provide a default implementation of an interface so that the
implementing class only needs to override the required methods. They are commonly used with event
listeners in graphical user interfaces (GUIs). Instead of implementing all the methods of an interface, you can
extend an adapter class and override only the methods you need, making the code more concise. Adapter
classes are typically abstract classes.
3 Distinguish between applet and application? Or
How is applet differing from stand atom application program?
A
4 Explain the life cycle of an Applet.
A he life cycle of an applet in Java refers to the various stages that an applet goes through from its creation to
its destruction. The life cycle of an applet is managed by the applet container and includes the following
methods:
• init(): This method is called to initialize the applet. It is invoked only once, when the applet is first
loaded.
• start(): This method is called to start the applet. It is invoked immediately after the init() method, and
every time the applet is restarted.
• stop(): This method is called to stop the applet. It is invoked when the user leaves the page containing
the applet or when the applet is no longer visible.
• destroy(): This method is called to destroy the applet. It is invoked when the browser is finished with the
applet and wants to reclaim its resources.

paint(): This method is called to paint the applet on the screen. It is invoked after the start() method and
whenever the applet needs to be repainted.
5 Explain the delegation event model. Or
What is event delegation model? Or
State event delegation model. Or
Describe the Delegation Event Model.
A The Delegation Event Model in Java is a way of handling events in GUI programming languages. It consists of
three main components: event source, event object, and event listener. When an event occurs, the source
object generates an event object and passes it to all the registered listeners. The listener waits until it
receives an event. Once it receives the event, it is processed by the listener and returns it. The UI elements
are able to delegate the processing of an event to a separate function. The key advantage of the Delegation
Event Model is that the application logic is completely separated from the interface logic. So, when you
interact with a graphical user interface, such as clicking on a button or scrolling, each is known as an event
that is mapped to a code to respond to functionality to the user. This is known as event handling
6 Explain the Event Handling Mechanism. Or
What is event handling mechanism? Give different event handling classes

35
MD Riyan Nazeer CSM-2A 160921748036

A In Java, an event is an object that represents an action such as a mouse click, key press, or window resize.
The mechanism that controls the event and decides what should happen if an event occurs is called the
Event Handling Mechanism.
Java uses the Delegation Event Model to handle events. This model defines the standard mechanism to
generate and handle events. It has Sources and Listeners. Events are generated from the source, which can
be buttons, checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc. Listeners are
used for handling the events generated from the source. Each of these listeners represents interfaces that
are responsible for handling events.

To perform Event Handling, we need to register the source with the listener. Different classes provide
different registration methods.

The java.awt.event package can be used to provide various event classes. Some examples of event classes in
Java are ActionEvent, AdjustmentEvent, ComponentEvent, ContainerEvent, FocusEvent, ItemEvent,
KeyEvent, MouseEvent, and MouseWheelEvent

7 List the different AWT controls. Or What is AWT?


A The AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based
applications in Java. Java AWT components are platform-dependent, meaning that components are
displayed according to the view of the operating system. The java.awt package provides classes for AWT API
such as CheckBox, Choice, List, Label, TextField, TextArea, RadioButton, etc.

The different AWT controls in Java include.


1. Button
2. Choice
3. Canvas
4. CheckBox
5. CheckBox Group
6. Dialog
7. File Dialog
8. Label
9. List
10. Text Field
11. Text Area

LAQ’s
1 Explain the purpose of Adapter classes with help of example program.
A Adapter classes in Java are used as a bridge between two incompatible interfaces. They are used when we
want to use an existing class, but its interface is not compatible with the interface we require. The adapter
class converts the interface of one class into another interface that is expected by the client.

In simpler terms, adapter classes help us use an existing class that doesn't quite fit our needs by providing a
way to convert its interface into one that we can use.

For example, let's say we have an interface called `Shape` which has methods like `draw()`, `resize()`, etc. We
also have a class called `Rectangle` which implements the `Shape` interface. Now let's say we want to add a
new class called `Circle` which also implements the `Shape` interface but has different methods like
`circumference()`, etc. We can create an adapter class called `ShapeAdapter` which implements the `Shape`
interface and provides default implementations for all the methods. Then we can create a new class called
`CircleAdapter` which extends the `ShapeAdapter` and overrides only the methods that are required for the
circle.

36
MD Riyan Nazeer CSM-2A 160921748036

Here is an example program that demonstrates how to use an adapter class in Java:
interface Shape {
void draw();
void resize();
}

class Rectangle implements Shape {


@Override
public void draw() {
System.out.println("Drawing rectangle");
}

@Override
public void resize() {
System.out.println("Resizing rectangle");
}
}

class ShapeAdapter implements Shape {


@Override
public void draw() {}

@Override
public void resize() {}
}

class CircleAdapter extends ShapeAdapter {


@Override
public void draw() {
System.out.println("Drawing circle");
}
}

2 Compare the differences between applets and applications


A Feature Java Applets Java Applications
Typically run within a web browser through HTML Standalone programs executed on
Deployment
pages. the local machine.
Execution Restricted by the browser's security sandbox for Run with full access to the system
Environment safety. resources.
Entry Point Initialized using the init() method. Started by the main() method.
Limited graphical capabilities using AWT or Swing. Can have richer GUI using AWT,
User Interface
Swing, JavaFX, etc.
Can make network connections to the server from Can perform various network
Networking
which they were loaded. operations.
Access to the client's filesystem is restricted for Has access to the local filesystem.
File Access
security.
Generally more portable since they run within a Portable across platforms, but
Portability JVM. require Java Runtime
Environment (JRE) installed.
Controlled by the browser; methods like init(), Controlled by the programmer
Applet
start(), stop(), and destroy() are called by the through the main() method.
Lifecycle
browser.
Can interact with the web page that hosts them. Limited interaction with the
Interactivity
operating system.
Used for small interactive components within a Used for a wide range of
Usage
webpage. standalone software.

37
MD Riyan Nazeer CSM-2A 160921748036

Must adhere to strict security policies imposed by Java applications have fewer
Security the browser. restrictions and need user
permission for certain operations
3 Explain event delegation model.
A “Delegation Event model has Sources and Listeners.

Source: Events are generated from the source. There are various sources like buttons, checkboxes, list,
menu-item, choice, scrollbar, text components, windows, etc., to generate events.

Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events. To perform Event Handling, we need to
register the source with the listener. Different Classes provide different registration methods.

Syntax: addTypeListener() where Type represents the type of event.


Example 1: For KeyEvent we use addKeyListener() to register.
Example 2: For ActionEvent we use addActionListener() to register.
4 Explain AWT components with examples. Or
Explain the AWT component classes with suitable example program.
A
5 List out and explain different types of event listeners supported by java
A
6 How is the use of ‘Event listeners’ in Java.
A
7 What is JDBC Driver? Explain each one of them in detail.

38
MD Riyan Nazeer CSM-2A 160921748036

A JDBC (Java Database Connectivity) is a Java API that provides a standard way to connect and interact with
relational databases. A JDBC driver is a software component that enables Java applications to connect and
communicate with a specific type of database. There are four types of JDBC drivers based on how they
interact with the database:

1. JDBC-ODBC Bridge Driver: Think of this driver as a "bridge" that connects Java with databases using the
ODBC standard. It's like having a translator who understands both Java and the ODBC language, helping
them communicate. This driver is built into Java and doesn't require any extra setup.
2. Native API/Partly Java Driver: This driver uses a specific "client library" provided by the database to talk
to it. It's like having a specialized tool that speaks the database's language. This driver requires installing
the client library on your computer to work properly.
3. Network Protocol Driver: Imagine this driver as a network-savvy intermediary between Java and the
database. It understands the network protocol used by the database server, so it can relay messages
between Java and the server. It's like having a translator who speaks both Java and the database's
network language.
4. Thin Driver: The thin driver is a purely Java-based solution. It doesn't rely on any external tools or
libraries. It's like having a self-sufficient language expert who speaks the language of the database
directly. This driver is written entirely in Java and can connect to databases that support network
communication without any additional dependencies.

8 Draw MVC architecture. Explain the concept of MVC with an example program
A

9 Illustrate about Delegation Event model and write a program to demonstrate Keyboarded Event Handling
A import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="simplicity" width="300" height="100"></applet>*/

public class simplicity extends Applet implements KeyListener {


String msg = "";
int x = 10, y = 20;

public void init() {


addKeyListener(this);

39
MD Riyan Nazeer CSM-2A 160921748036

public void keyPressed(KeyEvent ke) {


showStatus("Key down");
}

public void keyReleased(KeyEvent ke) {


showStatus("Key up");
}
public void keyTyped(KeyEvent ke) {
}
}

10 illustrate about Delegation Event model and write a program to demonstrate Mouse Event Handling
A Same as 9
11 a) Write a program for mouse event handling.
b) Write a program to read username and password for any application.
A import java.awt.*;
import java.awt.event.*;

public class MouseEventDemo extends Frame implements MouseListener {


private TextField tfMouseX;
private TextField tfMouseY;

public MouseEventDemo() {
addMouseListener(this);

tfMouseX = new TextField(10);


tfMouseY = new TextField(10);
add(tfMouseX);
add(tfMouseY);

setTitle("MouseEvent Demo");
setSize(350, 100);
setVisible(true);
}

public static void main(String[] args) {


new MouseEventDemo();
}

public void mouseClicked(MouseEvent e) {


tfMouseX.setText(e.getX() + "");
tfMouseY.setText(e.getY() + "");
}

public void mouseEntered(MouseEvent e) {}


public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}

Same as 12 b
12 a) Write a program for keyboard event handling.
b) Write a program to read username and password for any application.
A import java.awt.*;
import java.awt.event.*;
import java.applet.*;

40
MD Riyan Nazeer CSM-2A 160921748036

/*<applet code="simplicity" width="300" height="100"></applet>*/

public class simplicity extends Applet implements KeyListener {


String msg = "";
int x = 10, y = 20;

public void init() {


addKeyListener(this);
}

public void keyPressed(KeyEvent ke) {


showStatus("Key down");
}

public void keyReleased(KeyEvent ke) {


showStatus("Key up");
}
public void keyTyped(KeyEvent ke) {
}
}
import java.util.Scanner;

public class UsernamePasswordReader {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your username: ");


String username = scanner.nextLine();

System.out.print("Enter your password: ");


String password = scanner.nextLine();

System.out.println("Username: " + username);


System.out.println("Password: " + password);

scanner.close();
}
}

13 Write short notes on following:


a) Adapter classes b) Frame c) AWT controls d) Applets e) Life cycle of an applet
A a) Adapter classes: Adapter classes in Java provide a default implementation of an interface so that the
implementing class only needs to override the required methods. They are commonly used with event
listeners in graphical user interfaces (GUIs). Instead of implementing all the methods of an interface, you
can extend an adapter class and override only the methods you need, making the code more concise.
Adapter classes are typically abstract classes.

b) Frame: In Java, a Frame is a top-level window with a title bar and border. It serves as the main container
for building GUI applications using the Abstract Window Toolkit (AWT) or Swing framework. A Frame can
hold various components such as buttons, text fields, and panels. It provides the basic functionality for
interacting with the window, including minimizing, maximizing, and closing. Frames are often used as
the main application window or as dialog boxes.

c) AWT controls: AWT (Abstract Window Toolkit) controls are the graphical user interface components
provided by the Java AWT library. AWT controls include various classes such as buttons, text fields,
checkboxes, radio buttons, labels, lists, and more. These controls allow developers to create interactive
and visually appealing user interfaces for Java applications. AWT controls are platform-dependent,
meaning their appearance and behavior may vary across different operating systems.

41
MD Riyan Nazeer CSM-2A 160921748036

d) Applets: Applets are small Java programs that run within a web browser or applet viewer. They are
typically used to add interactive content to web pages. Applets are embedded in an HTML document
and can be executed when the web page is loaded. They provide a subset of the functionalities available
in Java applications. However, due to security concerns and the popularity of other web technologies,
the usage of applets has declined in recent years.

e) Life cycle of an applet: The life cycle of an applet consists of several stages, which are as follows:
1. Initialization: The applet is initialized by calling the `init()` method. This method is called once when
the applet is first loaded.
2. Start: The applet is started by calling the `start()` method. This method is called after the `init()`
method and can be used to start any background threads or animations.
3. Paint: The `paint()` method is called whenever the applet needs to be visually updated. It is
responsible for drawing the applet's content on the screen.

4. Stop: The applet is stopped by calling the `stop()` method. This method is called when the applet is
no longer visible or active, such as when another window overlaps it.
5. Destroy: The applet is destroyed by calling the `destroy()` method. This method is called when the
applet is being unloaded or the web page is closed.

During the applet's life cycle, events such as mouse clicks or keyboard input can trigger corresponding event
handlers to perform specific actions.
UNIT 5
SAQ’s
1 Define swing in java with example.
A Swing is a Java library for creating graphical user interfaces (GUIs). It is an improved version of the older
AWT library. Swing offers more features, better components, and excellent event handling.

Example:
import javax.swing.JButton;
import javax.swing.JFrame;

class GFG {
public static void main(String[] args) {
JFrame frame = new JFrame(); // Creating an instance of JFrame
JButton button = new JButton("GFG WebSite Click");

button.setBounds(150, 200, 220, 50);


frame.add(button); // Adding the button to the JFrame

frame.setSize(500, 600); // Setting the size of the frame


frame.setLayout(null); // Using no layout managers
frame.setVisible(true); // Making the frame visible
}
}

2 Compare the difference between Swing and AWT


A Swing AWT
More components, including advanced Limited components
Components
controls
Look and Feel Consistent appearance across platforms Native appearance based on OS

42
MD Riyan Nazeer CSM-2A 160921748036

Customization Highly customizable components Limited customization options


MVC Follows MVC pattern Does not strictly follow MVC pattern
Architecture
Accessibility Built-in accessibility features Limited accessibility features
Event Advanced event handling, including drag- Basic event handling
Handling and-drop
Portability Platform-independent Platform-dependent
More popular for modern GUI Less commonly used nowadays
Popularity
development
Entirely written in Java Combination of Java and platform-specific
Written in
code
3 What is the difference between the paint() and repaint() methods?
A
paint() Method repaint() Method
Renders the visual appearance of a Requests the repainting of a component or a
Definition
component on the screen. portion of it.
Automatically called by the Java runtime Invoked explicitly in code to indicate that a
Invocation when a component needs to be painted component's visual appearance has changed
or redrawn. and needs to be updated.
Can be overridden to provide custom Cannot be overridden.
Customization
painting code for a component.
Direct Should not be directly invoked by the Should be explicitly invoked by the developer
Invocation developer. when repainting is required.
4 What are the features of Swing in Java?
A Swing is a set of GUI components for Java. It provides a rich set of features such as:
• Lightweight components
• Pluggable look and feel
• Layout managers
• Accessibility API
• Internationalization and localization support
5 What is the life-cycle of a servlet?
A The life cycle of a servlet consists of the following stages:
1. Loading: When a request is received for a servlet, the web container loads the servlet class.
2. Instantiation: After loading the servlet class, the web container creates an instance of the servlet.
3. Initialization: After creating an instance of the servlet, the web container initializes it by calling its `init()`
method. This method is called only once during the life cycle of a servlet.
4. Servicing: After initialization, the servlet is ready to service client requests. The web container calls the
`service()` method of the servlet to process each request.
5. Destruction: When a servlet is no longer needed, the web container calls its `destroy()` method to
remove it from memory.

6 What is the life-cycle methods for a servlet?


A The life cycle methods of a servlet are as follows:
1. init(): This method is called by the web container to initialize a servlet after it has been loaded and
instantiated.
2. service(): This method is called by the web container to process client requests.
3. destroy(): This method is called by the web container to remove a servlet from memory when it is no
longer needed.

7 What is difference between Generic Servlet and HTTP Servlet?


A Generic Servlet HttpServlet
Works with multiple protocols (HTTP, Specifically designed for handling HTTP
Location
FTP, SMTP, etc.). protocol.

43
MD Riyan Nazeer CSM-2A 160921748036

Generic, protocol-independent Extends Generic Servlet to handle HTTP-


Functionality
servlet implementation. specific tasks.
Implements the javax.servlet.Servlet Extends Generic Servlet and adds HTTP-
Methods
interface. specific methods.
Handles requests from various Handles specifically HTTP requests and
Requests
protocols. related tasks.
Provides additional methods for handling
HttpServletRequest Not available.
HTTP requests.
Provides additional functionality for HTTP
HttpServletResponse Not available.
responses.
Used for servlets handling non-HTTP Used for servlets handling HTTP requests
Common Usage
protocols. and responses.
8 What are Cookies?
A Cookies are a small piece of data stored on the client-side which servers use when communicating with
clients. They are commonly used to implement simple, temporary data storage on the client side, such as
session management, remember password, shopping cart items, etc. In Java Servlet API, the
javax.servlet.http.Cookie class represents a cookie. A cookie’s value can uniquely identify a client, so cookies
are commonly used for session management
9 What is difference between Cookies and HTTP Session?
A Cookies and HTTP Session are both used for session management in Java. The main difference between
them is that sessions are saved on the server-side, whereas cookies are saved on the user’s browser or
client-side. Apart from this, there are also various other differences between both. Cookies are used to store
small amounts of data on the client-side, while sessions are used to store larger amounts of data on the
server-side. Cookies can be easily tampered with by the client, while sessions are more secure as they are
stored on the server-side
LAQ’s
1 Differentiate between AWT and Swings.
A AWT (Abstract Window Toolkit) Swing
AWT is the original GUI library in Java, introduced in Swing is a more advanced and flexible GUI library
JDK 1.0. introduced in JDK 1.2 as a replacement for AWT.
AWT components are heavyweight, meaning they Swing components are lightweight, as they are
rely on the underlying operating system's resources implemented entirely in Java and do not depend on
for rendering and handling events. the underlying operating system.
AWT components have a less modern look and feel Swing components provide a more consistent look
compared to Swing. and feel across different operating systems. They
can be customized using pluggable look and feel
(PLAF) themes.
AWT lacks certain components such as JTable Swing provides a rich set of components, including
(table), JTree (tree), JFileChooser (file chooser), etc. tables, trees, file choosers, tabbed panes, etc.
AWT has limited support for advanced features like Swing provides extensive support for advanced
double buffering, drag-and-drop, and accessibility. features, making it easier to create complex and
interactive user interfaces.
AWT uses native peer components for rendering, Swing components are rendered using Java's 2D
which can lead to inconsistencies across platforms. graphics library, resulting in consistent visuals and
behavior across platforms.
AWT is suitable for simple applications or when Swing is recommended for most GUI applications,
platform-specific appearance is desired. offering more flexibility, features, and better cross-
platform compatibility.
AWT has fewer layout managers compared to Swing provides a wider range of layout managers to
Swing. help with component positioning and resizing.
2 Explain the following classes in detail with an example program
JLabel, ImageIcon, JTextField, the Swing buttons, JTabbedpane, JScrollPane, JList, JComboBox.
A 1. JLabel: JLabel is a class of Java Swing. It 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. JLabel is
inactive to input events such as mouse focus or keyboard focus.

44
MD Riyan Nazeer CSM-2A 160921748036

2. ImageIcon: ImageIcon is a class of Java Swing. It is used to display an image in a GUI application.
ImageIcon can be created from an image file or from an array of bytes.

3. JTextField: JTextField is a class of Java Swing. It is used to create a single-line text field for accepting user
input.

4. Swing buttons: Swing buttons are classes of Java Swing. They are used to create buttons in a GUI
application. Some examples of Swing buttons are JButton, JToggleButton, JCheckBox, and JRadioButton.

5. JTabbedPane: JTabbedPane is a class of Java Swing. It is used to create a tabbed pane for displaying
multiple components in a single container.

6. JScrollPane: JScrollPane is a class of Java Swing. It is used to create a scrollable view of a component that
is larger than the visible area.

7. JList: JList is a class of Java Swing. It is used to create a list of items that can be selected by the user.

8. JComboBox: JComboBox is a class of Java Swing. It is used to create a drop-down list of items that can
be selected by the user.

import javax.swing.*;

public class SwingComponentsExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Components Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(new
BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));

JLabel label = new JLabel("Hello, I am a JLabel!");


frame.add(label);

ImageIcon icon = new ImageIcon("path/to/your/image.png");


JLabel imageLabel = new JLabel(icon);
frame.add(imageLabel);

JTextField textField = new JTextField(20);


frame.add(textField);

JButton button = new JButton("Click me!");


frame.add(button);

String[] listData = {"Item 1", "Item 2", "Item 3"};


JList<String> list = new JList<>(listData);
JScrollPane scrollPane = new JScrollPane(list);
frame.add(scrollPane);

String[] comboBoxData = {"Option 1", "Option 2", "Option 3"};


JComboBox<String> comboBox = new JComboBox<>(comboBoxData);
frame.add(comboBox);

frame.setVisible(true);
}
}
3 Explain the Life Cycle of Servlet in detail. Or Describe in detail Life Cycle of Servlet
A The life cycle of a servlet in Java refers to the various stages that a servlet goes through during its existence,
from its creation to its destruction. Understanding the servlet life cycle is essential for developing and
managing servlets effectively. The servlet life cycle consists of the following stages:

45
MD Riyan Nazeer CSM-2A 160921748036

1. Loading: When a web container starts or the first request for a servlet is received, the container loads
the servlet class. It is performed only once during the lifetime of the servlet.

2. Instantiation: After loading the servlet class, the container creates an instance of the servlet using its
default constructor or a no-arg constructor (if available).

3. Initialization: After creating the servlet instance, the container calls the init(ServletConfig config)
method to initialize the servlet. This method is called only once during the servlet's lifetime. It is here
that you can perform one-time setup tasks, such as loading resources or establishing connections to
databases.

4. Handling Requests: Once the servlet is initialized, it is ready to handle incoming client requests. The
container will call the service(ServletRequest request, ServletResponse response) method for each
request to process it. The service() method is responsible for generating the response to the client's
request. The servlet container may create multiple threads to handle concurrent requests, and each
thread will execute the service() method separately.

5. Servicing Requests: The service() method determines the type of request (e.g., GET, POST, PUT, DELETE)
and dispatches it to the appropriate doXXX() method, such as doGet(), doPost(), doPut(), etc. You must
override these doXXX() methods to provide the actual implementation of handling different types of
HTTP requests.

6. Destroying: When a servlet is no longer needed or when the web container is shutting down, the
container calls the destroy() method. The destroy() method allows you to release any resources that the
servlet is holding, such as closing database connections or stopping background threads. This method is
called only once during the lifetime of the servlet before it is removed from the memory.

7. Unloading: If the web container decides to unload the servlet, typically when it needs to free up
resources, it calls the servlet's destroy() method before removing it from the memory
4 Write a program to demonstrate JLabel, JTextField , JcheckBox with ImageIcon
A import javax.swing.*;
import java.awt.*;

public class ComponentDemo extends JFrame {


public ComponentDemo() {
setTitle("Component Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLayout(new FlowLayout());

// Create an ImageIcon
ImageIcon icon = new ImageIcon("image.png"); // Replace
"image.png" with your image file path

// Create a label with the ImageIcon


JLabel imageLabel = new JLabel(icon);

// Create a text field


JTextField textField = new JTextField(10);

// Create a checkbox
JCheckBox checkBox = new JCheckBox("Enable");

// Add components to the frame


add(imageLabel);
add(textField);
add(checkBox);

46
MD Riyan Nazeer CSM-2A 160921748036

setVisible(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new ComponentDemo());
}
}

47

You might also like