Java Programming
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.
Made By:
Name: Md Riyan Nazeer
Roll No: 160921748036
Branch: CSM-2A
MD Riyan Nazeer CSM-2A 160921748036
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
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.
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
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.
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.
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.
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).
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
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()`:
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.
// Default Constructor
public Person() {
}
}
7
MD Riyan Nazeer CSM-2A 160921748036
// Parameterized Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
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:
// Copy Constructor
public Person(Person p) {
this.name = p.name;
this.age = p.age;
}
}
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:
// Private Constructor
private Singleton() {
}
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
import java.io.*;
class Box {
9
MD Riyan Nazeer CSM-2A 160921748036
Box() {
height = 10;
width = 20;
depth = 30;
}
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:
10
MD Riyan Nazeer CSM-2A 160921748036
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.
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();
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();
}
// 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();
}
int sum = 0;
15
MD Riyan Nazeer CSM-2A 160921748036
UNIT 2
SAQ’s
16
MD Riyan Nazeer CSM-2A 160921748036
17
MD Riyan Nazeer CSM-2A 160921748036
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
18
MD Riyan Nazeer CSM-2A 160921748036
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.
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
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.
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
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
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;
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.
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.
import java.io.*;
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
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.*;
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
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
}
}
}
try {
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destinationFile);
fis.close();
fos.close();
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. 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
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
28
MD Riyan Nazeer CSM-2A 160921748036
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();
}
}
}
Reserve(int i) {
wanted = i;
}
30
MD Riyan Nazeer CSM-2A 160921748036
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
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;
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;
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;
try {
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destinationFile);
fis.close();
fos.close();
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
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();
}
@Override
public void resize() {
System.out.println("Resizing rectangle");
}
}
@Override
public void resize() {}
}
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.
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.*;
39
MD Riyan Nazeer CSM-2A 160921748036
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 MouseEventDemo() {
addMouseListener(this);
setTitle("MouseEvent Demo");
setSize(350, 100);
setVisible(true);
}
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
scanner.close();
}
}
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");
42
MD Riyan Nazeer CSM-2A 160921748036
43
MD Riyan Nazeer CSM-2A 160921748036
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.*;
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.*;
// Create an ImageIcon
ImageIcon icon = new ImageIcon("image.png"); // Replace
"image.png" with your image file path
// Create a checkbox
JCheckBox checkBox = new JCheckBox("Enable");
46
MD Riyan Nazeer CSM-2A 160921748036
setVisible(true);
}
47