Docsity

Sample document has uploaded, Cheat Sheet of Latin

Toggle sidebar
bg1
Experiment 1: Packages and Custom Exception Handling
1. Problem Statement
Write a Java program to create a custom user-defined package containing a custom exception
class. Demonstrate throwing and catching this custom exception when validating input marks
(0 to 100).
2. Input Specification
• An integer representing student marks passed into the validation method
checkMarks(int marks).
3. Output Specification
• If marks are valid (0 \le \text{marks} \le 100), display a confirmation message.
• If marks are invalid (<0 or >100), throw and catch MyException displaying an error
message.
4. Sample Input and Output
• Sample Input: checkMarks(85); checkMarks(120);
• Sample Output:
• Valid marks: 85
• Custom Exception: Marks must be between 0 and 100.
5. Code
package mypack;
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
import mypack.MyException;
public class Main {
static void checkMarks(int marks) throws MyException {
if (marks < 0 || marks > 100) {
throw new MyException("Marks must be between 0 and 100.");
}
System.out.println("Valid marks: " + marks);
}
public static void main(String[] args) {
try {
checkMarks(85);
checkMarks(120);
} catch (MyException e) {
System.out.println("Custom Exception: " + e.getMessage());
}
}}
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15

Partial preview of the text

Download Sample document has uploaded and more Cheat Sheet Latin in PDF only on Docsity!

Experiment 1: Packages and Custom Exception Handling

1. Problem Statement

Write a Java program to create a custom user-defined package containing a custom exception

class. Demonstrate throwing and catching this custom exception when validating input marks

(0 to 100).

2. Input Specification

  • An integer representing student marks passed into the validation method

checkMarks(int marks).

3. Output Specification

  • If marks are valid (0 \le \text{marks} \le 100), display a confirmation message.
  • If marks are invalid (<0 or >100), throw and catch MyException displaying an error

message.

4. Sample Input and Output

  • Sample Input: checkMarks(85); checkMarks(120);
  • Sample Output:
  • Valid marks: 85
  • Custom Exception: Marks must be between 0 and 100.

5. Code

package mypack; public class MyException extends Exception { public MyException(String message) { super(message); } } import mypack.MyException; public class Main { static void checkMarks(int marks) throws MyException { if (marks < 0 || marks > 100) { throw new MyException("Marks must be between 0 and 100."); } System.out.println("Valid marks: " + marks); } public static void main(String[] args) { try { checkMarks(85); checkMarks(120); } catch (MyException e) { System.out.println("Custom Exception: " + e.getMessage()); } }}

6. Output

this.threadName = threadName; } public void run() { for (int i = 0; i < 5; i++) { counter.increment(threadName); } } } public class Main { public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); MyThread t1 = new MyThread(counter, "Thread-1"); MyThread t2 = new MyThread(counter, "Thread-2"); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Final Count = " + counter.getCount()); } }

6. Output

Experiment 3: Collection Framework using ArrayList and

Iterator

1. Problem Statement

Write a Java program to demonstrate the use of the Java Collection Framework by storing a

collection of student names using ArrayList and traversing through the list using an

Iterator.

2. Input Specification

  • Elements added to ArrayList: "Amit", "Neha", "Rahul", "Sahil".

3. Output Specification

  • Sequence of strings printed line-by-line during iterator traversal.

4. Sample Input and Output

  • Sample Output:
  • Students in ArrayList:
  • Amit
  • Neha
  • Rahul
  • Sahil

5. Code

import java.util.ArrayList; import java.util.Iterator; public class Main { public static void main(String[] args) { ArrayList students = new ArrayList<>(); students.add("Amit"); students.add("Neha"); students.add("Rahul"); students.add("Sahil"); System.out.println("Students in ArrayList:"); Iterator itr = students.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } }

Experiment 4: Set and Map Interface (HashSet and

HashMap)

1. Problem Statement

Write a Java program to demonstrate Set and Map interfaces using HashSet to show

uniqueness of elements and HashMap to store key-value pairs (ID and Student Name).

2. Input Specification

  • HashSet additions: "Mumbai", "Pune", "Nashik", "Mumbai" (duplicate).
  • HashMap key-values: (101, "Amit"), (102, "Neha"), (103, "Rahul").

