0% found this document useful (0 votes)
2 views25 pages

Java (Up Police Programmer Topic-5)

Uploaded by

archer6480
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)
2 views25 pages

Java (Up Police Programmer Topic-5)

Uploaded by

archer6480
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

Topic-5

JAVA
Java is a high-level, object-oriented programming language developed by Sun
Microsystems (now owned by Oracle Corporation). It is widely used for building cross-
platform applications, meaning code written in Java can run on any device that has a Java
Virtual Machine (JVM).

Key Features of Java:

 Platform Independent: "Write Once, Run Anywhere" – Java programs run on the
JVM, so the same code can run on Windows, Linux, macOS, etc.
 Object-Oriented: Encourages modular programming using classes and objects.
 Robust and Secure: Features like strong memory management, exception handling,
and a security manager make Java reliable and secure.
 Multithreaded: Supports concurrent programming, allowing multiple tasks to run
simultaneously.
 Automatic Garbage Collection: Java automatically handles memory cleanup,
helping prevent memory leaks.

Common Use Cases:

 Web applications (e.g., with Spring framework)


 Android app development
 Enterprise software (banking systems, ERPs)
 Desktop applications
 Embedded systems

A Java Applet is a small Java program that was traditionally embedded in web pages and run in a
web browser using the Java Plugin. Applets were primarily used to create interactive features like
games, animations, or calculators on websites.

Important Note:

Java Applets are obsolete and no longer supported in modern browsers (like Chrome, Firefox, Edge)
due to security risks and the removal of the Java Plugin.

Characteristics of Java Applets:

 They extend the [Link] class (or [Link] for GUI-


based ones).
 They run inside a browser or AppletViewer (a tool provided by the JDK).
 They do not have a main method; instead, they use lifecycle methods.
Applet Lifecycle Methods:

public void init() // Initializes the applet


public void start() // Starts the applet
public void stop() // Pauses the applet
public void destroy() // Destroys the applet

Example Java Applet Code:

import [Link];
import [Link];

public class HelloWorldApplet extends Applet {


public void paint(Graphics g) {
[Link]("Hello, World!", 20, 20);
}
}

Embedding in HTML:

<html>
<body>
<applet code="[Link]" width="300"
height="100"></applet>
</body>
</html>

Why Applets Are Deprecated:

 Security vulnerabilities
 Browser plugin support removed
 Modern alternatives (JavaScript, WebAssembly, HTML5, etc.)

Graphics
Graphics in Java refers to the use of the [Link] and [Link] libraries to draw shapes,
text, and images on GUI components like windows, panels, or applets.

Common Classes for Graphics:

 [Link]: The base class used for drawing.


 [Link]: A panel where you can overridethe paintComponent()
method to draw graphics.
 [Link], [Link]: Used for customizing colors and text styles.
Example: Drawing Shapes in a Java Window:-

import [Link].*;

import [Link].*;

