Name Vineet Kumar
PROGRAM Bachelor of Computer Applications (BCA)
SEMESTER VI
COUSRE CODE & NAME DCA2202 JAVA PROGRAMMING
SET I
Q 1) Explain any five features of Java.
Answer: Java is one of the most popular and widely used programming languages in the world. It
was developed by Sun Microsystems in 1995 (now owned by Oracle). Java is known for its
simplicity, security, and platform independence. Below are five important features that make Java
a powerful programming language.
• Platform Independent: Java is a platform-independent language, which means that Java
code can run on any device or operating system that has the Java Virtual Machine (JVM).
When you write a Java program, it is compiled into bytecode, not machine code. This
bytecode can be run on any system that has a JVM, regardless of the underlying hardware
or OS. This feature is known as “Write Once, Run Anywhere (WORA)”, and it is one of
the biggest advantages of Java.
• Object-Oriented Programming (OOP): Java is an object-oriented programming language,
which means everything in Java is treated as an object. Object-oriented programming
makes it easier to manage and reuse code. It uses concepts like classes, objects, inheritance,
polymorphism, encapsulation, and abstraction. This feature helps developers build real-
world applications that are easy to understand, maintain, and scale.
• Simple and Easy to Learn: Java is designed to be easy to use and understand. It has a clean
and simple syntax, which is easy to read. Java removes many complex and confusing
features of other languages like C and C++, such as pointers and multiple inheritance. If
you know basic English and some programming logic, you can easily learn Java. Java also
comes with a huge library of pre-defined classes and methods which makes programming
easier and faster.
• Secure: Java is considered a secure language. It provides a runtime environment with
strong security features. Java does not use pointers, which helps avoid memory access
errors. It also runs programs inside a sandbox, which protects the system from harmful
code. Java includes built-in features like bytecode verification, exception handling, and
automatic memory management, which reduce the risk of viruses and crashes.
• Robust and Reliable: Java is a robust language, which means it is strong and less likely to
crash. It handles errors well using exception handling. Java also manages memory
automatically using a process called Garbage Collection, which removes unused objects
from memory. Java programs are less likely to crash due to memory leaks or incorrect
memory usage, making it suitable for long-running applications.
Q2). What are the different types of operators used in Java?
Answer: In Java, operators are special symbols used to perform operations on variables and
values. Java supports many types of operators to perform arithmetic, comparison, logical, and other
operations. These operators help in writing expressions and controlling the flow of programs.
Below are the main types of operators used in Java:
1. Arithmetic Operators: These operators are used for basic mathematical operations like
Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%)
Example:
int result = 10 + 5; // result is 15
2. Relational (Comparison) Operators: These operators are used to compare two values. The
result is either true or false. Like Equal to (=), Not equal to (!=), Greater than (>), Less than (<),
Greater than or equal to (>=), Less than or equal to (<=).
Example:
if (a > b) { System.out.println("a is greater"); }
3. Logical Operators: These are used to combine multiple conditions or expressions. E.g. Logical
AND (&&), Logical OR ( || ), Logical NOT (!).
Example:
if (age > 18 && has ID) { System.out.println("Allowed"); }
4. Assignment Operators: These operators assign values to variables. E.g. Simple assignment
(=), Add and assign (+=), Subtract and assign (-=), Multiply and assign (*=), Divide and assign
(/=).
Example:
x += 5; // Same as x = x + 5
5. Unary Operators: These work with a single operand. E.g. Positive (+), Negative (-), Increment
(++), Decrement (--), Logical NOT (!).
Example:
i++; // increases i by 1
6. Bitwise Operators: These are used to perform bit-level operations. E.g. AND (&), OR (|), XOR
(^), Complement (~), Left shift (<<), Right shift (>>),
7. Ternary Operator :This is a shortcut for if-else statement. Conditional operator (? :)
Example:
int result = (a > b) ? a : b;
Q3) What do you mean by Threads in java? Explain with an example.
Answer : In Java, a thread is a small unit of a process. It is like a lightweight sub-process that runs
independently and can perform tasks at the same time as other threads. Java supports
multithreading, which means a program can run multiple threads at the same time.
When we run a Java program, it runs in a single thread, starting from the main() method. But
sometimes we want to do multiple things at once — like playing music while downloading a file,
or handling many user requests on a website. In such cases, threads help to improve performance
and make programs faster and more responsive.
Benefits of Using Threads: Improves performance by doing multiple tasks at once. Makes
programs faster and more efficient. Useful in real-time systems like games, banking software, or
chat apps.
There are two main ways to create threads in Java:
1. By Extending the Thread Class
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
MyThread t1 = new MyThread(); // creating thread object
t1.start(); // starting the thread
}
}
the run() method contains the task the thread will perform. The start() method starts the thread, and
Java automatically calls run().
2. By Implementing Runnable Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread using Runnable is running...");
}
public static void main(String[] args) {
MyRunnable obj = new MyRunnable(); // create runnable object
Thread t1 = new Thread(obj); // pass to thread
t1.start(); // start the thread
}
}
This method is preferred when your class needs to extend another class because Java supports only
single inheritance.
SET II
Q4) What is the difference between errors and exceptions?
Answer: In Java, errors and exceptions are two types of problems that can occur while a program
is running. Both are part of Java’s exception handling mechanism, but they are different in purpose
and behavior. Understanding the difference helps in writing better and more stable programs.
Exceptions are problems you can expect and handle in your code. Errors are serious issues that
usually stop the program. A good programmer should always handle exceptions properly and avoid
situations that may cause errors.
Exception: - An exception is an unexpected event that occurs during the execution of a program,
which can be handled using Java code. Exceptions occur due to logical or user mistakes, like
dividing a number by zero, trying to open a file that does not exist, or accessing an invalid array
index. Java provides tools to handle exceptions using try block (where the error might occur), catch
block (to handle the exception), finally block (for code that should always run)
Example:
try {
int a = 10 / 0; // This will cause an exception
} catch (ArithmeticException e) {
System.out.println("You can't divide by zero.");
}
Exceptions are part of the java.lang.Exception class and are divided into Checked Exceptions
(must be handled, like IOException) and Unchecked Exceptions (run-time, like
NullPointerException, ArithmeticException)
Error: An error is a serious problem that occurs in the Java Virtual Machine (JVM), and cannot
be handled easily by the programmer. Errors are usually caused by the system or environment, not
by the program itself. Common errors include running out of memory or stack overflow.
Error e = new StackOverflowError();
throw e;
Errors are part of the java.lang.Error class and include OutOfMemoryError, StackOverflowError,
VirtualMachineError
Differences Between Error and Exception
Feature Exception Error
Handle Yes, using try-catch blocks No, usually not handled
Cause Programming mistakes or System or JVM-related issues
input issues
Class java.lang.Exception java.lang.Error
Examples ArithmeticException, OutOfMemoryError,
IOException StackOverflowError
Recovery Possible Very hard or not possible
Q 5) Explain the Synchronization of Threads.
Answer: In Java, synchronization is a way to control the access of multiple threads to shared
resources. When two or more threads try to access the same data or object at the same time, it may
lead to inconsistent results or errors. This is known as a race condition. Synchronization in Java is
important when multiple threads are working with shared data. It prevents data corruption and
ensures correct results by allowing only one thread to access critical sections at a time. However,
it should be used carefully to avoid slowing down the program or causing deadlocks. To avoid this
problem, Java provides synchronization, which ensures that only one thread can access the shared
resource at a time.
Why Synchronization is Needed: two threads are depositing money into a bank account at the
same time. If both threads read the old balance at the same time and add money, one of the
transactions might be lost. This happens because both threads are using the same data at the same
time. Synchronization prevents this by allowing only one thread to execute a block of code at a
time.
Types of Synchronization in Java
• Synchronized Method: We can declare a method as synchronized. When one thread is
executing a synchronized method, other threads are blocked from executing any
synchronized method on the same object.
class Bank {
synchronized void deposit(int amount) {
System.out.println("Depositing " + amount);
// some deposit logic
}
}
Here, if two threads call the deposit() method at the same time, only one thread will execute
it, and the other will wait.
• Synchronized Block: Sometimes we don’t need to lock the entire method, only a part of
it. In that case, we use a synchronized block.
class Bank {
void deposit(int amount) {
synchronized(this) {
System.out.println("Depositing " + amount);
}
}
}
This gives better performance by locking only the critical section, not the whole method.
When you use the synchronized keyword with a static method, the lock is applied on the class, not
the object. This means even if different objects call the method, only one thread can execute it at
a time. Drawbacks of Synchronization Slower performance: (Because threads must wait for each
other.), Deadlock risk (If not used properly, threads may wait forever.), More complex code
Managing synchronized code can be tricky in large programs.).
Q6). Explain the life cycle of a Servlet
Answer: A Servlet is a Java program that runs on a server and handles requests from web clients
(like browsers). It is used to create dynamic web pages. The life cycle of a Servlet is managed by
the Servlet Container (like Apache Tomcat). The Servlet life cycle defines how a Servlet is created,
used, and destroyed. It mainly has five stages:
• Loading the Servlet: When a client sends a request, the servlet container loads the Servlet
class into memory. This happens only once, when the Servlet is called for the first time or
when the server starts (if configured to load on startup).
• Instantiating the Servlet: After loading the class, the container creates an object (instance)
of the Servlet using its no-argument constructor. Like normal Java classes, the Servlet
object is created only once.
• Initialization (init() method): Once the object is created, the container calls the init()
method. This method is called only once during the servlet’s lifetime. It is used to perform
initialization tasks like Opening database connections, Reading configuration files, Setting
up resources
Syntax:
public void init(ServletConfig config) throws ServletException {
// Initialization code
}
• Request Handling (service() method): After initialization, the servlet is ready to handle
requests from clients. For each client request, the container calls the service() method. The
service() method receives HttpServletRequest and HttpServletResponse objects, which
help to read the request and write the response. This method can be called multiple times,
once for each request.
Syntax:
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// Request handling code
}
The service() method can call doGet() – for GET requests, doPost() – for POST requests
• Destruction (destroy() method): When the servlet is no longer needed (like when the server
shuts down or servlet is undeployed), the container calls the destroy() method. This method
is used to Close database connections, Release memory, Perform clean-up tasks. After this,
the servlet object is removed from memory.
Syntax:
public void destroy() {
// Clean-up code
}