3. Output Specification

  • Display distinct HashSet elements without duplicate values.
  • Display key-value mappings from HashMap.

4. Sample Input and Output

  • Sample Output:
  • HashSet: [Mumbai, Pune, Nashik]
  • HashMap:
  • 101 - > Amit
  • 102 - > Neha
  • 103 - > Rahul

5. Code

import java.util.HashSet; import java.util.HashMap; import java.util.Set; import java.util.Map; public class Main { public static void main(String[] args) { Set cities = new HashSet<>(); cities.add("Mumbai"); cities.add("Pune"); cities.add("Nashik"); cities.add("Mumbai"); System.out.println("HashSet: " + cities); Map students = new HashMap<>(); students.put(101, "Amit"); students.put(102, "Neha"); students.put(103, "Rahul"); System.out.println("HashMap:"); for (Map.Entry entry : students.entrySet()) { System.out.println(entry.getKey() + " - > " + entry.getValue()); } }}

6. Output

course.add("ENTC"); add(course); Button submit = new Button("Submit"); submit.addActionListener(this); add(submit); result = new Label(" "); add(result); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); } }); setVisible(true); } public void actionPerformed(ActionEvent e) { result.setText("Hello " + nameField.getText() + "! Course: " + course.getSelectedItem()); } public static void main(String[] args) { new AWTForm(); } }

6. Output

Experiment 6: AWT Components - Label, Button,

TextField, Checkbox

1. Problem Statement

Create a Java GUI program utilizing basic AWT components (TextField, Checkbox, Button,

Label) to evaluate user selection state and return welcome responses or validation warnings.

2. Input Specification

  • Text entry string for Name.
  • Boolean check state on the "I agree" Checkbox.

3. Output Specification

  • Displays "Welcome, [Name]" if checkbox is checked.
  • Displays "Please select I agree." if checkbox is left unchecked.

4. Sample Input and Output

  • Sample Input: Name: Sahil, Checkbox: Checked
  • Sample Output: Welcome, Sahil

5. Code

