Skip to content
Share
Explore

BCA V Sem Java Programming - Section A Solutions


Short Answer Type Questions (9×5=45 marks)

1(a) What is the difference between C++ and Java?

Key Differences:
Table 1
Aspect
C++
Java
Platform
Platform-dependent
Platform-independent (Write Once, Run Anywhere)
Memory Management
Manual (new/delete)
Automatic (Garbage Collection)
Compilation
Compiled to machine code
Compiled to bytecode, interpreted by JVM
Multiple Inheritance
Supports multiple inheritance
No multiple inheritance (uses interfaces)
Pointers
Explicit pointer support
No explicit pointers (references only)
Runtime
No virtual machine required
Requires JVM to run
Security
Less secure
More secure due to JVM sandboxing
There are no rows in this table

1(b) Explain public static void main()

Complete Breakdown:
java
public static void main(String[] args)
public: Access modifier - method can be accessed from anywhere, including JVM
static: Method belongs to class, not instance. JVM can call without creating object
void: Return type - method doesn't return any value
main: Method name - entry point identifier for JVM
String[] args: Parameter - command-line arguments passed as string array
Why this signature?
JVM looks specifically for this exact signature to start program execution
Static allows JVM to call without instantiating the class
Public ensures JVM can access it from outside the package

1(c) Define interface in Java

Interface Definition: An interface is a contract or blueprint that defines what methods a class must implement, without providing implementation details.
Key Characteristics:
Contains abstract methods (implicitly public and abstract)
Variables are implicitly public, static, and final
Supports multiple inheritance
Cannot be instantiated directly
Classes implement interfaces using implements keyword
Example:
java
interface Drawable {
int MAX_SIZE = 100; // implicitly public static final
void draw(); // implicitly public abstract
// Java 8+ features
default void print() {
System.out.println("Drawing...");
}
static void info() {
System.out.println("Interface info");
}
}

class Circle implements Drawable {
public void draw() {
System.out.println("Drawing circle");
}
}

1(d) WAP in Java to convert upper case string to lower case string and lower case string to upper case string

java
import java.util.Scanner;

public class StringCaseConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();
// Method 1: Using built-in methods
String lowerCase = input.toLowerCase();
String upperCase = input.toUpperCase();
System.out.println("Original: " + input);
System.out.println("Lower Case: " + lowerCase);
System.out.println("Upper Case: " + upperCase);
// Method 2: Manual conversion
String manualLower = "";
String manualUpper = "";
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
// Convert to lowercase manually
if (ch >= 'A' && ch <= 'Z') {
manualLower += (char)(ch + 32);
} else {
manualLower += ch;
}
// Convert to uppercase manually
if (ch >= 'a' && ch <= 'z') {
manualUpper += (char)(ch - 32);
} else {
manualUpper += ch;
}
}
System.out.println("Manual Lower: " + manualLower);
System.out.println("Manual Upper: " + manualUpper);
sc.close();
}
}

1(e) How do you define try/catch block?

Definition: Try/catch block is Java's exception handling mechanism to handle runtime errors gracefully without program termination.
Syntax:
java
try {
// Code that might throw exception
} catch (ExceptionType1 e1) {
// Handle specific exception type 1
} catch (ExceptionType2 e2) {
// Handle specific exception type 2
} finally {
// Always executes (optional)
}
Complete Example:
java
public class ExceptionHandling {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
int result = 10/0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Math error: " + e.getMessage());
} catch (Exception e) {
System.out.println("General error: " + e.getMessage());
} finally {
System.out.println("Cleanup code always runs");
}
}
}
Key Points:
Try block contains risky code
Catch blocks handle specific exceptions
Finally block always executes
Multiple catch blocks can handle different exceptions

1(f) What is the difference between process and thread?


