0% found this document useful (0 votes)
34 views11 pages

Java Unit 4,5 Discourse

The document outlines various Java programming tasks and concepts, including string operations using StringBuffer, event handling in GUI applications, and applet lifecycle management. It also discusses error handling, security risks, and the importance of proper resource management in Java applications. Additionally, it highlights common mistakes in event handling and provides corrections for code snippets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views11 pages

Java Unit 4,5 Discourse

The document outlines various Java programming tasks and concepts, including string operations using StringBuffer, event handling in GUI applications, and applet lifecycle management. It also discusses error handling, security risks, and the importance of proper resource management in Java applications. Additionally, it highlights common mistakes in event handling and provides corrections for code snippets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

9.Consider the general structure of the code to implement java string operations.

public
class StringBufferMethods { public static void main(String args[]) { StringBuffer S1=new
StringBuffer(“Welcome to CSE”); } } Modify the above given general structure to do the
following operation. a) Replace the string “CSE” in the above program with the string
“BIT” and find the length of the updated string (4 marks) b) Extract the substring from
index 5 to 8 (2 marks)

a)public class StringBufferMethods {


public static void main(String args[]) {
// String already contains "BIT"
StringBuffer S1 = new StringBuffer("Welcome to BIT");

// Display the string


System.out.println("String: " + S1);

// Find and display the length of the string


System.out.println("Length of the String: " + S1.length());
}
}

b)public class StringBufferMethods {


public static void main(String args[]) {
// String already contains "BIT"
StringBuffer S1 = new StringBuffer("Welcome to BIT");

// Display the string


System.out.println("String: " + S1);

// Find and display the length of the string


System.out.println("Length of the String: " + S1.length());

// Extract substring from index 5 to 8


String sub = S1.substring(5, 8);
System.out.println("Substring from index 5 to 8: " + sub);
}
}

20. A student is developing a Java application to manage user input for an online
registration form. The form collects user names, which must be formatted and compared
correctly before storing them in a database. To perform tasks such as joining names,
comparing values, trimming spaces, and managing string instances efficiently, the
student explores various String class methods in Java. While reviewing the code, the
student comes across the following method calls and wants to predict which of them are
invalid String methods in Java. a) concat() b) Equals () c) compareTo() d) intern() e) trim()
f) Abstract () g) break() h) final() i) extends()

Option Method Reason

f) Abstract ❌ Not a valid String method; “abstract” is a keyword in Java, not a


() method

g) break() ❌ Not a method; it’s a control statement used in loops/switch


h) final() ❌ Not a method; it’s a keyword used to declare constants or
prevent inheritance

i) extends( ❌ Not a method; it’s a keyword used in class inheritance


)

21. A developer is creating a financial tool in Java to calculate


values like interest, growth, and risk. To ensure correct usage,
they match each method with its function and real-world
financial application. Match the following for the mathematical
functions in java.

answer:

Java Method Description Financial Relevance

A1. Math.ceil() B2. Rounds a number upward C2. Applied when rounding
to the nearest integer currency to the nearest rupee or
cent

A2. B3. Rounds a number C4. Used to estimate floor price or


Math.floor() downward to the nearest conservative financial forecasts
integer
A3. Math.abs() B4. Returns the absolute C1. Helps ensure negative losses
(non-negative) value don’t distort risk metrics

A4. B1. Rounds to the nearest C3. Useful when calculating the
Math.round() integer (rounds .5 to nearest minimal payment due
even)

Step Description

1️⃣ Initialize StringBuffer: Create an instance of StringBuffer to hold log


messages. (Step 1)

2️⃣ Create Logging Method: Implement a synchronized method that appends log
messages to StringBuffer. (Step 4)

3️⃣ Capture User Action: Detect when a user performs an action (like login/logout).
(Step 5)

4️⃣ Invoke Logging Method: Call the synchronized logging method to append the log
message safely. (Step 3)

5️⃣ Flush/Output Logs: Finally, periodically or on events, output the accumulated logs.
(Step 2)
N Error Reason
o
.

