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

Java Notes

Uploaded by

sandyaselvam
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)
6 views22 pages

Java Notes

Uploaded by

sandyaselvam
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

Java unit-1 Basics of java

Advanced Java Programming (Government Arts College Autonomous)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by sandya selvam
COMPONENTS AND EVENT HANDLING

Event handling has three main components:


 Events
 Event source
 Event Listeners
Events:
 An event is an object that describes a change in state of an object.
 Events are the basic building blocks of event handling.
 The Java defines a number of such Event Classes inside [Link] package.
 Some of the events are ActionEvent, MouseEvent, KeyEvent, FocusEvent, ItemEvent
and etc.
Classification of Events
 Foreground Events
 Background Events

Foreground events are those events that require user interaction to generate. In order to generate
these foreground events, the user interacts with components in GUI. When a user clicks on a button,
moves the cursor, and scrolls the scrollbar, an event will be fired.

Background events don't require any user interaction. These events automatically generate in the
background. For example: OS failure, OS interrupts, operation completion, etc,.

Events Source:
 An event source is an object that generates an event.
 Some of the event sources are Button, CheckBox, List, Choice, Window and etc.
Event Listeners:
 A listener is an object that listens to the event. (or) A listener is an object that is
notified when an event occurs.
 Java has defined a set of interfaces for receiving and processing the events under the
[Link] package.
 Some of the listeners are ActionListener, MouseListener, ItemListener, KeyListener,
WindowListener and etc.

Downloaded by sandya selvam


Event Handling

 Event Handling is the mechanism that controls the event and decides what should happen if
an event occurs.
 This mechanism have 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.

Delegation event model

 The delegation model is a programming design pattern that is used to handle events and
event-driven programming in graphical user interfaces.
 A source generates an event and forwards it to one or more listeners, where the listener waits
until they receive an event. Once the listener gets the event, it is processed by the listener,
and then they return it.
 The advantage of this design is that a user interface element is able to “delegate” the
processing of an event to a separate piece of code.
 It eliminates overhead.

Some popular java event classes and listener interfaces:


Event classes Listener interfaces Methods
ActionEvent ActionListener  actionPerformed()
AdjustmentEvent AdjustmentListener  adjustmentValueChanged()
ComponentEvent ComponentListener  componentResized()
 componentShown()
 componentMoved()
 componentHidden()
2

Downloaded by sandya selvam


ContainerEvent ContainerListener  componentAdded()
 componentRemoved()
FocusEvent FocusListener  focusGained()
 focusLost()
ItemEvent ItemListener  itemStateChanged()
KeyEvent KeyListener  keyTyped()
 keyPressed()
 keyReleased()
MouseEvent MouseListener  mousePressed()
 mouseClicked()
 mouseEntered()
 mouseExited()
 mouseReleased()
MouseEvent MouseMotionListener  mouseMoved()
 mouseDragged()
MouseWheelEvent MouseWheelListener  mouseWheelMoved()
WindowEvent WindowListener  windowActivated()
 windowDeactivated()
 windowOpened()
 windowClosed()
 windowClosing()
 windowIconified()
 windowDeiconified()
TextEvent TextListener  textChanged()

Example:
import [Link].*;
import [Link].*;
class AEvent extends Frame implements
ActionListener{ TextField tf;
AEvent(){

//create components tf=new


TextField();
[Link](60,50,170,20);
3

Downloaded by sandya selvam


Button b=new Button("click me");
[Link](100,120,80,30);

//register listener
[Link](this); //passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
[Link]("Welcome");
}
public static void main(String args[])
{ new AEvent();
}
}

Output:

Downloaded by sandya selvam


Threading concepts
Multithreading:
 Multithreading in Java is a process of executing multiple threads
simultaneously.
 Multiprocessing and multithreading, both are used to achieve multitasking.
 A Thread is a light-weighted process, or we can say the smallest part of the
process.
 It allows a program to operate more efficiently by running multiple tasks
simultaneously(parallel).
 It shares the same address space.
 Threads are independent. If there occurs exception in one thread, it doesn't
affect other threads.
 Java Multithreading is mostly used in games, animation, etc.

Life cycle of a thread:


 Newborn state
 Runnable state
 Running state
 Blocked state
 Dead state

Downloaded by sandya selvam


Newborn:
 Whenever a thread is created it is said to be newborn state.
 It is not yet scheduled for running.
 At this stage, we can do only one of the following:
1. Schedule it for running using start() method.
2. Kill it using stop() method.

Runnable:
 A thread, that is ready to run(Executing) is then moved to the runnable
state.
 It is waiting for the availability of the processor.
 The thread has joined the queue

