AJP Unit 1
AJP Unit 1
JAVA
       Java is an object-oriented, class-based, concurrent, secured, versatile, object-oriented and
general purpose computer-programming language. It is a widely used robust technology. Java is a
developed by Sun Microsystems in 1995 and later acquired by Oracle Corporation. It follows
the "Write Once, Run Anywhere" principle, meaning Java applications can run on any platform
with a Java Virtual Machine (JVM). It supports multithreading, exception handling, and
garbage collection, making it efficient and scalable. Java is widely used for desktop applications
(Java SE), enterprise-level solutions (Java EE), and embedded systems (Java ME). Key
features include strong security, automatic memory management, and a vast ecosystem of
frameworks like Spring and Hibernate. Java remains essential for web, mobile, and cloud
computing.
Java Example
Simple.java
class Simple{
System.out.println("Hello Java");
                                                                                                  1
1. Java Standard Edition (JSE)
The Java Standard Edition (JSE) is the foundation of Java programming. It provides core
functionalities required for developing general-purpose applications. This edition includes:
   •   Java Virtual Machine (JVM) – the engine that runs Java applications.
   •   Core APIs such as collections, networking, concurrency, I/O operations, and database
       connectivity.
   •   Graphical User Interface (GUI) development using frameworks like Swing and JavaFX.
   •   Multithreading and Exception Handling for efficient and robust applications.
   •   Java Development Kit (JDK), which includes tools like the compiler (javac), debugger,
       and Java Runtime Environment (JRE).
JSE is widely used for standalone applications running on desktops or embedded devices.
The Java Enterprise Edition (JEE) is tailored for large-scale, distributed applications that
demand high performance and security. It expands upon JSE by adding:
JEE is extensively used for banking systems, e-commerce platforms, and corporate
applications requiring database interactions and complex business logic.
The Java Micro Edition (JME) is designed for resource-constrained devices such as mobile
phones, embedded systems, and Internet-of-Things (IoT) devices. It consists of:
                                                                                               2
   •   A small footprint JVM optimized for lightweight devices.
   •   Mobile-specific APIs for Bluetooth communication, telephony, and networking.
   •   Limited GUI libraries suited for small screens.
   •   Optimized memory management to work on hardware with restricted processing power.
JME was historically popular for mobile app development before smartphones became dominant.
Today, it's commonly found in IoT applications, smart cards, and embedded systems.
JAVA APPLICATIONS
       Java is an incredibly versatile programming language, and it's used to develop a wide
variety of applications. The main types of Java applications are :
 1. Standalone Applications
       Also known as       Desktop Applications     or   Window-based Applications , these are
traditional software programs that run locally on a computer. Examples include media players,
antivirus software, and word processors. They often use GUI frameworks like Swing , AWT , or
more recently, JavaFX to provide interactive user interfaces.
2. Web Applications
       Java is widely used for server-side development of web applications. These applications
run on web servers and provide dynamic content to users through web browsers. Servlets and
JSP (JavaServer Pages) are the primary technologies used in Java web development. Frameworks
like Spring MVC , Struts , and JSF (JavaServer Faces) are commonly employed to streamline
the development process.
Example: LinkedIn
                                                                                             3
LinkedIn’s backend system is heavily reliant on Java. It uses Java-based frameworks to manage
user profiles, job postings, and the extensive network of connections.
3. Enterprise Applications
       These are large-scale, distributed, and mission-critical applications designed for businesses
and organizations. They require a robust, secure, and scalable infrastructure. Java Enterprise
Edition (now known as Jakarta EE ) is the platform used for developing these applications.
Enterprise JavaBeans (EJB) , JMS (Java Message Service) , and JPA (Java Persistence API) are
some of the key components used in enterprise applications.
4. Mobile Applications
       Java is the official language for Android development. Mobile applications for Android
devices are primarily developed using Java and the Android SDK . These applications range
from simple tools and games to complex applications that integrate with various services and
hardware on the mobile device.
 5. Embedded Systems
       Java is used in the development of software for embedded systems, which are specialized
computing systems embedded within electronic devices. Examples include appliances,
telecommunications networks, and automotive control systems. The lightweight nature of Java,
along with its portability and security features, makes it ideal for this domain.
                                                                                                  4
 6. Distributed Applications
       Distributed applications are designed to operate on multiple computers within a network,
working as a single system. Java supports the development of these applications through
technologies like RMI (Remote Method Invocation) and CORBA (Common Object Request
Broker Architecture) . More modern approaches use frameworks like Apache Hadoop and Spark
for handling distributed processing.
 8. Cloud-Based Applications
       Java is also popular in developing cloud-based applications, leveraging platforms like
Google Cloud Platform (GCP), Amazon Web Services (AWS), and Microsoft Azure. These
platforms often provide Java SDKs, APIs, and tools to facilitate the development and deployment
of cloud-native applications.
1. Simple
       Java is designed to be easy to learn and use. Its syntax is clean and straightforward, making
it accessible for beginners. Java eliminates many complex features found in other languages, such
as explicit pointers and operator overloading .
                                                                                                   5
2. Object-Oriented
        Java is an object-oriented programming (OOP) language, which means it organizes
software design around data, or objects, rather than functions and logic. The core concepts of OOP
in Java include classes, objects, inheritance, polymorphism, abstraction, and encapsulation.
3. Platform Independent
        One of Java's most significant features is its platform independence. Java code is compiled
into bytecode, which can run on any device equipped with a Java Virtual Machine (JVM). This
"write once, run anywhere" capability makes Java highly portable.
4. Secure
        Java provides a secure environment for developing applications. It has built-in security
features such as the absence of explicit pointers, a classloader that separates local file system
classes from those imported from network sources, and a bytecode verifier that checks for illegal
code.
5. Robust
        Java is known for its robustness, which means it is reliable and can handle errors
effectively. It has strong memory management, automatic garbage collection, and exception
handling mechanisms that help in creating stable applications.
6. Architecture-Neutral
        Java is architecture-neutral, meaning it does not depend on the underlying hardware
architecture. The size of primitive data types is fixed, ensuring consistency across different
platforms.
7. Portable
        Java's portability stems from its platform independence. Java bytecode can be carried to
any platform without requiring any modifications, making it easy to distribute applications.
                                                                                                  6
8. High Performance
       While Java is an interpreted language, it offers high performance through the use of Just-
In-Time (JIT) compilers that convert bytecode into native machine code at runtime. This makes
Java faster than many other interpreted languages.
9. Distributed
       Java supports distributed computing, allowing developers to create applications that can
run on multiple computers connected over a network. Java's Remote Method Invocation (RMI)
and Enterprise JavaBeans (EJB) facilitate the development of distributed applications.
10. Multithreaded
       Java supports multithreading, enabling the concurrent execution of two or more threads.
This feature is particularly useful for developing interactive and real-time applications.
11. Dynamic
       Java is a dynamic language that supports the dynamic loading of classes and methods at
runtime. It also supports dynamic compilation and automatic memory management, making it
adaptable to changing environments.
Java consists of several key components that form the foundation of its ecosystem.
                                                                                                7
3. Java Virtual Machine (JVM)
   •   Converts Java bytecode into machine code specific to the operating system.
   •   Ensures platform independence (Write Once, Run Anywhere).
   •   Manages memory through Garbage Collection.
                                                                                    8
JVM Architecture
Class loader: The class loader is a component of the JVM. It is employed in the loading of class
files. When we launch a Java program, the class loader loads it first.
Method Area: It’s where you’ll keep all of your class information. Static variables, static
blocks, static methods, and instance methods are all stored in this section.
Heap: When the JVM boots up, it creates a heap. During the application’s runtime, it may grow
or shrink in size.
Stack: A thread stack is the same as a JVM stack. It is a data region established in the JVM
memory for a single execution thread. A thread’s JVM stack is used to hold numerous items like
local variables, partial results, and data for calling methods and returning data.
Native Stack: All native methods used in your program are included in this category.
                                                                                                 9
JIT Compiler: The runtime environment includes the Just-In-Time (JIT) compiler. To increase
the efficiency of Java applications, this compiler produces bytecodes at runtime. The JIT
compiler is enabled by default. When a compiled method is compiled, the JVM refers to it as a
method. The JIT compiler translates bytecode to machine code and compiles it for execution
“just-in-time.”
Garbage Collector: The garbage collector, which is a Java program, is used to manage the
memory. Mark and Sweep are the two steps of the system. The garbage collector uses Mark to
distinguish between used and unused memory chunks. The Sweep clears the Mark of the
specified object.
Native Interface: The Java Native Interface acts as a bridge between Java method calls and
native library calls.
Native Libraries: Java Native Libraries are libraries that include code or programs written in
languages other than Java, such as C, C++, and others. With the help of Java Native
Interface(JNI), they can be integrated into the Java application as needed.
EVENT HANDLING
Event
      Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character through
keyboard,selecting an item from list, scrolling the page are the activities that causes an event to
happen.
Types of Events
                                                                                                 10
   1. Foreground Events - Those events which require the direct interaction of user.They are
       generated as consequences of a person interacting with the graphical components in
       Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
       character through keyboard,selecting an item from list, scrolling the page etc.
   2. Background Events - Those events that require the interaction of end user are known as
       background events. Operating system interrupts, hardware or software failure, timer
       expires, an operation completion are the example of background events.
Event Handling
       Event Handling is the mechanism that controls the event and decides what should happen
if an event occurs. This mechanism has the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.Let's have a brief introduction
to this model.
The Delegation Event Model has the following key participants namely:
   1. Source - The source is an object on which event occurs. Source is responsible for providing
       information of the occurred event to it's handler. Java provide as with classes for source
       object.
   2. Listener - It is also known as event handler.Listener is responsible for generating response
       to an event. From java implementation point of view the listener is also an object. Listener
       waits until it receives an event. Once the event is received , the listener process the event
       an then returns.
                                                                                      12
Components in Event Handling
The following are the three main components of event handling in Java:
• Events
• Event Sources
• Event Listeners/Handlers
Events
       The events are defined as an object that describes a change in the state of a source object.
Java   defines   a   number    of    such   Event    Classes   inside   java.awt.event    package.
Some of the events are as follows:
                                                                                                13
14
Event Sources
         A source is an object that generates an event. An event generation occurs when an internal
state of that object changes in some way. A source must register listeners in order for the listeners
to       receive       notifications      about      a       specific      type       of      event.
Some of the event sources are as follows:
Event Listeners
         A listener is an object that is notified when an event occurs. A Listener has two major
requirements: it should be registered to one or more source objects to receive event notifications,
and it must implement methods to receive and process those notifications. Java has defined a set
of interfaces for receiving and processing the events under the java.awt.event package.
                                                                                                  15
16
Example
import java.awt.*;
import java.awt.event.*;
TextField tf;
AEvent()
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
add(b);
add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
                                                                                              17
            tf.setText("Welcome");
new AEvent();
Output:
                                              18
THREADING CONCEPTS
Thread
2. Override the run method with the code to be executed by the thread.
3. Create an instance of the class and call the start method to initiate the thread.
Example
class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " - " +
i);
            try {
                Thread.sleep(1000); // Sleep for 1 second
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
                                                                                             19
public class ThreadExample {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
          t1.start();
           t2.start();
     }
}
In this example, MyThread extends Thread and overrides the run method to print numbers from 0
to 4. The start method initiates the threads, allowing them to run concurrently.
         Implementing the Runnable interface is more flexible and preferred in many cases as it