Table 2
Aspect
Process
Thread
Definition
Independent program in execution
Lightweight subprocess within a process
Memory
Separate memory space
Shared memory space within process
Creation Cost
High (heavy-weight)
Low (light-weight)
Communication
Inter-Process Communication (IPC)
Direct communication through shared memory
Context Switching
Expensive
Cheaper
Independence
Completely independent
Dependent on parent process
Crash Impact
One process crash doesn't affect others
One thread crash can affect entire process
Resource Sharing
Limited sharing
Easy resource sharing
There are no rows in this table
Java Example:
java
// Thread example
class MyThread extends Thread {
public void run() {
System.out.println("Thread: " + Thread.currentThread().getName());
}
}

public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // Creates new thread
t2.start(); // Creates another thread
System.out.println("Main process continues...");
}
}

1(g) What is AWT?

AWT (Abstract Window Toolkit): AWT is Java's original platform-dependent GUI toolkit for creating graphical user interfaces.
Key Characteristics:
Platform-dependent: Uses native OS components
Heavy-weight components: Each component is a native OS window
Limited components: Basic GUI elements only
Part of java.awt package
Main Components:
Containers: Frame, Panel, Dialog, Window
Controls: Button, TextField, Label, Checkbox, Choice
Layout Managers: FlowLayout, BorderLayout, GridLayout
Graphics: Graphics class for drawing
Example:
java
import java.awt.*;
import java.awt.event.*;

public class AWTExample extends Frame implements ActionListener {
Button button;
TextField textField;
public AWTExample() {
setTitle("AWT Example");
setSize(300, 200);
setLayout(new FlowLayout());
textField = new TextField(20);
button = new Button("Click Me");
button.addActionListener(this);
add(new Label("Enter text:"));
add(textField);
add(button);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Text: " + textField.getText());
}
public static void main(String[] args) {
new AWTExample();
}
}
Advantages:
Direct OS integration
Fast performance
Native look and feel
Disadvantages:
Platform-dependent
Limited components
Heavy-weight

1(h) What is the difference between HTTPServlet and GenericServlet?


Table 3
Aspect
GenericServlet
HTTPServlet
Protocol
Protocol-independent
HTTP-specific
Parent Class
Implements Servlet interface
Extends GenericServlet
Methods
service() method only
doGet(), doPost(), doPut(), doDelete() etc.
Usage
General purpose
Web applications
HTTP Features
No HTTP-specific features
HTTP headers, sessions, cookies support
Abstract Nature
Abstract class
Abstract class
There are no rows in this table
GenericServlet Example:
java
import javax.servlet.*;
import java.io.*;

public class MyGenericServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Generic Servlet Response</h1>");
out.close();
}
}
HTTPServlet Example:
java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class MyHTTPServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>HTTP GET Request</h1>");
out.close();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>HTTP POST Request</h1>");
out.close();
}
}

1(i) What do you mean by JSP session?

JSP Session: A session represents a conversational state between a client (browser) and server across multiple HTTP requests. It maintains user-specific data throughout the user's interaction with the web application.
Key Characteristics:
Implicit Object: Available as session in JSP
Scope: Maintains data across multiple requests from same client
Storage: Server-side storage with client-side session ID
Timeout: Automatically expires after inactivity period
Interface: HttpSession interface implementation
Session Management:
jsp
<%-- Creating and using session --%>
<%
// Get existing session or create new one
HttpSession userSession = request.getSession();
// Store data in session
userSession.setAttribute("username", "john_doe");
userSession.setAttribute("loginTime", new Date());
userSession.setAttribute("cartItems", new ArrayList<String>());
// Retrieve data from session
String username = (String) userSession.getAttribute("username");
Date loginTime = (Date) userSession.getAttribute("loginTime");
// Session properties
String sessionId = userSession.getId();
boolean isNewSession = userSession.isNew();
int maxInactiveInterval = userSession.getMaxInactiveInterval();
%>

<html>
<body>
<h2>Session Information</h2>
<p>Session ID: <%= sessionId %></p>
<p>Username: <%= username %></p>
<p>Login Time: <%= loginTime %></p>
<p>Is New Session: <%= isNewSession %></p>
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.