Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

p---3.1. Java Programming Module

This course module on Java Programming from Bonga University provides an overview of Java, including its key features and data types. It covers variable types, including local, instance, and class/static variables, as well as control structures for decision-making and repetition, such as if statements and loops. Additionally, it introduces arrays and their usage in Java programming.

Uploaded by

yosephsim12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

p---3.1. Java Programming Module

This course module on Java Programming from Bonga University provides an overview of Java, including its key features and data types. It covers variable types, including local, instance, and class/static variables, as well as control structures for decision-making and repetition, such as if statements and loops. Additionally, it introduces arrays and their usage in Java programming.

Uploaded by

yosephsim12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Course Module on Java Programming

BONGA UNIVERSITY

College of Engineering and Technology


Department of Computer Science

Course Module on

JAVA programming (CoSc3053)

January, 2022
Bonga University

1|Page
Course Module on Java Programming

CHAPTER 1: OVERVIEW OF JAVA PROGRAMMING


Java is a high-level programming language originally developed by Sun Microsystems and released in 1995.
Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

Key features of java are:

• 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.

All variables have two important attributes:

 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.

Access modifiers cannot be used for local variables.


Local variables are visible only within the declared method, constructor, or block.
Local variables are implemented at stack level internally. ✓ Default values are not assigned to local
variables in Java.
Example
Let us see an example in which we take local variable to explain it. Here, age is a local variable. This
variable is defined under putAge() method and its scope is limited to this method only:

3|Page
Course Module on Java Programming

public class Dog


{
public void putAge()
{
int age = 0; //local variable
age = age + 6;
System.out.println("Dog age is : " + age);
}
public static void main(String
args[]){ Dog d = new Dog();
d.putAge();
}
}

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

public class Employee { }


public String name; // this instance
public static void main(String args[]) {
variable is visible for any child class.
private double salary; // salary Employee
variable empOne = new
is visible in Employee class only.
Employee("Ransika");
public Employee (String empName) {
name = empName; empOne.setSalary(1000);
} // The salary variable is assigned a
empOne.printEmp();
value. public void setSalary(double
empSal) { salary = empSal; }
}// This method prints the employee
}
details. public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);

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:

• A statement may be simple, block or null statement.


• The” if” keyword is used to execute a statement or block only if a condition is fulfilled.
• Where condition is the expression that is being evaluated. If this condition is true, statement under
the” if” clause will be executed. If it is false, the first set of code after the end of the if statement
will be executed.
For example, the following fragment of code prints "This is if statement" only if the value stored in the x
variable is indeed 100:
if( x ==100 ) {
System.out.print("This is if statement");
}
Conditional structure:
if..else
An if else statement in programming is a conditional statement that runs a different set of statements
depending on whether an expression is true or false.
Syntax: Example if (x == 100)
if (condition) System.out.print ("x is 100");
Statement1; else
else System.out.print ("x is not 100");
Statement2;

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

while (condition) { int x = 10; while(


statement1; … statement x < =20 ) {
n; System.out.print("value of x : " + x );
} x++; }
When executing, if the condition is
true, then the statement inside the loop will be executed. This will continue as long as the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
do…while loop
A do-while loop is similar to while loop except the condition is at the end of the loop. As a result, the loop
always executed at least once, regardless of whether the condition is true or not.
Syntax Example: do…while loop to display numbers from 10 -20 do
{ int x = 10; while(
x < =20 ) {
Statements; }
System.out.print("value of x : " + x );
while(Boolean_expression);
x++; }

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

public class TestArray { public class TestArray {


public static void main(String[] args) public static void main(String[] args)
{ int[] myList = {1, 2., 3, 5}; // { double[] myList = {1.9, 2.9, 3.4,
Print all the array elements for (int 3.5}; // Print all the array elements
i = 0; i < myList.length; i++) { for (double element: myList) {
System.out.println(myList[i] + " "); System.out.println(element);
} }
} }

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.

Chapter 2: Java Applets


Overview of Java Applets
A Java applet is a special kind of Java program that a browser enabled with Java technology can download
from the internet and run. An applet is typically embedded inside a web page and runs in the context of a
browser. Applet class provides the standard interface between the applet and the browser environment. The
Applet class is contained in the java.applet package. Applet contains several methods that give you detailed
control over the execution of your applet. In addition, java.applet package also defines three interfaces:
AppletContext, AudioClip, and AppletStub.

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.

Figure 1Applet inheritance hierarchy