1 sb = "Welcome"; String literal can’t


be assigned to
StringBuffer

2 ' to' Invalid char literal


(too many
characters)

3 StringBuffer String literal not


sb2 = "Java assignable to
Programming"; StringBuffer

4
sb2 = + not
sb2 + defined
" is for
fun!" StringB
uffer
;
5 Using Caus
sb.appe es
nd() Null
before Poin
proper terE
initializat xcep
ion tion

4 Q.No 24 Question Correct Answer Marks

1 Compute square Math.sqrt(number 1


root )

2 Effect of Measures 2
System.currentTi execution time
meMillis() between calls

3 Power of 6² Math.pow(6, 2) 1

4 Output of 0.0 because 1


Math.log(1) ln(1)=0

25. A GUI-based Java application allows users to submit feedback by clicking a "Submit"
button. When the button is clicked, a message is shown confirming submission. The
event handling mechanism behind this involves several steps from the moment the user
clicks the button to the final response. i) Identify the correct sequence of steps involved
in the event handling process by rearranging the following steps. ii) Identify the role of
ActionEvent in it. 1. Component is registered with the listener ,The Submit button is
linked using submitButton.addActionListener(this);. 2.Event is generated ,The user types
feedback in the TextField and clicks the Submit button, triggering an ActionEvent. 3.GUI
component is created, A JButton ("Submit") and a TextField are created and added to the
frame. 4. Event object is created by the event source ,The JVM creates an ActionEvent
object containing details about the source, type, and command 5.Event is dispatched to
the registered listener ,The event object is passed automatically to the listener. 6.Listener
is implemented ,The programmer implements the ActionListener interface and defines
the actionPerformed() method. 7.User feedback is displayed ,A dialog box
(JOptionPane.showMessageDialog) or label confirms the submission. 8.Event is handled
by the listener ,The actionPerformed() method executes: if input = "Delhi", show "Correct
Answer!", else show "Try Again."


i) Final Correct Order:​
3→6→1→2→4→5→8→7

ii) Role of ActionEvent

ActionEvent acts as a bridge between the event source and the event handler.​
When the user clicks the “Submit” button, the JVM creates an ActionEvent object that holds
information such as the event source (the button), the event type (action), and the command
string.​
This ActionEvent object is automatically passed to the actionPerformed(ActionEvent
e) method of the registered listener, allowing the program to identify which component triggered
the action and respond accordingly.

26. A university uses a Java Applet for online course registration. The Applet on the
client side has a GUI with a student ID field, a ComboBox for course selection, and a
Submit button. When submitted, the Applet sends the request to a Servlet through HTTP.
The Servlet checks the inputs, updates the database after verifying seat availability, and
sends the result back. Finally, the Applet shows either a confirmation message or an
error like “Course Full.” i)Represent error-handling mechanisms that ensure the Applet
shows meaningful messages when the Servlet or database fails in the server side with
justification. (2 Marks) ii)Indicate security risks if the Applet relies solely on
client/server-side validation with justification. (2 Marks)

i) Error Handling:​
Use try-catch blocks in the Applet to handle network or server errors and display clear
messages like “Server unavailable” or “Database error.” The Servlet should send standardized
error responses that the Applet can interpret for meaningful feedback.

ii) Security Risks:​


Relying only on client-side validation allows users to bypass rules, while only server-side
validation increases load and vulnerability. Both validations are needed to ensure data integrity
and system security.
. 27. Question A student is developing a Java applet for an interactive quiz. The applet
initializes questions, starts a timer when loaded, pauses if the user switches browser
tabs, and frees memory when the quiz is closed. The student uses the standard applet
lifecycle methods to manage these behaviors.. Based on the scenario, identify with the
correct matches by linking each method in Column A to its purpose from Column B and
its corresponding execution phase from Column C, based on the applet’s lifecycle
described in the scenario.

A (Applet B (Purpose) C (Execution


Method) Phase)

A1. init() B1. Allocate resources or UI setup C1. Initialization

A2. start() B2. Start or resume execution (e.g., start C2. Running
timer)

