0% found this document useful (0 votes)
3 views22 pages

Java001 Ex

The document covers various Java programming concepts including the differences between StringBuffer and StringBuilder, thread synchronization, adapter classes, prepared statements, servlet life cycle, and exception handling. It also discusses data structures like ArrayList and Vector, the use of HashMap, and the importance of access modifiers and keywords in Java. Additionally, it explains object serialization, multithreading, deadlocks, and provides examples for each topic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views22 pages

Java001 Ex

The document covers various Java programming concepts including the differences between StringBuffer and StringBuilder, thread synchronization, adapter classes, prepared statements, servlet life cycle, and exception handling. It also discusses data structures like ArrayList and Vector, the use of HashMap, and the importance of access modifiers and keywords in Java. Additionally, it explains object serialization, multithreading, deadlocks, and provides examples for each topic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

1.

Difference between StringBuffer and StringBuilder


StringBuffer and StringBuilder are both used to create mutable strings, but with key differences:

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");

StringBuilder sbld = new StringBuilder("Hello"); // Faster


sbld.append(" World");
2. Synchronizing Threads and Inter-Thread Communication
Thread synchronization ensures only one thread accesses shared resources at a time using synchronized
keyword. Inter-thread communication uses wait(), notify(), and notifyAll() methods.

Example:

java
class SharedResource {
synchronized void print(String msg) {
System.out.print("[" + msg);
try { Thread.sleep(1000); } catch (Exception e) {}
System.out.println("]");
}
}

class MyThread extends Thread {


SharedResource sr;
String msg;
MyThread(SharedResource sr, String msg) {
this.sr = sr;
this.msg = msg;
}
public void run() {
sr.print(msg);
}
}
public class Main {
public static void main(String[] args) {
SharedResource sr = new SharedResource();
new MyThread(sr, "Hello").start();
new MyThread(sr, "World").start();
}
}
3. Adapter Class with Example
Adapter classes provide default implementations of listener interfaces to reduce boilerplate code.

Example (WindowAdapter):

java
import java.awt.event.*;
import javax.swing.*;

public class AdapterExample {


public static void main(String[] args) {
JFrame frame = new JFrame();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Window closing");
System.exit(0);
}
});
frame.setSize(300, 300);
frame.setVisible(true);
}
}
4. Prepared Statement
PreparedStatement is an interface that represents precompiled SQL statements with advantages:

Precompiled for better performance

Prevents SQL injection

Allows parameterized queries

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

Service: service() handles client requests (calls doGet(), doPost() etc.)

Destruction: destroy() called before servlet is unloaded

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"); }
}

class Dog extends Animal {


void sound() { System.out.println("Bark"); }
}

public class Main {


public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound(); // Output: Bark (runtime polymorphism)
}
}
8. Nested and Inner Classes
Nested classes are classes defined within another class. Types:

Static nested class: Static member of outer class

Non-static nested class (Inner class): Associated with instance of outer class

Local inner class: Defined within a method

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;

public class ScannerExample {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter age: ");
int age = sc.nextInt();
System.out.println(name + " is " + age + " years old");
sc.close();
}
}
10. Flavors of Java
Java SE (Standard Edition): Core Java platform

Java EE (Enterprise Edition): For enterprise applications

Java ME (Micro Edition): For mobile/embedded devices

JavaFX: For rich client applications

Android Java: Modified Java for Android development

11. Shallow Copy vs Deep Copy


Shallow Copy:

Copies references to objects

Changes in copied object affect original

Default behavior of clone() method

Deep Copy:

Creates new copies of all objects

Independent of original

Must be implemented manually

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

Class-related: class, interface, extends, implements

Flow control: if, else, switch, case, for, while, do

Exception handling: try, catch, finally, throw, throws

Modifiers: static, final, abstract, synchronized, volatile

Others: new, this, super, package, import

14. Swing Program for Text Editor


java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TextEditor extends JFrame {


JTextArea textArea;

public TextEditor() {
setTitle("Simple Text Editor");
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);

textArea = new JTextArea();


JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);

JMenuBar menuBar = new JMenuBar();


JMenu fileMenu = new JMenu("File");

JMenuItem saveItem = new JMenuItem("Save");


saveItem.addActionListener(e -> saveFile());

fileMenu.add(saveItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
}

private void saveFile() {


JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
// Save logic here
JOptionPane.showMessageDialog(this, "File saved!");
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new TextEditor().setVisible(true));
}
}
15. Object Serialization
Object serialization is the process of converting an object's state to a byte stream for storage or
transmission. Deserialization reconstructs the object from the byte stream.