The Applet class is a descendant of the Container class. It can hold other objects. You do not need to create
a panel first to place objects on because the Applet class extends the Panel class. Because the Container

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.

Controlling applet life cycle (An Applet Skeleton)


Four methods in the Applet class give the framework to build any applet: init( ), start( ), stop( ), and destroy()
Applet Initialization and Termination
It is important to understand the order in which the various methods shown in the skeleton are called.
When an applet begins, the AWT calls the following methods, in this sequence:

1. init( ) 2. start( ) 3. paint( )

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.

import java.awt.Graphics; import


java.applet.*; public class WelcomeToApplet
extends Applet { public void init() {
setBackground(Color.black);

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 Applet vs Java Application


Java Application Java Applet
Course Module on Java Programming

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

Chapter 3: Java GUI using JAVAFX


Introduction
JavaFX is a set of graphics and media packages that enables developers to design, create, test, debug, and
deploy rich client applications that operate consistently across multiple platforms. The applications

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.

JAVAFX architecture and Program structure


JavaFX provides a complete API with a rich set of classes and interfaces to build GUI applications with
rich graphics. the following figure illustrates the architectural components of the JavaFX platform.

Figure 3.1 JavaFX Architecture

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.

Media and Images


JavaFX media functionality is available through the javafx.scene.mediaAPIs. JavaFX supports both visual
and audio media. Support is provided for MP3, AIFF, and WAV audio files and FLV video files. JavaFX
media functionality is provided as three separate components: the Media object represents a media file, the
media player plays a media file, and a MediaView is a node that displays the media.
Web Component
The Web component is a JavaFX UI control, based on Web kit, that provides a Web viewer and full
browsing functionality through its API. This Web Engine component is based on WebKit, which is an open
source web browser engine that supports HTML5, CSS, JavaScript, DOM, and SVG. It enables developers
to implement the following features in their Java applications:
▪ Render HTML content from local or remote URL
▪ Support history and provide Back and Forward navigation

20 | P a g e
Course Module on Java Programming

▪ Reload the content


▪ Apply effects to the web component
▪ Edit the HTML content
▪ Execute JavaScript commands
▪ Handle events

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.

JAVAFX layout components


JavaFX layouts are components, which contains other components inside them. The layout component
manages the layout of the components nested inside it. JavaFX layout components are also sometimes
called parent components because they contain child components. javafx.scene.layout package provides
various classes that represents the layouts. The classes are described in the table below.

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

GridPane Organizes the nodes in the form of rows and columns.

21 | P a g e
Course Module on Java Programming

HBox Organizes the nodes in a single row.

Pane It is the base class for all the layout classes.

StackPane Organizes nodes in the form of a stack i.e. one onto another

VBox Organizes nodes in a vertical column.

To create a layout, you need to

• Create node. E.g. Button playButton = new Button("Play");


• Instantiate the respective class of the required layout. E.g. HBox hbox = new HBox();
• Set the properties of the layout. E.g. hbox.setSpacing(10);
• Add all the created nodes to the layout. E.g. Group root = new Group(line);

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:

o Accordion o Menu o TableView o Button o MenuBar o TabPane o


CheckBox o PasswordField o TextArea o ChoiceBox o ProgressBar o
TextField o ColorPicker o RadioButton o TitledPane o ComboBox o Slider o
ToggleButton o DatePicker o Spinner o ToolBar o Label o SplitMenuButton
o TreeTableView o ListView o SplitPane o TreeView

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.

The syntax of addEventHandler()


node.addEventHandler(<EventType>,new EventHandler<Event-Type>()
{
public void handle(<EventType> e)
{
//handling code
}
});

Example
In the following example, the circle starts translating in the positive X direction when the Play button is
clicked

public class JavaFX_EventHandler extends trans.play(); //animation will be


Application{ played when the play button is clicked
public void start(Stage primaryStage) throws }
Exception { event.consume();
Circle c = new Circle(100,100,50); }
c.setFill(Color.GREEN); };
c.setStroke(Color.BLACK); //Adding Handler for the play
Button btn = new Button("Play"); btn.setOnMouseClicked(handler);
btn.setTranslateX(125); //Creating Group and scene
btn.setTranslateY(200); Group root = new Group();
TranslateTransition trans = new root.getChildren().addAll(c,btn,btn1);
TranslateTransition(); Scene scene = new
trans.setAutoReverse(true); Scene(root,420,300,Color.WHEAT);
trans.setByX(200); primaryStage.setScene(scene);
trans.setCycleCount(100); primaryStage.setTitle("EventHandler
trans.setDuration(Duration.millis(500)); example");
trans.setNode(c); primaryStage.show();
//Creating EventHandler
}
EventHandler<MouseEvent> handler =
public static void main(String[] args) {
new EventHandler<MouseEvent>() {
launch(args);
public void handle(MouseEvent event) {
}
if(event.getSource()==btn)
{ }

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);

//Setting color to the stroke


Color color = new Color.DARKSLATEBLUE
circle.setStroke(color);
In the above code block, we are using the static variables of the color class to create a color object.

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);

//creating color object by passing HSB values


Color c = Color.hsb(270,1.0,1.0);

//creating color object by passing the hash code for web


Color c = Color.web("0x0000FF",1.0);
Applying Image Pattern to the Nodes
To apply an image pattern to the nodes, instantiate the ImagePattern class and pass its object to the
setFill(), setStroke() methods.
The constructor of this class accepts six parameters:
• Image − The object of the image using which you want to create the pattern.
• x and y − Double variables representing the (x, y) coordinates of origin of the anchor rectangle.
• height and width − Double variables representing the height and width of the image that is used to
create a pattern.
• isProportional − This is a Boolean Variable; on setting this property to true, the start and end
locations are set to be proportional.
ImagePattern radialGradient = new ImagePattern(dots, 20, 20, 40, 40, false);
Applying Linear Gradient Pattern
To apply a Linear Gradient Pattern to the nodes, instantiate the LinearGradient class and pass its object to
the setFill(), setStroke() methods.
The constructor of this class accepts five parameters:
• startX, startY − These double properties represent the x and y coordinates of the starting point of
the gradient.
• endX, endY − These double properties represent the x and y coordinates of the ending point of the
gradient.
• cycleMethod − This argument defines how the regions outside the color gradient bounds, defined by
the starting and ending points, should be filled.
• proportional − This is a Boolean Variable; on setting this property to true, the start and end locations
are set to a proportion.
• Stops − This argument defines the color-stop points along the gradient line.
//Setting the linear gradient
Stop[] stops = new Stop[] {
new Stop(0, Color.DARKSLATEBLUE),
new Stop(1, Color.DARKRED)
};
LinearGradient linearGradient =
new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, stops);