allows the class to extend another class if needed:
2. Implement the run method with the code to be executed by the thread.
3. Create an instance of Thread passing the Runnable object and call the start method.
Example
class MyRunnable implements Runnable {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " - " +
i);
            try {
                Thread.sleep(1000); // Sleep for 1 second
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
          t1.start();
           t2.start();
                                                                                             20
        }
}
Here, MyRunnable implements Runnable, and the run method is executed by two concurrent
threads.
Thread Lifecycle
A thread in Java goes through various states in its lifecycle:
    •       New: A thread is in this state after being created but before the start method is invoked.
    •       Runnable: The thread is ready to run and waiting for CPU time.
    •       Blocked: The thread is waiting for a monitor lock to enter a synchronized block/method.
    •       Waiting: The thread is waiting indefinitely for another thread to perform a particular
            action.
Controlling Threads
Java provides several methods to manage thread execution:
    •       start(): Begins the thread's execution.
• yield(): Hints to the thread scheduler that the current thread is willing to yield its
                                                                                                         21
JAVA NETWORKING
       Java Networking is a concept of connecting two or more computing devices together so
that we can share resources. Java socket programming provides facility to share data between
different computing devices.
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
6. Socket
1) IP Address
       IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to 255. It is a logical address that can be changed.
2) Protocol
       A protocol is a set of rules basically that is followed for communication. For example: o