Example:

java
import java.io.*;

class Student implements Serializable {


String name;
int age;

Student(String name, int age) {


this.name = name;
this.age = age;
}
}

public class SerializationDemo {


public static void main(String[] args) throws Exception {
Student s = new Student("John", 20);

// 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();

System.out.println(s2.name + " " + s2.age);


}
}
16. Accessor and Mutator Methods
Accessor (getter) and mutator (setter) methods control access to class fields.

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; }

public int getAge() { return age; }


public void setAge(int age) {
if(age > 0) this.age = age;
}
}
17. Checked vs Unchecked Exceptions
Checked Exceptions:

Checked at compile-time

Must be handled or declared

Extend Exception class

Example: IOException, SQLException

Unchecked Exceptions:

Not checked at compile-time

Extend RuntimeException

Example: NullPointerException, ArrayIndexOutOfBoundsException

Example:

java
// Checked exception example
try {
FileReader file = new FileReader("nonexistent.txt");
} catch (IOException e) {
System.out.println("File not found");
}

// Unchecked exception example


int[] arr = new int[5];
try {
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds");
}
18. Thread Life Cycle
New: Thread created but not started

Runnable: Thread is ready to run (may or may not be running)

Running: Thread is executing

Blocked/Waiting: Thread is waiting for a resource or notification

Terminated: Thread has completed execution

Methods:

start(): moves from New to Runnable

run(): contains thread's code

sleep(), wait(): moves to Blocked/Waiting

notify(), notifyAll(): wakes up waiting threads

19. Mutable and Immutable String Demonstration


java
public class StringDemo {
public static void main(String[] args) {
// Immutable String
String s1 = "Hello";
System.out.println("Original String: " + s1);
s1.concat(" World");
System.out.println("After concat: " + s1); // Still "Hello"

// Mutable StringBuffer
StringBuffer s2 = new StringBuffer("Hello");
System.out.println("Original StringBuffer: " + s2);
s2.append(" World");
System.out.println("After append: " + s2); // "Hello World"
}
}

20. Writing User Input to File


java
import java.io.*;
import java.util.Scanner;

public class WriteToFile {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();

try (FileWriter fw = new FileWriter("output.txt");


BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(sentence);
System.out.println("Sentence written to file successfully");
} catch (IOException e) {
System.out.println("Error writing to file");
}
}
}
21. HashMap with Example
HashMap is a hash table implementation of Map interface that stores key-value pairs.

Example:

java
import java.util.*;

public class HashMapExample {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
// Adding elements
map.put("Alice", 25);
map.put("Bob", 30);
map.put("Charlie", 28);

// 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)

FlowLayout: Arranges components in a row, wrapping as needed

GridLayout: Divides container into equal-sized grid

CardLayout: Shows one component at a time like cards

GridBagLayout: Most flexible with constraints

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");
}
}

static int divide(int a, int b) {


return a / b;
}
}

24. Packages in Java


Packages are containers for classes that:

Prevent naming conflicts

Provide access control

Make classes easier to locate

Types:

Built-in (java.lang, java.util, java.io etc.)

User-defined

Example:

java
package com.example.myapp;

public class MyClass {


public void display() {
System.out.println("Inside MyClass");
}
}

// In another file
import com.example.myapp.MyClass;

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}

25. StringTokenizer with Example


StringTokenizer breaks strings into tokens based on delimiters.

Example:

java
import java.util.StringTokenizer;

public class TokenizerExample {


public static void main(String[] args) {
String str = "Hello,World,Java";
StringTokenizer st = new StringTokenizer(str, ",");

while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

// With multiple delimiters


String str2 = "Hello; World! Java";
StringTokenizer st2 = new StringTokenizer(str2, "; !");
while (st2.hasMoreTokens()) {
System.out.println(st2.nextToken());
}
}
}
26. Applet Life Cycle with Example
Applet life cycle methods:

init(): Initialization

start(): After init() or when applet is revisited


paint(): For drawing

stop(): When applet is no longer visible

destroy(): Before applet is terminated

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.

 It must be the first statement in the subclass constructor.

 If a subclass constructor doesn't explicitly call a superclass constructor, Java automatically


inserts a call to the no-argument constructor of the superclass.

 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) {}
}
}
}

