Unit I
Unit I
Unit I
BASICS OF JAVA
This diagram illustrates the internal working of a Java code, or precisely, Java Architecture!
⮚ There are three main components of Java language: JVM, JRE, and JDK.
⮚ Java Virtual Machine, Java Runtime Environment and Java Development Kit
respectively.
⮚ Let me elaborate each one of them one by one:
JVM architecture
Explanation:
Class Loader:
Class loader is a subsystem of JVM. It is used to load class files. Whenever we run the java
program, class loader loads it first.
Class method area:
It is one of the Data Area in JVM, in which Class data will be stored. Static Variables, Static
Blocks, Static Methods, Instance Methods are stored in this area.
Heap:
A heap is created when the JVM starts up. It may increase or decrease in size while the
application runs.
Stack:
JVM stack is known as a thread stack. It is a data area in the JVM memory which is created
for a single execution thread. The JVM stack of a thread is used by the thread to store
various elements (i.e) local variables, partial results, and data for calling method and
returns.
Native stack: It subsumes all the native methods used in your application.
Execution Engine:
● JIT compiler
● Garbage collector
JIT compiler:
The Just-In-Time (JIT) compiler is a part of the runtime environment. It helps in improving
the performance of Java applications by compiling bytecodes to machine code at run time.
The JIT compiler is enabled by default. When a method is compiled, the JVM calls the
compiled code of that method directly. The JIT compiler compiles the bytecode of that
method into machine code, compiling it “just in time” to run.
Garbage collector:
As the name explains that Garbage Collector means to collect the unused material. Well, in
JVM this work is done by Garbage collection. It tracks each and every object available in the
JVM heap space and removes unwanted ones.
Garbage collector works in two simple steps known as Mark and Sweep:
● Mark – it is where the garbage collector identifies which piece of memory is in use
and which are not
● Sweep – it removes objects identified during the “mark” phase.
The JRE software builds a runtime environment in which Java programs can be executed.
The JRE is the on-disk system that takes your Java code, combines it with the needed
libraries, and starts the JVM to execute it. The JRE contains libraries and software needed
by your Java programs to run. JRE is a part of JDK (which we will study later) but can be
downloaded separately.
The Java Development Kit (JDK) is a software development environment used to develop
Java applications and applets. It contains JRE and several development tools, an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(javadoc) accompanied with another tool.
The blue area shown in the diagram is JDK.
First source code is used by java compiler and is converted in .class file. The class file code
is in byte code form and that class file is used by JVM to convert into an object file. After
that, you can see the final output on your screen.
Event Handling in Java
While understanding the concept of event handling you might have come across terms such
as sources, events, etc. Sources and events are some of the basic terms which are to be
understood before we look at event handling.
Event
When you press a button in your program or Android application the state of the button
changes from ‘Unclicked’ to ‘Clicked’.This change in the state of our button is called an
Event. Events are generated based on how you interact with the GUI. For example- entering
some text through the keyboard, moving your cursor, scrolling, etc generates events.
Source
In Java, nearly everything is an object. The button you press is an object too. Sorce is the
object which generates an event. In other words, a source is an object which undergoes
state change. It also provides information about the event to the listener. We will talk about
the listener in the other half of this post.
Listeners
Now we know about the events and the sources. This is a good time to talk about the
listeners. Listeners are also called as event handlers as they are the ones responsible to
handle events occurring at the source. Listeners are interfaces and different types of
listeners are used according to the event.
Registration Methods
For registering the component with the Listener, many classes provide the registration
methods. For example:
⮚ Button
o public void addActionListener(ActionListener a){}
⮚ MenuItem
o public void addActionListener(ActionListener a){}
⮚ TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
⮚ TextArea
o public void addTextListener(TextListener a){}
⮚ Checkbox
o public void addItemListener(ItemListener a){}
⮚ Choice
o public void addItemListener(ItemListener a){}
⮚ List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
mouseMoved(MouseEvent me)
MouseEvent– Event generated by
MouseMotionListener
the mouse mouseDragged(MouseEvent
me)
Threading concepts
Java is a multi-threaded programming language which means we can develop multi-
threaded program using Java. A multi-threaded program contains two or more parts that
can run concurrently and each part can handle a different task at the same time making
optimal use of the available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing
resources such as a CPU. Multi-threading extends the idea of multitasking into
applications where you can subdivide specific operations within a single application into
individual threads. Each of the threads can run in parallel. The OS divides processing time
not only among different applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
Life Cycle of a Thread
A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies. The following diagram shows the complete life cycle of a
thread.
● New − A new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread. It is also referred to as a born thread.
● Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
● Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. A thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.
● Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.
Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot
guarantee the order in which threads execute and are very much platform dependent.
If your class is intended to be executed as a thread then you can achieve this by
implementing a Runnable interface. You will need to follow three basic steps −
Step 1
As a first step, you need to implement a run() method provided by a Runnable interface.
This method provides an entry point for the thread and you will put your complete
business logic inside this method. Following is a simple syntax of the run() method −
public void run( )
Step 2
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface
and threadName is the name given to the new thread.
Step 3
Once a Thread object is created, you can start it by calling start() method, which executes
a call to run( ) method. Following is a simple syntax of start() method −
void start();
Runnable Interface
The easiest way to create a thread is to create a class that implements
the Runnable interface.
To implement Runnable interface, a class need only implement a single method called
run( ), which is declared like this:
Inside run( ), we will define the code that constitutes the new thread
Example:
System.out.println("MyClass running");
}}
To execute the run() method by a thread, pass an instance of MyClass to a Thread in its
constructor(A constructor in Java is a block of code similar to a method that’s called when
an instance of an object is created). Here is how that is done:
t1.start();
When the thread is started it will call the run() method of the MyClass instance instead of
executing its own run() method. The above example would print out the text “MyClass
running“.
System.out.println("MyClass running");
}
}
To create and start the above thread you can do like this:
T1.start();
When the run() method executes it will print out the text “MyClass running“.
String name;
Thread t;
name = threadname;
t.start();
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
class MultiThread {
new MyThread("One");
new MyThread("Two");
new NewThread("Three");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Thread Methods
The previous methods are invoked on a particular Thread object. The following methods
in the Thread class are static. Invoking one of the static methods performs the operation
on the currently running thread.
Networking features:
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
5. Connection-oriented and connection-less protocol
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.
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.
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.
6) Socket
A socket is an endpoint between two way communications.
java.net package
The java.net package provides many classes to deal with networking applications in Java. A
list of these classes is given below:
o Authenticator
o CacheRequest
o CacheResponse
o ContentHandler
o CookieHandler
o CookieManager
o DatagramPacket
o DatagramSocket
o DatagramSocketImpl
o InterfaceAddress
o JarURLConnection
o MulticastSocket
o InetSocketAddress
o InetAddress
o Inet4Address
o Inet6Address
o IDN
o HttpURLConnection
o HttpCookie
o NetPermission
o NetworkInterface
o PasswordAuthentication
o Proxy
o ProxySelector
o ResponseCache
o SecureCacheResponse
o ServerSocket
o Socket
o SocketAddress
o SocketImpl
o SocketPermission
o StandardSocketOptions
o URI
o URL
o URLClassLoader
o URLConnection
o URLDecoder
o URLEncoder
o URLStreamHandler
o ContentHandlerFactory
o CookiePolicy
o CookieStore
o DatagramSocketImplFactory
o FileNameMap
o SocketOption<T>
o SocketOptions
o SocketImplFactory
o URLStreamHandlerFactory
o ProtocolFamily
Media techniques:
Modern world's rich internet applications must be capable to play and edit the media files
when required. JavaFX provides the media-rich API that can play audio and video on the
user's demand.
JavaFX Media API enables the users to incorporate audio and video into the rich internet
applications (RIAs). JavaFX media API can distribute the media content across the different
range of devices like TV, Mobile, Tablets and many more.
In this part of the tutorial, we will discuss the capability of JavaFX to deal with the media
files in an interactive way. For this purpose, JavaFX provides the
package javafx.scene.media that contains all the necessary
classes. javafx.scene.media contains the following classes.
1. javafx.scene.media.Media
2. javafx.scene.media.MediaPlayer
3. javafx.scene.media.MediaStatus
4. javafx.scene.media.MediaView
Media Events
The JavaFX team have designed media API to be event driven. The callback behaviour
attached with the media functions are used to handle media events. Instead of typing code
for a button via a EventHandler, a code is implemented that responds to the triggering of
the media player's OnXXXX events where XXXX is the event name.
java.lang.Runnable functional interfaces are used as the callbacks which are invoked
when an event is encountered. When playing the media content in javafx, we would create
the Lambda expressions (java.lang.Runnable interfaces) to be set on the onReady event.
Consider the following example.
The playMusic variable is assigned to a lambda expression. This get passed into the Media
player's setOnReady() method. The Lambda expression will get invoked when the onReady
event is encountered
MediaPlayer setOnEndOfMedia() The method is invoked when end of the media play
is reached.
MediaPlayer setOnPlaying() This method is invoked when the play event occurs.
MediaPlayer setOnStopped() This method is invoked when the media player has
stopped.
We must notice that MediaPlayer class contains the most number of events triggered while
MediaView and Media classes contains one event each.
javafx.scene.media.Media class
The properties of the class are described in the following table. All the properties are the
read only except onError.
Possible media and media-player events are discussed in the following table.
Property Description
duration The duration of the source media in seconds. This property is of object type
of the class Duration.
error This is a property set to media exception value when an error occurs. This
property is of the type object of the class MediaException.
height The height of the source media in pixels. This is an integer type property.
onError The event handler which is called when the error occurs. The
method setOnError() is used to set this property.
width The width of the source media in pixels. This is an integer type property
We must notice that MediaPlayer class contains the most number of events triggered while
MediaView and Media classes contains one event each.
javafx.scene.media.Media class
The properties of the class are described in the following table. All the properties are the
read only except onError.
Property Description
duration The duration of the source media in seconds. This property is of object type
of the class Duration.
error This is a property set to media exception value when an error occurs. This
property is of the type object of the class MediaException.
height The height of the source media in pixels. This is an integer type property.
onError The event handler which is called when the error occurs. The
method setOnError() is used to set this property.
width The width of the source media in pixels. This is an integer type property
Constructors
There is a single constructor in the table.
public Media(java.lang.String source): it instantiate the class Media with the specified
source file.
JavaFX.scene.media.MediaPlayer class
The properties of the class along with the setter methods are described in the following
table.
bufferProgressTime This is an object type Can not be set as it is read only property.
property of the class
Duration. It indicates
the duration of the
media which can be
played without
stalling the media-
player.
currentCount This is read only Can not be set as it is read only property.
integer type
property. It indicates
the number of
completed playback
cycles.
currentRate This is a double type Can not be set as it is read only property.
property. It indicates
the current rate of
the playback. It is
read only property.
currentTime This is an object type Can not be set as it is read only property.
property of the class
Duration. It indicates
the current media
playback time.
cycleDuration It is the ready only Can not be set as it is read only property.
property. It is of the
type object of the
class Duration. It
indicates the amount
of time between the
start time and stop
time of the media.
status This is the read only Can not be set as it is read only property.
property. It indicates
the current state of
the Media player.
Constructors
The class contains only a single constructor which is given below.