27 | P a g e
Course Module on Java Programming

Applying Radial Gradient Pattern


To apply a Radial Gradient Pattern to the nodes, instantiate the GradientPattern class and pass its object to
the setFill(), setStroke() methods.
The constructor of this class accepts a few parameters, some of them are:
• startX, startY − These double properties represent the x and y coordinates of the starting point of
the gradient.
• endX, endY − These double properties represent the x and y coordinates of the ending point of the
gradient.
• cycleMethod − This argument defines how the regions outside the color gradient bounds are defined
by the starting and ending points and how they should be filled.
• proportional − This is a Boolean Variable; on setting this property to true the start and end locations
are set to a proportion.
• Stops − This argument defines the color-stop points along the gradient line.
//Setting the radial gradient
Stop[] stops = new Stop[] {
new Stop(0.0, Color.WHITE),
new Stop(0.3, Color.RED),
new Stop(1.0, Color.DARKRED)
};
RadialGradient radialGradient =
new RadialGradient(0, 0, 300, 178, 60, false, CycleMethod.NO_CYCLE, stops);
JavaFX Text
In some of the cases, we need to provide the text based information on the interface of our application. JavaFX
library provides a class named javafx.scene.text.Text for this purpose. This class provides various methods
to alter various properties of the text. We just need to instantiate this class to implement text in our application.
Properties
The properties of JavaFX Text are described in the table below.

Property Description Setter Methods

Boundstype setBoundsType(TextBoundsType value)


This property is of object type. It determines the way
in which the bounds of the text is being calculated.

fontsmoothingType Defines the requested smoothing type for the font.


setFontSmoothingType(FontSmoothingType
value)

Linespacing setLineSpacing(double spacing)


Vertical space in pixels between the lines. It is double
type property.

28 | P a g e
Course Module on Java Programming

Strikethrough setStrikeThrough(boolean value)


This is a boolean type property. We can put a line
through the text by setting this property to true.

Textalignment Horizontal Text alignment setTextAlignment(TextAlignment value)

Textorigin setTextOrigin(VPos value)


Origin of text coordinate system in local coordinate
system.

Text setText(String value)


It is a string type property. It defines the text string
which is to be displayed.