public class MyGraphicsExample extends JPanel {

@Override

protected void paintComponent(Graphics g) {

[Link](g);

// Set color

[Link]([Link]);

[Link](20, 20, 100, 50); // Filled rectangle

[Link]([Link]);

[Link](150, 20, 100, 50); // Oval outline

[Link]([Link]);

[Link]("Hello, Graphics!", 20, 100); // Text

public static void main(String[] args) {

JFrame frame = new JFrame("Java Graphics Example");

MyGraphicsExample panel = new MyGraphicsExample();

[Link](panel);
[Link](300, 200);

[Link](JFrame.EXIT_ON_CLOSE);

[Link](true);

Graphical User Interface (GUI)


A Graphical User Interface (GUI) in Java allows users to interact with a program through
windows, buttons, text fields, menus, etc., instead of a command-line interface. Java
provides GUI libraries primarily through Swing and JavaFX.

Two Main Java GUI Toolkits:

1. Swing (older but widely used)

 Part of [Link] package.


 Lightweight and platform-independent.
 Common components: JFrame, JPanel, JButton, JTextField, etc.

2. JavaFX (modern, richer GUI)

 Part of javafx.* packages.


 Supports 2D/3D graphics, media playback, CSS styling.
 Requires separate setup in newer Java versions.

Example GUI with Swing:

import [Link].*;

import [Link].*;

public class SimpleSwingGUI {

public static void main(String[] args) {

JFrame frame = new JFrame("My First GUI");

JButton button = new JButton("Click Me");


JTextField textField = new JTextField("Hello, Java GUI!");

// Set layout and add components

[Link](null);

[Link](100, 100, 120, 30);

[Link](100, 50, 200, 30);

[Link](button);

[Link](textField);

// Add click event

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link]("Button Clicked!");

});

// Frame setup

[Link](400, 300);

[Link](JFrame.EXIT_ON_CLOSE);

[Link](true);

}
Key Swing Components:
Component Description

JFrame Main window

JPanel Container to hold components

JButton Clickable button

JTextField Text input field

JLabel Displays text/image

Exception handling in Java


Exception handling in Java is a powerful mechanism that allows you to manage runtime
errors, ensuring the program doesn't crash unexpectedly and can respond gracefully.

What is an Exception?

An exception is an event that occurs during the execution of a program that disrupts the normal
flow of instructions.

Two Types of Exceptions:

1. Checked Exceptions – Must be handled or declared in the method (e.g., IOException,


SQLException)
2. Unchecked Exceptions – Occur at runtime and are not checked at compile time (e.g.,
NullPointerException, ArithmeticException)

Basic Syntax:

try {

// Code that may throw an exception

} catch (ExceptionType1 e1) {

// Handle exception of type1

} catch (ExceptionType2 e2) {

// Handle exception of type2

} finally {

// Optional: always runs (cleanup code)


}

Example:
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Will throw ArithmeticException
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero!");
} finally {
[Link]("This always runs, even if there's an
exception.");
}
}
}

Output:

Error: Cannot divide by zero!


This always runs, even if there's an exception.

Common Exception Classes:


Exception Type Description

ArithmeticException Unchecked Error in arithmetic (e.g., divide by 0)

NullPointerException Unchecked Accessing object with null reference

IOException Checked Input/output failures

FileNotFoundException Checked File does not exist

ArrayIndexOutOfBoundsException Unchecked Accessing invalid array index

Custom Exception:

You can create your own exception by extending the Exception class:

class MyException extends Exception {


public MyException(String message) {
super(message);
}
}
Threads in Java – Basics
A thread in Java is a lightweight subprocess – the smallest unit of CPU
execution. Java allows you to run multiple threads concurrently, enabling
multithreading, which is useful for tasks like animations, parallel
computations, background tasks, etc.

Why Use Threads?

 Perform multiple tasks simultaneously


 Improve performance on multi-core systems
 Keep the UI responsive (e.g., in desktop apps)

Creating Threads in Java

1. Extending Thread class


class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
}

public static void main(String[] args) {


MyThread t = new MyThread();
[Link](); // Don't use run() directly
}
}

2. Implementing Runnable interface


class MyRunnable implements Runnable {
public void run() {
[Link]("Thread is running...");
}

public static void main(String[] args) {


Thread t = new Thread(new MyRunnable());
[Link]();
}
}

Thread Lifecycle

1. New – Thread is created.


2. Runnable – Thread is ready to run.
3. Running – Thread is executing.
4. Blocked/Waiting – Thread is paused.
5. Terminated – Thread has finished execution.
Common Methods in Thread class
Method Description

start() Starts the thread

run() Code that runs in the thread

sleep(ms) Pauses thread for a given time

join() Waits for a thread to finish

setPriority(int) Sets thread priority

isAlive() Checks if thread is still running