import java.awt.; import java.awt.event.; public class AWTComponents extends Frame implements ActionListener { TextField textField; Checkbox agree; Label result; AWTComponents() { setTitle("AWT Components Demo"); setSize(400, 250); setLayout(new FlowLayout()); add(new Label("Enter Name:")); textField = new TextField(20); add(textField); agree = new Checkbox("I agree"); add(agree); Button button = new Button("Submit"); button.addActionListener(this); add(button); result = new Label(" "); add(result); addWindowListener(new WindowAdapter() {

Experiment 7: Database Connectivity and CRUD

Operations using JDBC PreparedStatement

1. Problem Statement

Write a Java program to establish a connection with a database using DriverManager and

perform CRUD (Create, Read, Update, Delete) operations on a database table using

PreparedStatement.

2. Input Specification

  • Database details: MySQL connection URL

(jdbc:mysql://localhost:3306/testdb), username, and password.

  • Data inputs passed to SQL statements: Student ID, Name, and Course values.

3. Output Specification

  • Console messages confirming successful database connection and execution logs

showing rows inserted, selected, updated, and deleted.

4. Sample Input and Output

  • Sample Output:
  • Database Connected Successfully!
  • Inserted 1 record.
  • --- Current Records ---
  • ID: 101, Name: Sahil, Course: CSE
  • Updated 1 record.
  • --- After Update ---
  • ID: 101, Name: Sahil, Course: Computer Engineering
  • Deleted 1 record.

5. Code

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class JDBCCRUD { private static final String URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"; private static final String USER = "sa"; private static final String PASSWORD = ""; public static void main(String[] args) { try { Class.forName("org.h2.Driver");

Connection conn = DriverManager.getConnection(URL, USER, PASSWORD); System.out.println("Database Connected Successfully!"); Statement stmt = conn.createStatement(); stmt.execute("CREATE TABLE IF NOT EXISTS Student (id INT PRIMARY KEY, name VARCHAR(50), course VARCHAR(50))"); // 1. CREATE (Insert) String insertSQL = "INSERT INTO Student (id, name, course) VALUES (?, ?, ?)"; PreparedStatement pstmtInsert = conn.prepareStatement(insertSQL); pstmtInsert.setInt( 1 , 101 ); pstmtInsert.setString( 2 , "Sahil"); pstmtInsert.setString( 3 , "CSE"); int rowsInserted = pstmtInsert.executeUpdate(); System.out.println("Inserted " + rowsInserted + " record."); // 2. READ (Select) String selectSQL = "SELECT * FROM Student"; PreparedStatement pstmtSelect = conn.prepareStatement(selectSQL); ResultSet rs = pstmtSelect.executeQuery(); System.out.println("--- Current Records ---"); while (rs.next()) { System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Course: " + rs.getString("course")); } // 3. UPDATE String updateSQL = "UPDATE Student SET course =? WHERE id = ?"; PreparedStatement pstmtUpdate = conn.prepareStatement(updateSQL); pstmtUpdate.setString( 1 , "Computer Engineering"); pstmtUpdate.setInt( 2 , 101 ); int rowsUpdated = pstmtUpdate.executeUpdate(); System.out.println("Updated " + rowsUpdated + " record."); // 4. DELETE String deleteSQL = "DELETE FROM Student WHERE id = ?"; PreparedStatement pstmtDelete = conn.prepareStatement(deleteSQL); pstmtDelete.setInt( 1 , 101 ); int rowsDeleted = pstmtDelete.executeUpdate(); System.out.println("Deleted " + rowsDeleted + " record."); conn.close(); } catch (Exception e) { System.out.println("JDBC Error: " + e.getMessage()); } } }

Experiment 8: Servlet Filters and Listeners

1. Problem Statement

Demonstrate Java Web Servlet infrastructure by implementing a Servlet (HelloServlet), a

Servlet Filter (LoggingFilter) for intercepting requests, and an HttpSessionListener

(SessionListener) for tracking session creation and destruction events.

2. Input Specification

  • HTTP GET Request to /hello.

3. Output Specification

  • Web Browser output confirming request handling.
  • Server console logs showing filter execution and session lifecycle events.

4. Sample Input and Output

  • Browser Response: Hello from Servlet
  • Server Console:
  • Request received.
  • Request is being processed...
  • Response sent successfully.
  • Session Created: 8A72BC91F
  • Session Destroyed: 8A72BC91F

5. Code

HelloServlet.java:

import java.io.; import jakarta.servlet.; import jakarta.servlet.http.; import jakarta.servlet.annotation.; @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(""); out.println("Hello from Servlet"); out.println("

Request processed successfully.

"); out.println(""); } }

LoggingFilter.java:

import java.io.; import jakarta.servlet.; import jakarta.servlet.annotation.; @WebFilter("/") public class LoggingFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Request received."); System.out.println("Request is being processed..."); chain.doFilter(request, response); System.out.println("Response sent successfully."); } }

SessionListener.java:

import jakarta.servlet.http.; import jakarta.servlet.annotation.; @WebListener public class SessionListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent event) { System.out.println("Session Created: " + event.getSession().getId()); } public void sessionDestroyed(HttpSessionEvent event) { System.out.println("Session Destroyed: " + event.getSession().getId()); } }

6. Output

Welcome, <%= session.getAttribute("username") %>! Logout

<% } else { %>

Invalid Username or Password Try Again

<% } %>

logout.jsp:

session.invalidate(); %>

You have been logged out successfully. Login Again

6. Output

Experiment 10: JSP Form Handling

1. Problem Statement

Implement a single-page JSP form processing application that accepts user form inputs (name

and age) via POST request and renders response content dynamically on the same page.

2. Input Specification

  • Form inputs: name (String) and age (Integer string).

3. Output Specification

  • Displays dynamic greeting message echoing input name and age values upon

submission.

4. Sample Input and Output

  • Sample Input: Name: Sahil, Age: 18
  • Sample Output:
  • Result
  • Welcome, Sahil!
  • Your age is: 18

5. Code

JSP Form Handling

JSP Form Handling

Enter Name: Enter Age:

<% String name = request.getParameter("name"); String age = request.getParameter("age"); if (name != null && age != null) { %>

Result

Welcome, <%= name %>!

Your age is: <%= age %>

<% } %>