Underline setUnderLine(boolean value)


It is a boolean type property. We can underline the
text by setting this property to true.

Wrappingwidth setWrappingWidth(double value)


Width limit for the text from where the text is to be
wrapped. It is a double type property.

X X coordinate of the text setX(double value)

Y Y coordinate of the text setY(double value)

Creating a text node


The class javafx.scene.text.Text needs to be instantiated in order to create the text node. Use the setter
method setText(string) to set the string as a text for the text class object. Follow the syntax given below to
instantiate the Text class.
Text <text_Object> = new Text();
text.setText(<string-text>);

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:

1. Font(double s) : Creates a font object with specified size.

29 | P a g e
Course Module on Java Programming

30 | P a g e
Course Module on Java Programming

Follow the following instructions to create a Line. o


Instantiate the class javafx.scene.shape.Line. o
set the required properties of the class object.
o Add class object to the group

Properties
Line class contains various properties described below.

Property Description Setter Methods

endX The X coordinate of the end point of the line setEndX(Double)

endY The y coordinate of the end point of the line setEndY(Double)

startX The x coordinate of the starting point of the line setStartX(Double)

startY The y coordinate of the starting point of the line setStartY(Double)

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.

Property Description Setter Methods

centerX X coordinate of the centre of circle setCenterX(Double value)

center Y coordinate of the centre of circle setCenterY(Double value)

Radious Radius of the circle setRadius(Double value)

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

Property Description Setter Method

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)

Height Defines the height of the rectangle setHeight(Double height)

Width Defines the width of the rectangle setWidth(Double width)

X X coordinate of the upper left corner setX(Double X-value)

