Adv-Java Unit 1 & 2: Extra Questions
Generated and Prepared By Thiruselvan (ThiruXD)
1. Which of the following is OOPs?
Answer:OOP (Object-Oriented Programming) is a programming approach where programs are designed using objects and classes.
The four main concepts of OOP are:
- Encapsulation
- Abstraction
- Inheritance
- Polymorphism
Example: A Car object can have data such as color and speed, and methods such as start() and stop().
2. Explain the class keyword.
Definition:
The class keyword is used to create a class, which acts as a blueprint for creating objects.
Example:
class Student {
String name;
int age;
}Here, Student is a class.
3. Is String a primitive data type?
Answer:
No. String is not a primitive data type in Java. It is a class (reference data type).
Java primitive data types include:
byteshortintlongfloatdoublecharboolean
Example:
String name = "Harshith";4. What is the size of int in bytes?
Answer:
In Java, an int occupies 4 bytes (32 bits).
Range:
-2,147,483,648 to 2,147,483,647Example:
int age = 20;5. How is char used to store a single character?
Definition:
The char data type is used to store one single Unicode character.
It uses single quotes (' ').
Example:
char grade = 'A';
char letter = 'H';6. Explain the new keyword to create an object.
Definition:
The new keyword is used to create an object and allocate memory for it.
Example:
Student s = new Student();Here, new Student() creates an object of the Student class.
7. Explain the statement Student s = new Student() to create an object.
Student s = new Student();Explanation:
Student→ Class names→ Reference variablenew→ Allocates memory and creates the objectStudent()→ Calls the constructor
Example:
class Student {
String name;
}
Student s = new Student();
s.name = "Harshith";8. Define Abstraction (showing only required details).
Definition:Abstraction means hiding unnecessary implementation details and showing only the important features to the user.
Real-life example: When driving a car, you use the steering wheel and pedals without knowing how the engine works internally.
Java Example:
abstract class Vehicle {
abstract void start();
}9. Define Encapsulation.
Definition:Encapsulation means wrapping data and methods together inside a class and protecting the data using access modifiers such as private.
Example:
class Student {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}10. What is the protected access modifier?
Definition:
A protected member can be accessed:
- Within the same class
- Within the same package
- By subclasses, even if they are in different packages
Example:
class Parent {
protected int age = 50;
}11. What is the extends keyword in Inheritance?
Definition:
The extends keyword is used when one class inherits properties and methods from another class.
Example:
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
}Dog inherits the eat() method from Animal.
12. What is the implements keyword?
Definition:
The implements keyword is used when a class implements an interface.
Example:
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Bark");
}
}13. Define Polymorphism.
Definition:Polymorphism means one name having many forms.
In Java, there are two main types:
- Method Overloading – Compile-time polymorphism
- Method Overriding – Runtime polymorphism
Example:
Animal a = new Dog();
a.sound();The same method can behave differently depending on the object.
14. Explain Method Overloading (compile-time polymorphism).
Definition: Method overloading means having multiple methods with the same name but different parameters.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}The compiler decides which method to call, so it is called compile-time polymorphism.
15. Explain Method Overriding (runtime polymorphism).
Definition: Method overriding occurs when a child class provides its own implementation of a method already defined in the parent class.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}The method is decided at runtime.
16. Can methods be overloaded by changing the return type?
Answer: No. Methods cannot be overloaded only by changing their return type.
❌ Invalid:
int add(int a, int b) {
return a + b;
}
double add(int a, int b) {
return a + b;
}The parameters must be different.
17. What is a Constructor, and when is it invoked?
Definition: A constructor is a special method used to initialize an object.
It is automatically invoked when an object is created.
Example:
class Student {
Student() {
System.out.println("Object created");
}
}
Student s = new Student();The constructor is called when new Student() executes.
18. Does a constructor have a return type?
Answer:
No. A constructor does not have any return type, not even void.
Example:
class Student {
Student() {
}
}19. What is a Parameterized Constructor?
Definition: A parameterized constructor accepts parameters to initialize an object with specific values.
Example:
class Student {
String name;
Student(String name) {
this.name = name;
}
}
Student s = new Student("Harshith");20. What is a Default Constructor?
Definition: A default constructor is a constructor with no parameters.
If no constructor is written, Java provides a default no-argument constructor automatically.
Example:
class Student {
Student() {
System.out.println("Default constructor");
}
}Page 2
21. Explain the this keyword.
Definition:this refers to the current object.
It is commonly used to differentiate instance variables from local variables.
Example:
class Student {
String name;
Student(String name) {
this.name = name;
}
}22. Explain the super keyword.
Definition:super refers to the parent class object.
It can be used to access parent class variables, methods, and constructors.
Example:
class Animal {
String name = "Animal";
}
class Dog extends Animal {
void display() {
System.out.println(super.name);
}
}23. Why is there no multiple inheritance with classes in Java?
Answer: Java does not support multiple inheritance with classes because it can create ambiguity, known as the Diamond Problem.
Example idea:
If two parent classes have the same method, Java would not know which method the child should inherit.
Java solves this by allowing multiple inheritance through interfaces.
24. Explain the interface keyword.
Definition: An interface defines a set of methods that implementing classes must provide.
Example:
interface Vehicle {
void start();
}25. Can a class implement multiple interfaces?
Answer: Yes. A class can implement multiple interfaces.
Example:
interface A {
void methodA();
}
interface B {
void methodB();
}
class Test implements A, B {
public void methodA() {}
public void methodB() {}
}26. What is the enum keyword for enumeration?
Definition:
The enum keyword is used to define a fixed set of constants.
Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY
}27. What is the syntax for enum?
enum EnumName {
CONSTANT1,
CONSTANT2,
CONSTANT3
}Example:
enum Color {
RED, GREEN, BLUE
}28. Explain the final keyword for constant declaration.
Definition:
The final keyword is used to make a variable constant. Its value cannot be changed.
Example:
final double PI = 3.14159;After assigning the value, it cannot be changed.
29. Does a List allow duplicates?
Answer:
Yes. A List allows duplicate elements.
Example:
List<String> names = new ArrayList<>();
names.add("Harshith");
names.add("Sai");
names.add("Harshith");Duplicates are allowed.
30. What collection handles key-value pairs?
Answer:
The Map collection handles key-value pairs.
Example:
Map<Integer, String> students = new HashMap<>();
students.put(1, "Harshith");
students.put(2, "Sai");31. What is a Servlet?
Definition: A Servlet is a Java program that runs on a web server and handles client requests and generates dynamic responses.
Example: A servlet can receive login information from a user and send a response.
32. What is jakarta.servlet?
Definition:jakarta.servlet is the package/API containing classes and interfaces required for developing Java Servlets.
Example imports:
import jakarta.servlet.*;
import jakarta.servlet.http.*;33. Explain the servlet lifecycle methods: init(), service(), and destroy().
The servlet lifecycle has three main methods:
1. init()
Called once when the servlet is initialized.
2. service()
Called whenever a request comes to the servlet.
3. destroy()
Called once before the servlet is removed from memory.
Example:
public void init() {
System.out.println("Servlet started");
}
public void destroy() {
System.out.println("Servlet destroyed");
}34. What is doGet() to serve requests?
Definition:doGet() handles HTTP GET requests.
GET is generally used to retrieve data.
Example:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
}35. What is doPost() to handle POST requests?
Definition:doPost() handles HTTP POST requests.
POST is commonly used to send or submit data.
Example:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) {
}36. What is HttpServletRequest?
Definition:HttpServletRequest is an object used to receive information sent by the client to a servlet.
Example:
String name = request.getParameter("name");37. Explain RequestDispatcher (include & forward).
Definition:RequestDispatcher is used to transfer a request from one server resource to another.
It provides:
forward()include()
Example:
RequestDispatcher rd =
request.getRequestDispatcher("next.jsp");38. What is the forward action?
Definition:forward() transfers the request and response completely to another resource.
Example:
rd.forward(request, response);The browser URL does not change.
39. What is the include action?
Definition:include() includes the output of another resource in the current response.
Example:
rd.include(request, response);The current servlet continues after including the other resource.
40. Explain setAttribute() for storing and getAttribute() for retrieving data.
Definition:setAttribute() stores an object, and getAttribute() retrieves it.
Example:
request.setAttribute("name", "Harshith");Retrieving:
String name =
(String) request.getAttribute("name");41. What is sendRedirect()?
Definition:sendRedirect() tells the browser to send a new request to another URL.
Example:
response.sendRedirect("welcome.jsp");The browser URL changes.
42. Compare sendRedirect vs forward vs include.
| Feature | forward() | include() | sendRedirect() |
|---|---|---|---|
| Request | Same request | Same request | New request |
| URL changes | No | No | Yes |
| Control | Transferred | Returns back | Browser redirects |
| Performance | Faster | Faster | Comparatively slower |
43. What is HttpSession to manage user sessions?
Definition:HttpSession is used to store user information across multiple requests.
Example:
HttpSession session = request.getSession();
session.setAttribute("username", "Harshith");44. How does request.getSession() work?
Definition:request.getSession() returns the current session. If no session exists, it creates a new session.
Example:
HttpSession session = request.getSession();45. What does session.invalidate() do?
Definition:session.invalidate() destroys the current session and removes all session attributes.
Example:
session.invalidate();It is commonly used during logout.
46. What is a Cookie (small piece of data)?
Definition: A Cookie is a small piece of data stored in the user’s browser.
It is commonly used for:
- Remembering users
- Session tracking
- Preferences
Example:
Cookie cookie = new Cookie("username", "Harshith");
response.addCookie(cookie);47. What does the @ symbol mean (Annotation)?
Definition:
The @ symbol represents an Annotation in Java.
Annotations provide metadata or instructions to Java, the compiler, or frameworks.
Example:
@OverrideAnother example:
@WebServlet("/hello")48. What is the full form of JSF / JSP?
JSF: JavaServer Faces JSP: JavaServer Pages
49. What is the @WebServlet annotation?
Definition:@WebServlet is used to map a Servlet to a specific URL.
Example:
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
}When /hello is requested, this servlet handles the request.
50. Explain JSP for creating dynamic web pages.
Definition: JSP (JavaServer Pages) is a technology used to create dynamic web pages using HTML with Java-based server-side processing.
Example:
<h1>Welcome <%= request.getParameter("name") %></h1>51. What is the JSP translation phase to a servlet program?
Definition: During the JSP translation phase, the JSP file is converted into a Servlet source code by the web container.
Process:
JSP File
↓
Translated into Servlet
↓
Compiled
↓
Class File Created
↓
ExecutedPage 5
52. Name the JSP directives (page, include, taglib).
The three main JSP directives are:
pageincludetaglib
Example:
<%@ page language="java"%>
<%@ include file="header.jsp"%>
<%@ taglib prefix="c" uri="jakarta.tags.core"%>53. What implicit object represents the application context?
Answer:
The application implicit object represents the application context.
It is of type:
ServletContext54. Explain the four scopes in JSP.
1. Page Scope
Available only on the current JSP page.
2. Request Scope
Available during one HTTP request.
3. Session Scope
Available throughout the user’s session.
4. Application Scope
Available to all users throughout the application.
55. What is the Throwable implicit object for exceptions?
Answer:
The JSP implicit object used to handle exceptions is exception.
Its type is:
ThrowableIt is available on JSP error pages.
56. Explain <c:if> for conditionals in JSTL.
Definition:<c:if> is used to perform conditional operations in JSP using JSTL.
Example:
<c:if test="${age >= 18}">
You are eligible.
</c:if>57. Why is JSTL more advantageous than JSP scriptlets?
Answer: JSTL is preferred because it:
- Makes JSP code cleaner
- Reduces Java code inside HTML
- Improves readability
- Makes maintenance easier
- Supports separation of presentation and business logic
Scriptlet:
<% if(age >= 18) { %>JSTL:
<c:if test="${age >= 18}">JSTL is cleaner and recommended.
58. Explain Encapsulation & Abstraction with examples in Java.
Encapsulation
Definition: Encapsulation means protecting data by keeping variables private and accessing them through methods.
class Account {
private double balance;
public void setBalance(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
}Abstraction
Definition: Abstraction hides implementation details and shows only required functionality.
abstract class Vehicle {
abstract void start();
}59. Differentiate between RequestDispatcher.forward, RequestDispatcher.include, and response.sendRedirect.
| Feature | forward() | include() | sendRedirect() |
|---|---|---|---|
| Request | Same | Same | New |
| URL changes | No | No | Yes |
| Response | Fully transferred | Included in current response | New response |
| Speed | Fast | Fast | Slower |
60. Define Polymorphism. Discuss Method Overloading with an example.
Definition: Polymorphism means one method or object can take multiple forms.
Method Overloading occurs when methods have the same name but different parameters.
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}This is compile-time polymorphism.
61. Define Polymorphism. Discuss Method Overriding with an example.
Definition: Polymorphism allows the same method to behave differently.
Method Overriding occurs when a child class changes the implementation of a parent method.
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}This is runtime polymorphism.
62. Compare Method Overloading vs Method Overriding.
| Method Overloading | Method Overriding |
|---|---|
| Same class | Parent and child classes |
| Same method name | Same method name |
| Different parameters | Same parameters |
| Compile-time | Runtime |
| Inheritance not required | Inheritance required |
63. Define Inheritance. Explain with an example.
Definition: Inheritance is an OOP concept where one class acquires the properties and methods of another class.
Example:
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}Dog inherits eat() from Animal.
64. Define Interface. Explain with an example.
Definition: An interface defines a contract that implementing classes must follow.
Example:
interface Vehicle {
void start();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car starts");
}
}Page 4
65. Explain Enumerations and methods associated with enumerations.
Definition:
An enumeration (enum) represents a fixed set of constants.
Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY
}Common methods:
values()
Returns all enum constants.
Day[] days = Day.values();valueOf()
Converts a String into an enum constant.
Day d = Day.valueOf("MONDAY");ordinal()
Returns the position of the constant.
System.out.println(Day.MONDAY.ordinal());name()
Returns the name of the constant.
System.out.println(Day.MONDAY.name());66. Explain the lifecycle and working of Servlets and JSP.
Servlet Lifecycle
Loading
↓
init()
↓
service()
↓
destroy()init()→ Called onceservice()→ Handles requestsdestroy()→ Called before removal
JSP Lifecycle
JSP Translation
↓
Compilation
↓
Class Loading
↓
jspInit()
↓
_jspService()
↓
jspDestroy()JSP is translated internally into a Servlet.
67. Explain session management using Cookies and HttpSession.
Cookies
Cookies store small pieces of information in the browser.
Cookie c = new Cookie("name", "Harshith");
response.addCookie(c);HttpSession
HttpSession stores information on the server.
HttpSession session = request.getSession();
session.setAttribute("name", "Harshith");68. Write a complete sample Servlet program.
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>Hello, Welcome to Servlet!</h1>");
out.println("</body>");
out.println("</html>");
}
}When the /hello URL is accessed, the servlet displays the message.
69. Define JSP and explain its lifecycle.
Definition: JSP (JavaServer Pages) is a technology used to create dynamic web pages.
JSP Lifecycle
- Translation
- Compilation
- Class Loading
jspInit()_jspService()jspDestroy()
Explanation:
jspInit()→ Initializes JSP once_jspService()→ Handles requestsjspDestroy()→ Cleans resources
70. Explain the 9 Implicit Objects in JSP.
The nine JSP implicit objects are:
1. request
Represents client request data.
2. response
Used to send a response.
3. out
Used to send output to the browser.
4. session
Represents the user session.
5. application
Represents the application context.
6. config
Contains JSP configuration information.
7. pageContext
Provides access to page-related information.
8. page
Represents the current JSP object.
9. exception
Used for exception handling on error pages.
71. Explain JSP Directives with an example program.
JSP directives provide instructions to the JSP container.
1. Page Directive
<%@ page language="java"%>2. Include Directive
<%@ include file="header.jsp"%>3. Taglib Directive
<%@ taglib prefix="c" uri="jakarta.tags.core"%>Example:
<%@ page language="java"%>
<html>
<body>
<h1>Welcome to JSP</h1>
</body>
</html>72. Explain JSTL tags.
Definition: JSTL stands for JSP Standard Tag Library.
It provides tags for common operations without writing Java scriptlets.
Common JSTL libraries include:
- Core tags
- Formatting tags
- Function tags
- SQL tags
Example:
<c:if test="${age >= 18}">
Eligible
</c:if>73. State the advantages between JSP, JSTL, and Servlets.
Servlet Advantages
- Handles request processing
- Suitable for business logic
- High control over HTTP requests
JSP Advantages
- Easy to create dynamic web pages
- HTML-friendly
- Suitable for presentation layer
JSTL Advantages
- Reduces Java code in JSP
- Makes code cleaner
- Easy conditional and loop operations
Best architecture:
Servlet → Business Logic
JSP → Presentation
JSTL → Dynamic Page Operations74. Explain JSTL core tags and Expression Language (EL) with suitable examples.
JSTL Core Tags
Common tags include:
<c:if><c:forEach><c:set><c:choose>
Example:
<c:set var="name" value="Harshith"/>
<c:if test="${name == 'Harshith'}">
Hello Harshith
</c:if>Expression Language (EL)
EL is used to access variables easily.
Example:
${name}Instead of:
<%= request.getAttribute("name") %>75. Define constructor and differentiate between default and parameterized constructors.
Definition: A constructor initializes an object when it is created.
Default Constructor
No parameters.
Student() {
}Parameterized Constructor
Accepts parameters.
Student(String name) {
this.name = name;
}| Default | Parameterized |
|---|---|
| No arguments | Takes arguments |
| Basic initialization | Custom initialization |
76. Write a note on setAttribute and getAttribute in a Servlet.
setAttribute()
Used to store an object.
request.setAttribute("name", "Harshith");getAttribute()
Used to retrieve the stored object.
String name =
(String) request.getAttribute("name");These are commonly used when forwarding data from a Servlet to a JSP.
77. Explain operators in Java with examples.
1. Arithmetic Operators
+ - * / %Example:
int sum = 10 + 5;2. Relational Operators
== != > < >= <=Example:
10 > 53. Logical Operators
&& || !Example:
age >= 18 && age <= 604. Assignment Operators
= += -= *= /=5. Unary Operators
++ --78. Briefly explain Filters and mention the @WebFilter annotation with an example program.
Definition: A Filter is used to intercept requests and responses before they reach a Servlet or JSP.
Common uses:
- Authentication
- Logging
- Validation
- Security
Example:
import java.io.IOException;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
@WebFilter("/*")
public class MyFilter implements Filter {
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
System.out.println("Request received");
chain.doFilter(request, response);
}
}@WebFilter maps the filter to specific URLs.
79. Compare Filters vs Listeners.
| Filters | Listeners |
|---|---|
| Intercept requests and responses | Listen to application events |
| Used for authentication | Used for session/application events |
Uses doFilter() | Uses event methods |
| Can modify requests/responses | Usually monitors lifecycle events |
80. Compare Cookies vs HttpSession for session management in Java.
| Cookies | HttpSession |
|---|---|
| Stored in browser | Stored on server |
| Small data storage | Can store larger objects |
| Can be modified by user | More secure |
| Sent with requests | Identified using session ID |
Page 3
81. Write a sample JSP program.
<%@ page language="java"%>
<html>
<head>
<title>Sample JSP</title>
</head>
<body>
<h1>Welcome to JSP</h1>
<%
String name = "Harshith";
%>
<p>Hello <%= name %></p>
</body>
</html>82. Explain JSTL formatting and function libraries with an example.
Formatting Library
Used for:
- Date formatting
- Number formatting
- Internationalization
Example:
<fmt:formatNumber value="12345.67"
type="currency"/>Function Library
Provides useful string functions.
Example:
${fn:length(name)}This returns the length of the string.
83. Write a note on Java Access Modifiers with examples.
Java has four access modifiers:
1. private
Accessible only within the same class.
private int age;2. Default
Accessible within the same package.
int age;3. protected
Accessible within the package and subclasses.
protected int age;4. public
Accessible from anywhere.
public int age;84. How is Exception Handling done in Servlets and JSP?
Exception handling prevents programs from crashing when errors occur.
Servlet
Use try-catch.
try {
int a = 10 / 0;
} catch (Exception e) {
response.getWriter().println(e.getMessage());
}JSP
JSP can use an error page.
Main JSP:
<%@ page errorPage="error.jsp"%>error.jsp:
<%@ page isErrorPage="true"%>
Error: ${exception.message}85. Summarize the differences between forward, include, and sendRedirect.
forward()
Transfers the complete request to another resource.
rd.forward(request, response);- Same request
- URL does not change
- Current resource stops processing
include()
Includes another resource’s output.
rd.include(request, response);- Same request
- URL does not change
- Current resource continues processing
sendRedirect()
Tells the browser to make a new request.
response.sendRedirect("welcome.jsp");- New request
- URL changes
- Can redirect to another application or URL
Final Comparison
| Feature | Forward | Include | sendRedirect |
|---|---|---|---|
| Request | Same | Same | New |
| URL Changes | No | No | Yes |
| Current Processing | Stops | Continues | New request |
| Speed | Faster | Faster | Comparatively slower |