Running:
 Thread is executing.
 When the thread gets the CPU, it moves from the runnable to the running
state.
 The thread runs until it gives up control on its own or taken over by other
threads.

Blocked:
 A thread is inactive(Blocked) for a span of time (not permanently).
 A blocked thread is considered ”not runnable” ,”not dead” and therefore
fully qualified to run again. It is known as blocked state or waiting state.
 This state is achieved when we invoke suspend() or sleep() or wait()
methods.

Dead:
 When a thread has finished its job, then it exists or terminates normally. It
is a natural death (normal).
 When a thread has killed in born or in running or even in runnable state, it
is called prematurn death (abnormal).
 This state is achieved when we invoke stop() method or when the thread
completes it execution.

Downloaded by sandya selvam


Thread class creation:
Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a thread.
Thread class extends Object class (Thread class) and implements Runnable
interface.
Thread priority:
Each thread has a priority. Priorities are represented by a number between 1
and 10.
 The value of MIN_PRIORITY is 1.
 The value of NORM_PRIORITY is 5. (Default priority)
 The value of MAX_PRIORITY is 10.
getpriority():
The [Link]() method returns the priority of the given
thread.
setpriority():
 The [Link]() method updates or assign the priority of
the thread to new Priority.
 The method throws IllegalArgumentException if the value new Priority
goes out of the range, which is 1 (minimum) to 10 (maximum).
Here are some of the methods in the Thread class:
Methods Description
start() Starts the thread.
run() This method is executed when the thread starts.
sleep() Pauses the thread for a specified amount of time.
interrupt() Interrupts the thread.
join() Waits for the thread to die.
isAlive() Checks if the thread is alive.
getName() Gets the name of the thread.
setName() Sets the name of the thread.
getId() Gets the ID of the thread.
getPriority() Gets the priority of the thread.
setPriority() Sets the priority of the thread.
isDaemon() Checks if the thread is a daemon thread.
setDaemon() Sets the thread to be a daemon thread.
getContextClassLoader( Gets the context class loader of the thread.
)
setContextClassLoader( Sets the context class loader of the thread.
)
7

Downloaded by sandya selvam


Example:
class T1 extends Thread
{
public void run(){
[Link]("Start With T1");
for(int i=0; i<9; i++){
[Link]("i= "+i+" ");
}
[Link]("Exit in T1");
}}
class T2 extends Thread
{
public void run(){
[Link]("Start With T2");
try{
for(int j=0; j<9; j++){
[Link](1000);
[Link]("j= "+j+" ");
}
[Link]("Exit in T2");
}
catch(Exception e){
[Link](e);
}
}}
class T3 extends Thread
{
public void run(){
[Link]("Start With T3");
for(int k=0; k<9; k++){
[Link]("k= "+k+" ");
}
[Link]("Exit in T3");
}}
class Threads{
8

Downloaded by sandya selvam


public static void main(String args[])
{ T1 obj1=new T1();
T2 obj2=new T2();
T3 obj3=new T3();
[Link](10);
/*[Link]([Link]()+1);*/
[Link]();
[Link]();
[Link]();
}}
Output:

Downloaded by sandya selvam


Networking features
Networking:
Java Networking is a concept of connecting two or more computing devices
together so that we can share resources. (or) Group of computers that are linked
together to share the information with other computers. The [Link] package
supports two protocols,
 TCP (Transmission Control Protocol)
 UDP (User Datagram Protocol)
Transmission Control Protocol:
 TCP is connection-oriented protocol (Wired) which means it requires
connection prior to the communication.
 TCP is a reliable communication.
 In TCP, the two ends of the communication link must be connected at all
times during the communication.
 TCP is a transport layer protocol.
 TCP protocol ensures that the data is received correctly, no data is missing
and in order.
 TCP is typically used over the Internet Protocol, which is referred to as
TCP/IP.
 TCP is typically used for applications that require reliable communication,
such as file transfer and email.
User Datagram Protocol:
 UDP is a connectionless protocol (Wireless) which means it does not
require any connection.
 UDP is a faster communication.
 In UDP, no connection is established before data is sent.
 UDP is a transport layer protocol.
 It is also known as the "fire-and-forget" protocol as it sends the data and
does not care whether the data is received or not.
 UDP is typically used for applications that require fast communication,
such as streaming video and online gaming.
Advantage of Java Networking:
1. Sharing resources
2. Centralize software management
10

Downloaded by sandya selvam


Java Networking Terminology:
 IP Address
 Protocol
 Port Number
 MAC Address
 Connection-oriented and connection-less protocol
 Socket