Y Y coordinate of the upper left corner setY(Double( Y-value)

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

Default Style Sheet


JavaFX uses caspian.css as the default CSS file. It is found in JavaFX Run time JAR file, jfxrt.jar. This style
sheet defines the default style rules for the root node and UI controls. This file is located at the path /jre/lib
under the JDK installation directory. The following command can be used to extract the style sheet from the
JAR file.
# jar xf jfxrt.jar
# com/sun/javafx/scene/control/skin/caspian/caspian.css
Adding Style-sheets to scene
However, JavaFX provides us the facility to override the default style sheet and define our own styles for
every node of the application. The Style-sheet we create, must have the extension .css and it must be located
in the directory where the main class of the application resides.
In JavaFX,there is a specific syntax of applying CSS to the scene. The syntax is given as follows;
Scene scene = new Scene(root,500,400); scene.getStylesheet().add("path/Stylesheet.css");

Defining Styles in StyleSheet


A style definition can be given by using the name of the style which is also known as selecter and series of
the rules that set the properties for the styles. Styling rules are given within the braces. Consider the following
example named as mystyle.css. It defines the style definition for the each button node used in its container
application.
Example
.button {
-fx-font : 14px "serief";
-fx-padding : 10;
-fx-background-color : #CCFF99;
}
Selectors
There are various types of styles used in JavaFX. However, each type considers its own conventions regarding
selectors. Style class selectors naming conventions are,
1. If the style class selector consists of more than one word, use the hyphen between
them.

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

Defining Rules in Style-sheets


The rules for a style definition assigns values to the properties. There are some conventions for the property
names that are given as follows.
1. If the property name consists of more than one word then use hyphen (-) to seperate them.
2. Property name for the styles are preceded by -fx-.
3. Property name and the value are seperated by colon (:).
4. Rules are seperated by the semicolon (;).
Example of defining rules for the properties is as follows.
-fx-background-color : #333356;
-fx-font : 16px "serief";
There is a special style class named as .root defined in javafx. It is applied to the root node of the scene object.
Since all the nodes of the application are the children of the root node therefore, the style rules applied to this
class can be applied to the whole scene graph of the application.
.root
{
-fx-font-family : "serief";
-fx-background1 : rgb(225,227,2255);
}
Class Styles
The class styles can be created by adding its definition to our style sheet. For example;
.label1{
-fx-background-color : rgb(123,126,227);
-fx-padding : 5;
-fx-text-fill : rgb(245,123,201);
}
To add the above mentioned style class to the appropriate node, use the method getStyleClass(). add()
sequence of methods.
Button button = new Button("SUBMIT");
button.getStyleClass().add(button1);
ID Styles
JavaFX provides us the facility to create the style for the individual node. The style name can be given as the
ID name preceded by the hash(#) symbol.
#submit-button{
-fx-font : bold 18pt "serief";
-fx-background-color : rgb(120,190,201);
}

Setting Inline styles


JavaFX facilitates us to define the CSS rules in the JavaFX application code itself. However, the rules defined
in the JavaFX application code is given precedence over styles from the style sheet.
In the following example, we have defined the CSS rules in the code file itself which shows the way by which
the color and the font of a label can be changed using CSS rules.

34 | P a g e
Course Module on Java Programming

Label label1 = new Label("Name: ");

label1.setStyle("-fx-background-color : blue, -fx-text-fill : white");


Properties and Bindings
One of the benefits of using JavaFX is its powerful and comprehensive support for properties and binding.
Among other things, properties let you wire your scene so that the view updates automatically whenever you
modify the data that sits behind it.
Properties
Properties are observable objects that may be writeable, or read-only. There are 30 types of Property object
in JavaFX, including the StringProperty, SimpleListProperty and ReadOnlyObjectProperty. Each property
wraps an existing Java object, adding functionality for listening and binding.
Bindings
Bindings are a way to wire your objects together, enforcing a relationship in which one object is dependant
on at least one other. Properties can be bound natively themselves, as well as by creating Expression and
Binding objects. Expressions and Bindings are observable objects that also depend on the value of at least
one other observable object (but potentially more). That enables you to create expression chains with multiple
calculations: a super-simple way to string together string or number conversions

35 | P a g e
Course Module on Java Programming

Chapter 4: Streams and File I/O


Data stored in variables and arrays is temporary it’s lost when a local variable goes out of scope or when
the program terminates. For long-term retention of data, even after the programs that create the data
terminate, computers use files. Computers store files on secondary storage devices such as hard disks,
optical disks, flash drives and magnetic tapes. Data maintained in files is exists beyond the duration of
program execution.
File is a collection of related records those are containing fields and which represent data or information.
Java provides us the feature of manipulating these files either at the byte or character level. It also provides
the facility of reading and writing these files.

Input output streams


Stream refers to the transfer of data either to or from a storage medium. In file processing the input refers
to flow of data from a file means we can read the contents from a file with the help of java program and
output refers giving some text in the java’s program and this will write the data into the file which is
specified. But for doing this java uses a concept of streams which defines the interface between the
input/output and between the programs. There are two Streams those are provided by JAVA for reading or
writing the contents into a File.
1. Input Stream -- It reads the data from the source or file and send to the program.
2. Output Stream -- It takes the program and then it writes this data to it’s another destination file.

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.

o read() –Used to read a byte from input stream. o read(bytes


b[]) –It reads an array of bytes into b.
o read(byte b[], int n, int m) –It reads array of byte into b those
are equals to m and must start from n.
o Skip(n) –It skips the n bytes while taking input from a file. o
reset( ) – This will Set the File Pointer to beginning of a File.
o Close( ) –For closing streams

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 Stream Classes

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

Output and Input of Complex Objects


The writeObject and readObject methods are simple to use, but they contain some very sophisticated object
management logic. This isn't important for a class like Calendar, which just encapsulates primitive values.
But many objects contain references to other objects. If readObject is to reconstitute an object from a stream,
it has to be able to reconstitute all of the objects the original object referred to. These additional objects
might have their own references, and so on. In this situation, writeObject traverses the entire web of object
references and writes all objects in that web onto the stream. Thus a single invocation of writeObject can
cause a large number of objects to be written to the stream. This is demonstrated in the following figure,
where writeObject is invoked to write a single object named a. This object contains references to objects b
and c, while b contains references to d and e. Invoking writeobject(a) writes not just a, but all the objects
necessary to reconstitute a, so the other four objects in this web are written also. When a is read back by
readObject, the other four objects are read back as well, and all the original object references are preserved.

I/O of multiple referred-to objects

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

Object ob1 = in.readObject();


Object ob2 = in.readObject();
This results in two variables, ob1 and ob2, that are references to a single object.
However, if a single object is written to two different streams, it is effectively duplicated a single program
reading both streams back will see two distinct objects.

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.

5.2. Multithreading in java


If your class is intended to be executed as a thread, then you can achieve this in two ways first implementing
a Runnable interface and second by extending a Thread class we are going to see both ways in this chapter
step by step.
Create a Thread by Implementing a Runnable Interface
You will need to follow three basic steps:

Step 1: As a first step, you need to implement a run () method provided by a Runnable interface. This
method provides an entry point for the thread and you will put your complete business logic inside this
method. Following is a simple syntax of the run () method:
public void run ()
Step 2: As a second step, you will instantiate a Thread object using the following constructor:
Thread (Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the
name given to the new thread.
Step 3: Once a Thread object is created, you can start it by calling start () method, which executes a call
to run () method. Following is a simple syntax of start () method:
void start ();
Example 8: Following is the example to demonstrate threads using runnable interface

42 | P a g e
Course Module on Java Programming

class MyThread implements Runnable


{
String threadName; public MyThread (String
threadName) {
this.threadName = threadName;
System.out.println("Thread created");
}
@Override public void run ()
{
for (int i = 0; i < 10; i++) {
System.out.println(threadName + i); try {
Thread.sleep (1000);
} catch (InterruptedException ex) {
System.out.println("Error "+ex.getMessage());
}
}
}
} public class JavaThread {
public static void main (String [] args) {
Thread t = new Thread (new MyThread ("Thread one"));
t.start ();
Thread t2 = new Thread (new MyThread ("Thread two")); t2.start ();
}}

Create a Thread by Extending a Thread Class


The second way to create a thread is to create a new class that extends Thread class using the following
two simple steps. This approach provides more flexibility in handling multiple threads created using
available methods in Thread class.
Step 1: You will need to override run () method available in Thread class. 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 run () method:
public void run ()
Step 2: Once 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 9: Following is the example to demonstrate threads using Thread class

43 | P a g e
Course Module on Java Programming

class MyThread extends Thread {


String threadName; public MyThread (String
threadName) {
this.threadName = threadName;
System.out.println("Thread created");
}
@Override public void
run()
{ for (int i = 0; i < 10; i++) {
System.out.println(threadName + i); try
{
Thread.sleep(1000);
} catch (InterruptedException ex)

{ 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();
}}

5.3. Thread priorities


Every Java thread has a priority that helps the operating system determine the order in which threads are
scheduled. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a
constant of 5). Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which
threads execute and are very much platform dependent. We can set the priorities of threads using setPriority
() method.

public final void setPriority (int i)

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);

5.4. Synchronized and Unsynchronized threads


When we start two or more threads within a program, there may be a situation when multiple threads try to
access the same resource and finally, they can produce unforeseen result due to concurrency issues. For
example, if multiple threads try to write within a same file then they may corrupt the data because one of
the threads can override data or while one thread is opening the same file at the same time another thread
might be closing the same file.

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.

Chapter 6: Networking in java


5.5. Networking
This chapter presents key concepts of intercommunication between programs running on different
computers in the network. It introduces elements of network programming and concepts involved in
creating network applications using sockets. The chapter introduces the java.net package containing various
classes required for creating sockets and message communication using two different protocols. At a basic
level, network-based systems consist of a server, client, and a media for communication. A computer

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.

6.2. Socket programming


6.2.1. URL manipulation
URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a
Web page or FTP directory. This section shows you how to write Java programs that communicate with a
URL. A URL can be broken down into parts, as follows:
protocol://host:port/path?query#ref
Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the filename,
and the host is also called the authority. The following is a URL to a web page whose protocol is HTTP:
http://www.amrood.com/index.htm?language=en#j2se
Notice that this URL does not specify a port, in which case the default port for the protocol is used. With
HTTP, the default port is 80.
The java.net.URL class represents a URL and has a complete set of methods to manipulate URL in Java.
The URL class has several constructors for creating URLs, including the following:
Sr. No. Methods with Description

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.

3 public URL (String url) throws MalformedURLException


Creates a URL from the given String.

4 public URL (URL context, String url) throws MalformedURLException


Creates a URL by parsing together the URL and String arguments.

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

1 public String getPath (): Returns the path of the URL.

2 public String getQuery (): Returns the query part of the URL.

46 | P a g e
Course Module on Java Programming

3 public String getAuthority (): Returns the authority of the URL.

4 public int getPort (): Returns the port of the URL.

5 public int getDefaultPort (): Returns the default port for the protocol of the URL.

6 public String getProtocol (): Returns the protocol of the URL.

7 public String getHost (): Returns the host of the URL.

8 public String getHost (): Returns the host of the URL.

9 public String getFile (): Returns the filename of the URL.

10 public String getRef (): Returns the reference part of the URL.

11 public URLConnection openConnection () throws IOException: Opens a connection to the


URL, allowing a client to communicate with the resource.

6.2.2. Socket programming implementation


Sockets provide the communication mechanism between two computers using TCP. A client program
creates a socket on its end of the communication and attempts to connect that socket to a server. When the
connection is made, the server creates a socket object on its end of the communication. The client and the
server can now communicate by writing to and reading from the socket. The java.net.Socket class represents
a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for
clients and establish connections with them. The following steps occur when establishing a TCP connection
between two computers using sockets:
• The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
• The server invokes the accept () method of the ServerSocket class. This method waits until a client
connects to the server on the given port.
• After the server is waiting, a client instantiates a Socket object, specifying the server name and the
port number to connect to.
• The constructor of the Socket class attempts to connect the client to the specified server and the
port number. If communication is established, the client now has a Socket object capable of
communicating with the server.
• On the server side, the accept () method returns a reference to a new socket on the server that is
connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket has both an
OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and
the client's InputStream is connected to the server's OutputStream. TCP is a two-way communication
protocol; hence data can be sent across both streams at the same time. The following Greeting Client is a
client program that connects to a server by using a socket and sends a greeting, and then waits for a response.

47 | P a g e
Course Module on Java Programming

import java.io. * import


java.net.Socket; public class
GreetingClient {
public static void main(String [] args) { String serverName =
"localhost"; final int port = 1245;
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket (serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer); out.writeUTF("Hello from " +
client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer); System.out.println("Server says " +
in.readUTF()); client.close();
}
catch (IOException e) {
System.out.println("Error " + e.getMessage());
}
}
}

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();

}catch (SocketTimeoutException s){


System.out.println("Socket timed out!"); break;
} catch (IOException e) {
System.out.println("Error "+e.getMessage()); break; }
}
} public static void main(String[] args)
{

int port = 1245;try


{
Thread t = new GreetingServer(port);
t.start();
} catch (IOException e) {
System.out.println("Error "+e.getMessage());
}
}
}
48 | P a g e
Course Module on Java Programming

