19.paper XIX - JAVA 2022
19.paper XIX - JAVA 2022
Rajnish
AIMIT Kankarbagh, Patna
Contents
Java JDK, JRE and JVM................................................................................................................. 5
JRE? ............................................................................................................................................ 5
JDK? ........................................................................................................................................... 5
Relationship between JVM, JRE, and JDK. ............................................................................... 6
Java Identifiers ................................................................................................................................ 8
Rules ....................................................................................................................................... 8
Variable in Java ........................................................................................................................ 8
How to declare variables? ....................................................................................................... 9
How to initialize variables? .................................................................................................... 9
Types ..................................................................................................................................... 10
Local Variables ......................................................................................................................... 10
Instance Variables .................................................................................................................... 10
Operators in Java........................................................................................................................... 10
Ways to read input from console in Java .................................................................................. 12
Using Buffered Reader Class ................................................................................................ 12
Decision Making in Java............................................................................................................... 15
if ................................................................................................................................................ 15
If-else ........................................................................................................................................ 16
Switch-case ........................................................................................................................... 19
Jump ...................................................................................................................................... 19
Loops......................................................................................................................................... 20
While loop............................................................................................................................. 20
For loop ................................................................................................................................. 21
Do while ................................................................................................................................ 23
Jagged Array in Java ................................................................................................................. 24
Classes and Objects....................................................................................................................... 25
Classes................................................................................................................................... 25
Object .................................................................................................................................... 25
Declaring Objects.................................................................................................................. 25
Initializing an object ............................................................................................................. 25
Packages ........................................................................................................................................ 27
1
String class .................................................................................................................................. 30
String Methods ...................................................................................................................... 30
Interfaces ................................................................................................................................... 33
Applet ............................................................................................................................................ 36
JFrame ....................................................................................................................................... 38
Buttons ...................................................................................................................................... 40
Text Fields ................................................................................................................................ 41
JTextArea .................................................................................................................................. 42
J Combo Box:- .......................................................................................................................... 43
Checkbox:- ................................................................................................................................ 46
JRadioButton class:- ................................................................................................................. 48
Dialog class ............................................................................................................................... 50
J-Option .................................................................................................................................. 52
Slider ......................................................................................................................................... 52
Progress Bar:-............................................................................................................................ 53
Tables:- ................................................................................................................................. 54
Event Handling ......................................................................................................................... 54
Delegation Event Model ....................................................................................................... 54
Event Classes ............................................................................................................................ 56
Event Listener Interface ............................................................................................................ 56
ActionEvent and ActionListener............................................................................................... 56
MouseEvent and MouseListener............................................................................................... 58
WindowEvent and WindowListener ......................................................................................... 63
KeyEvent and KeyListener ....................................................................................................... 65
Exceptions in Java......................................................................................................................... 68
What is an Exception? .................................................................................................................. 68
Error vs Exception ................................................................................................................ 68
Exception Hierarchy ............................................................................................................. 68
Types of Exceptions ............................................................................................................. 69
Built-in Exceptions ............................................................................................................... 69
User-Defined Exceptions ...................................................................................................... 69
Java finally block .................................................................................................................. 70
2
User-defined Custom Exception ........................................................................................... 72
File Handling ............................................................................................................................ 73
Stream ....................................................................................................................................... 73
Byte Stream ........................................................................................................................... 74
Character Stream ................................................................................................................... 74
File Operations .......................................................................................................................... 75
Create a New File ................................................................................................................. 75
Write into a File ............................................................................................................................ 76
Multithreading........................................................................................................................... 77
Thread Control Methods ........................................................................................................... 77
Thread Life Cycle ..................................................................................................................... 77
Socket Programming ................................................................................................................. 79
Socket Programming ............................................................................................................. 80
What is a Socket........................................................................................................................ 80
Client Side Programming .......................................................................................................... 80
Establish a Connection .......................................................................................................... 81
Server Side Programming ......................................................................................................... 82
Communication ......................................................................................................................... 82
TCP/IP........................................................................................................................................... 84
Mechanism for Socket Programming ................................................................................... 84
Client-Side Programming ..................................................................................................... 85
Connection: ........................................................................................................................... 85
Communication:.................................................................................................................... 85
Terminating Connection: .......................................................................................................... 86
Implementation: ........................................................................................................................ 86
Server-Side Programming ......................................................................................................... 87
Communication:........................................................................................................................ 87
Terminating Connection: .......................................................................................................... 88
Implementation: ........................................................................................................................ 88
Execution .................................................................................................................................. 90
UDP Protocol:-.......................................................................................................................... 91
UDP Header Format ............................................................................................................. 92
3
JDBC:- .......................................................................................................................................... 93
JDBC Architecture ................................................................................................................ 93
JDBC-ODBC Bridge Driver ..................................................................................................... 94
DriverManager class ..................................................................................................................... 94
java.sql Package ........................................................................................................................ 95
SQL Exception class ............................................................................................................. 95
4
Java JDK, JRE and JVM
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java
program.
When you run the Java program, Java compiler first compiles your Java code to bytecode. Then,
the JVM translates bytecode into native machine code (set of instructions that a computer's CPU
executes directly).
Java is a platform-independent language. It's because when you write Java code, it's ultimately
written for JVM but not your physical machine (computer). Since JVM executes the Java bytecode
which is platform-independent, Java is platform-independent.
JRE?
JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java
Virtual Machine (JVM), and other components that are required to run Java applications.
JDK?
JDK (Java Development Kit) is a software development kit required to develop applications in
Java. When you download JDK, JRE is also downloaded with it.JRE, JDK also contains a number
of development tools (compilers, JavaDoc, Java Debugger, etc).
5
Relationship between JVM, JRE, and JDK.
Java Development Kit (JDK) is a software development environment used for developing Java
applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader
(Java), a compiler (javac), an archive (jar), a documentation generator (Javadoc), and other tools
needed in Java development.
Now we need an environment to make a run of our program. Henceforth, JRE stands for “Java
Runtime Environment” and may also be written as “Java RTE.” The Java Runtime Environment
provides the minimum requirements for executing a Java application; it consists of the Java
Virtual Machine (JVM), core classes, and supporting files.
Now let us discuss JVM, which stands out for java virtual machine. It is as follows:
A specification where the working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
An implementation is a computer program that meets the requirements of the JVM
specification.
Runtime Instance Whenever you write a java command on the command prompt to run the
java class, an instance of JVM is created.
Before proceeding to the differences between JDK, JRE, and JVM, let us discuss them in brief
first and interrelate with the image below being proposed.
6
1. JDK (Java Development Kit) is a Kit that provides the environment to develop and
execute(run) the Java program. JDK is a kit(or package) that includes two things
a) Development Tools(to provide an environment to develop your java programs)
b) JRE (to execute your java program)
2. JRE (Java Runtime Environment) is an installation package that provides an environment
to only run (not develop) the java program(or application)onto your machine. JRE is only
used by those who only want to run Java programs that are end-users of your system.
3. JVM (Java Virtual Machine) is a very important part of both JDK and JRE because it is
contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into
JVM and JVM is responsible for executing the java program line by line, hence it is also
known as an interpreter.
7
Java Identifiers
Identifiers are used for identification purposes. In Java, an identifier can be a class name, method
name, variable name, or label.
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
In the above java code, we have 5 identifiers namely:
Test: class name.
Main: method name.
String: predefined class name.
args : variable name.
a: variable name.
Rules
There are certain rules for defining a valid java identifier. These rules must be followed,
otherwise we get compile-time error.
The only allowed characters for identifiers are all alphanumeric characters ([A-Z],[a-
z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “geek@” is not a valid java
identifier as it contain ‘@’ special character.
Identifiers should not start with digits ([0-9]). For example “123geeks” is a not a valid
java identifier.
Java identifiers are case-sensitive.
There is no limit on the length of the identifier but it is advisable to use an optimum
length of 4 – 15 letters only.
Reserved Words can’t be used as an identifier. For example “int while = 20;” is an
invalid statement as while is a reserved word. There are 53 reserved words in Java.
Variable in Java
It is a data container that saves the data values during Java program execution. Every variable is
assigned a data type that designates the type and quantity of value it can hold. Variable is a memory
location name of the data.
A variable is a name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
In Java, all the variables must be declared before use.
8
How to declare variables?
Illustrations:
float simpleInterest;
// Declaring float variable
int time = 10, speed = 20;
// Declaring and Initializing integer variable
char var = 'h';
9
// Declaring and Initializing character variable
Types
1. Local Variables
2. Instance Variables
3. Static Variables
Local Variables
A variable defined within a block or method or constructor is called a local variable.
These variables are created when the block is entered, or the function is called and destroyed
after exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variable is declared. i.e.,
we can access these variables only within that block.
Initialization of the local variable is mandatory before using it in the defined scope.
Instance Variables
Instance variables are non-static variables and are declared in a class outside any method,
constructor, or block.
As instance variables are declared in a class, these variables are created when an object of the
class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifier for instance variables. If we do not specify
any access specifier, then the default access specifier will be used.
Initialization of Instance Variable is not mandatory. Its default value is 0
Instance Variable can be accessed only by creating objects.
Static Variables
Static variables are also known as Class variables.
These variables are declared similarly as instance variables. The difference is that static
variables are declared using the static keyword within a class outside any method constructor
or block.
Unlike instance variables, we can only have one copy of a static variable per class irrespective
of how many objects we create.
Static variables are created at the start of program execution and destroyed automatically when
execution ends.
Initialization of Static Variable is not mandatory. Its default value is 0
If we access the static variable like the Instance variable (through an object), the compiler will
show the warning message, which won’t halt the program. The compiler will replace the object
name with the class name automatically.
If we access the static variable without the class name, the compiler will automatically append
the class name.
Operators in Java
Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are:
10
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operator
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
Arithmetic Operators: They are used to perform simple arithmetic operations on primitive data
types.
+ : Addition
– : Subtraction
* : Multiplication
/ : Division
% : Module
Unary Operators: Unary operators need only one operand. They are used to increment,
decrement or negate a value.
–: Unary minus, used for negating the values.
+: Unary plus indicates the positive value
++: Increment operator, used for incrementing the value by 1. There are two varieties
of increment operators.
Post-Increment: Value is first used for computing the result and then
incremented.
Pre-Increment: Value is incremented first, and then the result is computed.
—: Decrement operator, used for decrementing the value by 1. There are two varieties of
decrement operators.
Post-decrement: Value is first used for computing the result and then
decremented.
Pre-Decrement: Value is decremented first, and then the result is computed.
! : Logical not operator, used for inverting a Boolean value.
Assignment Operator: ‘=’ Assignment operator is used to assign a value to any variable.
Relational Operators: These operators are used to check for relations like equality, greater than,
less than. They return Boolean results after the comparison and are extensively used in looping
statements as well as conditional if-else statements. The general format is,
== Equal to: returns true if the left-hand side is equal to the right-hand side.
!= Not equal to: returns true if the left-hand side is not equal to the right-hand
side.
< Less than: returns true if the left-hand side is less than the right-hand side.
<= less than or equal to returns true if the left-hand side is less than or equal to
the right-hand side.
> Greater than: returns true if the left-hand side is greater than the right-hand side.
11
>= Greater than or equal to: returns true if the left-hand side is greater than or
equal to the right-hand side.
Logical Operators: These operators are used to perform “logical AND” and “logical OR”
operations,
Conditional operators are:
&& Logical AND: returns true when both conditions are true.
|| Logical OR: returns true if at least one condition is true.
Ternary operator: Ternary operator is a shorthand version of the if-else statement. It
has three operands and hence the name ternary.
The general format is:
Condition? If true: if false
Bitwise Operators: These operators are used to perform the manipulation of individual
bits of a number. They can be used with any of the integer types. They are used when
performing update and query operations of the Binary indexed trees.
& bitwise AND operator: returns bit by bit AND of input values.
| Bitwise OR operator: returns bit by bit OR of input values.
^ Bitwise XOR operator: returns bit by bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which returns
the one’s complement representation of the input value, i.e., with all bits
inverted.
Shift Operators: These operators are used to shift the bits of a number left or right,
thereby multiplying or dividing the number by two, respectively. They can be used when
we have to multiply or divide a number by two.
<< Left shift operator: shifts the bits of the number to the left and fills 0 on
voids left as a result. Similar effect as of multiplying the number with some
power of two.
>> Signed Right shift operator: shifts the bits of the number to the right and
fills 0 on voids left as a result. The leftmost bit depends on the sign of the initial
number. Similar effect as of dividing the number with some power of two.
>>> Unsigned Right shift operator: shifts the bits of the number to the right
and fills 0 on voids left as a result. The leftmost bit is set to 0.
Ways to read input from console in Java
In Java, there are four different ways for reading input from the user in the command line
environment (console).
Using Buffered Reader Class
This is the Java classical method to take input, Introduced in JDK1.0. This method is used
by wrapping the System.in (standard input stream) in an InputStreamReader which is
wrapped in a BufferedReader, we can read input from the user in the command line.
The input is buffered for efficient reading.
The wrapping code is hard to remember.
12
Implementation:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args)
throws IOException
{
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
String name = reader.readLine();
System.out.println(name);
}
}
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string " + s);
int a = in.nextInt();
System.out.println("You entered integer " + a);
float b = in.nextFloat();
System.out.println("You entered float " + b);
in.close();
}
}
13
3. Using Console Class
It has been becoming a preferred way for reading user’s input from the command line. In
addition, it can be used for reading password-like input without echoing the characters
entered by the user; the format string syntax can also be used (like System.out.printf()).
Advantages:
class Hello {
public static void main(String[] args)
{
if (args.length > 0) {
System.out.println(
"The command line arguments are:")
for (String val : args)
System.out.println(val);
}
else
System.out.println("No command line "
+ "arguments found.");
}
}
14
Decision Making in Java
Example:
class prg
{
public static void main(String args[])
{
int i = 10;
if (i > 15)
{
System.out.println("10 is less than 15");
}
}
}
15
If-else: The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if the
condition is false. Here comes the else statement. We can use the else statement with if statement
to execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flow Chart
Example:
class prg
{
public static void main(String args[])
{
int i = 10;
if (i < 15)
{
System.out.println("i is smaller than 15");
}
Else
{
System.out.println("i is greater than 15");
}
}
}
16
nested-if: A nested if is an if statement that is the target of another if or
else. Nested if statements mean an if statement inside an if statement.
Yes, java allows us to nest if statements within if statements. i.e, we can
place an if statement inside another if statement.
Syntax:
if (condition1)
{
//Statements
if (condition2)
{
//Statements
}
}
Flowchart
Example:
class prg
{
public static void main(String args[])
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
{
System.out.println("i is smaller than 15");
// Nested - if statement
17
// Will only be executed if statement above
// it is true
if (i < 12)
{
System.out.println( "i is smaller than 12 too");
}
Else
{
System.out.println("i is greater than 15");
}
}
}
18
Example:
Class prg
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Switch-case: The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Jump: Java supports three jump statements: break, continue and return. These three statements
transfer control to another part of the program.
Break: In Java, a break is majorly used for:
Terminate a sequence in a switch statement (discussed above).
To exit a loop.
Used as a “civilized” form of goto .
Continue: Sometimes it is useful to force an early iteration of a loop. That is, you might
want to continue running the loop but stop processing the remainder of the code in its body
for this particular iteration. This is, in effect, a goto just past the body of the loop, to the
loop’s end. The continue statement performs such an action.
19
Example:-
class prg {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is even
// skip and continue
if (i % 2 == 0)
continue;
Loops
While loop: A while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought of as a
repeating if statement.
Syntax:
while (boolean condition)
{
loop statements...
}
20
Example:-
class prg
{
public static void main(String args[])
{
int x = 1;
while (x <= 4)
{
System.out.println("Value of x:" + x);
x++;
}
}
}
For loop: for loop provides a concise way of writing the loop structure. Unlike a
while loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.
Syntax:
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}
21
1. Initialization condition: Here, we initialize the variable in use. It marks the
start of a for loop. An already declared variable can be used or a variable
can be declared, local to loop only.
2. Testing Condition: It is used for testing the exit condition for a loop. It must
return a boolean value. It is also an Entry Control Loop as the condition is
checked prior to the execution of the loop statements.
3. Statement execution: Once the condition is evaluated to true, the
statements in the loop body are executed.
4. Increment/ Decrement: It is used for updating the variable for next iteration.
5. Loop termination: When the condition becomes false, the loop terminates
marking the end of its life cycle.
Example.
class prg
{
public static void main(String args[])
{
for (int x = 2; x <= 4; x++)
{
System.out.println("Value of x:" + x);
}
}
}
Enhanced For loop
Java also includes another version of for loop introduced in Java 5. Enhanced
for loop provides a simpler way to iterate through the elements of a collection or
array. It is inflexible and should be used only when there is a need to iterate
through the elements in a sequential manner without knowing the index of the
currently processed element.
Also note that the object/variable is immutable when enhanced for loop is used
i.e it ensures that the values in the array can not be modified, so it can be said
as read-only loop where you can’t update the values as opposite to other loops
where values can be modified.
We recommend using this form of the for statement instead of the general form
whenever possible.(as per JAVA doc.)
Syntax:
for (T element:Collection obj/array)
{
22
statement(s)
}
Example
public class prg
{
public static void main(String args[])
{
String array[] = {"Ron", "Harry", "Hermoine"};
}
}
Do while: do while loop is similar to while loop with only difference that it checks for
condition after executing the statements,
Syntax:
do
{
statements..
}
while (condition);
23
Flowchart:
1. do while loop starts with the execution of the statement(s). There is no checking of any
condition for the first time.
2. After the execution of the statements, and update of the variable value, the condition is
checked for true or false value. If it is evaluated to true, next iteration of loop starts.
3. When the condition becomes false, the loop terminates which marks the end of its life cycle.
4. It is important to note that the do-while loop will execute its statements at least once before
any condition is checked, and therefore is an example of exit control loop.
Example
class prg
{
public static void main(String args[])
{
int x = 21;
do
{
System.out.println("Value of x:" + x);
x++;
}
while (x < 20);
}
}
24
Syntax:
data_type array_name[][] = new data_type[n][]; array_name[] = new
data_type[n1]
array_name[] = new data_type[n2]
array_name[] = new data_type[n3]
array_name[] = new data_type[nk]
Declaring Objects
When an object of a class is created, the class is said to be instantiated. All the instances
share the attributes and the behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any number of instances.
Initializing an object
The new operator instantiates a class by allocating memory for a new object and returning a
reference to that memory. The new operator also invokes the class constructor.There are four
ways to create objects in java.Strictly speaking there is only one way(by using new keyword),and
the rest internally use new keyword.
25
Using new keyword: It is the most common and general way to create object in
java. Example:
// creating object of class Test
Test t = new Test();
Using Class.forName(String className) method: There is a pre-defined class in
java.lang package with name Class. The forName(String className) method returns the
Class object associated with the class with the given string name.We have to give the
fully qualified name for a class. On calling new Instance() method on this Class object
returns new instance of the class with the given string name.
Test obj = (Test)Class.forName("com.p1.Test").newInstance();
Using clone() method: clone() method is present in Object class. It creates and returns a
copy of the object.
Test t1 = new Test();
Test t2 = (Test)t1.clone();
Deserialization: De-serialization is technique of reading an object from the saved state
in a file.
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();
Complete Example
26
return age;
}
// method 4
public String getColor()
{
return color;
}
@Override
public String toString()
{
return("Hi my name is "+ this.getName()+
".\nMy breed,age and color are " +
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
}
public static void main(String[] args)
{
Dog tuffy = new Dog("tuffy","papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
Packages
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
Preventing naming conflicts. For example there can be two classes with name Employee in
two packages, college.staff.cse.Employee and college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations and annotations
easier
Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A default
member (without any access specifier) is accessible by classes in the same package only.
Packages can be considered as data encapsulation (or data-hiding).
Example :
import java.util.*;
util is a subpackage created inside java package.
Accessing classes inside a package
Consider following two statements :
// import the Vector class from util package.
import java.util.vector;
// import all the classes from util package
import java.util.*;
27
First Statement is used to import Vector class from util package which is contained
inside java.
Second statement imports all the classes from util package.
// All the classes and interfaces of this package
// will be accessible but not subpackages.
import package.*;
// Only mentioned class of this package will be accessible.
import package.classname;
// Class name is generally used when two packages have the same
// class name. For example in below code both packages have
// date class so using a fully qualified name to avoid conflict
import java.util.Date;
import my.package.Date;
Types of packages:
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package names.
28
// Name of the package must be same as the directory
// under which this file is saved
package myPackage;
obj.getNames(name);
}
}
29
Using Static Import
Static import is a feature introduced in Java programming language ( versions 5 and above )
that allows members ( fields and methods ) defined in a class as public static to be used in Java
code without specifying the class in which the field is defined.
Important points:
1. Every class is part of some package.
2. If no package is specified, the classes in the file goes into a special unnamed package (the
same unnamed package for all files).
3. All classes/interfaces in a file are part of the same package. Multiple files can specify the
same package name.
4. If package name is specified, the file must be in a subdirectory called name (i.e., the
directory name must match the package name).
5. We can access public classes in another (named) package using: package-name.class-
name
String class
String is a sequence of characters. In java, objects of String are immutable which means a
constant and cannot be changed once created.
Creating a String
There are two ways to create string in Java:
String literal
String s = “varsha”;
Using new keyword
String s = new String (“himalya”);
String Methods
30
String output = s1.concat(s2); // returns “asian institute”
int indexOf (String s):
Returns the index within the string of the first occurrence of the specified string.
String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
int indexOf (String s, int i):
Returns the index within the string of the first occurrence of the specified string, starting at
the specified index.
String s = ”Learn Share Learn”;
int output = s.indexOf("ea",3);// returns 13
Int lastIndexOf( String s):
Returns the index within the string of the last occurrence of the specified string.
String s = “Asian institute of information and technology”;
int output = s.lastIndexOf("a"); // returns 14
boolean equals( Object otherObj): Compares this string to the specified object.
Boolean out = “Aimit”.equals(“Aimit”); // returns true
Boolean out = “Aimit”.equals(“aimit”); // returns false
boolean equalsIgnoreCase (String anotherString):
Compares string to another string, ignoring case considerations.
Boolean out= “Aimit”.equalsIgnoreCase(“Aimit”); // returns true
Boolean out = “Aimit”.equalsIgnoreCase(“aimit”); // returns true
int compareTo( String anotherString): Compares two string lexicographically.
int out = s1.compareTo(s2); // where s1 ans s2 are
// strings to be compared
This returns difference s1-s2. If:
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
int compareToIgnoreCase( String anotherString): Compares two string
lexicographically, ignoring case considerations.
int out = s1.compareToIgnoreCase(s2);
// where s1 ans s2 are
// strings to be compared
This returns difference s1-s2. If :
31
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase
or lowercase).
String toLowerCase(): Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase();
String to Uppercase (): Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”
String trim ():
Returns the copy of the String, by removing whitespaces at both ends. It does not affect
whitespaces in the middle.
String word1 = “ASIAN INSTITUTE ”;
String word2 = word1.trim(); // returns “Learn Share Learn”
String replace (char oldChar, char newChar):
Returns new string by replacing all occurrences of oldChar with newChar.
String s1 = “ASIAN INSTITUTE”;
String s2 = “ASIAN INSTITUTE”.replace(‘K’ , ‘I’);
import java.io.*;
import java.util.*;
class prg
{
public static void main (String[] args)
{
String s= "ASIAN INSTITUTE OF INFROMATION";
// Returns the number of characters in the String.
System.out.println("String length = " + s.length());
// Returns the character at ith index.
System.out.println("Character at 3rd position = "+ s.charAt(3));
// Return the substring from the ith index character
// to end of string
System.out.println("Substring " + s.substring(3));
// Returns the substring from i to j-1 index.
System.out.println("Substring = " + s.substring(2,5));
// Concatenates string2 to the end of string1.
String s1 = " ASIAN INSTITUTE ";
String s2 = "MANAGEMENT AND INFORMATION TECHNOLOGY";
System.out.println("Concatenated string = " + s1.concat(s2));
System.out.println("Index of Share " + s4.indexOf("Share"));
System.out.println("Index of a = " + s4.indexOf('a',3));
// Checking equality of String
out = "YOGESH".equals("YOGESH");
32
System.out.println("Checking Equality " + out);
out = "yOGESH".equalsIgnoreCase("yOgEsh ");
System.out.println("Checking Equality " + out);
//If ASCII difference is zero then the two strings are similar
int out1 = s1.compareTo(s2);
System.out.println("the difference between ASCII value is="+out1);
// Converting cases
String word1 = "HALLOW";
System.out.println("Changing to lower Case " +word1.toLowerCase());
// Converting cases
String word2 = "AaSHisH";
System.out.println("Changing to UPPER Case " + word2.toUpperCase());
// Trimming the word
String word4 = " asian institute of management and information technology ";
System.out.println("Trim the word " + word4.trim());
// Replacing characters
String str1 = "yogesh";
System.out.println("Original String " + str1);
String str2 = "yogesh".replace('k' ,'y') ;
System.out.println("Replaced k with y -> " + str2);
}
Interfaces
An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. An interface in Java is a blueprint of a class. A Java interface contains static
constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not the method body. It is used to achieve abstraction and multiple
inheritance in Java. In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body. Java Interface also represents the IS-A relationship.
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is the blueprint of the class.
An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set of
methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then the class must be declared abstract.
A Java library example is Comparator Interface. If a class implements this interface, then it
can be used to sort a collection .
Syntax:
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
33
To declare an interface, use the interface keyword. It is used to provide total abstraction. That
means all the methods in an interface are declared with an empty body and are public and all
fields are public, static, and final by default. A class that implements an interface must implement
all the methods declared in the interface. To implement interface use implements keyword.
Why do we use an Interface?
It is used to achieve total abstraction.
Since java does not support multiple inheritances in the case of class, by using an interface
it can achieve multiple inheritances.
It is also used to achieve loose coupling.
Interfaces are used to implement abstraction. So the question arises why use interfaces
when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in the
interface are final, public and static.
Difference Between Class and Interface
The major differences between a class and an interface are:
34
35
Applet
An applet is a Java program that can be embedded into a web page. It runs inside the web browser
and works at client side. An applet is embedded in an HTML page using the APPLET or
OBJECT tag and hosted on a web server.
Applets are used to make the website more dynamic and entertaining.
Important points:
1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
2. Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer. JDK provides a standard applet viewer tool called applet viewer.
3. In general, execution of an applet does not begin at main () method.
4. Output of an applet window is not performed by System.out.println(). Rather it is handled
with various AWT methods, such as drawString().
Life cycle of an applet:
36
It is important to understand the order in which the various methods shown in the above image
are called. When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
4. stop( )
5. destroy( )
1. init( ) : The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet after it
has been stopped. Note that init( ) is called once i.e. when the first time an applet is loaded
whereas start( ) is called each time an applet’s HTML document is displayed onscreen. So, if a
user leaves a web page and comes back, the applet resumes execution at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-based 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. This parameter will contain the
graphics context, which describes the graphics environment in which the applet is running. This
context is used whenever output to the applet is required.
Note: This is the only method among all the method mention above, which is parameterized.
4. Stop ( ) : The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page, for example. When stop( ) is called, the
applet is probably running. You should use stop( ) to suspend threads that don’t need to run
when the applet is not visible. You can restart them when start ( ) is called if the user returns to
the page.
37
5. Destroy ( ): The destroy ( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using. The stop( ) method is always called before destroy( ).
JFrame:-
JFrame class is a type of container which inherits the java.awt.Frame class. JFrame works like the
main window where components like labels, buttons, textfields are added to create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
Fields
static int EXIT_ON_CLOSE The exit application default window close operation.
protected JRootPane rootPane The JRootPane instance that manages the contentPane and optional menuBar
for this frame, as well as the glassPane.
protected boolean rootPaneCheckingEnabled If true then calls to add and setLayout will be forwarded to the contentPane.
Constructors
Constructor Description
JFrame(GraphicsConfiguration gc) It creates a Frame in the specified GraphicsConfiguration of a screen device and a blank
title.
JFrame(String title) It creates a new, initially invisible Frame with the specified title.
JFrame(String title, GraphicsConfiguration It creates a JFrame with the specified title and the specified GraphicsConfiguration of a
gc) screen device.
38
Useful Methods
protected void addImpl(Component comp, Object constraints, int Adds the specified child Component.
index)
protected void frameInit() Called by the constructors to init the JFrame properly.
lose
Code:-
39
Buttons:-
The JButton class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed. It inherits AbstractButton class.
JButton class declaration:-
public class JButton extends AbstractButton implements Accessible
Constructor Description
Methods Description
40
void setEnabled(boolean b) It is used to enable or disable the button.
Example:-
Text Fields TextField class is used to create a textfield control, which allows a user to enter a
single line text and edit it. When an enter key is pressed in a TextField, an ActionEvent is
generated. In order to handle such event, ActionListener interface should be implemented.
TextField is a component which extends TextComponent class, which further
extends Component class.
Constructor Description
public TextField(String text, int width) Creates a TextField with a specified default text and width.
41
public void setText(String text) Sets a String message on the TextField.
JTextArea:-
JTextArea is a part of java Swing package. It represents a multi-line area that displays
text. It is used to edit the text.
JTextArea inherits JComponent class. The text in JTextArea can be set to different
available fonts and can be appended to new text. A text area can be customized to the
need of user.
3. JTextArea(int row, int column) : constructs a new text area with a given number
of rows and columns.
4. JTextArea(String s, int row, int column) : constructs a new text area with a given
number of rows and columns and a given initial text.
42
2. getLineCount() : get number of lines in the text of text area.
4. setColumns(int c) : sets the number of columns of the text area to given integer.
5. setRows(int r) : sets the number of rows of the text area to given integer.
J Combo Box:-
JComboBox consists of an editable field and a drop-down list. A user can either select or edit any
value from drop-drop list. In order to handle the events generated by clicking or editing in
combobox created by JComboBox, an ActionListener interface is implemented. JComboBox is a
is a component which extends JComponent class and it can be added to a container like JFrame or
a component like JPanel.
Constructors of JComboBox
43
Constructor Description
Methods Description
public Object getSelectedItem() Gets the item selected by the user from JCombobox.
import javax.swing.*;
44
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Combo2
{
public static void main(String... ar)
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
new A();
}
});
}//Closing the main method
}//Closing the class Combo
class A //implements ActionListener
{
String [] planets;
JFrame jf;
DefaultComboBoxModel<String> combo1;
JComboBox<String> combo2;
A()
{
planets = new String[]{"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Pluto"};
combo1= new DefaultComboBoxModel<String>(planets);
combo2= new JComboBox<String>(combo1);
jf= new JFrame("JComboBox");
jf.add(combo2);
jf.setLayout(new FlowLayout());
jf.setSize(300,250);
jf.setVisible(true);
}
}
When we run the code, you are presented a window shown:-
When you click on the arrow pointing down, you are presented with a dropdown list, with its first option
"Mercury"preselected:
45
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Combo3
{
public static void main(String... ar)
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
new A();
}
});
}//Closing the main method
}//Closing the class Combo4
Checkbox:-
Checkbox class is used to create a checkbox control, which contains a box that can be checked or
unchecked by clicking on it. Checkbox is a component which extends Component class and it can
be added to the container like Frame or a component like Panel.
Constructors of Checkbox
Constructor Description
public Checkbox() Creates a checkbox with no text, this checkbox is unchecked by default..
public Checkbox(String text) Creates a checkbox with a text, this checkbox is unchecked by default..
46
Methods Description
public void setName(String text) Sets a name on the Checkbox, this name will not be displayed.
public String getName() Gets a String message of Checkbox, this name will not be displayed.
Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.EmptyBorder;
public class chkb1
{
JFrame jf;
Checkbox chk1, chk2, chk3, chk4;
chkb1()
{
jf= new JFrame("Variants of Checkbox");
//Creating an no-message Checkbox
chk1 = new Checkbox();
//Creating a pre-selected Checkbox with a message
chk2 = new Checkbox("Yes",true);
//Creating an unselected Checkbox with a message
chk3 = new Checkbox("No");
jf.add(chk1);
jf.add(chk2);
jf.add(chk3);
jf.setLayout(new FlowLayout());
jf.setSize(300,120);
jf.setVisible(true);
}
Another Example
import java.awt.*;
import java.awt.event.*;
public class chkb2 implements ItemListener
{
Frame jf;
Checkbox chk1, chk2;
Label label1;
chkb2()
{
47
jf= new Frame("Checkbox");
chk1 = new Checkbox("Water");
chk2 = new Checkbox("Coffee");
label1 = new Label();
jf.add(chk1);
jf.add(chk2);
chk1.addItemListener(this);
chk2.addItemListener(this);
jf.setLayout(new FlowLayout());
jf.setSize(232,150);
jf.setVisible(true);
}
public void itemStateChanged(ItemEvent ie)
{
Checkbox ch =(Checkbox)ie.getItemSelectable();
if(ch.getState()==true)
{
label1.setText(ch.getLabel()+ " is checked");
jf.add(label1);
jf.setVisible(true);
}
else
{
label1.setText(ch.getLabel()+ " is unchecked");
jf.add(label1);
jf.setVisible(true);
}
}
public static void main(String... ar)
{
new chkb2();
}
}
JRadioButton class:- RadioButton class is used to create a radio button control, which contains
a circle that can be selected or unselected by clicking on it. JRadioButton is a component which
extends JComponent class and it can be added to the container like JFrame or a component like
JPanel.
Constructors of JRadioButton
Constructor Description
public JRadioButton(String text) Creates an unselected radio button with specified text.
public JRadioButton(String text, boolean Creates a radio button with specified text, which is selected or
b) unselected on the basis of boolean value.
public JRadioButton(String text, Icon Creates a radio button with specified text and icon, which is selected or
image, boolean b) unselected depending on boolean value.
public void setName(String text) Sets a name on the JRadioButton, this name will not be displayed.
48
public String getName() Gets a String message of JRadioButton, this name will not be displayed.
public void setIcon(Icon icon) Sets an icon or image over the JRadioButton.
Example:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class rbt1
{
public static void main(String... ar)
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
new A();
}
});
}//Closing the main method
}//Closing the class A
class A //implements ActionListener
{
JFrame jf;
JRadioButton radio1, radio2, radio3, radio4;
A()
{
jf= new JFrame("Variants of JCheckbox");
radio1 = new JRadioButton(); //JRadioButton()
radio2 = new JRadioButton("Water",true); //JRadioButton(String, boolean)
radio3 = new JRadioButton("Tea"); //JRadioButton(String)
radio4 = new JRadioButton("Coffee", new ImageIcon("Coffee.png"), true);//JRadioButton(String, Icon, boolean)
jf.add(radio1);
jf.add(radio2);
jf.add(radio3);
jf.add(radio4);
jf.setLayout(new FlowLayout());
jf.setSize(400,200);
jf.setVisible(true);
}
}
49
JLabel label1;
A()
{
jf= new JFrame("JRadioButton");
radio1 = new JRadioButton("Summer");
radio2 = new JRadioButton("Winter");
label1 = new JLabel();
jf.add(radio1);
jf.add(radio2);
radio1.addActionListener(this); OUTPUT
radio2.addActionListener(this);
jf.setLayout(new FlowLayout());
jf.setSize(200,150);
jf.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
JRadioButton rb = (JRadioButton)ae.getSource();
if(rb.isSelected()==true)
{
label1.setText(ae.getActionCommand()+ " is checked");
jf.add(label1);
jf.setVisible(true);
}
else
{
label1.setText(ae.getActionCommand()+ " is unchecked");
jf.add(label1);
jf.setVisible(true);
}
}
}
Dialog class
Dialog class is used to create a top-level container Dialog window which contains a set of
components.
public Dialog() Creates a modeless Dialog window without a Frame owner or title..
50
public Dialog(Dialog owner, String Creates a Dialog window with a Frame owner, title and let's you define
title, boolean modal) modality of Dialog window.
Example
import java.awt.*;
import java.awt.event.*;
public class dex1 extends WindowAdapter implements ActionListener
{
Frame frame;
Label label1;
TextField field1;
Button button1, button2, button3;
Dialog d1, d2, d3;
dex1()
{
frame = new Frame("Frame");
button1 = new Button("Open Modal Dialog");
frame.add(label1);
frame.add(button1); OUTPUT
button1.addActionListener(this);
frame.pack();
frame.setLayout(new FlowLayout());
frame.setSize(330,250);
frame.setVisible(true);
}
d1.addWindowListener(this);
d1.pack();
d1.setLocationRelativeTo(frame);
d1.setLocation(new Point(100,100));
d1.setSize(400,200);
d1.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
public class dex2 extends WindowAdapter implements ActionListener
{
Output 51
Frame frame;
Label label1;
TextField field1;
Button button1, button2, button3;
Dialog dg;
dex2()
{
frame = new Frame("Frame");
button1 = new Button("Open Modeless Dialog");
label1 = new Label("Click on the button to open a Modal Dialog");
frame.add(label1);
frame.add(button1);
button1.addActionListener(this);
frame.pack();
frame.setLayout(new FlowLayout());
frame.setSize(330,250);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("Open Modeless Dialog"))
{
//Creating a Modeless Dialog which doesn't block the other parts of application
dg= new Dialog(frame,"Modeless Dialog");
Label label= new Label("You need not to close this dialog window to use the Frame Window",Label.CENTER);
dg.add(label);
dg.addWindowListener(this);
dg.pack();
dg.setLocationRelativeTo(frame);
dg.setLocation(new Point(100,100));
dg.setSize(400,200);
dg.setVisible(true);
}
}
public void windowClosing(WindowEvent we)
{
dg.setVisible(false);
}
public static void main(String...ar)
{
new dex2();
}
}
J-Option
import javax.swing.JOptionPane;
int i= Integer.parseInt(userenters);
Slider
52
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class SwingControlDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingControlDemo(){
prepareGUI();}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showSliderDemo();}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);} });
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true); }
private void showSliderDemo(){
headerLabel.setText("Control in action: JSlider");
JSlider slider = new JSlider(JSlider.HORIZONTAL,0,100,10);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
statusLabel.setText("Value : " + ((JSlider)e.getSource()).getValue());
}});
controlPanel.add(slider);
mainFrame.setVisible(true);
}}
Progress Bar:-
import java.awt.*;
import javax.swing.*;
public class pbart {
static int MAXIMUM = 100;
static JFrame jFrame = new JFrame("JProgress Demo");
static JProgressBar progressBar = new JProgressBar();
public static void main(String[] args) {
progressBar.setMinimum(0);
progressBar.setMaximum(MAXIMUM);
progressBar.setStringPainted(true);
jFrame.setLayout(new FlowLayout());
jFrame.getContentPane().add(progressBar);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(300, 200);
jFrame.setVisible(true);
int currentNumber = 0;
try {
while (currentNumber <= MAXIMUM) {
if (currentNumber > 30 && currentNumber < 70)
progressBar.setString("wait for sometime");
else if (currentNumber > 70)
progressBar.setString("almost finished loading");
else
progressBar.setString("loading started");
53
progressBar.setValue(currentNumber + 10);
Thread.sleep(3000);
currentNumber += 20;
}
}
catch (Exception e) {
System.out.println(e);}}}
Tables:-
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class tab {
JFrame f;
JTable j;
tab()
{
f = new JFrame();
f.setTitle("Java Table Example");
String[][] data = {
{ "Rajnish Jha", "4031", "CSE" },
{ "Yogesh Kumar", "6014", "IT" }
};
String[] columnNames = { "Name", "Roll Number", "Department" };
j = new JTable(data, columnNames);
j.setBounds(30, 40, 200, 300);
JScrollPane sp = new JScrollPane(j);
f.add(sp);
f.setSize(500, 200);
f.setVisible(true);
}
public static void main(String[] args)
{
new tab();
}
}
Event Handling
User interaction with the elements of graphical user interface (GUI) of a Java program leads
to events. These elements could be a button, checkbox, radio button, menu, list, table, scrollbar,
mouse, window etc. Such elements are also known as source of an event and there is a specific
class corresponding to each source and each event.
Some of the events could be –
A click on button, checkbox, radio button.
Selecting a menuitem or list item.
Clicking or movement of a mouse.
Entering or editing the data in a textfield.
54
Source
Listener
Source
Interaction with a source generates an event, which is an object of event class describing the current
state of source. A source must register the listener class that wishes to listen and respond to its event,
by calling a method, which has a general form of –
public void addEventTypeListener(EventTypeListener el)
where,
EventType could be replaced by the name of the type of event.
Listener
The event is delegated to the registered listener classes. In order to listen and respond to events,
such registered listener class must implement EventTypeListener interface,
where, EventType could be replaced by the name of the type of event.
Interaction with elements of GUI raises events, which are nothing but objects
of classes. EventObject is the superclass of all the events. Let's see a table containing some
different kinds of event classes and the description of their events.
Event Classes Description
Let's see a table of some important event classes and their corresponding interfaces that should
55
be implemented by classes in order to listen and respond to the events.
ActionEvent ActionListener
ItemEvent ItemListener
KeyEvent KeyListener
MouseEvent MouseListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
Returns the name over the button, item or menuitem that was clicked to
public String getActionCommand()
trigger the ActionEvent.
public long getWhen() Returns the time when an ActionEvent was generated.
Method Description
An ActionEvent source which could be a button, menu item or a list item, must call this method -
Method Description
56
where object is an object of the class that has
public void implemented ActionListener interface and wanted to register itself to
addActionListener(ActionListener object) listen and respond to ActionEvent generated by a click on this
specific source.
Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ActionEx1 implements ActionListener
{
Frame jf;
Button button1, button2;
Label label;
ActionEx1()
{
jf= new Frame("Button click events");
button1= new Button("Button1");
button2= new Button("Button2");
label = new Label();
jf.add(button1);
jf.add(button2);
jf.add(label);
button1.addActionListener(this); //this represents current object of ActionEx1 class.
button2.addActionListener(this);
jf.setLayout(new FlowLayout(FlowLayout.CENTER,60,10));
jf.setSize(250,150);
jf.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("Button1"))
{
label.setText("You've clicked Button1");
jf.add(label);
jf.setVisible(true);
}
if(ae.getActionCommand().equals("Button2"))
{
label.setText("You've clicked Button2");
jf.add(label);
jf.setVisible(true);
}
}
public static void main(String... ar)
{
new ActionEx1();
}
}
AdjustmentEvent and AdjustmentListener
an event of type adjustmentEvent is generated when a scrollbar is dragged around.
Methods
Methods Description
public int getAdjustmentType() Returns the type of adjustment that caused AdjustmentEvent.
57
A class to listen and respond to AdjustmentEvent, must perform the two steps:
It should implement an interface, AdjustmentListener by implementing its methods –
Methods Description
Methods
Method Description
A class to listen & respond to a MouseEvent, must perform the next two steps -
It should implement an interface, MouseListener, by providing an implementation of its methods
Method Description
public void mouseEntered(MouseEvent This method is called when a mouse cursor enters a window listening
me) for MouseEvent
58
public void mousePressed(MouseEvent
This method is called when a mouse button is being pressed.
me)
A MouseEvent source is a window in which such event is generated, must call a method -
Method Description
where object is an object of the class that wants to listen and respond to
public void
MouseEvent and has implemented MouseListener interface. This
addMouseListener(ItemListener object)
registers the class to listen & respond to MouseEvent.
Example:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseEx1 implements MouseListener
{
Label label1, label2;
Frame frame;
String str;
MouseEx1()
{
frame = new Frame("Window");
label1= new Label("Handling mouse events in the Frame window", Label.CENTER);
label2= new Label();
frame.setLayout(new FlowLayout());
frame.add(label1);
frame.add(label2);
frame.addMouseListener(this);
frame.setSize(340,200);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent we)
{
str+=" and Mouse button was clicked";
label2.setText(str);
frame.setVisible(true);
}
public void mouseEntered(MouseEvent we)
{
label2.setText("Mouse has entered the window area");
frame.setVisible(true);
}
public void mouseExited(MouseEvent we)
{
label2.setText("Mouse has exited the window area");
frame.setVisible(true);
}
59
public void mousePressed(MouseEvent we)
{
label2.setText("Mouse button is being pressed");
frame.setVisible(true);
}
public void mouseReleased(MouseEvent we)
{
str="Mouse button is released";
label2.setText(str);
frame.setVisible(true);
}
public static void main(String... ar)
{
new MouseEx1();
}
}
When you run the code, you are presented a window shown in the window below -:
When you move your mouse cursor in the Frame's window area, it generates a MouseEvent. The
following method is executed and you are notified about it in the window :
mouseEntered()
Figure 2
When you move your mouse cursor out of the Frame's window area, it generates a MouseEvent. The
following method is executed and you are notified about it in the window:
mouseExited()
Figure 3
When we move your mouse cursor back in the Frame's window area and press and hold any of
60
mouse's button, it generates a Mouse Event. The following method is executed and you are notified
about it in the window:
mousePressed()
Figure 4
When you release the pressed mouse button, it generates a MouseEvent. The following method are
executed in sequence and you are notified about it in the window:
mouseReleased()
mouseClicked()
In order to create a class that handles mouse motion events, we need to understand some
important methods of MouseEvent class in the table below.
Methods
Method Description
A class to listen and respond to event type MouseEvent, must perform two steps:
61
A class that wants to handle and respond to mouse motion events of type MouseEvent should
implement an interface i.e. MouseMotionListener and also provide implementation of its
methods shown in the table below -
Method Description
public void mouseMoved(MouseEvent This method is called when a mouse cursor moves in a window listening
me) for mouse motion event of type MouseEvent.
public void mouseDragged(MouseEvent This method is called when a mouse cursor is being dragged in a
me) window listening for mouse motion event of type MouseEvent.
A MouseEvent source is a window in which such event is generated, must call its method -
Method Description
Example:-
When a mouse is moved within the Frame's window area.
When a mouse button is pressed and dragged within the Frame's window.
import java.awt.*;
import java.awt.event.*;
import java.awt.Point;
public class MouseEx3 extends WindowAdapter implements MouseMotionListener
{
Label label1, label2;
Frame frame;
String str;
Point p;
MouseEx3()
{
frame = new Frame("Window");
label1= new Label("Tracking mouse cursor in the Frame window", Label.CENTER);
label2= new Label();
frame.setLayout(new FlowLayout());
frame.add(label1);
frame.add(label2);
frame.addMouseMotionListener(this);
frame.addWindowListener(this);
frame.setSize(280,200);
frame.setVisible(true);
}
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
public void mouseDragged(MouseEvent me)
{
String s = me.getX() + "," + me.getY();
62
label2.setText("Mouse dragged "+ s);
frame.setVisible(true);
}
public void mouseMoved(MouseEvent me)
{
String s = me.getX() + "," + me.getY();
label2.setText("Mouse moved "+ s);
frame.setVisible(true);
}
public static void main(String... ar)
{
new MouseEx3();
}
}
When you run the code, you are presented a window shown in the window below -:
When you move your mouse cursor in the Frame's window area, it generates an event
i.e. MouseEvent. Method mouseMoved() is executed to handle mouse movement event and as
you move your mouse cursor, you are notified about the current x and y coordinates of your mouse
cursor in the window :
mouseMoved()
Figure 2
When you drag your mouse cursor within the Frame's window area, it generates a MouseEvent,
the method mouseDragged() is executed to handle mouse drag event and you are notified about
current x and y coordinates of your mouse cursor in the window, where the mouse is dragged :
Figure 3
WindowEvent and WindowListener
63
When a window is brought up back from minimized state.
When the close button (x) of window is clicked to close it.
Methods
Method Description
public Window getWindow() Returns the window which triggered the WindowEvent.
A class to listen & respond to a WindowEvent must perform the next two steps:
It should implement WindowListener interface, by implementing its all next seven methods -
Method Description
public void windowOpened(WindowEvent e) This method is called when a window is opened for the first time.
public void windowActivated(WindowEvent e) This method is called when a window shows up on screen.
public void windowDeiconified(WindowEvent This method is called when a window is brought up on the screen
e) from a minimized state.
This method is called a user clicks on the (x) icon to close the
public void windowClosing(WindowEvent ke)
window.
public void windowClosed(WindowEvent e) This method is called when a window has been closed.
A WindowEvent event source is a window in which such event is generated, must call its
method –
Method Description
Example:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class WindowEx1 implements WindowListener
64
{
Label label1;
Frame frame;
WindowEx1()
{
frame = new Frame("Handling KeyEvent");
label1= new Label("-See window events -", Label.CENTER);
frame.setLayout(new FlowLayout());
frame.add(label1);
frame.addWindowListener(this);
frame.setSize(340,200);
frame.setVisible(true);
}
public void windowActivated(WindowEvent we)
{
System.out.println("Window Activated");
}
public void windowClosed(WindowEvent we)
{
System.out.println("Window Closed");
}
public void windowClosing(WindowEvent we)
{
frame.dispose();
System.out.println("Window Closing");
}
public void windowDeactivated(WindowEvent we)
{
System.out.println("Window Deactivated");
}
public void windowDeiconified(WindowEvent we)
{
System.out.println("Window Deiconified");
}
public void windowIconified(WindowEvent we)
{
System.out.println("Window Iconified/minimized");
}
public void windowOpened(WindowEvent e)
{
System.out.println("Window Opened for the first time");
}
public static void main(String... ar)
{
new WindowEx1();
}
}
Methods
Method Description
65
which triggered the KeyEvent.
Returns an int key code associated with the key pressed on the
public int getKeyCode() keyboard.
Returns true if key pressed was an "action" key, i.e. keys that don't
public boolean isActionKey() generate a character, such as Cut, Copy, Paste, Page Up, Caps Lock, the
arrow and function keys.
A class to listen and respond to a KeyEvent, must perform the next two steps -
It should implement an interface, KeyListener, by providing an implementation of its three
methods -
Method Description
public void keyPressed(KeyEvent e) This method is called when a key is pressed on the keyboard.
public void keyReleased(KeyEvent ke) This method is called when a key is released on the keyboard.
A KeyEvent source which could be a textfield or a textarea, must call its method –
Method Description
Example:-
When you run the code, you are presented a window shown in the window below -:
66
Figure 1
When you press a key on the keyboard, it triggers a KeyEvent, three methods defined in
KeyEventEx1 are called in sequence -
keyPressed()
keyTyped()
keyReleased()
And you are presented a window showing the code of key a -
Figure 2
When you press SHIFT key on the keyboard, it triggers a KeyEvent, but this time two methods
defined in KeyEventEx1 are called in sequence -
keyPressed()
keyReleased()
Method keyTyped() is not called because SHIFT key doesn't generate or remove any character.
You are presented a window showing the co de of key SHIFT -
Figure 3
When you press Backspace key on the keyboard, it triggers a KeyEvent, three methods defined
in KeyEventEx1 are called in sequence -
keyPressed()
keyTyped()
keyReleased()
And you are presented a window showing the code of key Backspace-
67
Figure 4
Exceptions in Java
Exception Handling in Java is one of the effective means to handle the runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to
handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
What is an Exception?
An exception is an unwanted or unexpected event, which occurs during the execution of a
program i.e at run time, that disrupts the normal flow of the program’s instructions. Exceptions
can be caught and handled by the program. When an exception occurs within a method, it creates
an object. This object is called the exception object. It contains information about the exception
such as the name and description of the exception and the state of the program when the
exception occurred.
An exception can occur for many reasons. Some of them are:
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
What is an Error?
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not try to handle errors.
Error vs Exception
Error: An Error indicates a serious problem that a reasonable application should not try to
catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Exception Hierarchy
All exception and errors types are subclasses of class Throwable, which is the base class of the
hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that
user programs should catch. NullPointerException is an example of such an exception. Another
68
branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the
run-time environment itself(JRE). StackOverflowError is an example of such an error.
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.
2. User-Defined Exceptions
Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries.
These exceptions are suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler.
Unchecked Exceptions: The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions at compile time. In simple words,
if a program throws an unchecked exception, and even if we didn’t handle or declare it, the
program would not give a compilation error.
User-Defined Exceptions: Sometimes, the built-in exceptions in Java are not able to describe a
certain situation. In such cases, users can also create exceptions which are called ‘user-defined
Exceptions’.
69
Advantages of Exception Handling:
Syntax
try {
STATEMENTS……………….
………………….
{
// Catch block
}
COMPLETE EXAMPLE PICTURE WITH OUTPUT
Java, the “finally” block is always executed no matter whether there is an exception or not.
The “finally” block is optional. And, for each “try” block, there can be only one “finally” block.
Syntax
try {
70
STATEMENTS……………….
………………….
{
// Catch block
}
Finally
{
// final block
}
COMPLETE EXAMPLE PICTURE WITH OUTPUT
Syntax:
try {
// code
71
}
catch (ExceptionType1 | Exceptiontype2 ex)
{
// catch block
}
72
File Handling
File is an abstract data type. A named location used to store related information is known as
a File. There are several File Operations like creating a new File, getting information about File,
writing into a File, reading from a File and deleting a File.
Before understanding the File operations, it is required that we should have knowledge
of Stream and File methods. If you have knowledge about both of them, you can skip it.
Stream
A series of data is referred to as a stream. In Java, Stream is classified into two types, i.e., Byte
Stream and Character Stream.
73
Byte Stream
Byte Stream is mainly involved with byte data. A file handling process with a byte stream is a
process in which an input is provided and executed with the byte data.
Character Stream
Character Stream is mainly involved with character data. A file handling process with a character
stream is a process in which an input is provided and executed with the character data.
74
File Operations
o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File
In order to create a new file, inbuilt files and functions are used which definitely will
throw Exceptions here playing it safe. So in order to deal with it, we will be using Exception
Handling Techniques. Here, we will use one of them known as-try-catch block techniques.
Secondary, additional work is simply we will be importing File Class for which we will be
importing File Class.
import java.util.File ;
Syntax: To create a new file
There are two standards methods to create a new file either directly with the help of File class or
indirectly with the help of FileOutputStream by creating an object of the file in both the
approaches.
By using File Class
By using FileOutputStream Class
It is used for those objects which do not have physical It is used for those objects which are already existing
existence
75
Method 1: Create a new file using the File class
76
Multithreading: -
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Thread Control Methods
Sr.No. Method & Description
This method puts a thread in the suspended state and can be resumed using resume() method.
This method resumes a thread, which was suspended using suspend() method.
Causes the current thread to wait until another thread invokes the notify ().
77
5. Timed Waiting
6. Terminated
The diagram shown below represents various states of a thread at any instant in time.
78
of our new class and call start () method to start the execution of a thread. Start () invokes the
run () method on the Thread object.
we create a new class which implements java.lang.Runnable interface and override run () method.
Then we instantiate a Thread object and call start () method on this object.
Socket Programming
Socket programming is a way of connecting two nodes on a network to communicate with each
other. One socket (node) listens on a particular port at an IP, while other socket reaches out to the
other in order to form a connection.
79
The server forms the listener socket while the client reaches out to the server. Socket and Server
Socket classes are used for connection-oriented socket programming.
Socket Programming
Socket programming is a way of connecting two nodes on a network to communicate with each
other. One socket (node) listens on a particular port at an IP, while other socket reaches out to the
other in order to form a connection. The server forms the listener socket while the client reaches
out to the server. Socket and Server Socket classes are used for connection-oriented socket
programming.
What is a Socket
A socket in Java is one endpoint of a two-way communication link between two programs running
on the network. A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent to.
An endpoint is a combination of an IP address and a port number. The package in the Java platform
provides a class, Socket that implements one side of a two-way connection between your Java
program and another program on the network. The class sits on top of a platform-dependent
implementation, hiding the details of any particular system from your Java program. By using the
class instead of relying on native code, your Java programs can communicate over the network in
a platform-independent fashion.
In order to initiate a client’s request, you need to follow the below-mentioned steps:
80
Establish a Connection
The very first step is to establish a socket connection. A socket connection implies that the two
machines have information about each other’s network location (IP Address) and TCP port.
2. Communication
In order to communicate over a socket connection, streams are used for both input and output the
data. After establishing a connection and sending the requests, you need to close the connection.
The socket connection is closed explicitly once the message to the server is sent.
import java.net.*;
import java.io.*;
public class ClientProgram
{
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
try
{
socket = new Socket(address, port);
System.out.println("Connected");
input = new DataInputStream(System.in);
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
String line = "";
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
81
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[]) {
Client client = new Client("127.0.0.1", 5000);
}}
In order to code the server-side application, you need two sockets and they are as follows:
A ServerSocket which waits for the client requests (when a client makes a new Socket())
A plain old socket for communication with the client.
Communication
getOutputStream() method is used to send the output through the socket.
Close the Connection
It is important to close the connection by closing the socket as well as input/output streams
once everything is done.
import java.net.*;
import java.io.*;
public class ServerSide
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
82
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i){
System.out.println(i);
}
}
public static void main(String args[]){
Server server = new Server(5000);
}
}
After configuring both client and server end, you can execute the server side program first. After
that, you need to run client side program and send the request. As soon as the request is sent from
the client end, server will respond back. Below snapshot represents the same.
1. When you run the server side script, it will start and wait for the client to get started.
2. Next, the client will get connected and inputs the request in the form of a string.
83
3. When the client sends the request, the server will respond back.
TCP/IP
TCP is a Network Protocol that stands for Transfer Control Protocol, which allows well-founded
communication between applications. TCP is consistently used over the Internet Protocol, and that
is why referred to as TCP/IP. The communication mechanism between two systems, using TCP,
can be established using Sockets and is known as Socket Programming. Hence, socket
programming is a concept of Network Programming, that suggests writing programs that are
executed across multiple systems, which are connected to each other using a network.
Mechanism for Socket Programming
A client creates a socket at its end of transmission and strives to connect the socket to the server.
When a connection is established, the server creates a socket at its end and, the client and server
can now ready communicate through writing and reading methods. Following is the elaborated
2. The accept method of ServerSocket is invoked, in order to hold the server in listening mode.
This method won’t resume until a client is connected to the server through the given port
number.
84
3. Now, on the client-side, an object of Socket is instantiated, and desired port number and IP
address is specified for the connection.
4. An attempt is made, for connecting the client to the server using the specified IP address and
port number. If the attempt is successful, the client is provided with a Socket that is capable of
communicating to the respective server, with write and read methods. If unsuccessful, the
desired exception is raised.
5. Since a client is connected to the server, accept method on the server-side resumes, providing
a Socket that is capable of communicating to the connected client.
6. Once the communication is completed, terminate the sockets on both, the server and the client-
side.
Now, communication is held using input/output streams of Sockets. The InputStream of the client
is coupled with the OutputStream of the server and the OutputStream of the client is coupled with
the InputStream of the server. Since TCP is a two-way network protocol, hence information can
For the Client machine, we need to now establish the socket connection. Socket Connection is when
the two machines have information about each other’s network location (IP Address) and the TCP
port.
Connection:
Socket socket = new Socket(IP Address, port number);
//IP Address of the server
//TCP port Number on which the server is listening
Communication:
The communication is held using the output and input streams. These streams are responsible for
transmitting the information in the form of byte array. An object can also be transmitted through
85
these streams, but it needs to be serialized before transmitting and deserialized after it has been
received. Input and output streams are made available through socket instances.
Terminating Connection:
The socket connection needs to be terminated explicitly once the communication is fulfilled.
Implementation:
86
x=inputStreamReader.read();
if(x==’#’ || x==-1) break; // reads till the terminator
stringBuffer.append((char)x);
}response=stringBuffer.toString();
System.out.println(response);socket.close(); //closing the connection
}catch(Exception exception)
{
// Raised in case, connection is refused or some other technical issue
System.out.println(exception);
}
}
}
Server-Side Programming
For the server-side programming, a ServerSocket is required, which will wait for the client in the
listening mode, on a particular TCP port. This ServerSocket holds until a Client Socket is connected
successfully. As soon as the client is connected, another Socket comes into existence that will
enable data sharing between the respective client and server. A temporary Socket is created to
handle the request from that particular client and our main server socket will be free again, to listen
Creating ServerSocket:
The ServerSocket is instantiated on a specific port number. Then, the server starts listening for the
client requests coming in for that port number. The accept method waits until a client connects to
the server. After a successful connection, accept returns a Socket that will facilitate the
communication.
Communication:
For data transfer, the getOutputStream method is used to send the output through the socket, and
input is received using getInputStream method. The Server keeps receiving messages until it
87
Terminating Connection:
Once the response is sent, the socket, along with the input and output streams needs to be closed
explicitly.
Implementation:
The Server implemented below is a multi-threaded server, so it can listen to multiple clients
without any interruption. This works efficiently because, after establishing the connection, the
server diverts the request, along with the respective socket, to another Thread or another Request
Processor. The request processor will continue to work by using the socket, it received.
Meanwhile, Server can listen to other requests coming in. As the connection is closed, the thread
is also terminated.
import java.io.*;
import java.net.*;class RequestProcessor extends Thread //for multi-threaded server
{
private Socket socket;
RequestProcessor(Socket socket)
{
this.socket=socket;
start(); // will load the run method
}public void run()
{
try
{//Declaring properties and streams
OutputStream outputStream;
OutputStreamWriter outputStreamWriter;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuffer stringBuffer;
String response;
String request;int x;
int temp1,temp2;
String part1,part2,part3;
int rollNumber;
String name;
String gender;//getting input stream and its reader, for reading request or acknowledgement
inputStream=socket.getInputStream();
inputStreamReader=new InputStreamReader(inputStream);
88
stringBuffer=new StringBuffer();
while(true)
{
x=inputStreamReader.read();
if(x=='#' || x==-1) break; //reads until terminator
stringBuffer.append((char)x);
}
request=stringBuffer.toString();
System.out.println("Request : "+request);//parsing and extracting Request data
temp1=request.indexOf(",");
temp2=request.indexOf(",",temp1+1);
part1=request.substring(0,temp1);
part2=request.substring(temp1+1,temp2);
part3=request.substring(temp2+1);
rollNumber=Integer.parseInt(part1);
name=part2;
gender=part3;
System.out.println("Roll number : "+rollNumber);
System.out.println("Name : "+name);
System.out.println("Gender : "+gender);
89
}private void startListening()
{
try
{
Socket socket;
while(true)
{System.out.println("Server is listening on port : "+this.portNumber);
socket=serverSocket.accept(); // server is in listening mode
System.out.println("Request arrived..");// diverting the request to processor with the socket reference
new RequestProcessor(socket);
}
}catch(Exception e)
{
System.out.println(e);
}
}public static void main(String data[])
{
int portNumber=Integer.parseInt(data[0]);
Server server=new Server(portNumber);
}
}
Execution
To run, compile the server and client code. First, start the server in a prompt like this:
After the data is sent from the client, the server prompt will look like this:
90
Multiple printing of Server is listening on port: 5050 is the proof of concept that, once the request
has arrived, the server diverts it onto another thread and gets ready for listening to another request.
And extracting and processing the data takes place on another thread in parallel.
UDP Protocol:-
Connectionless
The UDP is a connectionless protocol as it does not create a virtual path to transfer the data. It
does not use the virtual path, so packets are sent in different paths between the sender and the
receiver, which leads to the loss of packets or received out of order.
In the case of UDP, the datagrams are sent in some order will be received in the same order is
not guaranteed as the datagrams are not numbered.
Ports
The UDP protocol uses different port numbers so that the data can be sent to the correct
destination. The port numbers are defined between 0 and 1023.
Faster transmission
UDP enables faster transmission as it is a connectionless protocol, i.e., no virtual path is required
to transfer the data. But there is a chance that the individual packet is lost, which affects the
transmission quality. On the other hand, if the packet is lost in TCP connection, that packet will
be resent, so it guarantees the delivery of the data packets.
Acknowledgment mechanism
The UDP does have any acknowledgment mechanism, i.e., there is no handshaking between the
UDP sender and UDP receiver. If the message is sent in TCP, then the receiver acknowledges that
I am ready, then the sender sends the data. In the case of TCP, the handshaking occurs between
the sender and the receiver, whereas in UDP, there is no handshaking between the sender and the
receiver.
91
Segments are handled independently.
Each UDP segment is handled individually of others as each segment takes different path to reach
the destination. The UDP segments can be lost or delivered out of order to reach the destination as
there is no connection setup between the sender and the receiver.
Stateless
It is a stateless protocol that means that the sender does not get the acknowledgement for the packet
which has been sent.
In UDP, the header size is 8 bytes, and the packet size is upto 65,535 bytes. But this packet size is
not possible as the data needs to be encapsulated in the IP datagram, and an IP packet, the header
size can be 20 bytes; therefore, the maximum of UDP would be 65,535 minus 20. The size of the
data that the UDP packet can carry would be 65,535 minus 28 as 8 bytes for the header of the UDP
packet and 20 bytes for IP header.
o Source port number: It is 16-bit information that identifies which port is going t send the
packet.
o Destination port number: It identifies which port is going to accept the information. It is
16-bit information which is used to identify application-level service on the destination
machine.
o Length: It is 16-bit field that specifies the entire length of the UDP packet that includes the
header also. The minimum value would be 8-byte as the size of the header is 8 bytes.
o Checksum: It is a 16-bits field, and it is an optional field. This checksum field checks
whether the information is accurate or not as there is the possibility that the information
can be corrupted while transmission. It is an optional field, which means that it depends
upon the application, whether it wants to write the checksum or not. If it does not want to
write the checksum, then all the 16 bits are zero; otherwise, it writes the checksum.
92
JDBC:-
JDBC stands for Java Database Connectivity. It is a standard API provided by Oracle for Java
applications to interact with different set of databases. JDBC uses Structured Query Language(SQL)
for performing database queries like database access, storage, update or delete.
JDBC Architecture
JDBC architecture consists of two layers -
JDBC Application Layer
JDBC Application Layer consists of two components - Java application and JDBC API. In
Application layer, a java Application that wishes to communicate with a database uses the JDBC
API to access the required JDBC driver. The JDBC API contains the JDBC driver manager, which
connects Java application with the JDBC driver.
JDBC Driver Layer
JDBC Driver Layer consists of several database drivers that may be required to connect a Java
application to its choice of a specific database. For example - the JDBC Driver Layer may contain
a MySQL database driver, an Oracle driver and a MariaDB Database driver to connect any Java
application with any of these databases as per the requirement of this Java application.
This JDBC driver is nothing but a program through which a Java application can easily
communicate with a database. This JDBC driver translates the requests of a Java application such
a database query like database access, update or storing procedures from Java language to
Structured Query Language (SQL), which is then forwarded to a specific database of choice of
this Java application.
These SQL statements are executed by the preferred database and the result is sent back to JDBC
93
driver. The JDBC driver sends the result back to Java application (through JDBC API) in the form
which it can easily understand.
Using the JDBC-ODBC Bridge Driver, a Java application can easily communicate with a database
that has provided an ODBC driver.
DriverManager class
The DriverManager class is the component of JDBC API and also a member of
the java.sql package. The DriverManager class acts as an interface between users and
drivers. It keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver.
94
java.sql Package
We have relational databases, from which at many times we need to access the data. For
various data processing related matters from RDDBMS we have java.sql package. The
various classes in the package are shown below:
Class Description
Date It gives time in milliseconds. It is a wrapper type. It provides sql with dates. The class is declared as:
public class Date extends Date
The class methods are inherited from date class.
DriverManager The class is designed for managing the various JDBC drivers. The class is declared as follows:
public class DriverManager extends Object
The class methods are inherited from Object class.
DriverPropertyInfo The class keeps an account for managing the various properties of JDBC drivers which are required for making a
secure connection. The class is declared as follows:
public class DriverPropertyInfo extends Object
The class methods are inherited from Object class.
SQLPermission The class manages the various SQL related permissions which are provided to the accessing objects. The class is
declared as follows:
public final class SQLPermission extends BasicPermission
The class methods are inherited from BasicPermission class.
Time It is wrapper class around java.util. The class provides time related information. The class is declared as follows:
public class Time extends Date
The class methods are inherited from Date class.
Timestamp It is wrapper class around java.util. The class allows JDBC API to identify as TIMESTAMP value. The class is
declared as follows:
public class Timestamp extends Date
The class methods are inherited from Date class.
Types The class defines various SQL constants. The class is declared as follows:
public class Types extends Object
The class methods are inherited from Object class.
An SQLException can occur both in the driver and the database. When such an exception occurs,
an object of type SQLException will be passed to the catch clause.
95
The passed SQLException object has the following methods available for retrieving additional
information about the exception:
Method Description
getMessage( ) Gets the JDBC driver's error message for an error, handled by
the driver or gets the Oracle error number and message for a
database error.
getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC driver error,
no useful information is returned from this method. For a
database error, the five-digit XOPEN SQLstate code is
returned. This method can return null.
printStackTrace(PrintStream s) Prints this throwable and its backtrace to the print stream you
specify.
printStackTrace(PrintWriter w) Prints this throwable and it's backtrace to the print writer you
specify.
96
97