IP Address:
 An Internet Protocol (IP) address is a unique numerical identifier for every
device or network that connects to the internet.
 It is composed of octets that range from 0 to 255.
( [Link] to [Link])
 It is a logical address that can be changed.
 For example: [Link]
 The four sections of an IP address – network class, network, subnet, and
device.
Protocol:
In networking, a protocol is a set of rules for formatting and processing data.
Some of mostly used protocols are,
 SMTP (Simple Mail Transfer Protocol)
 PPP (Point-to-Point Protocol)
 FTP (File Transfer Protocol)
 SFTP (Secure File Transfer Protocol)
 HTTP (Hyper Text Transfer Protocol)
 POP (Post Office Protocol)
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.
 There are 65,535 port numbers, but not all are used every day.
MAC Address:
 MAC (Media Access Control) address is a unique identifier of NIC
(Network Interface Controller).
11

Downloaded by sandya selvam


 A network node can have multiple NIC but each with unique MAC address.
 It contains a 48 bit or 64-bit address, which is combined with the network
adapter.
 MAC address can be in hexadecimal composition.
 In simple words, a MAC address is a unique number that is used to track a
device in a network.
Connection-oriented and connection-less protocol:
 In connection-oriented protocol, acknowledgement is sent by the receiver.
So it is reliable but slow.
 The example of connection-oriented protocol is TCP.

 But, in connection-less protocol, acknowledgement is not sent by the


receiver. So it is not reliable but fast.
 The example of connection-less protocol is UDP.
Socket:
 A socket is an endpoint between two way communications.
 The socket mechanism presents a method of inter-process communication
(IPC) by setting named contact points between which the communication
occurs.
 A socket is tied to a port number so that the TCP layer can recognize the
application to which the data is intended to be sent.

The 7 layers of the OSI model in Java:


1. Physical Layer:
 This layer is responsible for the physical transmission of data over a
network medium.
 It is the lowest layer of the OSI model.
 It establishes, maintains and deactivates the physical connection.
Main Functions of the Physical Layer
1. Bit Transmission
o Transfers data as electrical, optical, or radio signals
o Does not understand data meaning—only bits
2. Transmission Media
o Defines the medium used:
 Twisted pair cable
 Coaxial cable
 Optical fiber
 Wireless (radio waves)
3. Data Rate
Downloaded by sandya selvam
o Specifies the speed of data transfer (bps, Mbps, Gbps)
4. Line Coding
o Converts digital data into signals
o Examples: NRZ, Manchester encoding
5. Synchronization
o Ensures sender and receiver are synchronized at bit level
6. Physical Topology
o Defines how devices are connected
o Examples: Bus, Star, Ring, Mesh
7. Transmission Mode
o Simplex (one-way)
o Half-duplex (two-way, not simultaneous)
o Full-duplex (two-way, simultaneous)

Downloaded by sandya selvam


2. Data Link Layer:
 This layer is responsible for the reliable transmission of data frames
between two directly connected devices.
 It provides error detection and correction, as well as flow control.
Main Functions of Data Link Layer
1. Framing
o Divides the data into frames

o Adds header and trailer to each frame

2. Physical Addressing
o Uses MAC address (Media Access Control)

o Each device has a unique MAC address

3. Error Detection
o Detects errors using CRC (Cyclic Redundancy Check)

o Requests retransmission if error occurs

4. Flow Control
o Prevents a fast sender from overwhelming a slow receiver

o Techniques: Stop-and-Wait, Sliding Window

5. Access Control
o Determines which device can access the channel

o Important in shared media networks

3. Network Layer:
 This layer is responsible for routing and forwarding data packets from the
source to the destination.
 It provides logical addressing and path selection.
 The protocols used to route the network traffic are known as Network layer
protocols.
Main Functions of Network Layer

1. Logical Addressing
o Uses IP address (IPv4 / IPv6)
o Identifies source and destination systems uniquely
2. Routing
o Determines the best path to send data
o Uses routing algorithms and routing tables
3. Packet Forwarding
o Forwards packets from one router to another
o Works between different networks
4. Packetization
Downloaded by sandya selvam
oBreaks data into packets
o Adds IP header information
5. Congestion Control
o Controls traffic to avoid network congestion
6. Fragmentation and Reassembly
o Breaks large packets into smaller fragments
o Reassembles them at the destination


4. Transport Layer:
 This layer is responsible for providing reliable end-to-end communication
between applications.
 The main responsibility of the transport layer is to transfer the data
completely.
 It receives the data from the upper layer and converts them into smaller
units known as segments.
 The two protocols used in this layer are: TCP ,UDP