6.3. Remote method invocation


6.3.1. Remote Message Invocation (RMI)
The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another JVM. The
RMI provides remote communication between the applications using two objects stub and skeleton. RMI
uses stub and skeleton object for communication with the remote object. A remote object is an object whose
method can be invoked from another JVM. Let's understand the stub and skeleton objects:

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

It initiates a connection with remote Virtual Machine (JVM),


It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
It waits for the result
It reads (unmarshals) the return value or exception, and ✓ It finally, returns the value to
the caller.

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

It reads the parameter for the remote method


It invokes the method on the actual remote object, and
It writes and transmits (marshals) the result to the caller.

public interface Registry extends Remote {

public static final int REGISTRY_PORT = 1099;

public Remote lookup(String name) throws Rem oteException, NotBoundException, AccessException;

public void bind(String name, Remote obj) throws RemoteException, AlreadyBoundException, AccessException;

public void unbind(String name) throws RemoteException, NotBoundException, AccessException;


public void rebind(String name, Remote obj) throws RemoteException, AccessException;
49 | P a g e
public String[] list( ) throws RemoteException, AccessException;
}

50 | P a g e
Course Module on Java Programming

6.3.2. Register of RMI


The RMI registry is implemented as an RMI server. Underlying Naming’s static methods is an interface
that extends Remote and an implementation of that interface. In Java 2, these are:
The java.rmi.registry.Registry interface This extends Remote and defines the methods an
implementation of Registry must implement.
The sun.rmi.registry.RegistryImpl implementation class This is an actual RMI server that
implements the Registry interface.
The Registry interface is straightforward. It defines five methods, each of which maps directly to one of
the static methods defined in Naming:
Lookup (): It returns the reference of the remote object.
Bing (): It binds the remote object with the given name.
Unbind (): It destroys the remote object which is bound with the given name.
Rebind (): It binds the remote object to the new name.
List (): It returns an array of the names of the remote objects bound in the registry.

