p---3.1. Java Programming Module
p---3.1. Java Programming Module
BONGA UNIVERSITY
Course Module on
January, 2022
Bonga University
1|Page
Course Module on Java Programming
• Object Oriented
• Platform Independent
• Simple
• Secure
• Architecture-neutral
• Portable
• Robust
Data type and Variables
A data type is a classification of data which tells the compiler or interpreter how the programmer intends to
use the data. specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:
1. Primitive data types: are predefined by the language and named by a keyword. The primitive data
types include Boolean, char, byte, short, int, long, float and double.
2. Reference/Object Data Types: are those which contains reference/address of dynamically created
objects. The non-primitive data types include Classes, Interfaces, and Arrays.
To declare a variable using a reference type, you simply list the class name as the data type. For
example, the following statement defines a variable that can reference objects created from a class
named Ball:
Ball b;
A variable is a container for information you want to store. variable provides us with named storage that our
programs can manipulate. Each variable in Java has a specific type, which determines the size and layout
of the variable's memory; the range of values that can be stored within that memory; and the set of operations
that can be applied to the variable.
A type which is established when the variable is defined (e.g., int, float, char).
2|Page
Course Module on Java Programming
A value which can be changed by assigning a new value to the variable, the kind of values a
variable can assume depends on its type. For example, an integer variable can only take integer
values (e.g., 2, 100, -12).
We could have called the variables any names we wanted to invent, as long as they were valid identifiers.
A valid identifier is a sequence of one or more letters, digits or underscores characters (_). Neither spaces
nor punctuation marks or symbols can be part of an identifier. Only letters, digits and underscore characters
are valid. In addition, variable identifiers always have to begin with a letter or underscore (_). In no case
they can begin with a digit. Another rule that you have to consider when inventing your own identifiers is
that they cannot match many keywords of the java language. The java language is a "case sensitive"
language. That means that an identifier written in capital letters is not equivalent to another one with the
same name but written in small letters. Thus, for example, the RESULT variable is not the same as the
result variable or the Result variable. These are three different variable identifiers. You must declare all
variables before they can be used. Syntax:
data type variable_Name = value; value is optional because in java, we can
accept the value from the keyboard.
The following are valid examples of variable declaration and initialization in Java: -
int a, b, c; // Declares three ints, a, b, and c. int a = 10, b =
10; // Example of initialization double pi = 3.14159; // declares
and assigns a value of pi. char a = 'a'; // the char variable a
iis initialized with value 'a'
Types of Variables
There are three kinds of variables in Java: -
1. Local variables
2. Instance variables
3. Class/Static variables
Local Variables
A local variable is a variable declared inside a method body, block or constructor. It means variable is only
accessible inside the method, block or constructor that declared it.
3|Page
Course Module on Java Programming
Instance Variables
Instance variables are non-static variables and are declared in a class outside any method, constructor, or
block.
Instance variables are created when an object is created with the use of the keyword 'new' and
destroyed when the object is destroyed.
Access modifiers can be given for instance variables. If we do not specify any access modifier, then
the default access modifier will be used.
Initialization of instance variable is not mandatory. Its default value is 0 for numbers, false for
Booleans and null for object references.
Example
4|Page
Course Module on Java Programming
Class/Static Variables
Class variables/static variables are declared with the static keyword in a class, but outside a method,
constructor or a block.
• There would only be one copy of each class variable per class, regardless of how many objects are
created from it.
• Static variables are rarely used other than being declared as constants. Constants are variables that
are declared as public/private, final, and static. Constant variables never change from their initial
value.
• Static variables are stored in the static memory. It is rare to use static variables other than declared
final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program stops.
• Visibility is similar to instance variables. However, most static variables are declared public since
they must be available for users of the class.
• Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it
is false; and for object references, it is null. Values can be assigned during the declaration or within
the constructor. Additionally, values can be assigned in special static initializer blocks.
• Static variables can be accessed by calling with the class name ClassName.VariableName.
• When declaring class variables as public static final, then variable names (constants) are all in upper
case. If the static variables are not public and final, the naming syntax is the same as instance and
local variables. Example public class Employee { private static double salary; // salary variable
is a private static variable
// DEPARTMENT is a constant public static final
String DEPARTMENT = "Development "; public static
void main(String args[]) { salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
Decision and Repetition statement
A program is usually not limited to a linear sequence of instructions. During its process it may divide, repeat
code or take decisions. For that purpose, java provides control structures that serve to specify what has to
be done by our program, when and under which circumstances. The decision and repetition statements
manage the flow of execution in a program. Statements represent the lowest-level building blocks of a
program.
Decision making structures have one or more conditions to be evaluated or tested by the program, along
with a statement or statements that are to be executed if the condition is determined to be true, and optionally,
5|Page
Course Module on Java Programming
other statements to be executed if the condition is determined to be false. Java programming language
provides following types of decision-making statements.
1. conditional statement
2. switch statement
Conditional statement: if
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
if (condition)
Statement1; Note:
The above example fragment of code prints on the screen x is 100 if indeed x has a value of 100, but if it
has not it prints out x is not 100.
Note: If this condition is true, statement under the” if” clause will be executed. If it is false, statement under
else clause will be executed.
6|Page
Course Module on Java Programming
Nested if statement
You can use one if or else if statement inside another if or else if statement(s).
Syntax
if(condition 1) {
statements;
if(condition 2) {
statements;
}
}
Switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a
case, and the variable being switched on is checked for each case.
Syntax Example
switch(expression) switch (operator) {
{case constant 1 :
case '+': result = operand1 + operand2; break;
Statements;
break; // optional case case '-': result = operand1 - operand2; break;
constant 2: case '*': result = operand1 * operand2; break;
Statements;
case '/': result = operand1 / operand2; break;
break; // optional
… default: System.out.println ("unknown operator ");
default: // Optional break;
Statements;
}
}
For example, the above switch statement performs the operation and stored the value to result based on the
selected operator.
Iterative statement(Loop)
A loop statement allows us to execute a statement or group of statements multiple times. Java programming
language provides the following types of loop to handle looping requirements.
• while loop
• do-while loop • for loop while loop
While loop executes a set of statements as long as the condition specified at the beginning is true. The
condition is evaluated at the beginning of the loop.
Syntax: Example: to display numbers from 10 -20
7|Page
Course Module on Java Programming
The output is the same as of the while loop above. The difference is when the condition is false at the
beginning itself. E.g if we have assigned ‘x’ a value 21 in the beginning instead of 10, the while loop will
not execute even once as the condition is evaluated in the beginning, but the do-while loop will execute at
least once (value of x:21 will be displayed) as the condition is evaluated only at the end of the first iteration.
The for loop
The for statement (also called for loop) is similar to the while statement, but has two additional components:
an expression which is evaluated only once before everything else, and an expression which is evaluated
once at the end of each iteration.
Syntax:
for(initialization; Boolean_expression; update) {
Statements:
}
Here is the flow of control in a for loop:
1. The initialization step is executed first, and only once.
2. The Boolean expression is evaluated if it is true the loop continues, otherwise the loop ends and
statement is skipped (not executed).
3. After the body of the for loop gets executed, the control jumps back up to the update statement. This
statement allows you to update any loop control variables.
8|Page
Course Module on Java Programming
4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats
(body of loop, then update step, then Boolean expression). After the Boolean expression is false, the
for loop terminates.
Example, fragment of code to display numbers from 10-20 using for loop.
for(int x = 10; x <= 20; x = x + 1) {
System.out.print(x );
}
}
Arrays
Array is collection of a fixed number of variables of the same type stored sequentially in the memory. An
item in the array is called Element. Dimension refers to size of the array. An array is a series of elements of
the same type placed in contiguous memory locations that can be individually referenced by adding an index
instead of declaring individual variables.
For example, we can store 5 values of type int in an array without having to declare 5 different variables,
each one with a different identifier.
Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array. An array variable is defined
by specifying its dimension and the type of its elements.
Syntax:
dataType[] arrayName; // preferred way. or dataType
arrayName []; // works but not preferred way.
Array objects occupy space in memory. Like other objects, arrays are created with keyword new. To create
an array object, you specify the type of the array elements and the number of elements as part of an array-
creation expression that uses keyword new. Such an expression returns a reference that can be stored in an
array variable. The following declaration and array-creation expression create an array object containing 12
int elements and store the array’s reference in array variable c:
int[] c = new int[ 12 ];
Processing of an array usually involves a loop which goes through the array element by element. The
following examples show how to create, initialize, and process arrays.
9|Page
Course Module on Java Programming
JDK 1.5 introduced a new for loop known as for each loop or enhanced for loop, which enables you to
traverse the complete array sequentially without using an index variable as you look in the second example.
Passing Arrays to a Methods
To pass an array argument to a method, specify the name of the array without any brackets. For example, if
array hourlyTemperatures is declared as double[] hourlyTemperatures = new double[ 24 ];
then the method call modifyArray(
hourlyTemperatures );
passes the reference of array hourlyTemperatures to method modifyArray(). Every array object “knows”
its own length (via its length field). Thus, when we pass an array object’s reference into a method, we need
not pass the array length as an additional argument.
The Arrays Class
The java.util.Arrays class contains various static methods for common array manipulations. These methods
include sort for sorting an array (i.e., arranging elements into increasing order), binarySearch for searching
an array (i.e., determining whether an array contains a specific value and, if so, where the value is located),
equals for comparing arrays and fill for placing values into an array. These methods are overloaded for
primitive-type arrays and for arrays of objects.
Exception-Handling
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an
exception is a runtime error. An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out of
memory.
10 | P a g e
Course Module on Java Programming
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner. Java’s exception handling avoids these problems and, in the
process, brings run-time error management into the object-oriented world.
Exception-Handling Fundamentals
A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a
piece of code. When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error. That method may choose to handle the exception itself, or pass
it on. Either way, at some point, the exception is caught and processed. Exceptions can be generated by the
Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to
fundamental errors that violate the rules of the Java language or the constraints of the Java execution
environment. Manually generated exceptions are typically used to report some error condition to the caller
of a method.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Here is how
they work. Program statements that you want to monitor for exceptions are contained within a try block. If
an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch) and
handle it in some rational manner. System-generated exceptions are automatically thrown by the Java
runtime system. To manually throw an exception, use the keyword throw. Any exception that is thrown out
of a method must be specified as such by a throws clause. Any code that absolutely must be executed after
a try block completes is put in a finally block.
This is the general form of an exception-handling block: try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ... finally
{
// block of code to be executed after try block ends
}
Here, ExceptionType is the type of exception that has occurred.
11 | P a g e
Course Module on Java Programming
Basic Syntax
It is very important to keep in mind the following points about java programs.
▪ Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different
meaning in Java.
▪ Class Names - For all class names the first letter should be in upper case. If several words are used
to form a name of the class, each inner word's first letter should be in upper case. Example: class
MyFirstJavaClass
▪ Method Names - All method names should start with a lower case letter. If several words are used
to form the name of the method, then each inner word's first letter should be in upper case. Example:
public void myMethodName()
▪ Program File Name - Name of the program file should exactly match the class name. When saving
the file, you should save it using the class name (Remember Java is case sensitive) and append '.java'
to the end of the name (if the file name and the class name do not match, your program will not
compile). Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
▪ public static void main(String args[]) - Java program processing starts from the main() method
which is a mandatory part of every Java program.
Applets must also import java.awt. Since all applets run in a window, it is necessary to include support for
that window by importing java.awt package. Applets are not executed by the console-based Java run-time
interpreter. Rather, they are executed by either a Web browser or an applet viewer. Execution of an applet
does not begin at main( ). Output to your applet’s window is not performed by System.out.println( ). Rather,
it is handled with various AWT methods, such as drawString( ), which outputs a string to a specified X,Y
location. Input is also handled differently than in an application. Once an applet has been compiled, it is
12 | P a g e
Course Module on Java Programming
included in an HTML file using the APPLET tag. The applet will be executed by a Java-enabled web
browser when it encounters the APPLET tag within the HTML file. The Applet Class
Applet extends the AWT class Panel. In turn, Panel extends Container, which extends Component. These
classes provide support for Java’s window-based, graphical interface. Thus, Applet provides all of the
necessary support for window-based activities. Applet Architecture
An applet is a window-based program. As such, its architecture is different from the so-called normal,
console-based programs. First, applets are event driven. it is important to understand in a general way how
the event driven architecture impacts the design of an applet. Here is how the process works. An applet
waits until an event occurs. The AWT notifies the applet about an event by calling an event handler that has
been provided by the applet. Once this happens, the applet must take appropriate action and then quickly
return control to the AWT.
13 | P a g e
Course Module on Java Programming
class is derived from the Component class, we have the ability to respond to events, grab and display images,
and display text among many other things.
Let us see some of the methods you have access to because of all the classes that have been extended to get
to the Applet class.
setBackground(Color): Sets the background color.
setFont(Font): Sets the font of the component.
setForeground(Color): Sets the foreground color. show():
Shows the component.
setColor(Color): sets the color for the image to be draw.
When an applet is terminated, the following sequence of method calls takes place:
1. stop( ) 2. destroy( )
init( ):init( ) method is called once the first time an applet is loaded. The init( ) method is the first method
to be called. This is where you should initialize variables.
start():The start( ) method is called after init( ). It is also called to restart an applet after it has been
stopped(i.e start() method is called every time, the applet resumes execution).
paint():The paint( ) method is called each time your applet’s output must be redrawn. This situation can
occur for several reasons. For example, the window in which the applet is running may be overwritten by
another window and then uncovered or the applet window may be minimized and then restored. paint( ) is also
called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint(
) is called. The paint( ) method has one parameter of type Graphics. stop( ):The stop() method is called
when the applet is stopped(i.e for example ,when the applet is minimized the stop method is called).
14 | P a g e
Course Module on Java Programming
destroy( ):The destroy( ) method is called when the environment determines that your applet needs to be
removed completely from memory(i.e destroy() method is called when the applet is about to terminate).The
stop( ) method is always called before destroy( ).
Writing your first applet program
A simple applet program that displays a welcome message.
15 | P a g e
Course Module on Java Programming
setForeground(Color.green);
}
public void paint(Graphics g){
g.drawString("Welcome to applet programming.", 100, 100);
}}
Java Applications are the stand-alone programs which can Java Applets are small Java programs which are
be executed independently designed to exist within HTML web document
Java Applications must have main() method for them to
Java Applets do not need main() for execution
execute
Java Applets cannot run independently and require
Java Applications just needs the JRE
API’s
Java Applications do not need to extend any class unless
Java Applets must extend java.applet.Applet class
required
Java Applications can execute codes from the local system Java Applets Applications cannot do so
Java Applications has access to all the resources available Java Applets has access only to the browser-specific
in your system services
16 | P a g e
17 | P a g e
Course Module on Java Programming
developed using JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs,
Tablets, etc.
To develop GUI Applications using Java programming language, the programmers rely on libraries such
as Advanced Windowing Toolkit and Swings. After the advent of JavaFX, the Java programmers can now
develop GUI applications effectively with rich content.
Features of JavaFX
Following are some of the important features of JavaFX: -
▪ Written in Java: The JavaFX library is written in Java and is available for the languages that can
be executed on a JVM.
▪ FXML: JavaFX features a language known as FXML, which is a HTML like declarative markup
language. The sole purpose of this language is to define a user Interface.
▪ Scene Builder: JavaFX provides an application named Scene Builder. On integrating this
application in IDE’s such as Eclipse and NetBeans, the users can access a drag and drop design
interface.
▪ Swing Interoperability: In a JavaFX application, you can embed Swing content using the Swing
Node class.
▪ Built-in UI controls: JavaFX library caters UI controls using which we can develop a full-featured
application.
▪ CSS like Styling: JavaFX provides a CSS like styling. By using this, you can improve the design
of your application with a simple knowledge of CSS.
▪ Rich set of API’s: JavaFX library provides a rich set of API’s to develop GUI applications, 2D
and 3D graphics, etc.
18 | P a g e
Course Module on Java Programming
Scene Graph
In JavaFX, the GUI Applications were coded using a Scene Graph. Scene Graph is the starting point for
constructing a JavaFX application. It is a hierarchical tree of nodes that represents all of the visual elements
of the application's user interface. A single element in a scene graph is called a node. Each node has an ID,
style class, and bounding volume.
The javafx.scene API allows the creation and specification of several types of content, such as:
▪ Nodes: Shapes (2-D and 3-D), images, media, embedded web browser, text, UI controls, charts,
groups, and containers
▪ State: Transforms (positioning and orientation of nodes), visual effects, and other visual state of
the content
▪ Effects: Simple objects that change the appearance of scene graph nodes, such as blurs, shadows,
and color adjustment
Java Public APIs for JavaFX Features
The top layer of the JavaFX architecture shown in Figure3.1 provides a complete set of public APIs that
support rich client application development. These new Java APIs for JavaFX features:
• Allow the use of powerful Java features, such as generics, annotations, and multithreading.
• Make it easier for Web developers to use JavaFX from other JVM-based dynamic languages, such
as Groovy, and JavaScript.
• Allow Java developers to use other system languages, such as Groovy, for writing large or complex
JavaFX applications.
• Extend the Java collections library to include observable lists and maps, which allow applications
to wire user interfaces to data models, observe changes in those data models, and update the
corresponding UI control accordingly.
Graphics System
The JavaFX Graphics System is an implementation detail beneath the JavaFX scene graph layer. It
supports both 2-D and 3-D scene graphs. It provides software rendering when the graphics hardware on a
system is insufficient to support hardware accelerated rendering.
Two graphics accelerated pipelines are implemented on the JavaFX platform:
▪ Prism processes render jobs. It can run on both hardware and software renderers, including 3-D.
It is responsible for rasterization and rendering of JavaFX scenes. The following multiple render
paths are possible based on the device being used: o DirectX 9 on Windows XP and Windows
Vista o DirectX 11 on Windows 7 o OpenGL on Mac, Linux, Embedded
19 | P a g e
Course Module on Java Programming
▪ Quantum Toolkit ties Prism and Glass Windowing Toolkit together and makes them available to
the JavaFX layer above them in the stack. It also manages the threading rules related to rendering
versus events handling.
Glass Windowing Toolkit
The Glass Windowing Toolkit is the lowest level in the JavaFX graphics stack. Its main responsibility is to
provide native operating services, such as managing the windows, timers, and surfaces. It serves as the
platform-dependent layer that connects the JavaFX platform to the native operating system. Threads
The system runs two or more of the following threads at any given time.
▪ JavaFX application thread: This is the primary thread used by JavaFX application developers.
▪ Prism render thread: This thread handles the rendering separately from the event dispatcher.
▪ Media thread: This thread runs in the background and synchronizes the latest frames through the
scene graph by using the JavaFX application thread.
Pulse
A pulse is an event that indicates to the JavaFX scene graph that it is time to synchronize the state of the
elements on the scene graph with Prism. A pulse is throttled at 60 frames per second (fps) maximum and is
fired whenever animations are running on the scene graph. Even when animation is not running, a pulse is
scheduled when something in the scene graph is changed. For example, if a position of a button is changed,
a pulse is scheduled.
When a pulse is fired, the state of the elements on the scene graph is synchronized down to the rendering
layer. A pulse enables application developers a way to handle events asynchronously. This important
feature allows the system to batch and execute events on the pulse.
20 | P a g e
Course Module on Java Programming
CSS
JavaFX Cascading Style Sheets (CSS) provides the ability to apply customized styling to the user interface
of a JavaFX application without changing any of that application's source code. CSS can be applied to any
node in the JavaFX scene graph and are applied to the nodes asynchronously. JavaFX CSS styles can also
be easily assigned to the scene at runtime, allowing an application's appearance to dynamically change.
UI Controls
The JavaFX UI controls available through the JavaFX API are built by using nodes in the scene graph. They
can take full advantage of the visually rich features of the JavaFX platform and are portable across different
platforms. JavaFX CSS allows for theming and skinning of the UI controls. These controls reside in the
javafx.scene.control package.
Class Description
BorderPane Organizes nodes in top, left, right, center and the bottom of the screen.
FlowPane Organizes the nodes in the horizontal rows according to the available horizontal
spaces. Wraps the nodes to the next line if the horizontal space is less than the total
width of the nodes
21 | P a g e
Course Module on Java Programming
StackPane Organizes nodes in the form of a stack i.e. one onto another
UI Controls
JavaFX controls are JavaFX components which provide some kind of control functionality inside a JavaFX
application. For instance, a button, radio button, table, tree etc. For a control to be visible it must be attached
to the scene graph of some Scene object. Controls are usually nested inside some JavaFX layout component
that manages the layout of controls relative to each other.
JavaFX contains the following controls:
Event Handling
In JavaFX, An event is occurred whenever the user interacts with the application nodes. There are various
sources by using which, the user can generate the event. For example, User can make the use of mouse or
it can press any button on the keyboard or it can scroll any page of the application in order to generate an
event. Hence, we can say that the events are basically the notifications that tell us that something has
occurred at the user's end.
22 | P a g e
Course Module on Java Programming
The javafx.event package provides the basic framework for JavaFX events. The Event class serves as the
base class for JavaFX events. Associated with each event is an event source, an event target, and an event
type.
• Source — GUI objects (e.g., a Button object) which generate an ActionEvent (e.g., when the button
is clicked). The source implements the EventTarget interface.
• Listener — An object that subscribes (listens) for a particular type of event to occur. The listener
must implement an interface like EventHandler or InvalidationListener1.
• Type — An additional classification that are used to specify the specific type of event. For example,
a MouseEvent has the following types: ANZ, MOUSE_CLICKED, MOUSE_PRESSED,
MOUSE_RELEASED, MOUSE_MOVED, MOUSE_DRAGGED, MOUSE_ENTERED,
MOUSE_EXITED, MOUSE_ENTERED_TARGET, MOUSE_EXITED_TARGET,
DRAG_DETECTED.
The operating system or windowing system captures generated events and notifies the listener objects when
a type of event they are listening for has occurred. The operating system notifies the listener object by
sending a message to (calling) the event handling method. If no listener object is subscribed to listen for
the event that occurred, the event is ignored.
Types of Events
In general, the events are mainly classified into the following two types.
1. Foreground Events – are mainly occurred due to the direct interaction of the user with the GUI of
the application. Such as clicking the button, pressing a key, selecting an item from the list, scrolling
the page, etc.
2. Background Events – doesn't require the user's interaction with the application. These events are
mainly occurred to the operating system interrupts, failure, operation completion, etc. Event
Delivery Process
1. Route Construction
2. Event Capturing Phase
3. Event Bubbling
4. Event Handlers and Filters
EventHandler
JavaFX facilitates us to use the Event Handlers to handle the events generated by Keyboard Actions, Mouse
Actions, and many more source nodes.
Adding an Event Handler
Event Handler must be registered for a node in order to process the events in the event bubbling phase.
Event handler is the implementation of the EventHandler interface. The handle() method of the interface
contains the logic which is executed when the event is triggered.
23 | P a g e
Course Module on Java Programming
To register the EventHandler, addEventHandler() is used. In this method, two arguments are passed. One
is event type and the other is EventHandler object.
Example
In the following example, the circle starts translating in the positive X direction when the Play button is
clicked
24 | P a g e
Course Module on Java Programming
Shapes
The Shape class provides definitions of common properties for objects that represent some form of geometric
shape. These properties include:
The Paint to be applied to the fillable interior of the shape.
The Paint to be applied to stroke the outline of the shape.
The decorative properties of the stroke, including:
• The width of the border stroke.
• Whether the border is drawn as an exterior padding to the edges of the shape, as an interior
edging that follows the inside of the border, or as a wide path that follows along the border
straddling it equally both inside and outside.
• Decoration styles for the joins between path segments and the unclosed ends of paths.
25 | P a g e
Course Module on Java Programming
• Dashing attributes.
Color
In JavaFX, we can fill the shapes with colors. To apply colors to an application, JavaFX provides various
classes in the package javafx.scene.paint package. This package contains an abstract class called Paint and
it is the base class of all the classes that are used to apply colors. These classes are Color, ImagePattern,
LinearGradient, RadialGradient. Using these classes, you can apply colors in the following patterns −
Uniform − In this pattern, color is applied uniformly throughout node.
Image Pattern − This lets you to fill the region of the node with an image pattern.
Gradient − In this pattern, the color applied to the node varies from one point to the other. It has two
kinds of gradients namely Linear Gradient and Radial Gradient.
The JavaFX Color class represents a solid (uniform) color. To create a JavaFX Color instance you use its
constructor. The JavaFX Color constructor takes four parameters: Red, Green, Blue and Alpha.
The ImagePattern class fills a shape with an image pattern. The user may specify the anchor rectangle, which
defines the position, width, and height of the image relative to the upper left corner of the shape. The
LinearGradient class fills a shape with a linear color gradient pattern. The user may specify two or more
gradient colors, and this Paint will provide an interpolation between each color.
The RadialGradient class provides a way to fill a shape with a circular radial color gradient pattern. The user
may specify two or more gradient colors, and this paint will provide an interpolation between each color. All
those node classes to which you can apply color such as Shape, Text (including Scene), have methods named
setFill() and setStroke(). These will help to set the color values of the nodes and their strokes respectively.
These methods accept an object of type Paint. Therefore, to create either of these type of images, you need to
instantiate these classes and pass the object as a parameter to these methods.
Applying Color to the Nodes
To set uniform color pattern to the nodes, you need to pass an object of the class color to the setFill(),
setStroke() methods as follows.
//Setting color to the text Color
color = new Color.BEIGE
text.setFill(color);
26 | P a g e
Course Module on Java Programming
In the same way, you can also use the RGB values or HSB standard of coloring or web hash codes of colors
as shown below.
//creating color object by passing RGB values
Color c = Color.rgb(0,0,255);
27 | P a g e
Course Module on Java Programming
28 | P a g e
Course Module on Java Programming
JavaFX Font
By default, the Text Class in JavaFX is responsible for creating and displaying text does not have many
options to change the appearance of the text itself. However, the JavaFX Font class comes equipped with the
necessary options required to modify various things regarding the text, like its size, font-family, positioning
etc. The JavaFX Font Class is represented by javafx.scene.text.Font.
Constructors of the class:
29 | P a g e
Course Module on Java Programming
30 | P a g e
Course Module on Java Programming
Properties
Line class contains various properties described below.
Cirlce
A circle is a special type of ellipse with both of the focal points at the same position. Its horizontal radius is
equal to its vertical radius. JavaFX allows us to create Circle on the GUI of any application by just
instantiating javafx.scene.shape.Circle class. Just set the class properties by using the instance setter methods
and add the class object to the Group.
Properties
The class properties along with the setter methods and their description are given below in the table.
31 | P a g e
Course Module on Java Programming
Rectangle
Rectangles can be defined as the geometrical figure consists of four sides, out of which, the opposite sides are
always equal and the angle between the two adjacent sides is 90 degree. A Rectangle with four equal sides is
square. JavaFX library allows the developers to create a rectangle by instantiating javafx.scene.shape.
Rectangle class.
Properties
ArcHeight Vertical diameter of the arc at the four corners of rectangle setArcHeight(Double height)
ArcWidth Horizontal diameter of the arc at the four corners of the rectangle setArcWidth(Double Width)
CSS Styling
CSS (Cascading Style Sheets) is a design language which is used to enhance the appearance of the web pages
without changing its functionality. It only deals with the way, a web page is presented on the web browser.
By using CSS, we can define the color, size, font styles, spacing between the paragraph, alignment and many
more thing for a web page so that it can look more precise and better. We can also configure the background
of the application, layout, design and variety of display for the different size devises.
CSS in JavaFX
JavaFX, being the new generation UI library, provides the facility to configure the theme of the application.
JavaFX provides the package javafx.css which contains all the classes to apply the CSS to the JavaFX
application. Applying CSS to the JavaFX application is similar to applying CSS to the HTML page. In this
part of the tutorial, we will discuss styling rules and the steps to invoke them in JavaFX.
32 | P a g e
Course Module on Java Programming
2. Style class selector names are preceded by a dot(.) Examples of the selectors are:
.button
.check-box
.label
the style for a particular node can be defined by using the node's ID. This ID can be set using setId() method.
Use the # symbol before the Node_ID to make a style name for that node. For example, the node having id
my_label can have the following type of selector name.
#my_label
33 | P a g e
Course Module on Java Programming
34 | P a g e
Course Module on Java Programming
35 | P a g e
Course Module on Java Programming
Stream Classes
The java.io package provides us the large number of stream classes to perform input and output (I/O) in
Java. The stream classes in the java.io package supports many data such as primitives, object, characters,
etc. All these streams classes represent an input source and an output destination. These classes are
divided into groups.
1) Byte Stream Classes -- For handling the operation on files at the byte level.
2) Character Stream Classes – For handling the operation on files at the character level. And this
Stream uses 16-bit character codes.
Byte Stream Classes
Byte-based streams input and output data in its binary format. If the value 5 were being stored using a byte-
based stream, it would be stored in the binary format of the numeric value 5, or 101. Files that are created
36 | P a g e
Course Module on Java Programming
using byte-based streams are referred to as binary files. Byte Stream classes are in divided in two groups
for handling input and output operation.
1) InputStream Classes - These classes are subclasses of an abstract class InputStream and they are
used to read bytes from a source(file, memory or console).
2) OutputStream Classes - These classes are subclasses of an abstract class OutputStream and they
are used to write bytes to a destination(file, memory or console).
Let's see a little bit more about the two abstract classes InputStream and OutputStream.
InputStream Class
InputStream class is a base class of all the classes that are used to read bytes from a file, memory or console.
InputStream is an abstract class and hence we can't create its object but we can use its subclasses for reading
bytes from the input stream. Some of the subclasses of InputStream class are FileInputStream,
DataInputStream, BufferedInputStream and StringBufferInputStream and many more. The InputStream
class contains various methods to read the data from an input stream. These methods are overridden by the
classes that inherit the InputStream class. The following methods are inherited by InputStream subclasses.
OutputStream class
Output stream classes are used to write 8-bit bytes to a stream. The OutputStream class is the superclass for
all byte-oriented output stream classes. OutputStream is an abstract class and hence we can't create its object
but we can use its subclasses for writing bytes to the output stream. Some of the subclasses of OutputStream
class are BufferedOutputStream, ByteArrayOutputStream, DataOutputStream, FileOutputStream,
FilterOutputStream, ObjectOutputStream and many more. The OutputStream class provides various
methods to write bytes to the output streams. The following are some of the methods.
37 | P a g e
Course Module on Java Programming
o write( ) –It writes a byte to output stream. o write(byte b( )) – It writes all the array of bytes b into
output stream. o write(byte b, int n, int m) – It writes all the array of bytes from nth position those
are equal to m. o close( ) – It closes the output stream.
o flush( ) – It flushes or pushing the output stream.
Character streams are defined by using two class hierarchies. At the top are two abstract classes: Reader
and Writer. These abstract classes handle Unicode character streams. Java has several concrete subclasses
of each of these for handling input and output operations.
1) Reader Stream Classes – These are designed for reading the characters it is the base class of all
other classes and it is used for handling all the methods like the input stream but these are used for reading
the characters.
2) Writer Stream Classes -- These are used for performing all output operations on files just like the
output stream classes but the difference is that these are used for writing characters rather than bytes.
Object Streams
Just as data streams support I/O of primitive data types, object streams support I/O of objects. Most, but not
all, standard classes support serialization of their objects. Those that do implement the marker interface
Serializable.The object stream classes are ObjectInputStream and ObjectOutputStream. These classes
implement ObjectInput and ObjectOutput, which are subinterfaces of DataInput and DataOutput. That
means that all the primitive data I/O methods covered in Data Streams are also implemented in object
streams. So an object stream can contain a mixture of primitive and object values. The ObjectStreams
example illustrates this. ObjectStreams creates the same application as DataStreams, with a couple of
changes. First, prices are now BigDecimalobjects, to better represent fractional values.
Second, a Calendar object is written to the data file, indicating an invoice date.
If readObject() doesn't return the object type expected, attempting to cast it to the correct type may throw a
ClassNotFoundException. In this simple example, that can't happen, so we don't try to catch the exception.
Instead, we notify the compiler that we're aware of the issue by adding ClassNotFoundException to the
main method's throws clause.
38 | P a g e
Course Module on Java Programming
You might wonder what happens if two objects on the same stream both contain references to a single
object. Will they both refer to a single object when they're read back? The answer is "yes." A stream can
only contain one copy of an object, though it can contain any number of references to it. Thus if you
explicitly write an object to a stream twice, you're really writing only the reference twice. For example, if
the following code writes an object ob twice to a stream:
Object ob = new Object();
out.writeObject(ob); out.writeObject(ob);
Each writeObject has to be matched by a readObject, so the code that reads the stream back will look
something like this:
39 | P a g e
Course Module on Java Programming
File Management
Several other classes that would be going through to get to know the basics of File navigation and I/O.
• File Class • FileReader Class •
FileWriter Class File Class
The File class is Java’s representation of a file or directory path name. Because file and directory names
have different formats on different platforms, a simple string is not adequate to name them. The File class
contains several methods for working with the path name, deleting and renaming files, creating new
directories, listing the contents of a directory, and determining several common attributes of files and
directories.
The various methods those are provided by the File class are :-
▪ getName :- Gives Name of File
▪ getPath :- Gives Relative Path Means Directory but not Drive.
▪ getAbsolutePath – Gives Complete Path With a Drive ▪ getParent :- Whether it has a
Parent Directory or not.
▪ canExists:- Whether this File is Exists or not.
▪ canWrite :- Can we Write into this File
▪ canRead :- Can We read the Contents from the File
▪ isDirectory :- Whether it is a Directory or a File
▪ lastModified :- Gives Date and Time of Last Accessed
▪ length :- Gives Length of a File depending on the Number of Characters in a File.
List of constructors to create a File object.
Constructor Description
40 | P a g e
Course Module on Java Programming
File(File parent, String child) It creates a new File instance from a parent abstract pathname and a child
pathname string.
File(String pathname)
It creates a new File instance by converting the given pathname string into an
abstract pathname.
File(String parent, It creates a new File instance from a parent pathname string and a child
String child) pathname string.
File(URI uri) It creates a new File instance by converting the given file: URI into an
abstract pathname.
When we are doing any operations related with Files there may some occurrence of exceptions, which stops
the execution of current program. So that they must be handled the most important exceptions those might
have occurred are: -
▪ EOF Exception – It tells us that this is the end point of file at the input time.
▪ File Not Found Exception.
▪ IOException -- It tells that an IO Exception of some sort has occurred.
For handling the file, input output follows the following steps.
▪ Select the filename
▪ Declare the file object.
▪ Specify the name of the file object declared.
▪ Declaring a file stream object.
▪ Connect the file to the file stream object. For exp.
1. file my=new file(mytext/.text);
2. file reader fr=new file reader(my);
3. fr.read( );
Chapter 5: Multithreading
5.1. Multithreading and processes
Java is a multi-threaded programming language which means we can develop multithreaded program using Java. A
multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task
41 | P a g e
Course Module on Java Programming
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. Multithreading allows you to do
multiple tasks at the same time.
A process is a program at execution including the current values of program counter, registers and variables processes
have their own resources. Threads are also called light weight process a single process could have a multiple thread
which are sharing the same resources but they are being executed individually one another. Threads are called light
weight processes because the doesn’t have their own resource since they share the processes recourse. 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.
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 ();
Example 8: Following is the example to demonstrate threads using runnable interface
42 | P a g e
Course Module on Java Programming
43 | P a g e
Course Module on Java Programming
{ System.out.println("Error "+ex.getMessage());
}
}
}
} public class JavaThread
{ public static void main(String[] args) {
MyThread myThread1=new MyThread("Thread one"); myThread1.start();
MyThread myThread2=new MyThread("Thread two"); myThread2.start();
}}
44 | P a g e
Course Module on Java Programming
The above tables show the structure of setPriority method. The following example shows how to set a
priority of thread.
myThread2.setPriority(Thread.MIN_PRIORITY);
myThread2.setPriority(Thread.NORM_PRIORITY);
myThread2.setPriority(Thread.MAX_PRIORITY);
So, there is a need to synchronize the action of multiple threads and make sure that only one thread can
access the resource at a given point in time. This is implemented using a concept called monitors. Each
object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time
may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing their task by
using synchronized blocks. You keep shared resources within this block. Following is the general form of
the synchronized statement:
synchronized(objectidentifier) {
// Access shared variables and other shared resources }
Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the
synchronized statement represents.
45 | P a g e
Course Module on Java Programming
running a program that makes a request for services is called client machine. A computer running a program
that offers requested services from one or more clients is called server machine. The media for
communication can be wired or wireless network. Java has a huge library to perform networking Tasks.
Sockets provide an interface for programming networks at the transport layer. Network communication
using Sockets is very much similar to performing fi le I/O. In fact, socket handle is treated like fi le handle.
The streams used in fi le I/O operation are also applicable to socket-based I/O. Socket-based communication
is independent of a programming language used for implementing it. That means, a socket program written
in Java language can communicate to a program written in non-Java (say C or C++) socket program.
1 public URL (String protocol, String host, int port, String file) throws
MalformedURLException Creates a URL by putting together the given parts.
2 public URL (String protocol, String host, String file) throws MalformedURLException
Identical to the previous constructor, except that the default port for the given protocol is used.
The URL class contains many methods for accessing the various parts of the URL being represented. Some
of the methods in the URL class include the following:
Sr. No. Methods with Description
2 public String getQuery (): Returns the query part of the URL.
46 | P a g e
Course Module on Java Programming
5 public int getDefaultPort (): Returns the default port for the protocol of the URL.
10 public String getRef (): Returns the reference part of the URL.
47 | P a g e
Course Module on Java Programming
48 | P a g e
Course Module on Java Programming
The following GreetingServer program is an example of a server application that uses the Socket class to
listen for clients on a port number specified by a command-line argument: This example uses some thread
concept so, beware of that.
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{ private static ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{ serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000); }
@Override public void
run()
{ while (true)
{ try
{
System.out.println("Waiting " + serverSocket.getLocalPort() + "..."); Socket server = serverSocket.accept();
System.out.println("Connected to "+ server.getRemoteSocketAddress());
DataInputStream in= new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out= new DataOutputStream(server.getOutputStream()); out.writeUTF("Thank "+
server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
Stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through
it. It resides at the client side and represents the remote object. When the caller invokes method on
the stub object, it does the following tasks
The skeleton is an object, acts as a gateway for the server side object. All the incoming requests
are routed through it. When the skeleton receives the incoming request, it does the following tasks
public void bind(String name, Remote obj) throws RemoteException, AlreadyBoundException, AccessException;
50 | P a g e
Course Module on Java Programming
52 | P a g e
Course Module on Java Programming
The remote class defines two methods: Hello is our constructor and will be used by the server to set define
the standard message that will always be sent back to the client. say is a method that takes a string as the
input. It returns a string containing the input with the characters reversed followed by a newline followed
by our standard message (set in the constructor). the class extends UnicastRemoteObject this will allow the
methods to be invoked remotely the class implements the interface we defined each method must throw
RemoteException because remote procedure calls might fail the say method accepts a String and returns
a String. String is defined to be Serializable. If you were to accept or return an object you defined, it would
have to be defined to implement Serializable.
The server is a plain program that is responsible for two things: 1, creating and installing a security
manager. We do this with: System.setSecurityManager (new RMISecurityManager ()); The security
manager makes sure that classes that get loaded do not perform operations that they are not allowed to
perform. 2, Registering at least one remote object with the object registry. We do this with:
Naming.rebind (object_name, object); where object name is a String that names the remote object and
object is the remote object that we are registering. All that our server does is: set the security manager
create the remote object register it print a message saying “Server is running…”.
53 | P a g e
Course Module on Java Programming
The client invokes the remote method. To do this, the client must have a handle (reference) to the remote
object. The object registry allows the client to get this reference to a remote object. To get the reference
to the remote object, we need to know three things: 1, Internet name (or address) of machine that is
running the object registry for which the remote object is registered (can omit if localhost). 2, Port on
which the object registry is running (can omit if it is 1099 - default). 3, Name of the object within the
object registry. The Naming.lookup method obtains an object handle from the object registry running
on localhost on the default port (we could have just looked up “Hello” in this case). The result of
Naming.lookup must be cast to the type of the Remote Interface. The remote invocation of the object
is the call to hello.say(“abc”). It returns a String which we print. Remember again, that we can get a
String only because String is a Serializable class.
54 | P a g e
Course Module on Java Programming
55 | P a g e
Course Module on Java Programming
Java Applications.
Java Applets.
Java Servlets.
Java server pages (JSP)
Java enterprise edition (JEE)
All of these different executables are able to use a JDBC driver to access a database, and take advantage
of the stored data. JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.
56 | P a g e
Course Module on Java Programming
Driver: This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages
objects of this type. It also abstracts the details associated with working with Driver objects.
Connection: This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection
object only.
Statement: You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored procedures.
ResultSet: These objects hold data retrieved from a database after you execute an SQL query using
Statement objects. It acts as an iterator to allow you to move through its data.
SQLException: This class handles any errors that occur in a database application.
57 | P a g e
Course Module on Java Programming
package jframedemo;
import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "username"; static final String PASS =
"password";
public static void main(String [] args)
{
Connection conn;
Statement stmt; try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database..."); conn =
DriverManager.getConnection(DB_URL, USER, PASS); //STEP 4: Execute a query
System.out.println("Creating database..."); stmt = conn.createStatement();
String sql = "CREATE DATABASE STUDENTS"; stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
} catch (SQLException | ClassNotFoundException se) {
System.out.println("Error "+se.getMessage()); }
}
}
Creating table
import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username"; static final String PASS =
"password";
public static void main(String[] args) { Connection conn;
Statement stmt; try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database..."); conn =
DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
| P a g e System.out.println("Creating table in given database..."); stmt =
conn.createStatement();
58
Course Module on Java Programming
}
}
Statement stmt;
String sql; try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database..."); conn =
DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a insertion query
System.out.println("Inserting records into the table..."); stmt = conn.createStatement();
sql = "INSERT INTO Registration VALUES (100, 'Zara', 'Ali',18)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
//STEP 4: Execute a update query sql = "UPDATE Registration SET age = 30 WHERE id
in (100, 101)";
stmt.executeUpdate(sql);
System.out.println("Update records from the table...");
//STEP 4: Execute a delete query sql = "DELETE FROM
Registration WHERE id = 100";
stmt.executeUpdate(sql);
System.out.println("Delete records from the table...");
} catch (SQLException | ClassNotFoundException se) { System.out.println("Error "+se.getMessage());
} }
57} | P a g e
Course Module on Java Programming
62 | P a g e
Course Module on Java Programming
import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username"; static final String PASS =
"password";
public static void main(String[] args) { Connection conn;
Statement stmt; try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database..."); conn =
DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Creating statement..."); stmt = conn.createStatement();
String sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
//Extract data from result set while (rs.next()) {
//Retrieve by column name int id =
rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.println("ID: " + id);
System.out.println(", Age: " + age);
System.out.println(", First: " + first); System.out.println(", Last: " + last);
} rs.close();
} catch (SQLException | ClassNotFoundException se) { System.out.println("Error "+se.getMessage());
}}
}
64 | P a g e
Course Module on Java Programming
• Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page
or it could also come from an applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media
types and compression schemes the browser understands, and so forth.
• Process the data and generate the results. This process may require talking to a database, executing
an RMI or CORBA call, invoking a Web service, or computing the response directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a
variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
• Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or
other clients what type of document is being returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.
The following diagram shows the position or architecture of Servlets in a Web Application
65 | P a g e
Course Module on Java Programming
only Host is required. So, always check for null before using a request header. Header names are not case
sensitive. So, for example, request.getHeader ("Connection") is interchangeable with
request.getHeader("connection"). Although getHeader is the general-purpose way to read incoming
headers, a few headers are so commonly used that they have special access methods in HttpServletRequest.
Following is a summary.
Sr. No. Methods with Description
1 getCookies () The getCookies method returns the contents of the Cookie header, parsed and stored in an
array of Cookie objects. This method is discussed in more detail in Chapter 8 (Handling Cookies).
2 getAuthType () and getRemoteUser () The getAuthType and getRemoteUser methods break the
Authorization header into its component pieces.
3 getContentLength () The getContentLength method returns the value of the Content-Length header (as an
int).
4 getContentType () The getContentType method returns the value of the Content-Type header (as a String).
5 getDateHeader () and getIntHeader () The getDateHeader and getIntHeader methods read the specified
headers and then convert them to Date and int values, respectively.
6 getHeaderNames () Rather than looking up one particular header, you can use the getHeaderNames
method to get an Enumeration of all header names received on this particular request. This capability is
illustrated in Section 5.2 (Making a Table of All Request Headers).
7 getHeaders () In most cases, each header name appears only once in the request. Occasionally, however,
a header can appear multiple times, with each occurrence listing a separate value. Accept-Language is one
such example. You can use getHeaders to obtain an Enumeration of the values of all occurrences of the
header.
8 getMethod () The getMethod method returns the main request method (normally, GET or POST, but
methods like HEAD, PUT, and DELETE are possible).
9 getRequestURI the getRequestURI method returns the part of the URL that comes after the host and port
but before the form data. For example, for a URL of
http://randomhost.com/servlet/search.BookSearch?subject=jsp, getRequestURI would return
"/servlet/search.BookSearch".
The following java code shows all the request headers sent on the current request
66 | P a g e
Course Module on Java Programming
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class
ShowRequestHeaders extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n"; out.println(docType + "<HTML>\n" +
"<HEAD><TITLE>"
+ title + "</TITLE></HEAD>\n"
+ "<BODY BGCOLOR=\"#FDF5E6\">\n"
+ "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n"
+ request.getRequestURI() + "<BR>\n"
+ "<B>Request Protocol: </B>"
+ request.getProtocol() + "<BR><BR>\n"
+ "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
+ "<TR BGCOLOR=\"#FFAD00\">\n"
+ "<TH>Header Name<TH>Header Value");
67 | P a g e
Course Module on Java Programming
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*; public class HelloWorld extends
HttpServlet {
private String message;
public void init() throws ServletException {
message = "Hello World";
} public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>");
} public void destroy() {
}
}
Reading Form Data using Servlet: Servlets handles form data parsing automatically using the following
methods depending on the situation:
getParameter (): You call request.getParameter() method to get the value of a form parameter
getParameterValues (): Call this method if the parameter appears more than once and returns
multiple values, for example checkbox.
getParameterNames (): Call this method if you want a complete list of all parameters in the
current request.
Given below is the HelloForm.java servlet program to handle input given by web browser. We are going to
use getParameter () method which makes it very easy to access passed information:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data"; String
docType
= "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
62 | P a g
eout.println(docType
+
"<html>\n"
Course Module on Java Programming
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>
63 | P a g e </html>"
);
}
<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" /> </form>
</body>
</html>
64 | P a g e