Main Functions of Transport Layer
1. Process-to-Process Delivery
o Delivers data between applications on different hosts
o Uses port numbers
2. Segmentation and Reassembly
o Breaks data into segments
o Reassembles them at the destination
3. Connection Control
o Connection-oriented (TCP)
o Connectionless (UDP)
4. Flow Control
o Controls data flow using sliding window
o Prevents receiver overflow
5. Error Control
o Error detection and recovery
o Uses acknowledgements and retransmissions
6. Multiplexing and Demultiplexing
o Allows multiple applications to use the network simultaneously

13

Downloaded by sandya selvam


5. Session Layer:
 This layer is responsible for establishing, managing, and terminating
sessions between applications.
Main Functions of Session Layer
1. Session Establishment
o Starts a communication session between two applications

2. Session Maintenance
o Keeps the session active during data transfer

3. Session Termination
o Properly closes the session after communication ends

4. Dialog Control
o Controls who can transmit data and when

o Supports:

 Half-duplex

 Full-duplex

5. Synchronization
o Inserts checkpoints in data transfer

o Allows recovery from failures without restarting entire transmission

6. Presentation Layer:
 This layer is responsible for transforming data into a format that can be
understood by the receiving application.
 It acts as a data translator for a network.
 The Presentation layer is also known as the syntax layer.
Main Functions of Presentation Layer

1. Data Translation
o Converts data formats between systems
o Example: ASCII ↔ Unicode, EBCDIC ↔ ASCII
2. Encryption
o Encrypts data before transmission
o Decrypts data at the receiver side
o Ensures data security
3. Compression
o Reduces data size for faster transmission
o Decompression at receiver side
4. Syntax and Semantics
o Defines how data is structured and interpreted

Downloaded by sandya selvam


7. Application Layer:
 An application layer is not an application, but it performs the application
layer functions.
 An application layer serves as a window for users.
 This layer provides the network services to the end-users.
 It handles issues such as network transparency, resource allocation, etc.
 It includes protocols such as HTTP, FTP, and SMTP.
o File transfer, access, and management (FTAM)
o Mail services
o Directory services

14

Downloaded by sandya selvam


15

Downloaded by sandya selvam


Media techniques
 The Java Media Framework (JMF) is a Java library that provides a
comprehensive set of APIs for working with audio, video, and other time-
based media to be added to Java applications and applets.
 JMF is a powerful tool for developing multimedia applications in Java.

1. Creating media player:


 Create the URL for media file.
 Create the player for the media.
 Tell the player to prefetch.
 Add the player to the applet.
 Start the player.
 init() method.
2. Prefetching the Media
 Prefetching causes two things:
 The player goes through a process called realization.
 It then starts to download the media file so that some of it can be
cached.
 This reduces the latency time before the player can start actually playing
the media.
 start() method.
3. Adding Player to your Application
 The player itself is not an AWT component. So you don't add the player
it self, but it's visual representation.
 To get the visual component, player has a method called
getVisualComponent().
 Player has a method called getState() that returns the state of the current
player.
 ControllerListener has one method- ControllerUpdate(ControllerEvent).
4. Cleaning Up and Stopping the Player
 stop() method must be used to stop the media player and clean up.
 The player has deallocate() method. As soon as you know that you no
longer need a media, you should tell the player to deallocate it so that it
can be garbage collected.
16

Downloaded by sandya selvam


5. States of the Players

 Unrealized: At this stage, the player does not know anything about the
media except what the URL to the media is.
 Realizing: In the realizing state, the player acquired all of resources that
are non-exclusive.
 Realized: When the player enters the realized state, the
RealizeCompleteEvent is issued.
 Prefetching: To get the player to move into the prefetching state, you
can use the prefetch() method.
 Prefetched: Entering the prefetched state, a player issues the
PrefetchCompleteEvent.
 Started: When player is started, it enters the started state.
6. Adding Controls to the Players
 Each type of the player has the capability to give you a set of controls
using the ControlPanelComponent() method.
 Like the getVisualComponent() method, the
getControlPanelComponent() cannot be used until after the player has
been realized.
7. Setting the media time and Changing rate
 The setMediaTime() method takes long parameter and that number
represents the time in nanoseconds.
 The setRate() method returns to you the actual rate that has been applied.

17

Downloaded by sandya selvam


8. Features and Formate of media
 JMF supports many popular media formats such as JPEG,
MPEG QuickTime, AVI, WAV, MP3, GSM and MIDI.
 JMF supports popular media access protocols such as file, HTTP,
HTTPS, FTP, RTP, and RTSP.

18

Downloaded by sandya selvam

You might also like