6.3.3. Remote interface and implementation of RMI


The Remote Interface represents the type of an object handle and tells clients how to invoke remote
methods. The remote class defines those objects. The interface definition must be public, must extend the
interface java.rmi.Remote and every method in the interface must declare that it throws
java.rmi.RemoteException (but other exceptions may be thrown as well)
Now let’s see a sample program in which a client program invokes a remote method with string as a
parameter then the sever returns a string containing the reversed input string and a message. We define an
interface for a remote class that includes one remote method: say accepts a String as an input parameter and
returns a String as a result. Note that the interface extends Remote and that each method (there’s only one
here) throws Remote Exception.
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

Chapter 7: Java Database Connectivity


7.1. Database and SQL
A database provides various functions like data security, data integrity, data sharing, data concurrence, data
independence, data recovery etc. However, all database management systems that are now available in the
market like Sybase, Oracle, and MS-Access do not provide the same set of functions, though all are meant
for data management. Almost all relational database management systems use SQL (Structured Query
Language) for data manipulation and retrieval. SQL is the standard language for relational database
systems. SQL is a non-procedural language, where you need to concentrate on what you want, not on how
you get it. Put it in other way, you need not be concerned with procedural details. SQL Commands are
divided into four categories, depending upon what they do.

DDL (Data Definition Language)