TCP o FTP o Telnet o SMTP o POP etc.
3) Port Number
       The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications. The port number is associated with the IP address
for communication between two applications.
                                                                                             22
4) MAC Address
       MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address. For
example, an Ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
6) Socket
       Socket programming in Java allows different programs to communicate with each other
over a network, whether they are running on the same machine or different ones. A socket is an
endpoint between two way communications. Client connects, sends messages to the server and the
server shows them using a socket connection.
Java.net package
       The java.net package supports two protocols,
                                                                                               23
Java Networking classes
       The java.net package of the Java programming language includes various classes that
provide an easy-to-use means to access network resources. The classes covered in the java.net
package                are                   given                as              follows                 –
   1. CacheRequest – The CacheRequest class is used in java whenever there is a need to store
       resources in ResponseCache. The objects of this class provide an edge for the
       OutputStream          object     to      store       resource       data   into      the      cache.
   5. InetAddress – The InetAddress class is used to provide methods to get the IP address of
       any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number.
       InetAddress           can      handle         both      IPv4         and     IPv6          addresses.
                                                                                                         24
6. Server Socket – The ServerSocket class is used for implementing system-independent
   implementation of the server-side of a client/server Socket Connection. The constructor for
   ServerSocket class throws an exception if it can’t listen on the specified port. For example
   –    it     will        throw   an        exception       if        the    port      is       already      being     used.