public class MultiThreadDemo {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
28. Deadlock with Example
Deadlock occurs when two or more threads wait forever for locks held by each other.

Example:

java
public class DeadlockDemo {
static Object lock1 = new Object();
static Object lock2 = new Object();

static class Thread1 extends Thread {


public void run() {
synchronized (lock1) {
System.out.println("Thread1 holds lock1");
try { Thread.sleep(100); } catch (Exception e) {}
synchronized (lock2) {
System.out.println("Thread1 holds lock1 and lock2");
}
}
}
}

static class Thread2 extends Thread {


public void run() {
synchronized (lock2) {
System.out.println("Thread2 holds lock2");
try { Thread.sleep(100); } catch (Exception e) {}
synchronized (lock1) {
System.out.println("Thread2 holds lock2 and lock1");
}
}
}
}

public static void main(String[] args) {


new Thread1().start();
new Thread2().start();
}
}

29. JDBC Program for Employee Details


java
import java.sql.*;

public class EmployeeDetails {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/company";
String user = "root";
String password = "password";

try (Connection con = DriverManager.getConnection(url, user, password);


Statement stmt = con.createStatement()) {

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.*;

public class RegexDemo {


public static void main(String[] args) {
Pattern pattern = Pattern.compile("Java", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Learn java programming");
boolean matchFound = matcher.find();
System.out.println("Match found: " + matchFound);
}
}
Nested Classes (as explained in Q8):

Static nested class

Inner class (non-static nested class)

Local inner class

Anonymous inner class

Example combining both:

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");
}
}
}

public static void main(String[] args) {


Outer.Nested nested = new Outer.Nested();
nested.validateEmail("[email protected]");
}
}
###Java GUI
import java.awt.*;
import java.awt.event.*;
public class FormAWT extends Frame {
FormAWT() {
// Set layout
setLayout(null);
// Labels
Label nameLabel = new Label("Name:");
nameLabel.setBounds(50, 50, 100, 20);
add(nameLabel);
TextField nameField = new TextField();
nameField.setBounds(160, 50, 150, 20);
add(nameField);
Label mobileLabel = new Label("Mobile:");
mobileLabel.setBounds(50, 90, 100, 20);
add(mobileLabel);
TextField mobileField = new TextField();
mobileField.setBounds(160, 90, 150, 20);
add(mobileField);
// Gender -- Label genderLabel = new Label("Gender:");
genderLabel.setBounds(50, 130, 100, 20);
add(genderLabel);
CheckboxGroup genderGroup = new CheckboxGroup();
Checkbox male = new Checkbox("Male", genderGroup, false);
male.setBounds(160, 130, 60, 20);
add(male);
Checkbox female = new Checkbox("Female", genderGroup, false);
female.setBounds(230, 130, 70, 20);
add(female);
// Hobbies-- Label hobbyLabel = new Label("Hobbies:");
hobbyLabel.setBounds(50, 170, 100, 20);
add(hobbyLabel);
Checkbox music = new Checkbox("Music");
music.setBounds(160, 170, 100, 20);
add(music);
Checkbox dance = new Checkbox("Dance");
dance.setBounds(160, 200, 100, 20);
add(dance);
Checkbox travel = new Checkbox("Travelling");
travel.setBounds(160, 230, 100, 20);
add(travel);
// Submit Button
Button submit = new Button("Submit");
submit.setBounds(120, 270, 80, 30);
add(submit);
// Frame settings
setTitle("AWT Form");
setSize(400, 350);
setVisible(true);
// Close the window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose(); }});}
public static void main(String[] args) {
new FormAWT();}}

JDBC Driver Types Demonstration (Type 4 -


Thin Driver)

Here's a complete Java program demonstrating the most commonly used


Type 4 JDBC driver (MySQL in this example):
java

Copy

Download

import java.sql.*;

public class JdbcType4Demo {


public static void main(String[] args) {
// JDBC URL for MySQL (Type 4 driver)
String jdbcUrl = "jdbc:mysql://localhost:3306/company";
String username = "root";
String password = "password"; // Replace with your actual password
Connection connection = null;

try {
// 1. Register the driver (not required since JDBC 4.0 - automatic loading)
// Class.forName("com.mysql.cj.jdbc.Driver");

// 2. Establish connection using Type 4 driver


System.out.println("Connecting to database using Type 4 JDBC driver...");
connection = DriverManager.getConnection(jdbcUrl, username, password);

// 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");

System.out.println(id + "\t" + name + "\t\t" + dept);


}

} 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();
}
}
}
}

Key Points About This Type 4 Driver Demonstration:

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

Connection closed successfully


5. Comparison with Other Driver Types:
o Unlike Type 1 (JDBC-ODBC bridge), no ODBC configuration
needed
o Unlike Type 2 (Native API), no platform-specific native code
o Unlike Type 3 (Network Protocol), no middleware server required

You might also like