A3. stop() B3. Pause execution or release temporary C3. Idle / Paused
resources

A4. destroy() B4. Perform final cleanup and free memory C4. Termination

28. A programmer is building a Java Swing application that includes a "Login" button
(event source).They write a class LoginHandler that implements ActionListener (event
listener) to validate user credentials.The actionPerformed() method in LoginHandler
compiles correctly and contains proper logic, but clicking the button does not trigger any
action.
i)Assess the flow of event listener when a button is clicked in a Java application.
Illustrate with relevant method calls. (2 Marks)
ii)Assuming the LoginHandler logic is correct and compiles with error, predict the most
likely mistake the programmer made using the event handling flow with proper
justification. (3 Marks)

i) Flow of Event Listener (2 Marks)

When the button is clicked in a Java Swing application, the following event-handling flow
occurs:

1️⃣ Event Source registers the listener –

loginButton.addActionListener(new LoginHandler());

This links the button (JButton) with the event listener (LoginHandler).

2️⃣ Event is generated – When the user clicks the button, the JVM generates an
ActionEvent object.

3️⃣ Event is dispatched – The ActionEvent object is automatically passed to the listener’s
method:

public void actionPerformed(ActionEvent e) {


// Handle login logic
}
4️⃣ Event is handled – The actionPerformed() method executes the intended action (e.g.,
validating credentials).

ii) Most Likely Mistake and Justification (3 Marks):​


The programmer likely forgot to register the listener using
loginButton.addActionListener(new LoginHandler());.​
Justification: Without registering the listener, the button’s click event has no handler to receive
it, so actionPerformed() never executes even though the code compiles correctly.

29. import java.applet.Applet; import java.awt.Graphics; public class MyApplet Extends


Applet { public void paint() { g.drawstring("Hello Applet", 20, 20) } } Identify the error in
this applet code that prevents the message from being displayed correctly. Justify your
answer based on the code provided.

Corrected code:
import java.applet.Applet;
import java.awt.Graphics;

public class MyApplet extends Applet {


public void paint(Graphics g) {
g.drawString("Hello Applet", 20, 20);
}
}

Justification:
The paint() method in an applet must have the exact signature public void
paint(Graphics g) to receive the Graphics context for drawing. Using the wrong method
name (drawstring) or syntax errors (Extends, missing semicolon) prevents compilation, so
the message “Hello Applet” will not display.

30. Question The Applet Life Cycle diagram shows the different states of a Java applet,
managed through methods like init(), start(), stop(), and destroy(). It illustrates how an
applet is initialized, executed, stopped, and finally destroyed by the browser or applet
viewer. Figure.Applet Life Cycle

1)Identify the lifecycle methods that are triggered when an applet is inactive after
initialization and the browser is closed immediately. (1 Mark) ii) Classify the roles of init()
and start() methods in applet lifecycle management and explain how they help in proper
resource handling. (2 Marks) iii) Select the transitions between applet states when a user
navigates away from and then returns to the page containing the applet, based on the
Applet Life Cycle figure. Justify it. (2 Marks)

i) (1 Mark)

When the applet is inactive after initialization and the browser is closed, the following

👉
methods are triggered:​
stop() – called when the applet becomes inactive.​
👉 destroy() – called when the browser or applet viewer is closed, permanently removing
the applet from memory.

ii) (2 Marks)

●​ init() – Called once when the applet is first loaded. It is used to initialize resources,
set up UI components, and allocate memory or connections.​

●​ start() – Called every time the applet becomes active or visible. It is used to start
animations, threads, or processes that should run while the applet is active.​

✅ Together, they ensure efficient resource management—init() prepares resources once,


and start() activates them only when needed.

iii) (2 Marks)
When the user navigates away from the page containing the applet, the stop() method is
called, moving the applet from Running → Stopped state.​
When the user returns to the page, the start() method is invoked again, transitioning the
applet from Stopped → Running state.

✅ Justification:​
The applet life cycle allows temporary suspension (stop()) and resumption (start())
without reinitializing resources, improving performance and resource efficiency.

You might also like