7. Socket – The Socket class is used to create socket objects that help the users in
   implementing all fundamental socket operations. The users can implement various
   networking actions such as sending, reading data, and closing connections. Each Socket
   object built using java.net.Socket class has been connected exactly with 1 remote host; for
   connecting         to     another    host,      a     user          must    create        a        new   socket    object.
9. Proxy – A proxy is a changeless object and a kind of tool or method or program or system,
   which serves to preserve the data of its users and computers. It behaves like a wall between
   computers and internet users. A Proxy Object represents the Proxy settings to be applied
   with                                                  a                                                        connection.
10. URL – The URL class in Java is the entry point to any available sources on the internet. A
   Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the
   World Wide Web. A source can denote a simple file or directory, or it can indicate a more
   difficult     object,      such      as     a   query          to     a    database           or    a    search    engine.
                                                                                                                           25
   11. URLConnection – The URLConnection class in Java is an abstract class describing a
       connection of a resource as defined by a similar URL. The URLConnection class is used
       for assisting two distinct yet interrelated purposes. Firstly it provides control on interaction
       with a server(especially an HTTP server) than a URL class. Furthermore, with a
       URLConnection, a user can verify the header transferred by the server and can react
       consequently. A user can also configure header fields used in client requests using
       URLConnection.
1. Java.net Package
   •   Contains classes to implement network protocols such as TCP/IP, UDP, Sockets, and
       URLs.
   •   Enables developers to establish connections and communicate with other computers over
       a network.
2. Socket Programming
   •   The java.net.Socket class provides a low-level interface for networking.
   •   Used to create client-server applications using TCP/IP or UDP protocols.
   •   Allows sending and receiving data over a network.
3. URL Handling
   •   The java.net.URL class provides methods to handle URLs.
   •   Developers can read and write data from a specified URL, such as reading a webpage or
       downloading a file from the internet.
4. InetAddress Class
   •   The java.net.InetAddress class represents Internet Protocol (IP) addresses.
   •   Provides methods to:
           o Get the IP address of a host.
                                                                                                    26
          o Resolve hostnames.
          o Perform IP address manipulation.
5. Network Interfaces
   •   The java.net.NetworkInterface class retrieves information about network interfaces on the
       system.
   •   Developers can determine:
          o Available network interfaces.
          o Their IP addresses and other details.
6. ServerSocket Class
   •   The java.net.ServerSocket class helps developers create server applications that listen for
       incoming connections on a specific port.
   •   Used for server-side socket programming.
8. MulticastSocket Class
   •   The java.net.MulticastSocket class enables multicast networking in Java.
   •   Supports sending and receiving IP multicast packets, facilitating communication
       between multiple hosts on a network.
                                                                                               27
1. Image Manipulation
Java offers various libraries and classes for loading, manipulating, and saving images:
2. Audio Playback
Java provides multiple ways to play and manipulate audio files:
   •   Java Sound API: Enables playback of various audio formats using classes like Clip and
       AudioInputStream.
   •   JavaFX Media Classes: Offers advanced features such as playback controls and volume
       management.
3. Video Playback
JavaFX includes built-in media capabilities for video playback:
   •   javafx.scene.media:
           o MediaPlayer: Handles video playback.
           o MediaView: Displays video content with additional control features.
   •   Allows event handling and the application of visual effects.
4. Animation
Java supports smooth animations through different frameworks:
                                                                                          28
5. 3D Graphics
For handling three-dimensional graphics:
   •   JavaFX WebView:
          o Allows integration of media elements such as images, audio, and video from web
              sources.
29