Note:

 Always use .start() to run a thread, not .run() directly.


 Java threads are preemptively scheduled, meaning the JVM decides which thread runs and
when.

Java Coding Conventions


Java coding conventions are standard guidelines used by Java developers to write clean, consistent, and
readable code. Following these conventions helps maintain uniformity across projects and teams.

1. Class Naming

 Use PascalCase.
 Class names should be nouns.

public class EmployeeRecord {


// ...
}

2. Method Naming

 Use camelCase.
 Method names should be verbs or verb phrases.

public void calculateSalary() {


// ...
}

3. Variable Naming

 Use camelCase.
 Be descriptive but concise.

int employeeCount;
String firstName;

4. Constant Naming

 Use ALL_UPPER_CASE with words separated by underscores.

public static final int MAX_USERS = 100;

5. Package Naming

 Use all lowercase.


 Typically starts with a reverse domain name.

package [Link];

6. Indentation & Spacing

 Use 4 spaces per indentation level.


 Add space after keywords and commas, and around operators.

if (isValid) {
total = amount + tax;
}

7. Braces {} Usage

 Always use braces for blocks, even if it's a single line.

// Good
if (x > 0) {
doSomething();
}

// Bad
if (x > 0)
doSomething();
8. Comments

 Use Javadoc comments (/** ... */) for classes and public methods.
 Use // for short, inline comments.

/**
* Calculates the area of a circle.
* @param radius Radius of the circle
* @return Area as double
*/
public double calculateArea(double radius) {
return [Link] * radius * radius;
}

9. Access Modifiers Order

 Order: public → protected → private

public class User {


private String name;
protected int age;
public void display() {
// ...
}
}

10. File Structure Order

1. Package and import statements


2. Class-level Javadoc comment
3. Class declaration
4. Constants
5. Fields
6. Constructors
7. Methods (public first, then private)

Java API (Application Programming Interface)


The Java API is a large collection of prewritten classes and interfaces that come with the
Java Development Kit (JDK). It provides a rich set of built-in tools that simplify common
programming tasks, such as file handling, networking, data structures, and user interface
development.

What is Java API?

 A library of classes and methods organized into packages.


 Helps avoid "reinventing the wheel" – you reuse tested, efficient code.
 Example: Instead of writing your own list class, use [Link].
Common Java API Packages:
Package Purpose

[Link] Core language classes (String, Math, etc.)

[Link] Data structures, collections, utilities

[Link] Input/output (files, streams)

[Link] Networking (sockets, URLs)

[Link] Database connectivity using JDBC

[Link] Date and time API

[Link] GUI components (buttons, frames, etc.)

[Link] Non-blocking I/O, buffers, channels

Example Using Java API

Reading a file using [Link]:


import [Link];
import [Link];
import [Link];

public class ReadFileExample {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}
}
}

Java API Documentation

 Official documentation: [Link]


 Use it to:
o Explore class definitions and methods
o Learn about parameters, return types, and exceptions
Tools to Work with Java API

 IDE IntelliSense: Most IDEs (e.g., IntelliJ, Eclipse) auto-suggest API usage.
 Javadoc Tool: Generate HTML documentation for your own classes.

Garbage Collection in Java


Garbage Collection (GC) in Java is the process of automatically identifying and reclaiming memory
occupied by objects that are no longer in use, to avoid memory leaks and improve application
performance.

Why Garbage Collection?

 Java manages memory automatically.


 Eliminates the need for manual memory deallocation (like free() in C/C++).
 Prevents memory leaks and out-of-memory errors by clearing unused objects.

How It Works

1. The JVM keeps track of all objects in memory.


2. When it detects an object is no longer reachable (no references pointing to it), it marks it for
removal.
3. The Garbage Collector reclaims that memory space.

