java
java
Introduction to Java
Features of Java
The primary objective of Java programming language creation was to make it
portable, simple and secure programming language. Apart from this, there are
also some excellent features which play an important role in the popularity of
this language. The features of Java are also known as java buzzwords.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10.Multithreaded
11.Distributed
12.Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms. It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms,
i.e., Write Once and Run Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
Robust
Robust simply means strong. Java is robust because:
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and
4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for
both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java.
RMI and EJB are used for creating distributed applications. This feature of Java makes us
able to access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Applet in Java
An applet is a special kind of Java program that runs in a Java enabled browser. This is
the first Java program that can run over the network using the browser. Applet is typically
embedded inside a web page and runs in the browser.
In other words, we can say that Applets are small Java applications that can be accessed
on an Internet server, transported over Internet, and can be automatically installed and
run as apart of a web document.
After a user receives an applet, the applet can produce a graphical user interface. It has
limited access to resources so that it can run complex computations without introducing
the risk of viruses or breaching data integrity.
To create an applet, a class must class extends java.applet.Applet class.
An Applet class does not have any main() method. It is viewed using JVM. The JVM can
use either a plug-in of the Web browser or a separate runtime environment to run an
applet application.
JVM creates an instance of the applet class and invokes init() method to initialize an
Applet.
Note: Java Applet is deprecated since Java 9. It means Applet API is no longer considered
important.
1. Applet is initialized.
2. Applet is started
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
A Simple Applet
import java.awt.*;
import java.applet.*;
}
Every Applet application must import two packages - java.awt and java.applet.
java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the
user (either directly or indirectly) through the AWT. The AWT contains support for a
window-based, graphical user interface. java.applet.* imports the applet package, which
contains the class Applet. Every applet that you create must be a subclass of Applet
class.
The class in the program must be declared as public, because it will be accessed by code
that is outside the program.Every Applet application must declare a paint() method. This
method is defined by AWT class and must be overridden by the applet. The paint()
method is called each time when an applet needs to redisplay its output. Another
important thing to notice about applet application is that, execution of an applet does not
begin at main() method. In fact an applet application does not have any main() method.
Advantages of Applets
Applet class
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods
that load and play audio clips.
An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.
init() : init() is the first method to be called. This is where variable are initialized.
stop() : stop() method is called to suspend thread that does not need to run
Example of an Applet
import java.applet.*;
import java.awt.*;
{
int height, width;
height = getSize().height;
width = getSize().width;
setName("MyApplet");
Container Class
It represents objects in graphical representation and it is an abstract class in the GUI
interface.
The following are the list of commonly used UI elements in the GUI or commonly known
as Graphical User Interface.
1. Label
A label is a user for placing text inside the container. A label is used only for inputting
text. The label does not imply that the text can be altered or it can be used as a button
which can be further worked upon.
Syntax:
2. Button
This command generates a button in the User Interface. Clicking on the button would
move the command to another page or another web server which is used to show several
other outputs in the user interface page.
Syntax:
a1=new Button("submit");
a2=new Button("cancel");
3. Checkbox
There can be a certain question and the checkbox is used to determine the true or false
nature of the question being asked. If the checkbox is ticked then it means that the said
question is true which if it is unchecked it means that the said question is false. It is
basically a true or false state in Java programming language.
Syntax:
4. Checkbox Group
As the name implies the checkbox group is a set of checkboxes that are being
used in the programming language. There are many checkboxes that are being
used and hence the group of checkboxes is known as the checkbox group.
Syntax:
5. List
The list gives a scrolling list of items for the user. The scrolling list of items is also
being set by the user. The user sets the scrolling list of items such as Fruits,
Vegetables, some questionnaire or other facts.
Syntax:
6. Text Field
A text field is used for the editing of a particular line of text which can be used within the
programming concept.
Syntax:
na=new TextField(20);
7. Text Area
A text area is used for the editing of multiple lines of text. The only difference between
the Text field and Text area is that Text Field is used for editing a single line of text
within the user interface while a Text Area is used for editing multiple lines of text.
Syntax:
8. Choice
A choice, as the name implies, shows the various options and the choice that is selected
is shown in the top menu bar of the screen.
Syntax:
9. Canvas
In the canvas space, there can be an input being given by the user or the user can draw
something on the Canvas space being given.
Syntax:
f.add(new MyCanvas());
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
10. Image
There can be a single image or multiple images within a UI. There can be a button being
associated with an image and when it is clicked it can produce some functionality.
Syntax:
Image i=t.getImage("pic2.gif");
Syntax:
12. Dialog
The dialog is used to take some form of input from the user and produce it in a
sequential manner.
Syntax:
d = new Dialog(f , "Hello World", true);
Syntax:
FileDialog(Dialog parent)
</applet>
Before we begin with the programs(code) of creating threads, let’s have a look at
these methods of Thread class. We have used few of these methods in the
example below.
Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
Let's see the code to print output and an error message to the console.
System.out.println("simple message");
System.err.println("error message");
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given
below.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some
sink.
Swing
Swing is the collection of user interface components for the Java programs. It is
part of Java foundation classes that are referred to as JFC. In simple words, Swing
is the graphical user interface toolkit that is used for developing the windows
based java applications or programs. Swing is the successor of AWT which is
known as Abstract window toolkit API for Java and AWT components are a mainly
heavyweight.
Features of Swing
The features of the Swing are as follows:
5. MVC: They mainly follows the concept of MVC that is Model View Controller.
With the help of this, we can do the changes in one component without
impacting or touching other components. It is known as loosely coupled
architecture as well.
Examples of Swing
The component class is mainly used and there are some of the methods that are
frequently used like adding a component in another component (add
(Component a)), setting the size, layout, and visibility of components
accordingly.
import javax.swing.*;
public class Test extends JFrame {
public Test() {
super("Test");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(new JLabel("Test, Application!"));
pack();
setVisible(true);
}
public static void main(final String[] args) {
new Test();
}
}
Difference between Swing and AWT
The difference between Swing and AWT are as follow:
Architecture It follows the Model view controller It doesn’t follow the model view
architecture. architecture.
Speed If components are more used, it can Its speed would be normal if
be slow. components are used more.
1. ImageIcon
The ImageIcon component creates an icon sized-image from an image residing
at the source URL.
Example:
This returns an icon of a home button. The string parameter is the path at which
the source image is present.
Example:
Example:
4. JTextField
JTextField renders an editable single-line text box. A user can input non-
formatted text in the box. To initialize the text field, call its constructor and pass
an optional integer parameter to it. This parameter sets the width of the box
measured by the number of columns. It does not limit the number of characters
that can be input in the box.
Example:
Example:
JTextArea txtArea = new JTextArea(“This text is default text for text area.”, 5,
20);
The above code renders a multi-line text-area of height 5 rows and width 20
columns, with default text initialized in the text-area.
6. JPasswordField
JPasswordField is a subclass of JTextField class. It renders a text-box that masks
the user input text with bullet points. This is used for inserting passwords into
the application.
Example:
It returns a password field of 15 column width. The getPassword method gets the
value entered by the user.
7. JCheckBox
JCheckBox renders a check-box with a label. The check-box has two states –
on/off. When selected, the state is on and a small tick is displayed in the box.
Example:
It returns a checkbox with the label Show Help. Notice the second parameter in
the constructor. It is a boolean value that indicates the default state of the
check-box. True means the check-box is defaulted to on state.
8. JRadioButton
JRadioButton is used to render a group of radio buttons in the UI. A user can
select one choice from the group.
Example:
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton(“Easy”, true);
JRadioButton rb2 = new JRadioButton(“Medium”);
JRadioButton rb3 = new JRadioButton(“Hard”);
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);
The above code creates a button group and three radio button elements. All
three elements are then added to the group. This ensures that only one option
out of the available options in the group can be selected at a time. The default
selected option is set to Easy.
9. JList
JList component renders a scrollable list of elements. A user can select a value or
multiple values from the list. This select behavior is defined in the code by the
developer.
Example:
The above code renders a list of cities with 5 items in the list. The selection
restriction is set to SINGLE_SELECTION. If multiple selections is to be allowed, set
the behavior to MULTIPLE_INTERVAL_SELECTION.
10. JComboBox
JComboBox class is used to render a dropdown of the list of options.
Example:
Example:
The above code creates a file chooser dialog and attaches it to the button. The
button click would open the file chooser dialog. The selected file is returned
through the getSelectedFile method.
12. JTabbedPane
JTabbedPane is another very useful component that lets the user switch between
tabs in an application. This is a highly useful utility as it lets the user browse
more content without navigating to different pages.
Example:
The above code creates a two tabbed panel with headings Tab 1 and Tab 2.
13. JSlider
JSlider component displays a slider which the user can drag to change its value.
The constructor takes three arguments – minimum value, maximum value, and
initial value.
Example:
The above code creates a slider from 0 to 100 with an initial value set to 50. The
value selected by the user is returned by the getValue method.
SWING - Containers
Containers are an integral part of SWING GUI components. A container provides
a space where a component can be located. A Container in AWT is a component
itself and it provides the capability to add a component to itself. Following are
certain noticable points to be considered.
Sub classes of Container are called as Container. For example, JPanel,
JFrame and JWindow.
Container can add only a Component to itself.
A default layout is present in each container which can be overridden
using setLayout method.
SWING Containers
Following is the list of commonly used containers while designed GUI using
SWING.
Panel
1
JPanel is the simplest container. It provides space in which any other
component can be placed, including other panels.
Frame
2
A JFrame is a top-level window with a title and a border.
Window
3
A JWindow object is a top-level window with no borders and no menubar.
Swing Controls
Swing controls are playing major role in swing applications, every application
will have some components and their corresponding event listener. Swing
controls will inherit the properties from following classes.
Component
Container
JComponent.
JLabel
JCheckBox
JComboBox
JProgressBar
JToggleButton
JSlider
// frame
static JFrame f;
// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");
// create a object
solve s = new solve();
// create a panel
JPanel p = new JPanel();
f.add(p);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("click")) {
// create a dialog Box
JDialog d = new JDialog(f, "dialog Box");
// create a label
JLabel l = new JLabel("this is a dialog box");
d.add(l);
// setsize of dialog
d.setSize(100, 100);
Swing Slider
slider is normally constructed by a JSlider component. JSlider is a component
that lets the users select a value by sliding a knob within a specified interval. For
the knob, it always points to the point which matches the integer values within
the interval.
For JSlider , six different constructors can be used:
JSlider(): creates a horizontal slider ranging from 0 to 100 with the initial value
to be 50.
JSlider(BoundedRangeModel brm): creates a horizontal slider using the
specified BounedRangeModel.
JSlider(int orientation): creates a slider using the specified orientation ranging
from 0 to 100, with the initial value to be 50.
JSlider(int min, int max): creates a slider using the specified min and max
value, with a initial value equals to the average of the min plus the max.
JSlider(int min, int max, int value): creates a horizontal slider using the
specified min, max and the initial value.
JSlider(int orientation, int min, int max, int value): very similar to the above
one, with the orientation specified.
The code above could be summarized in the
code simpleSliderExample.java below:.
simpleSliderExample.java
package javaCodeGeeks;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import java.util.Hashtable;
/*
* A simple swing slider example with different constructors
*/
}
}
JProgressBar
JProgressBar is a part of Java Swing package. JProgressBar visually displays the
progress of some specified task. JProgressBar shows the percentage of
completion of specified task.The progress bar fills up as the task reaches it
completion. In addition to show the percentage of completion of task, it can also
display some text .
Constructors of JProgressBar :
1. JProgressBar() : creates an progress bar with no text on it;
2. JProgressBar(int orientation) : creates an progress bar with a specified
orientation. if SwingConstants.VERTICAL is passed as argument a vertical
progress bar is created, if SwingConstants.HORIZONTAL is passed as
argument a horizontal progress bar is created.
3. JProgressBar(int min, int max) : creates an progress bar with specified
minimum and maximum value.
4. JProgressBar(int orientation, int min, int max) : creates an progress bar with
specified minimum and maximum value and a specified orientation.if
SwingConstants.VERTICAL is passed as argument a vertical progress bar is
created, if SwingConstants.HORIZONTAL is passed as argument a horizontal
progress bar is created.
// create a frame
static JFrame f;
static JProgressBar b;
// create a panel
JPanel p = new JPanel();
// create a progressbar
b = new JProgressBar();
b.setStringPainted(true);
// add progressbar
p.add(b);
// add panel
f.add(p);
fill();
}
filter_none
edit
play_arrow
brightness_4
// Packages to import
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
// Constructor
JTableExamples()
{
// Frame initiallization
f = new JFrame();
// Frame Title
f.setTitle("JTable Example");
// Column Names
String[] columnNames = { "Name", "Roll Number", "Department" };
// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
f.add(sp);
// Frame Size
f.setSize(500, 200);
// Frame Visible = true
f.setVisible(true);
}
// Driver method
public static void main(String[] args)
{
new JTableExamples();
}
}
Output:
import javax.swing.JFrame;
The lines that arguably do most of the work are the ones in bold which construct
the window, specifically an instance of JFrame, and then make it visible. We
mentioned that user interface components are generally represented by classes
inside the javax.swing package with names beginning with J. In this case, a
"window with decorations" is strictly speaking called a frame, and represented by
the JFrame class. So creating a window means creating an instance of JFrame.
We construct one just like most Java objects: by calling its constructor. Note that,
as with many constructors, most allow us to specify some common parameters:
in this case, the title of the window.
The call to set the size of the window is hopefully self-explanatory once you see
it; let us just comment for now that in general, you need to think about the size
(and potentially layout) of all windows/components when you're programming
with Swing. The call to setDefaultCloseOperation() is a shortcut we can use in the
very simple case where we want our application to exit when the window is
closed: Swing will dutifully call System.exit() for us. We'll see later that we can
customise what happens when a window is closed.
java.sql package
The java.sql package provides the API for accessing and processing data stored
in a data source (usually a relational database) using the Java programming
language. This API includes a framework whereby different drivers can be
installed dynamically to access different data sources. Although the JDBC API is
mainly geared to passing SQL statements to a database, it provides for reading
and writing data from any data source with a tabular format. The reader/writer
facility, available through the javax.sql.RowSet group of interfaces can be
customized to use and update data from a spreadsheet, flat file, or any other
tabular data source.
ResultSet interface
4. Standard mappings for SQL types to classes and interfaces in the Java
programming language
JdbcExceptions.java
import java.sql.*;
Class.forName(driver);
try {
con = DriverManager.getConnection(url + db, user, pass);
} catch (Exception e) {
System.err.println(e);
url = "jdbc:mysql://localhost:3306/";
db = "komal";
user = "root";
pass = "root";
Output
To get started with this demo, go ahead and download the SQLite sample
database. Unzip the .db file and save it somewhere you won't forget.
This file contains both a functional file-based database and sample schema and
data we can use.
Assuming you have the Java platform developer tools installed, we can start by
creating a simple Java program. In your text editor, paste in the code shown in
Listing 1. Call this file WhatIsJdbc.java.
class WhatIsJdbc{
public static void main(String args[]){
System.out.println("Hello JavaWorld");
}
}
Now compile the code by entering the command: javac
WhatIsJdbc.java. Compiling will output the WhatIsJdbc.class file.
Execute this file from the command line with the call: java WhatIsJdbc.
Download the SQLite driver from GitHub. Be sure to get the most recent .jar file
and store it somewhere you'll remember.
The next time you execute your Java program, you will pull that .jar file in via the
classpath. There are several ways to set the classpath. Listing 3 shows how to do
it using a command-line switch.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
class WhatIsJdbc{
public static void main(String[] args) {
Connection conn = null;
try {
String url = "jdbc:sqlite:path-to-db/chinook/chinook.db";
conn = DriverManager.getConnection(url);
System.out.println("Got it!");
} catch (SQLException e) {
throw new Error("Problem", e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
class WhatIsJdbc{
public static void main(String[] args) {
Connection conn = null;
try {
String url = "jdbc:sqlite:path-to-db-file/chinook/chinook.db";
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
throw new Error("Problem", e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
}
PreparedStatement prepState =
connection.prepareStatement(sql);
prepState.setString(1, "Uprising");
prepState.setString(2, "Bob Marley and the Wailers ");
Basic Requirements
Since we shall be going hands on down the line, the basic software requirements for JDBC
programming are as follows.
1.Java SDK
2.RDBMS Package (For example, MySQL, Oracle, PostgreSQL, etc.)
3.IDE (For example, Eclipse, NetBeans, JDeveloper, etc.)
4.JDBC driver (JDBC drivers are database specific, especially, if we use a driver
other than Type1:JDBC-ODBC Bridge. For example, MySQL Connector/J is the
official JDBC driver for MySQL, ojdbc for Oracle and so on...PostgreSQL JDBC
Driver)
Navigation Model
The JavaServer Faces navigation model makes it easy to define page navigation
and to handle any additional processing that is needed to choose the sequence
in which pages are loaded.
In JavaServer Faces technology, navigation is a set of rules for choosing the
next page or view to be displayed after an application action, such as when a
button or link is clicked.
Navigation can be implicit or user-defined. Implicit navigation comes into play
when user-defined navigation rules are not configured in the application
configuration resource files.
When you add a component such as a commandButton to a Facelets page, and
assign another page as the value for its action property, the default navigation
handler will try to match a suitable page within the application implicitly. In the
following example, the default navigation handler will try to locate a page
named response.xhtml within the application and navigate to it:
<description></description
<from-view-id></from-view-id>
<navigation-case>
<from-action></from-action>
<from-outcome></from-outcome>
<if></if>
<to-view-id></to-view-id>
</navigation-case>
</navigation-rule>
Refer to an outcome String from the button or link component's action attribute. This
outcome String is used by the JavaServer Faces implementation to select the navigation
rule.
<navigation-rule>
<from-view-id>/greeting.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/response.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
Notes:
The Java download bundle of the NetBeans IDE enables you to install the GlassFish
server. You require the GlassFish server to work through this tutorial.
The MySQL Connector/J JDBC Driver, necessary for communication between Java
platforms and the MySQL database protocol, is included in the NetBeans IDE.
If you need to compare your project with a working solution, you can download the
sample application.
java RMI
RMI stands for Remote Method Invocation. It is a mechanism that allows an
object residing in one system (JVM) to access/invoke an object running on
another JVM.
RMI is used to build distributed applications; it provides remote communication
between Java programs. It is provided in the package java.rmi.
RMI Architecture
In distributed application architecture, it is always a need for communication
between two different applications. In Java-based applications, one application
communicates with another remote/different application running somewhere
else by using a mechanism called RMI architecture.
RMI stands for Remote Method Invocation. It is an API provided by java which
allows an object residing in one JVM (Java Virtual Machine) to access or invoke an
object running on another JVM. The other JVM could be on the same machine or
remote machine. This is an interesting feature because in real time applications
it becomes very easy for Java applications to communicate directly with each
other without any external communication mechanism. Also, it is always a need
for secure communication between applications based on distributed application
architecture.
RMI Design
RMI API is provided in the package java.rmi. Let’s introduce two terms for
the understanding of RMI design architecture. First is the client; the JVM
that will call remote object and second is server; the JVM that contains the
remote object. So, the client will call the server, in this case on the object
for method invocation.
The server will then return the reference of the object to the client. The
catch here is both the objects i.e. local and remote will appear as a local
object on the server. There will be no differentiation between the two. The
syntax of the methods of both objects is also the same. Therefore, the
server JVM acts like normal JVM without knowing of any object whether it
is local or remote.
The same object can be both a server and a client. The remote objects
reference is obtained, and it is used as if it was a local object. The RMI
infrastructure is responsible for finding the remote object, intercepting
method call and processing the remote request remotely. The client
invokes methods on the object only after obtaining a reference to a
remote object.
RMI Architecture
Below is the diagram of RMI architecture in a simple way. On the internet, you
will find various forms of the same architecture, but we have a simple one which
will help to explain it better.
Let’s start by connecting dots from a design perspective with an architecture
diagram.
The client application and server application are the respective JVMs of the client
machine and server machine. In RMI application we write two programs
respectively; the client program which resides on the client and server program
which resides on the server machine.
So, before we jump into the depth of Servlets, let’s see the technology that was used
before servlets came into the picture.
Properties of Servlets :
Servlets work on the server-side.
Servlets are capable of handling complex requests obtained from web server.
Execution of Servlets :
Execution of Servlets involves six basic steps:
1. The clients send the request to the web server.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of
output.
5. The servlet sends the response back to the web server.
6. The web server sends the response back to the client and the client browser
displays it on the screen.
CGI vs Servlets
Before servlets, we had CGI i.e. Common Gateway Interface. It is a standard way for
a Web server to pass a user’s request to an application program and receives the
response to forward to the user. When the user requests a Web page, the server
sends back the requested page. However, when a user fills out a form on a Web
page and sends it in, it is processed by an application program. The Web server
typically passes the form information to a small application program. This program
processes the data and sends back a confirmation message. This process of
passing data back and forth between the server and the application is called the
common gateway interface (CGI). It is part of the Web’s Hypertext Transfer Protocol.
But, why did we stopped using it and switched to servlets? Let’s understand this with
the help of the below table:
init() and destroy() methods are called only once. Finally, a servlet is garbage
collected by the garbage collector of the JVM. So this concludes the life cycle of a
servlet. Now, let me guide you through the steps of creating java servlets
To run a servlet program, we should have Apache Tomcat Server installed and
configured. Eclipse for Java EE provides in-built Apache Tomcat. Once the server is
configured, you can start with your program. One important point to note – for any
servlet program, you need 3 files – index.html file, Java class file, and web.xml file.
The very first step is to create a Dynamic Web Project and then proceed further.
Now, let’s see how to add 2 numbers using servlets and display the output in the
browser.
</body>
</html>
Above program creates a form to enter the numbers for the addition operation.
Without the Java class file, you can’t perform addition on 2 numbers. So let’s now
create a class file.
package edureka;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Add extends HttpServlet{
public void service(HttpServletRequest req, HttpServletResponse res) throws
IOException
{
int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2"));
int k= i+j;
PrintWriter out = res.getWriter();
out.println("Result is"+k);
}
}
After writing the Java class file, the last step is to add mappings to the web.xml file.
Networking
Introduction to Java Networking
Java Networking is a notion of connecting two or more computing devices together
to share the resources. Java program communicates over the network at
the application layer. java.net package is useful for all the Java networking classes
and interfaces.
The java.net package provides support for two protocols. They are as follows:
Note: Networking in Java is mainly used for sharing the resources and also for
centralized software management.
With this, let’s move further and learn various terminologies used in Networking.
Networking Terminologies
The widely used Java networking terminologies used are as follows:
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1. IP Address
The 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 followed for communication. For example:
TCP
FTP
Telnet
SMTP
POP etc.
3. Port Number
The port number uniquely identifies different applications. It acts as a communication endpoint
between applications. To communicate between two applications, the port number is used along
with an IP Address.
4. MAC Address
A MAC address is basically a hardware identification number which uniquely identifies each device
on a network. For example, an Ethernet card may have a MAC address of 00:0d:83:b1:c0:8e.
5. Connection-oriented and connection-less protocol
In the connection-oriented protocol, acknowledgment is sent by the receiver. So it is reliable but
slow. The example of a connection-oriented protocol is TCP. But, in the connection-less protocol,
acknowledgment is not sent by the receiver. So it is not reliable but fast. The example of a
connection-less protocol is UDP.
6. Socket
A socket in Java is one endpoint of a two-way communication link between two programs running
on the network. A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent to.
Now that you know various terminologies used in Java Networking, let’s move further and
understand some of the important classes that it supports.
Inet Address
Inet Address is used to encapsulate both the numerical IP address and the domain name for that
address. It can handle both IPv4 and Ipv6 addresses. Below figure depicts the subclasses of Inet
Address class.
To create an Inet Address object, you have to use Factory methods. Basically, there are three commonly used
Inet Address factory methods. They are as follows:
1 import java.net.*;
2 public class InetAddressExample
3 {
4 public static void main(String[] args) throws UnknownHostException
5 {
6 InetAddress address = InetAddress.getLocalHost(); // returns the system details i.e. Inet Address
7 System.out.println(address);
8 address = InetAddress.getByName("www.facebook.com"); // returns the address of the website
9 System.out.println(address);
10 InetAddress ia[] = InetAddress.getAllByName("www.google.com");
11 for(int i=0; i< ia.length; i++)
12 {
13 System.out.println(ia[i]);
14 }
15 }
16 }
Client
A client is a program that runs on the local machine requesting service from the server. A
client program is a finite program means that the service started by the user and
terminates when the service is completed.
Server
A server is a program that runs on the remote machine providing services to the clients.
When the client requests for a service, then the server opens the door for the incoming
requests, but it never initiates the service.
A server program is an infinite program means that when it starts, it runs infinitely unless
the problem arises. The server waits for the incoming requests from the clients. When
the request arrives at the server, then it responds to the request.
There are two kinds of TCP sockets in Java. One is for servers, and the other is
for clients. The ServerSocket class is designed to be a "listener," which waits
for clients to connect before doing anything. Thus, ServerSocket is for servers.
The Socket class is for clients. It is designed to connect to server sockets and
initiate protocol exchanges. Because client sockets are the most commonly
used by Java applications, they are examined here.
int getPort( ) : Returns the remote port to which the invoking Socket object is
connected. It returns 0 if the socket is not connected.
int getLocalPort( ) : Returns the local port to which the invoking Socket object is
bound. It returns –1 if the socket is not bound.
You can gain access to the input and output streams associated with
a Socket by use of
the getInputStream( ) and getOuptutStream( ) methods, as shown here.
Each can throw an IOException if the socket has been invalidated by a loss of
connection. These streams are used exactly like the I/O streams described in
Chapter 20 to send and receive data.
Several other methods are available, including connect( ), which allows you to
specify a new connection; isConnected( ), which returns true if the socket is
connected to a server; isBound( ), which returns true if the socket is bound to
an address; and isClosed( ), which returns true if the socket is closed. To close
a socket, call close( ). Closing a socket also closes the I/O streams associated
with the socket. Beginning with JDK 7, Socket also implements AutoCloseable,
which means that you can use a try-with-resources block
throws UnknownHostException
throws UnknownHostException
throws UnknownHostException
All three of these may make a connection to the local DNS server to fill out the
information in the InetAddress object.
Datagrams in Java
TCP/IP-style networking provides a serialized, predictable, reliable stream of packet
data. This is not without its cost, however. TCP includes algorithms for dealing with
congestion control on crowded networks, as well as pessimistic expectations about
packet loss. This leads to inefficient way to transport data.
Clients and servers that communicate via a reliable channel, such as a TCP socket,
have a dedicated point-to-point channel between themselves. To communicate, they
establish a connection, transmit the data, and then close the connection. All data
sent over the channel is received in the same order in which it was sent. This is
guaranteed by the channel.
In contrast, applications that communicate via datagrams send and receive
completely independent packets of information. These clients and servers do not
have and do not need a dedicated point-to-point channel. The delivery of datagrams
to their destinations is not guaranteed. Nor is the order of their arrival.
Datagram
A datagram is an independent, self-contained message sent over the network
whose arrival, arrival time, and content are not guaranteed.
Datagrams plays a vital role as an alternative.
Datagrams are bundles of information passed between machines. Once the
datagram has been released to its intended target, there is no assurance
that it will arrive or even that someone will be there to catch it.
Likewise, when the datagram is received, there is no assurance that it
hasn’t been damaged in transit or that whoever sent it is still there to
receive a response and it is crucial point to note.
Java implements datagrams on top of the UDP (User Datagram Protocol) protocol
by using two classes:
1. DatagramPacket object is the data container.
2. DatagramSocket is the mechanism used to send or receive the
DatagramPackets.
DatagramSocket Class
DatagramSocket defines four public constructors. They are shown here:
DatagramSocket( ) throws SocketException : It creates a
DatagramSocket bound to any unused port on the local computer.
DatagramSocket(int port) throws SocketException : It creates a
DatagramSocket bound to the port specified by port.
DatagramSocket(int port, InetAddress ipAddress) throws
SocketException : It constructs a DatagramSocket bound to the specified
port and InetAddress.
DatagramSocket(SocketAddress address) throws
SocketException : It constructs a DatagramSocket bound to the specified
SocketAddress.
SocketAddress is an abstract class that is implemented by the concrete class
InetSocketAddress. InetSocketAddress encapsulates an IP address with a port
number. All can throw a SocketException if an error occurs while creating the
socket. DatagramSocket defines many methods. Two of the most important are
send( ) and receive( ), which are shown here:
void send(DatagramPacket packet) throws IOException
void receive(DatagramPacket packet) throws IOException
A Datagram Example
// an array of buffer_size
public static byte buffer[] = new byte[buffer_size];
InetAddress.getLocalHost(), clientPort));
pos = 0;
break;
default:
// otherwise put the input in buffer array
buffer[pos++] = (byte)c;
}
}
}
ds.receive(p);
To create a server program using Netbeans IDE, you need to perform the
following steps:
Select the Java Application option in the Projects section of the Choose
Project page.
Click the Next button. The NameandLocation page is displayed.
Type ServerActivity in the Project Name text box.
Type <Drive Letter>:\JavaProjects in the Project Location text box.
Click the Finish button. The NetBeans IDE 5.5.1 - ServerActivity window is
displayed.
Select the Java Classes option in the Categories section of the Choose File
Type page.
Select the JApplet option in the File Types section of the Choose File
Type page. Click the Next button. The NewJApplet dialog box appears.
Replace the text in the Class Name text box with CustomerApplet.
Click the Finish button. The NetBeans IDE 5.5.1 ServerActivity window is
displayed.
JavaBeans Architecture
JavaBeans is an architecture for both using and building components in Java. This
architecture supports the features of software reuse, component models, and
object orientation. One of the most important features of JavaBeans is that it
does not alter the existing Java language. If you know how to write software in
Java, you know how to use and create Beans. The strengths of Java are built
upon and extended to create the JavaBeans component architecture.
public MyBean()
{
}
This is a real Bean named MyBean that has state (the variable theValue) that will
automatically be saved and restored by the JavaBeans persistence mechanism,
and it has a property named MyValue that is usable by a visual programming
environment. This Bean doesn’t have any visual representation, but that isn’t a
requirement for a JavaBean component.
Advantages of Beans
A Bean may register to receive events from other objects and can generate
events that are sent to other objects.
Software
As software developers, we are constantly being asked to build applications in less time and with less
money. In addition, these applications are expected to be better and faster than ever before. Object-
oriented techniques and component software environments are in wide use now, in the hope that they
can help us build applications more quickly. Development tools like Microsoft's Visual Studio have
made it easier to build applications faster by taking a building-block approach to software
development. Such tools provide a visual programming model that allows you to include software
components rapidly in your applications. The JavaBeans architecture brings the component
development model to Java, and that is the subject of this course. But before we get started, I want to
spend a little time describing the component model, and follow that with a general overview of
JavaBeans.
1. Create a JAR file: To create a .jar file , we can use jar cf command in the following
way:
jar cf jarfilename inputfiles
Here, cf represents create the file. For example , assuming our package pack is
available in C:\directory , to convert it into a jar file into the pack.jar , we can give
the command as:
C:\> jar cf pack.jar pack
Now , pack.jar file is created
2. Viewing a JAR file: To view the contents of .jar files, we can use the command as:
jar tf jarfilename
Here , tf represents table view of file contents. For example, to view the contents of
our pack.jar file , we can give the command:
C:/> jar tf pack.jar
Now , the contents of pack.jar are displayed as:
META-INF/
META-INF/MANIFEST.MF
pack/
pack/class1.class
pack/class2.class
..
..
where class1 , class2 etc are the classes in the package pack. The first two entries
represent that there is a manifest file created and added to pack.jar. The third entry
represents the sub-directory with the name pack and the last two represent the
files name in the directory pack.
When we create .jar files , it automatically receives the default manifest file. There
can be only one manifest file in an archive , and it always has the pathname.
META-INF/MANIFEST.MF
This manifest file is useful to specify the information about other files which are
packaged.
3. Extracting a JAR file: To extract the files from a .jar file , we can use:
jar xf jarfilename
Here, xf represents extract files from the jar files. For example , to extract the
contents of our pack.jar file, we can write:
C:\> jar xf pack.jar
This will create the following directories in C:\
META-INF
pack // in this directory , we can see class1.class and class2.class.
4. Updating a JAR File The Jar tool provides a ‘u’ option which you can use to update
the contents of an existing JAR file by modifying its manifest or by adding files. The
basic command for adding files has this format:
jar uf jar-file input-file(s)
here uf represent update jar file. For example , to update the contents of our
pack.jar file, we can write:
C:\>jar uf pack.jar
5. Running a JAR file: In order to run an application packaged as a JAR file (requires
the Main-class manifest header) , following command can be used:
C:\>java -jar pack.jar
Introspection
Introspection is the automatic process of analyzing a bean's design patterns to
reveal the bean's properties, events, and methods. This process controls the
publishing and discovery of bean operations and properties. This lesson explains
the purpose of introspection, introduces the Introspection API, and gives an
example of introspection code.
Purpose of Introspection
A growing number of Java object repository sites exist on the Internet in answer
to the demand for centralized deployment of applets, classes, and source code in
general. Any developer who has spent time hunting through these sites for
licensable Java code to incorporate into a program has undoubtedly struggled
with issues of how to quickly and cleanly integrate code from one particular
source into an application.
Introspection API
The JavaBeans API architecture supplies a set of classes and interfaces to provide introspection.
The BeanInfo (in the API reference documentation) interface of the java.beans package defines
a set of methods that allow bean implementors to provide explicit information about their beans. By
specifying BeanInfo for a bean component, a developer can hide methods, specify an icon for the
toolbox, provide descriptive names for properties, define which properties are bound properties, and
much more.
The getBeanInfo(beanName) (in the API reference documentation) of the Introspector (in
the API reference documentation) class can be used by builder tools and other automated
environments to provide detailed information about a bean. The getBeanInfo method relies on the
naming conventions for the bean's properties, events, and methods. A call to getBeanInfo results
in the introspection process analyzing the beanÂ’s classes and superclasses.
The Introspector class provides descriptor classes with information about properties, events, and
methods of a bean. Methods of this class locate any descriptor information that has been explicitly
supplied by the developer through BeanInfo classes. Then the Introspector class applies the
naming conventions to determine what properties the bean has, the events to which it can listen, and
those which it can send.
start the BDK and create an instance of the’ Colors Bean in the Bean Box
window. Create an instance of the Tick Tock BFan. The Properties window should
show one property for, this component. It is “Interval” and its initial value is 5. This
represents the number of seconds that’elapse between property change events
generated by the Tick Tock Bean. Change the value to 1.
Basically, any html file can be converted to JSP file by just changing the file
extension from “.html” to “.jsp”, it would run just fine. What differentiates JSP
from HTML is the ability to use java code inside HTML. In JSP, you can embed
Java code in HTML using JSP tags. for e.g. run the code below, every time you run
this, it would display the current time. That is what makes this code dynamic .
<HTML>
<BODY>
Hello BeginnersBook Readers!
Current time is: <%= new java.util.Date() %>
</BODY>
</HTML>
Your First JSP
Let’s start learning JSP with a simple JSP.
JSP – Architecture
The web server needs a JSP engine, i.e, a container to process JSP pages. The
JSP container is responsible for intercepting requests for JSP pages. This tutorial
makes use of Apache which has built-in JSP container to support JSP pages
development.
A JSP container works with the Web server to provide the runtime environment
and other services a JSP needs. It knows how to understand the special
elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web
application.
JSP Processing
The following steps explain how the web server creates the Webpage using JSP −
As with a normal page, your browser sends an HTTP request to the web
server.
The web server recognizes that the HTTP request is for a JSP page and
forwards it to a JSP engine. This is done by using the URL or JSP page
which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet
content. This conversion is very simple in which all template text is converted
to println( ) statements and all JSP elements are converted to Java code.
This code implements the corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards
the original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML
format. The output is furthur passed on to the web server by the servlet
engine inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of
static HTML content.
Finally, the web browser handles the dynamically-generated HTML page
inside the HTTP response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −
Typically, the JSP engine checks to see whether a servlet for a JSP file already
exists and whether the modification date on the JSP is older than the servlet. If the
JSP is older than its generated servlet, the JSP container assumes that the JSP
hasn't changed and that the generated servlet still matches the JSP's contents. This
makes the process more efficient than with the other scripting languages (such as
PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having
to be a Java programming wiz. Except for the translation phase, a JSP page is
handled exactly like a regular servlet.
out javax.servlet.jsp.JspWriter
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
session javax.servlet.http.HttpSession
application javax.servlet.ServletContext
exception javax.servlet.jsp.JspException
page java.lang.Object
pageContext javax.servlet.jsp.PageContext
config javax.servlet.ServletConfig
1.Out: This is used for writing content to the client (browser). It has several
methods which can be used for properly formatting output message to the
browser and for dealing with the buffer.
2.Request: The main purpose of request implicit object is to get the data on a JSP page
which has been entered by user on the previous JSP page. While dealing with login and
signup forms in JSP we often prompts user to fill in those details, this object is then used
to get those entered details on an another JSP page (action page) for validation and other
purposes.
3.Response: It is basically used for modfying or delaing with the response which is
being sent to the client(browser) after processing the request.
4.Session: It is most frequently used implicit object, which is used for storing the
user’s data to make it available on other JSP pages till the user session is active.
5.Application: This is used for getting application-wide initialization parameters and
to maintain useful data across whole JSP application.
6.Exception: Exception implicit object is used in exception handling for displaying
the error messages. This object is only available to the JSP pages, which has
isErrorPage set to true.
Developing a simple JSP web
application
Setting Up the Project
We are going to start by creating a Dynamic Web Project with a minimal
structure, that is with just required facets.
The jspHello node should be visible in the upper-left Package Explorer view.
Figure 5.2. New Web Project
In our simple application we need to create only one JSP page which displays a "Hello
World!" message.
In the next window you can choose a template for your JSP page and see its preview.
o Select New JSP File (xhtml) template and click the Finish button.
Figure 5.3. Create JSP Page
Our hello.jsp page will now appear in the Project Explorer view.
To edit the JSP page so that it displays the “Hello World!” message, insert the following line inside
the <body> </body> tags:
After this line has been added, your hello.jsp page should look like this:
Figure 5.5. Hello.jsp Page Source
This line will actually output "Hello World!" message in the Console. To make the message
displayed in the Browser, just replace this line with the simple Hello World!.
When you are creating web project the wizard creates the web.xml file for you automatically.
The web.xml file editor provided by JBoss Developer Studio is available in two
modes: Tree and Source.
Figure 5.6. Web.xml in Design and Source Mode
Both modes are fully synchronized. To add a mapping to the hello.jsp page in the web.xml file:
If you go back to Tree tab you will see that the changes made in the Source tab are automatically
reflected.
Writing any scripts and managing the packaging process can be quite a complicated and time
consuming task for even the most trivial web applications. However, JBoss Developer
Studio relieves you of this burden. All you need is to start your JBoss Server and launch your
application in your favorite browser.
You can also create a JAR archive with JBoss Developer Studio's Archive Tools and export it to any
web server.
o Select Window → Show view → Other → JBoss Tools → Project archives from the
menu bar
o Select a project in Package Explorer you want to be archived
In the Project Archives view you will see the that the project is now listed:
In the New JAR dialog you can see automatically selected default values.
o Click the Finish button. The .JAR file will appear in Package Explorer and also in Project
Archives view as structure tree:
Figure 5.10. Archive is Created
Using the Project Archives view you can rebuild the archive:
When you create a web application and register it on the JBoss Server it is automatically deployed
into the /deploy directory of the server. JBoss Developer Studio's auto-redeploy feature ensures
you do not need to restart the server. Any changes made in the application in exploded format will
trigger a redeployment on the server.
You can also use the "Finger touch" button for a quick restart of the project without restarting the
server:
JBoss Developer Studio comes with JSP design-time preview features. When designing JSP pages
you can easily preview how they will look during runtime. You can even attach your stylesheet to
the Preview.
o Make a little change to hello.jsp page. For example, insert this piece of code:
<%= new java.util.Date() %>
o Start a JBoss Server from the Servers view by clicking the Start the server icon ( ).
o Click the Run icon or right-click your project folder and select Run As → Run on Server. If
you have not made any changes in the web.xml file or cleared it out you can launch the
application by right clicking the hello.jsp page and selecting Run on the
Server( ).