DML (Data Manipulation Language)
DCL (Data Control Language) and Query (Retrieving data)
7.2. JDBC programming
JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent
connectivity between the Java programming language, and a wide range of databases. The JDBC library
includes APIs for each of the tasks mentioned below that are commonly associated with database usage.

 Making a connection to a database.


 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database. ➢ Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable
access to an underlying database. Java can be used to write different types of executables, such as:

 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.

7.2.1. JDBC components


 DriverManager: This class manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication subprotocol. The first
driver that recognizes a certain subprotocol under JDBC will be used to establish a database
Connection.

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.

7.2.2. The JDBC packages


The java.sql and javax.sql are the primary packages for JDBC. It offers the main classes for interacting with
your data sources. These packages have the following common features.

• Automatic database driver loading.


• Exception handling improvements.
• Enhanced BLOB/CLOB functionality.
• Connection and statement interface enhancements.
• National character set support.
• SQL ROWID access.
• SQL 2003 XML data type support.
• Annotations.

57 | P a g e
Course Module on Java Programming

7.2.3. Executing Database Quires


Creating database

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

60 | P a g e Course Module on Java Programming


String sql = "CREATE TABLE REGISTRATION (id INTEGER not NULL, "
+ " first VARCHAR(255),last VARCHAR(255),age INTEGER, "
+ " PRIMARY KEY ( id ))"; stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}} catch (SQLException | ClassNotFoundException se) {

}
}

Inserting, deleting and updating data to and from the 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;
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

Selecting and extracting data from 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 {
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

Chapter 8: Introduction Servlets


8.1. Servlets and Architecture of servlets
Java Servlets are programs that run on a Web or Application server and act as a middle layer between a
request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from a database
or another source, and create web pages dynamically. Servlets perform the following tasks:

• 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

8.2. HTTP Requests


One of the keys to creating effective servlets is understanding how to manipulate the Hypertext Transfer
Protocol (HTTP). Thoroughly understanding this protocol is not an esoteric, theoretical concept, but rather
a practical issue that can have an immediate impact on the performance and usability of your servlets. This
section discusses the HTTP information that is sent from the browser to the server in the form of request
headers. It explains the most important HTTP 1.1 request headers, summarizing how and why they would
be used in a servlet. Reading headers is straightforward; just call the getHeader method of
HttpServletRequest with the name of the header. This call returns a String if the specified header was
supplied in the current request, null otherwise. In HTTP 1.0, all request headers are optional; in HTTP 1.1,

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"

+ "<B>Request Method: </B>" + request.getMethod()


+ "<BR>\n" + "<B>Request URI: </B>"

+ 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");

Enumeration headerNames = request.getHeaderNames(); while


(headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement(); out.println("<TR><TD>" + headerName);
out.println(" <TD>" + request.getHeader(headerName));
}
out.println("</TABLE>\n</BODY></HTML>");
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { doGet(request, response);
}
}

67 | P a g e
Course Module on Java Programming

8.3. Servlet Programming Example using GET method


Following is the sample source code structure of a servlet example to show Hello World: Note the message
will be displayed on the web.

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

Course Module on Java Programming

+ "<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></html>");
}
}
8.4. Servlet Programming Example using POST method

// Import required java libraries import java.io.*;


Here is a simple example which passes two values using HTML FORM and submit button. We are going
to import javax.servlet.*;
use same Servlet HelloForm to handle this input.import javax.servlet.http.*;
// Extend HttpServlet class

public class HelloForm extends HttpServlet { // Method to


handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type 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";

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>"
);
}

// Method to handle POST method request.


Course Module on Java Programming

<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>

here is the actual output of the above form.

First Name: Last Name: Submit


Try to enter First Name and Last Name and then click submit button to see the result on
your local machine where tomcat is running. Based on the input provided, it will generate similar result as
mentioned in the above example.

64 | P a g e

You might also like