Example:
public class GarbageDemo {
public static void main(String[] args) {
GarbageDemo obj1 = new GarbageDemo();
GarbageDemo obj2 = new GarbageDemo();

obj1 = null; // obj1 is now eligible for GC


obj2 = null; // obj2 is also eligible for GC

// Requesting JVM to run Garbage Collector


[Link]();
}

@Override
protected void finalize() {
[Link]("Garbage collected object");
}
}

Key Methods & Concepts:


Concept Description

[Link]() Suggests JVM to start garbage collection (not guaranteed)

finalize() method Called before object is garbage collected (deprecated in Java 9+)
Concept Description

Reference Types Strong, Weak, Soft, Phantom (for advanced GC control)

GC Algorithms (Used by JVM)

 Serial GC – Single-threaded, good for small applications.


 Parallel GC – Multi-threaded, faster throughput.
 G1 (Garbage First) – Low pause time, default in newer Java versions.
 ZGC & Shenandoah – Low-latency collectors for large-scale apps.

Tips

 Avoid creating unnecessary objects.


 Set objects to null when no longer needed (if you're done using them early).
 Use profiling tools (like VisualVM, JConsole) to monitor GC behavior.

I/O Streams in Java


I/O Streams in Java are used to perform input and output operations (such as reading from a file,
keyboard input, writing to files, etc.). Java uses streams to abstract these operations in a uniform
way.

What is a Stream?

A stream is a sequence of data. Java has:

 Input streams – for reading data (e.g., from a file, keyboard).


 Output streams – for writing data (e.g., to a file, console).

Java I/O Stream Classes

Java provides two main types of streams:

Type Purpose Examples

Byte Streams Handles binary data (1 byte at a time) InputStream, OutputStream

Character Streams Handles text data (2 bytes at a time) Reader, Writer


Common I/O Classes
Class Description

FileInputStream Reads bytes from a file

FileOutputStream Writes bytes to a file

FileReader Reads characters from a file

FileWriter Writes characters to a file

BufferedReader Efficiently reads text from character input

BufferedWriter Efficiently writes text to output

Scanner Reads input from console/file

PrintWriter Writes formatted text to output

Example: Reading a Text File


import [Link];
import [Link];
import [Link];

public class ReadFile {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}
}
}

Example: Writing to a Text File


import [Link];
import [Link];
import [Link];

public class WriteFile {


public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new
FileWriter("[Link]"))) {
[Link]("Hello, Java I/O!");
} catch (IOException e) {
[Link]();
}
}
}
Tips

 Always close streams (try-with-resources is preferred).


 Use buffered streams for better performance.
 Use character streams for text and byte streams for binary files (images, audio, etc.).

Java Database Connectivity (JDBC)


Java Database Connectivity (JDBC) is an API in Java that allows you to connect to and interact with
databases (like MySQL, PostgreSQL, Oracle, etc.). It provides methods to query, update, and manage
databases from Java programs.

Steps in JDBC

1. Import JDBC package


2. Load JDBC Driver
3. Establish Connection
4. Create Statement
5. Execute SQL Query
6. Process Result
7. Close Connection

Example: Connect to MySQL Database


import [Link];
import [Link];
import [Link];
import [Link];

public class JDBCExample {


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

try {
// 1. Load the driver (optional for modern JDBC)
[Link]("[Link]");

// 2. Establish connection
Connection conn = [Link](url, user,
password);

// 3. Create statement
Statement stmt = [Link]();

// 4. Execute query
ResultSet rs = [Link]("SELECT * FROM users");

// 5. Process result
while ([Link]()) {
[Link]([Link]("id") + ": " +
[Link]("name"));
}
// 6. Close everything
[Link]();
[Link]();
[Link]();

} catch (Exception e) {
[Link]();
}
}
}

Required Dependency for MySQL

If you're using Maven, add this to [Link]:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>

Common JDBC Interfaces


Interface Description

Connection Connects to the database

Statement Executes static SQL queries

PreparedStatement Executes parameterized SQL queries

ResultSet Holds data retrieved from database

