Java001 Ex
Java001 Ex
StringBuffer is thread-safe (synchronized) which makes it slower but safe for multithreaded
environments
StringBuilder is not thread-safe (non-synchronized) which makes it faster but unsuitable for
multithreaded environments
Example:
java
StringBuffer sbuff = new StringBuffer("Hello"); // Thread-safe
sbuff.append(" World");
Example:
java
class SharedResource {
synchronized void print(String msg) {
System.out.print("[" + msg);
try { Thread.sleep(1000); } catch (Exception e) {}
System.out.println("]");
}
}
Example (WindowAdapter):
java
import java.awt.event.*;
import javax.swing.*;
Example:
java
String sql = "INSERT INTO Employees (id, name) VALUES (?, ?)";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, 101);
pstmt.setString(2, "John");
pstmt.executeUpdate();
5. Servlet Life Cycle
Initialization: init() called once when servlet is loaded
Example lifecycle:
java
public class MyServlet extends HttpServlet {
public void init() { /* Initialization code */ }
protected void doGet(HttpServletRequest req, HttpServletResponse res) { /* Handle GET */ }
public void destroy() { /* Cleanup code */ }
}
6. ArrayList vs Vector
ArrayList Vector
Not synchronized Synchronized (thread-safe)
Faster Slower due to synchronization
Increases capacity by 50% Increases capacity by 100%
Introduced in Java 1.2 Legacy since Java 1.0
Preferred in single-thread Used in multithread environments
7. Runtime Polymorphism with Example
Runtime polymorphism (method overriding) allows a subclass to provide specific implementation of a
method already defined in its superclass.
Example:
java
class Animal {
void sound() { System.out.println("Animal sound"); }
}
Non-static nested class (Inner class): Associated with instance of outer class
Anonymous inner class: Without name, defined and instantiated in single expression
Example:
java
class Outer {
static class Nested { } // Static nested class
class Inner { } // Inner class
void method() {
class Local { } // Local inner class
Runnable r = new Runnable() { // Anonymous inner class
public void run() { }
};
}
}
9. Scanner Class
Scanner class is used to parse primitive types and strings from input streams.
Example:
java
import java.util.Scanner;
Deep Copy:
Independent of original
Example:
java
class Person implements Cloneable {
String name;
Address address;
// Shallow copy
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
// Deep copy
protected Object deepClone() throws CloneNotSupportedException {
Person p = (Person)super.clone();
p.address = (Address)address.clone();
return p;
}
}
12. Keywords in Java
Keywords are reserved words with special meaning:
Access modifiers: public, private, protected
public TextEditor() {
setTitle("Simple Text Editor");
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
fileMenu.add(saveItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
}
Example:
java
import java.io.*;
// Serialization
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"));
oos.writeObject(s);
oos.close();
// Deserialization
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"));
Student s2 = (Student)ois.readObject();
ois.close();
Example:
java
public class Person {
private String name;
private int age;
// Accessor (getter)
public String getName() { return name; }
// Mutator (setter)
public void setName(String name) { this.name = name; }
Checked at compile-time
Unchecked Exceptions:
Extend RuntimeException
Example:
java
// Checked exception example
try {
FileReader file = new FileReader("nonexistent.txt");
} catch (IOException e) {
System.out.println("File not found");
}
Methods:
// Mutable StringBuffer
StringBuffer s2 = new StringBuffer("Hello");
System.out.println("Original StringBuffer: " + s2);
s2.append(" World");
System.out.println("After append: " + s2); // "Hello World"
}
}
Example:
java
import java.util.*;
// Accessing elements
System.out.println("Bob's age: " + map.get("Bob"));
// Iterating
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Removing
map.remove("Alice");
System.out.println("Size after removal: " + map.size());
}
}
22. Layouts in Java
Layout managers arrange components in containers:
BorderLayout: Divides container into five regions (NORTH, SOUTH, EAST, WEST, CENTER)
Example (BorderLayout):
java
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("Center"), BorderLayout.CENTER);
23. Exception Handling with Example
Exception handling manages runtime errors using try-catch blocks.
Example:
java
public class ExceptionHandling {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("This always executes");
}
}
Types:
User-defined
Example:
java
package com.example.myapp;
// In another file
import com.example.myapp.MyClass;
Example:
java
import java.util.StringTokenizer;
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
init(): Initialization
Example:
java
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {
public void init() { setBackground(Color.white); }
public void start() { System.out.println("Applet started"); }
public void paint(Graphics g) { g.drawString("Hello Applet", 20, 20); }
public void stop() { System.out.println("Applet stopped"); }
public void destroy() { System.out.println("Applet destroyed"); }
expliain super keyword in contructor chaining with example
super() is used to call the constructor of the immediate parent class.
If the superclass doesn't have a no-argument constructor, and the subclass doesn't explicitly
call another superclass constructor, a compile-time error occurs.
// Superclass--class Animal {
Animal() { System.out.println("Animal constructor called");}}
// Subclass ---class Dog extends Animal {
Dog() { super(); // Calls the constructor of Animal
System.out.println("Dog constructor called");}}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();}}
output--Animal constructor called
Dog constructor called
27. Multithreading in Java
Multithreading allows concurrent execution of multiple threads.
Example:
java
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try { Thread.sleep(500); } catch (Exception e) {}
}
}
}
Example:
java
public class DeadlockDemo {
static Object lock1 = new Object();
static Object lock2 = new Object();
String query = "SELECT eno, ename, department, sal FROM employees " +
"WHERE department = 'Computer Science'";
ResultSet rs = stmt.executeQuery(query);
System.out.println("Employee Details:");
System.out.println("----------------");
while (rs.next()) {
System.out.println("ID: " + rs.getInt("eno"));
System.out.println("Name: " + rs.getString("ename"));
System.out.println("Department: " + rs.getString("department"));
System.out.println("Salary: " + rs.getDouble("sal"));
System.out.println("----------------");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
30. Regular Expressions and Nested Classes
Regular Expressions:
Pattern matching using java.util.regex package (Pattern and Matcher classes).
Example:
java
import java.util.regex.*;
java
public class Outer {
// Static nested class
static class Nested {
void validateEmail(String email) {
if (email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
System.out.println("Valid email");
} else {
System.out.println("Invalid email");
}
}
}
Copy
Download
import java.sql.*;
try {
// 1. Register the driver (not required since JDBC 4.0 - automatic loading)
// Class.forName("com.mysql.cj.jdbc.Driver");
// 3. Create statement
Statement statement = connection.createStatement();
// 4. Execute query
String sql = "SELECT * FROM employees LIMIT 5";
ResultSet resultSet = statement.executeQuery(sql);
// 5. Process results
System.out.println("\nEmployee Data:");
System.out.println("ID\tName\t\tDepartment");
System.out.println("--------------------------------");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String dept = resultSet.getString("department");
} catch (SQLException e) {
System.out.println("Error connecting to database:");
e.printStackTrace();
} finally {
// 6. Close connection
try {
if (connection != null) {
connection.close();
System.out.println("\nConnection closed successfully");
}
} catch (SQLException e) {
System.out.println("Error closing connection");
e.printStackTrace();
}
}
}
}
1. Driver Characteristics:
o Pure Java implementation
o Directly connects to the database (no middleware)
o Most efficient JDBC driver type
o Platform independent
2. Setup Requirements:
o You need the MySQL Connector/J JAR file (mysql-connector-java-
x.x.xx.jar)
o Must be added to your classpath
3. Advantages Shown:
o Simple connection string (no ODBC or native libraries required)
o Direct database communication
o Full Java implementation
4. Typical Output:
Copy
Download
Connecting to database using Type 4 JDBC driver...
Employee Data:
ID Name Department
--------------------------------
101 John Smith Engineering
102 Jane Doe Marketing
103 Bob Johnson HR
104 Alice Brown Engineering
105 Charlie Davis Sales