DriverManager Manages JDBC drivers

Security Tip

Use PreparedStatement instead of Statement to prevent SQL injection:

PreparedStatement ps = [Link]("SELECT * FROM users WHERE id


= ?");
[Link](1, 10);
ResultSet rs = [Link]();

AWT in Java (Abstract Window Toolkit)


AWT (Abstract Window Toolkit) is Java’s original GUI (Graphical User Interface) toolkit for
creating platform-independent window-based applications.
It provides classes for:

 Windows
 Buttons
 Text fields
 Menus
 Event handling
 Layout management

Package
import [Link].*;

Basic AWT Components


Component Description

Frame Main window container

Button Clickable button

Label Display text label

TextField Single-line text input

TextArea Multi-line text input

Checkbox Checkbox component

Choice Drop-down list

List Selectable list

Panel Container for components

Example: Simple AWT Application


import [Link].*;

public class AWTExample {


public static void main(String[] args) {
// Create a frame
Frame f = new Frame("AWT Example");

// Create a label and button


Label label = new Label("Enter your name:");
TextField textField = new TextField();
Button button = new Button("Submit");

// Set positions and sizes


[Link](50, 50, 150, 20);
[Link](50, 80, 200, 20);
[Link](50, 120, 80, 30);
// Add components to frame
[Link](label);
[Link](textField);
[Link](button);

// Set layout and size


[Link](300, 200);
[Link](null);
[Link](true);
}
}

AWT Event Handling

To handle user actions (like button clicks), you must implement event listeners:

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
});

Don't forget: add import [Link].*;

AWT vs Swing
Feature AWT Swing

Type Heavyweight (uses native OS UI) Lightweight (pure Java)

Look & Feel OS dependent Customizable

Components Basic Richer set (e.g., JTable)

Summary

AWT is simple and good for basic UIs but is largely replaced by Swing and JavaFX in modern Java
applications due to richer features and better control.

Swing in Java
Swing is a part of Java’s [Link] package used to create graphical user interfaces
(GUIs). It is lightweight, platform-independent, and provides rich components such as
tables, trees, sliders, tabbed panes, and more.

Swing is built on top of AWT and provides more advanced components and a pluggable
look-and-feel.
Key Features of Swing

 Lightweight (doesn’t rely on native OS GUI)


 Highly customizable
 Rich set of components
 Follows MVC architecture

Common Swing Components


Component Description

JFrame Top-level window

JButton Clickable button

JLabel Displays text/image

JTextField Single-line text input

JTextArea Multi-line text area

JCheckBox Checkbox

JRadioButton Radio button

JComboBox Drop-down list

JPanel Container for organizing components

Simple Swing Example


import [Link].*;

public class SwingExample {


public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("Swing Example");

// Create components
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField();
JButton button = new JButton("Submit");

// Set layout
[Link](null);

// Set component positions


[Link](50, 50, 150, 20);
[Link](50, 80, 200, 25);
[Link](50, 120, 100, 30);

// Add components to frame


[Link](label);
[Link](textField);
[Link](button);
// Set frame properties
[Link](300, 250);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Event Handling in Swing


[Link](e -> {
String name = [Link]();
[Link](frame, "Hello, " + name + "!");
});

JOptionPane is used to show pop-up dialogs (like alert boxes).

Swing vs AWT vs JavaFX


Feature AWT Swing JavaFX

Type Heavyweight Lightweight Lightweight

UI Complexity Basic Rich Modern and rich

Modern Support Deprecated Active (limited) Recommended by Oracle

CSS Styling ❌ ❌ ✅

Advanced Server Techniques in Java: Servlets


Servlets are Java programs that run on a web server and handle HTTP requests and responses. They
are the foundation of Java web applications, often used in combination with JSP, Spring, and
frameworks like Jakarta EE.

Servlet API Overview

Servlets belong to the [Link] and [Link] packages (now part of Jakarta
EE).

Basic Servlet Lifecycle

1. Initialization – init() method


2. Request handling – service() → doGet() / doPost()
3. Destruction – destroy() method

Example: Basic HTTP Servlet


import [Link].*;
import [Link].*;
import [Link].*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello, Servlet!</h1>");
}
}

Deployment: [Link] (Servlet Mapping)


<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

You can also use annotations (Servlet 3.0+):

@WebServlet("/hello")
public class HelloServlet extends HttpServlet { ... }

doGet() vs doPost()

 doGet() – handles URL parameters (visible in URL)


 doPost() – handles form data (secure, hidden)

Example: Handling Form Data


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String name = [Link]("username");
PrintWriter out = [Link]();
[Link]("Hello, " + name);
}

Advanced Servlet Topics


Feature Description

Session Management Using HttpSession to track user data

Cookies Store small data on client side


Feature Description

Filters Intercept requests/responses (e.g., logging, auth)

Listeners Event-based hooks for context/session lifecycle

Request Dispatcher Forward or include content from other servlets/pages

ServletContext/Config Share data between servlets or configure them

Running Servlets

To run servlets, you need a Servlet container like:

 Apache Tomcat ✅
 Jetty
 GlassFish (Jakarta EE)

Security Considerations

 Validate user input


 Avoid exposing sensitive info via GET
 Sanitize outputs to prevent XSS/Injection
 Use HTTPS for secure communication

JSP in Java (JavaServer Pages)


JSP (JavaServer Pages) is a technology used to create dynamic web content using Java and
HTML. It allows embedding Java code directly into HTML pages, making it easier to build
server-side web applications.

JSP is part of the Jakarta EE (formerly Java EE) platform and runs on Java servlet containers
like Apache Tomcat.

Key Features of JSP

 Simplifies dynamic page generation


 Easier to write than servlets for UI
 Translates into servlets at runtime
 Supports JavaBeans, custom tags, and EL (Expression Language)

Basic JSP Syntax


<%@ page language="java" contentType="text/html" %>
<html>
<head><title>JSP Example</title></head>
<body>
<h1>Hello from JSP!</h1>
<% [Link]("Current time: " + new [Link]()); %>
</body>
</html>

JSP Scripting Elements


Type Syntax Description

Directive <%@ ... %> Controls page settings

Scriptlet <% code %> Java code block

Expression <%= expression %> Outputs the value of a Java expression

Declaration <%! method/variable %> Declares variables or methods

Handling Form Data in JSP


<form method="post" action="[Link]">
Name: <input type="text" name="username">
<input type="submit">
</form>

<%-- [Link] --%>


Hello, <%= [Link]("username") %>

JSP Lifecycle

1. JSP file is translated into a servlet by the server.


2. Servlet is compiled and executed.
3. Output is sent to the browser.

Using JavaBeans in JSP


<jsp:useBean id="user" class="[Link]" />
<jsp:setProperty name="user" property="name" value="Alice" />
<jsp:getProperty name="user" property="name" />

JSTL & EL

JSTL (JSP Standard Tag Library) provides tag-based logic:

<%@ taglib uri="[Link] prefix="c" %>


<c:if test="${name == 'Alice'}">
Welcome Alice!
</c:if>

EL (Expression Language) makes accessing data easy:

Hello ${[Link]}
JSP vs Servlet
Feature Servlet JSP

Focus Business logic Presentation (HTML/UI)

Code Java HTML + embedded Java

Maintenance Harder to maintain UI Easier for UI designers

Running JSP

You can run JSP pages in Apache Tomcat, Jetty, or GlassFish by placing .jsp files in the /webapp
directory of a Java web project.

Best Practices

 Avoid scriptlets (<% %>) — use JSTL/EL instead


 Use MVC: JSP for view, Servlets for controller
 Use JSP includes for reusable layouts
 Separate business logic using Beans/Java classes

You might also like