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

Java

The document provides an overview of 5 units that make up a Core Course Programming in Java. Unit 1 covers object-oriented programming fundamentals like classes, objects, inheritance, polymorphism and the history and features of Java. Unit 2 discusses arrays, strings, inheritance and interfaces. Unit 3 covers exception handling, multithreading, files and I/O streams. Unit 4 presents applets and GUI programming. Unit 5 focuses on GUI programming and Java database connectivity.

Uploaded by

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

Java

The document provides an overview of 5 units that make up a Core Course Programming in Java. Unit 1 covers object-oriented programming fundamentals like classes, objects, inheritance, polymorphism and the history and features of Java. Unit 2 discusses arrays, strings, inheritance and interfaces. Unit 3 covers exception handling, multithreading, files and I/O streams. Unit 4 presents applets and GUI programming. Unit 5 focuses on GUI programming and Java database connectivity.

Uploaded by

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

CORE COURSE

PROGRAMMING IN JAVA
UNIT - I:
Foundation, Essentials, Control Statement and Classes & Objects, Stage of Java – origin of Java – challenges -
features - Object-Oriented Programming; Java Essentials: Elements - API - variables - primitive data types –
String Class - operators –combined assignment operators - conversion –scope – comments - keyboard input;
Control Statements: if ,if-else, nested if & if-else-if statements – logical operators – comparison – conditional
operator – switch – increment and decrement – while, do-while & for loops – nested loops – break and
continue; Classes and Objects: classes and objects -modifiers - passing arguments– constructors - package &
import - static class members –method overloading– constructor overloading –returning objects – this variable
– recursion – nested & inner classes – abstract classes & methods.

UNIT - II:
Arrays, String Handling, Inheritance, Interface and Packages, Introduction –processing array – passing arrays –
returning arrays – String arrays – two Dimensional Arrays - Arrays with Three or More Dimensions; String
Handling : String class – concatenation – comparison – substring – methods – other methods–String Buffer,
String Builder & String Tokenizer classes; Inheritance: basics –inheriting and overriding superclass methods –
calling superclass constructor – polymorphism – inherit from different classes – abstract classes – final Class;
Interfaces: Basics – multiple Interfaces – multiple inheritance using interface – multilevel interface – Packages
– Create and access packages in Net Beans IDE – static Import and package class – access specifiers.

UNIT - III:
Exception Handling, I/O and File Handling and Multithreading, Introduction - try and catch block - multiple
catch block - nested try - finally Block – throw Statement – exception propagation – throw Clause - custom
exception – built-in exception; Multithreading: Introduction – threads – thread creation – life cycle – joining a
thread – scheduler &priority – synchronization – inter-thread communication – thread control – thread Pool –
thread group – daemon thread; Files and I\O Streams: file Class – streams – byte streams – filtered byte
streams – Random Access File class – character streams.

UNIT - IV:
Applet and GUI Part I, Fundamentals – applet class – life cycle – steps for applet program – passing values
through parameters – graphics – event handling; GUI I:GUI – creating windows – dialog boxes – layout
managers – AWT component classes – Swing component classes – applications of AWT controls.

UNIT - V:
GUI Part II and Java Database Connectivity, Event handling – AWT components – AWT graphics classes –
Swing controls – application using Swing and AWT; Java Database Connectivity: types of drivers – JDBC
architecture – JDBC classes &interfaces – steps in JDBC applications – creating a new Database and table with
JDBC.

UNIT 1

Fundamentals of Object Oriented Programming:

Many programming models have evolved in the domain of software solutions. The main models are

1. Procedural Programming Model : Each problem is divided into smaller problems and solved using
specified modules that act on data.

2. Object oriented programming model: It perceived the entire software system as a collections of objects
which contain attributes and behaviors.

Object:
An object is a tangible entity that may exhibit some well-defined behavior. (Or) Object is an
instance of Class (or) Everything is an object.

Class:
A class is a se of attributes and behaviors shared by similar objects. (or) in simple way
Collection of objects is called Class.

Abstraction:
Abstraction focuses on the essential characteristics of an objects.

Encapsulation :

Encapsulation hides the implementation details of an object and thereby , hides its complexity.

Inheritance :

Inheritance creates a hierarchy of classes and helps in the reuse of the attributes and methods of a class.

Polymorphism:

Polymorphism triggers different reactions in objects in response to the same message.(or) More
than one function in same name.
Ex:
Public void abc (int a , int b)
{

}
public void abc (int x, int y, int z)
{

Super class :
A super class shares its attributes and behavior with its child classes.

Sub class:
A subclass inherits attributes and behaviors from its super class.

HISTORY OF JAVA:

IN 1991, SUN Microsystems began a project called “Green “ to develop software for use in consumer
electronics. The leader of the project James Gosling and include Patrick Naughton, Mike Sheridan. The team
wanted a fundamentally new way of computing, based on the power of networks , and wanted the same
software to run on different kinds of computers and different operating system. They create new language
and give the name OAK.

In this time the WWW (World Wide Web) was in a period of dramatic growth , Sun realized that Oak was
perfectly suited for Internet process. In 1994 , they completed work on a product known as a Webrunner.
Later renamed as HotJava. Hotjava demonstrated the power of Oak as Internet development tools.

In 1995 , OAK was renamed as Java (Marketing purpose).


FEATURES OF JAVA :

Java is a simple language that can be learned easily, even if you have just started programming.

A java programmer need not know the internals of java. The syntax of Java is similar to C++. Unlike C++
in which the programmer handles memory manipulation, Java handles the required memory manipulation and
thus prevents errors that arise due to improper memory usage.

Java is purely object-oriented and provides abstraction, encapsulation, inheritance , and polymorphism.
Even the most basic program ha a class. Any code that you write in Java is inside a class.

Java is tuned to the Web. Java programs can access data across the Web as easily as they access data from a
local system. You can build Distributed applications in Java that use resources from any other networked
computer.

Java is both Interpreted and Compiled. The code is compiled to a bytecode that is binary
and platform-independent.

When you compile a piece of code, all the errors are listed together. You can execute a program only
when all the errors have been rectified. Only when the execution reaches the statement with an error is the
error reported. This makes it easy for a programmer to debug the code.

A programmer cannot write Java code that interacts with the memory of the system. Instead of assuming
that programmers know what they are doing, java ensures the same. For instance , Java forces you to handle
unexpected errors. This ensures that Java programs are robust(reliable), and bug free and do not crash.
A program traveling across the Internet to your machine could possibly be carrying a virus. Due to strong
type-checking done by Java on the user’s machine, any changes to the program are tagged as errors and the
program will not execute. Java is, therefore, secure.

Java programs are comparable in speed to the programs written in other compiler-based languages like C
and C++. Java is faster than other interpreter-based languages like BASIC since it is compiled and
interpreted.

Multithreading is the ability of an application to perform multiple tasks at the same time. For example,
when you play a game on your computer, one task of the program is to handle sound effects and another to
handle screen display. A single program accomplishes many tasks simultaneously. Microsoft Word is another
multithreaded program in which the data automatically saved as you key it in. You can create multithreaded
programs using Java. The core of Java is also multithreaded.

A Java program can consist of many modules that are written by many programmers. These modules may
undergo many changes. Java makes interconnections between modules at run-time, which easily avoids the
problems caused by the change of the code used by your program. Java is thus dynamic.

The following definition of Java by Sun Microsystems lists all the features of Java.

“ java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral ,portable,
high-performance, mulththreaded, and dynamic language”.
JDK TOOLS:

Java Development ToolKit(JDK) is a software package form Sun Microsystems. Version 1.1 was
released with major revisions to the original version(1.0). The latest version of JDK is JDK 1.3.

The javac Compiler:

You can create Java programs using any text editor. The file you create should have the extension
.java. Every file that you create (source code) can have a maximum of one public definition. The source code
is converted to byte code by the javac compiler converts the .java file that you create to a .class file, which
contains byte code.

Syntax for compiling java code using javac:

Javac<filename.java>

The java Interpreter

The java interpreter is used to execute compiled java applications. The byte code that is the result of
compilation is interpreted so that it can be executed.

Syntax for executing a java application using java:

Java<filename.class>

 open a new file in the editor and type the following script class first
{
public static void main(String args[])
{
System.out.println(“This is a simple java program”);
}
}

 save file as first.java


 compile by typing javac first.java on the command line.
 On successful compilation execute the program by typing java first on the command line
 The program display This is a simple java program on the screen.

In this program class to declare that a new class is being defined. First is an identifier that is the name of
the class. The entire class definition, including all of its members, will be between the opening curly brace( {
) and the closing curly brace ( }).
Next line begins the main( ) method. As the comment preceding it suggests, this the line at which the
program will begin executing. All java applications begin execution by calling main( ).
The public keyword is an access specifier, which allows the programmer to control the visibility of class
member. When a class member is preceded by public, then that member may be accessed by code outside
the class in which it is declared.
The static allows main( ) to be called without having to instantiate a particular instance of objects are
made.
The keyword void simply tells the compiler that main( ) does not return a value.
String args[ ] declares a parameter named args, which is an array of instances of the class String.
(Arrays are collections of similar objects.). objects of type String store character strings. In this case, args
receives any command-line arguments present when the program is executed.
Next System.out.println( ); Output is actually accomplished by the built-in println(
) method. In this case, println( ) displays the string which is passed to it. System is a predefined class that
provides access to the system, and out is the output stream that is connected to the console.

Data Types:
The data that is stored in memory can be of many types. For example, a person’s age is stored as a numeric
value and an address is stored as alphanumeric characters. Data types are used to define the operations possible
on them and the storage method.

The data types in Java are classified as


* Primitive or Standard data types
* Abstract or derived data types.

Standard Data Types Integer:

Integers are used for storing integer values. There are four kinds of integer types in Java. Each of these
can hold a different range of values. The values can either be positive or negative.

Type Size/form Range


at
Byte 8 bit -128 to +127
Short 16 bit -32,768 to + 32,767 (-215 to 215-1)
Int 32 bit -2,147,483,648 to +2,147,483,647
-9223372036854775808 to
Long 64 bit
+9223372036854775807 (-263 to 263-1)

Float:

Float is used to store numbers with decimal part. There are two floating point data types in Java .

Type Size/format Range


Float 32 bit +/- about 1039
double 64 bit +/- about 10317

Character:

It is used for storing individual characters.

char 16 bits of precision and it is unsigned.


Boolean:

Boolean data types hold either a true or a false value. boolean 1 bit

(true or false)

Derived Data Types:

Abstract data types are base on primitive data types and have more functionality than primitive data
types. For example, String is an abstract data type that can store letters, digits and other characters like /,( ) : ;
$ and #.
String provides methods for concatenating two strings , searching for one string within another, and
extracting a portion of a string. The standard data types do not have these features.
VARIABLES:

Variables are locations in the memory that can hold values. Before assigning any value to a variable, it
must be declared. To use the variable number storing an integer value , the variable number must be declared
and it should be of the type int.

Rules for Naming Variable:

The name of a variable needs to be meaningful, short, and without any embedded space or symbol like - ?
@ # % ^&*( ) [ ] . , ; ; “ ‘ / and \ . However , underscores can be used wherever a space is required; for
example basic salary.

Variable names must be unique. For example, to store four different numbers, four unique variable
names need to be used.

A variable name must begin with a letter , a dollar symbol($) which may be followed by a sequence
of letters or digits (0 – 9) ,’&’ or ‘_’.

Keywords cannot be used for variable names. For example , you cannot declare a variable called
switch.
Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime. These elementsare examined next.

Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of
a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s atomic types, or the nam interface types are discussed later in Part I of this
book.) The identifier is the name of the variable.

Here are several examples of variable declarations of various types. Note that
some include an initialization.

int a, b, c; // declares three ints, a, b, and c.


int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an
approximation of pi. char x = 'x'; // the variable x has the
value 'x'.

The Scope and Lifetime of Variables


So far, all of the variables used have been declared at the start of the main( ) method. However, Java
allows variables to be declared within any block. As explained in Chapter 2, a block is begun with an opening
curly brace and ended by a closing curlybrace. A block defines a scope. Thus, each time you start a new
block, you are creating a new scope. As you probably know from your previous programming experience, a
scope determines what objects are visible to other parts of your program. It also determines the lifetime of
those objects.
Most other computer languages define two general categories of scopes: global and local. However,
these traditional scopes do not fit scope defined by a method begins with its opening curly brace.

To understand the effect of nested scopes, consider the following


program: // Demonstrate block scope.

Type Conversion and Casting


If you have previous programming experience, then you already know that it is fairly common to assign a
value of one type to a variable of another type. If the two types are compatible, then Java will perform the
conversion automatically. For example, it is always possible to assign an int value to a long variable.
However, not all types are compatible, and thus, not all type conversions are implicitly allowed.

Java’s Automatic Conversions

When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
■ The two types are compatible.
■ The destination type is larger than the sou

When these two conditions are met, a widening conversion takes place. For example, the int type is
always large enough to hold all valid byte values, so no explicit cast statement is required.

It has this general form:

(target-type) value

Here, target-type specifies the desired type to convert the specified value to. For
example, the following fragment casts an int to a byte. If the integer’s valu than the range of a byte, it will be
reduced modulo (the remainder of an integer
division by the) byte’s range.

int a;
byte
b;
// ...
b = (byte) a;

A different type of conversion will occur when a floating-point value is assigned to an integer type:
truncation. As you know, integers do not have fractional components.Thus, when a floating-point value is
assigned to an integer type, the fractional component is lost. For example,
if the value 1.23 is assigned to an integer, the resulting value will simply be 1. The 0.23 will have been
truncated. Of course, if the size of the whole number component is too large to fit into the target integer
type, then that value will be
The following program demonstrates some type conversions that require casts:

// Demonstrate casts.

class Conversion {
public static void main(String args[])
{byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int
tobyte."); b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double
to int."); i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double
to byte."); b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:

Conversion of int to
byte. i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to
byte. d and b 323.142 67

LITERALS:

The variables in Java can be assigned constant values. The values assigned must match the data type
of the variables. Literals are the values that may be assigned to primitive or string type variables and
constants.

The Boolean literals are true and false.


The integer literals are numeric data. Ex(45)
The floating-point literals are numbers that have decimal fraction. Ex(34.5) Character literals are
enclosed in single quotes ex(‘a’).
String literals are enclosed in double quotes ex (“soft”).

Escape sequence character:


\n new line . \t tab. \b backspace.
OPERATORS:

Operators are used to compute and compare values, and test multiple conditions. They classified are
Arithmetic Operator, Assignment Operator , Unary Operators, Comparison Operators, Shift Operators, Bit-
Wise Operators , Logical Operators, Conditional Operators, new Operator.

Arithmetic Operators:

Operat Description Exampl Explanation


or e
+ Adds the operands X=y + z Adds the value of y and z
and stores the result in x.
- Subtracts the right X=y– Subtracts z from y and stores
operand z the result in x.
form the left operand
* Multiplies the operands X=y* Multiples the values y and z
z and store the result in x.
/ Divides the left operand by X=y/z Divides y by z and stores the
the result in x.
right operand.
% Calculates the remainder of X=y% Divides y by z and stores the
an integer division. z remainder in x.
The + operator with Numeric data types:

When you add two operands of the primitive numeric data type, the result is a primitive numeric data
type.
byte soft = 100;
byte arun= 20;
byte simi=soft+arun; Then print the

simi value is 120.

The + operator with String Data types:

When you use the + operator with numeric operands, the result is numeric. When both the operands
are strings, the + operator concatenates(joins) them. When one of the operands is a String object, the second
operand is converted to String before concatenation. For ex.

Operand1 Operand2 Result


5 6 11
5 “soft” “5soft”
“soft” “arun” “softarun”

ASSIGNMENT OPERATOR:

Operat Description Example Explanation


or
= Assigns the value of the right X=40 Assigns the value of 40 to x
operand to the left
-= Subtracts the right operand x-=y Subtracts y from x. x= x – y
form the left operand and
stores the
result in the left operand.
+= Adds the operands and X+= y Adds the value of y to x. X= x + y
assigns the result to the left
operand.
*= Multiplies the left operand by X*=y Multiplies the values x and y and stores the
the right operand and stores result in x.
the x = x * y.
result in left operand
/= Divides the left operand by the X/=y Divides x by y and stores the result in x. x =
right operand and stores the x/y
result
%= Divides the left operand by the X%=y Divides x by y and stores the remainder in
right operand and stores the x. x = x % y.
remainder in the left operand
UNARY OPERATORS
++ Increases the value X++ Equivalent to x = x + 1
of the operand by
one
-- Decrease the value X-- Equivalent to x = x – 1.
of the
operand by one
Ex : Pre-increment Post-increment
a=1; b=++a; c=1; d=c++;
After executing b=2. After executing d=1.
COMPARISON (RELATIONAL ) OPERATORS
== Evaluates whether the operands X==y Returns true if the values are
are equal equal otherwise false.
!= Evaluates whether the operands X != y Returns true if the values are
are not equal otherwise false.
not equal
> Evaluates whether the left X>y Returns true if x is greater
operand is greater than the right than y otherwise false..
operand
< Evaluates whether the left X<y Returns true if x is less than
operand is less than the right y otherwise false.
operand.
>= Evaluates whether the left X >= y Returns true if x is greater
operand than or equal to y otherwise
is greater than or equal to the false.
right operand
<= Evaluates whether the left X <= y Returns true if x is less than
operand is less than or equal to or equal to y otherwise false.
the right operand

BIT-WISE OPERATORS

Operat Description Exampl Explanation.


or e
& Evaluates to a binary value X&Y AND results in a 1 if both
( AND) after a bit wise AND on the the
operand bits are 1. any other
combination results in a 0.
| Evaluates to a binary value X|Y OR results in a 0 if the both
(O after a bit wise OR on the two the bits are 0. any other
R) operand combination results in a 1.
^ Evaluates to a binary value X^Y XOR results in a 0 if both
(XO after a bit wise XOR on the the bits are of the same
R) two operand. value and
1if the bits have diff. values.
~ Converts all 1 bits to 0s and all Example given
0s bits to 1s bellow
Example:
a=1010001 a~ = 0101110

LOGICAL OPERATORS

&& Evaluates to true if both the X>5 The result is true if


condition evaluate to true && Y condition1(x>5) and
other wise false. <5 condition2 (y<5) are both
true. If one of them false ,
the result
is false.
|| Evaluates to true if at least X > 5 || y The result is true if either
one of the conditions evaluates <10 condition1(x>5) or
to true, and false if none of the condition2 (y<10) or both
conditions evaluates to true. evaluate to true. If both the
conditions are false,
the result is false
CONDITIONAL OPERATOR

(Condition)
Evaluates to val1 if the X = (y>z) X is assigned the value of
? val1 : val2
condition returns true and ? y if y is greater than z ,
val2 if the condition y :z else x is assigned the
returns value of z.
false
SHIFT OPERATORS

>> Shifts bits to the right, filling sign X=10 >>3 The result of this is 10
bits at the left and it is also called divided by 23. an
the signed right shift operator explanation is given
bellow.
<< Shifts bits to the left filling zeros at X=10<<3 Result of this is 10
the right. multiplied
by 23.
>>> Also called the unsigned shift X= -10 An
operator works like the >> >>> explanation is given
operator, but fills in zeroes for the 3 bellow.
left.

The int data type occupies four bytes in the memory. The rightmost eight bits of the number 10 are
represented in binary as
0 0 0 0 1 0 1 0

When you do a right shift by 3 ( 10 >>3), the result is 10/23


0 0 0 0 0 0 0 1

When you do a left shift by 3 ( 10 <<3) , the result is 10 * 2 3 which is equivalent to 80.
0 1 0 1 0 0 0 0
The new Operator:

When you create an instance of a class, you need to allocate memory for it. When you declare an
object, you merely state its data type.
Pen blcakPen; This tells the compiler that the variable blackPen is an object of the Pen class. It does
not allocate the memory for the object.
To allocate the memory, you need to use the new operator.

Syntax:

<class_name> = new<class_name>( ); Example:


Pen blockPen= new Pen( );

ORDER OF PRECEDENCE OF OPERATORS:

[ ] , ( ) , + , - , ~ , !, ++ , -- , *,/,%,+,-,
<<,>>,>>>,<,<=,>=,>,= =,!=,
&,^,|,&&,||,?:,=,+=,-=,*=,/=,%=
CONTROL STATEMENTS:

if .. else statements.

The if decision construct is followed by a logical expression in which data is compared and a
decision is made based on the result of comparison. The condition is true then true part statement is to be
executed and exit the loop otherwise else part statement is to be executed and exit the loop.

Syntax:
if (boolean_expr)
{
statements;
}
else
{
statements;

example
: class ifodd
{
public static void main(String args[])
{
int n=Integer.parseInt(args [0]);
if(n%2 ==0)
System.out.println("Given number " + n +"is even");
else
System.out.println("Given number " + n + "is odd ");
}
}
while Loop statements.
The while loop is a looping construct available in java. The while loop continues until the
evaluating condition becomes false. The evaluating condition has to be a logical expression and must return
a true or false value. The variable that is checked in the Boolean expression is called the loop control
variable.

Syntax
While(Boolean_expr)
:
{
statements
}

example:

class facwhile
{
public static void main(String args[])
{
int n=Integer.parseInt(args [0]); int i=1, f=1;
while(i<=n)
{
f=f*i; i=i+1;
}
System.out.println(+f);
}}

do .. while Loop:

In a while loop, the condition is evaluated at the beginning of the loop. If the condition is false, the
body of the loop is not executed. If the body of the loop must be executed at least once, than the do..while
construct should be used. The do .. while construct places the test expression at the end of the loop.
The keyword do marks the beginning of the loop. The braces delimit the body of the loop. Finally,
a while statement provides the condition and ends the body of the loop.

Syntax:
do
{
statements;
}while(boolean_expr);example:

class arms
{
public static void main(String args[])
{
int n=Integer.parseInt(args[0]); int s=0,t=n,r;
do
{ r=n%10;
s=s+r*r*r; n=n/10;
}while(n!=0); if(t==n)
System.out.println("Given number is arms"+t); else
System.out.println("Given number is not arms"+t);
}}

for Loop:

The while and the do..while loops are used when the number of iterations(the number of the times
the loop body is executed) is not known. The for loop is used in situations when the number of iterations is
known in advance. For example, it can be used to determine the square of each of the first ten numbers.
The for statement consists of the keyword for, followed by parentheses containing three expressions
each separated by a semicolon. These are the initialization expression, the test expression and the
increment/decrement expression.

Syntax
: for(initialization_expr;test_expr;increment/decrement_expr)
{
statements;
}

Initialization expression:

The initialization expression is executed only once, when the control is passed to the loop for the first
time. It gives the loop variable an initial value.
Test expression:

The condition is executed each time the control passes to the beginning of the loop. The body of the
loop is executed only after the condition has been checked. If the condition evaluated to true, the loop is
executed otherwise, the control passes to the statement following the body of the loop.

Increment / Decrement expression:

The increment / decrement expression is always executed when the control returns to the beginning
of the loop.

example:
class fib
{
public static void main (String args[])
{
int n=Integer.parseInt(args[0]);
int n1=-1, n2=1,int n3;
System.out.println("FIBONACCI SERIES ");
for(int i=1;i<n;i++)
{
n3=n1+n2;
System.out.println(n3);
n1=n2;
n2=n3;
}}}
switch statement:

The switch statement is Java’s multi way branch statement. It provides an easy way to dispatch
execution to different parts of your code based on the value of an expression. As such, it often provides a
better alternative than a large series of if-else-if statements .

Syntax:

switch(expression)
{
case value1:
stt. break;
case value2:
Stt. break;
case value n:
Stt. break;
default: stt.
}

The expression must be of type byte, short, int, or char; each of the values specified in the case
statements must be of a type compatible with the expression. Each case value must be a unique literal(that is,
it must be a constant, not a variable). Duplicate case values are not allowed.
The switch statement works like this: The value of the expression is compared with each of the literal
values in the case statements. If a match is found, the code sequence following that case statement is executed.
If none of the constants matches the value of the expression, then the default statement is executed. However,
the default statement is optional. If no case matches and no default is present, then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence. When a break
statement is encountered, execution branches to the first line of code that follows the entire switch statement.
This has effect of “jumping out” of the switch.

CLASSES AND OBJECTS


Concepts of classes and objects:
Class Fundamentals
Classes have been used since the beginning of this book. However, until now, only the most
rudimentary form of a class has been used. The classes created in the preceding chapters primarily exist
simply to encapsulate the main( ) method, which has been used to demonstrate the basics of the Java syntax.
Thus, a class is a template for an object, and an object is an instance of a class. Because an object is
an instance of a class, you will often see the two words object and instance used interchangeably.
The General Form of a Class

When you define a class, you declare its exact form and nature. You do this by specifying
the data that it contains and the code that operates on that data.
A class is declared by use of the class keyword. The classes that have been used up to this point
are actually very limited examples of its complete form. Classes can (and usually do) get much more
complex. The general form of a class definition is shown here:
class classname {
type
in
stance-variable1; typeinstance-variable2; // ... type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is contained
within methods. Collectively, the methods and variables defined within a class are called members of the
class. In most classes, the instance variables are acted upon and accessed
by the methods defined for that class. Thus, it is the methods that de can be used.

Declaring Objects

As just explained, when you create a class, you are creating a new data type. You can use this type to
declare objects of that type. However, obtaining objects of a class is a two-step process. First, you must
declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable
that can refer to an object. Second, you must acquire an actual, physical copy of the object and assign it to
that variable. You can do this using the new operator. The new operator dynamically allocates (that is,
allocates at run time) memory for an object and returns a reference to it. This reference is, more or less, the
address in memory of the object allocated by new.
Ex: Box mybox = new Box();

This statement combines the two steps just described. It can be rewritten like this
to show each step more clearly:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box
object

A Closer Look at new

As just explained, the new operator dynamically allocates memory for an object. It has this
general form:

class-var = new classname( );

Here, class-var is a variable of the class type being created. The classname is the name of the class that is
being instantiated. The class name followed by parentheses specifies the constructor for the class. A
constructor defines what occurs when an object of a class is created. Constructors are an important part of all
classes and have many significant attributes. Most real-world classes explicitly define their own constructors
within their class definition. However, if no explicit constructor is specified, then Java will automatically
supply a default constructor. This is the case with Box.

JAVA AS AN OOP LANGUAGE


Java is a true object-oriented language and therefore the underlying structure of all java programs is
classes. Anything we wish to represent in a java program must be encapsulated in a class that defines the
stateand behavior of the basic program components known as objects. Classes create objects and objects use
methods to communicate between them. That is all about object-oriented programming.

Classes provide a convenient method for packing together a group of logically related data items and
functions that work on them. In java, the data items are called fields and the functions are called methods.
Calling a specific method in an object is described as sending the object a message

A class is essentially a description of how to make an object that contains fields and methods. It
provides a sort of templatefor an object and behaves like a basic data type such as int. it is therefore important
to understand how the fields and methods are defined in a classes and how they are used to build a java
program that incorporates the basic OOP concepts such as encapsulation, inheritance and polymorphism.

Class :
Class is collection of objects.

Object:
Object is a instance of a particular class.

General form of class: class class name


{
type instance variable 1; type instance
variable 2;
….
….
….
type instance variable n;
class name1(parameter-list)
{
body of constructor;
}

class name2(parameter-list)
{
body of constructor;
}
class name n(parameter-list)
{
body of constructor;
}

type methodname1(parameter-list)
{
body of method;
}

type methodname2(parameter-list)
{
body of method;
}

…..
type method name n(parameter-list)
{
body of method;
}
}

Instance variable:

Data or Variable declare within the class is called instance variable.

Method:

The source code within the class is called method.

Member:

The methods and variables defined within a class are called members of the class.
Creating a class:

class sample
{
int a; int b; int c;
}

This declaration defines a class called sample that consists of three integer members: a , b and
c. It is important to understand that this declaration does not actually create any objects.

Creating objects:

An object in java is essentially a block of memory that contains space to store all the instance
variables. Creating an object is also referred to as instantiating an object.
Objects in java are created using the new operator. The new operator dynamically allocates(that is ,
allocates run time)memory for an object and returns a reference to that object.
To create objects of type sample, use statements such as the following: sample one = new sample( );
sample two = new sample( );
After these statements execute, there are two objects that have the form described by sample. The
variable one holds a reference to one of these objects. The variable two holds a reference to the other. Each
object has its own copies of variables a, b, and c.

Dot Operator:
The dot notation is used to obtain the value of the instance variables. It has two parts namely the
object on the left side of the dot and the variable on the right side of the dot. Dot expressions are evaluated
from left to right. The general form for accessing instance variables using the dot operator is given below:
Objectreference.variable name
We can store values into instance variables using the dot operator as shown below:
one.a=10; one.b=20; one.c=30; two.a=15;
two.b=10; two.c=35;
We can refer to values of instance variables using the dot operator as given below:
System.out.println(“a=”+one.a +”b=” +one.b +”c=”+one.c); System.out.println(“a=”+two.a +”b=”
+two.b +”c=”+two.c);

example for class and object:

This program save filename is excla this is the main class name. class add
{
double a,b,c;
}
class excla
{
public static void main(String args[])
{
add one=new add(); double val;
one.a=10; one.b=20; one.c=30;
val=one.a+one.b+one.c; System.out.println(val);
}}
METHODS:

Methods are functions that operate on instances of classes in which they are defined. Objects can
communicate with each other using methods and can call methods in other classes.

Defining Methods:

Method definition has four parts. They are, name of the method, type of object or primitive type the
method returns, a list of parameters and body of the method. A method’s signature is a combination of the
first three parts mentioned above. Java permits different methods to have the same name as long as the
argument list is different. This is called method overloading. This is the general form of a method
type name(parameter-list)
{
body of method;
}

here, type specifies the type of data returned by the method. This can be any valid type, including class
types that you create. If the method does not return a value, its return type must be void. The name of the
method is specified be name. The parameter-list is a sequence of type and identifier pairs separated by
commas, the method when it is called. If the method has no parameters, then the parameter list will be empty.
Methods that have a return type other than void return a value to the calling routine using the
following form of the return statement: return value;
Here , value is the value returned.

Calling Methods:

Calling a method is similar to calling or referring to an instance variable. The methods are accessed
using the dot notation. The object whose method is called is on the left of the dot while the name of the
method and its arguments are on the right.
obj. method name(parameter1, parameter2);
example for method:

class exmet
{
int a,b,c; void cal( )
{
System.out.println("example of method "); System.out.println(a*b*c);
}
public static void main(String args[])
{
exmet mymul=new exmet( );
mymul.a=Integer.parseInt(args[0]); mymul.b=20;
mymul.c=15; mymul.cal( );
}}

passing Argument to methods:

The objects that are passed to the body of the method are passed by reference and the basic types are
passed by value. This results in a change in original value of the object if the valued is modified in the
method.
Example the passing of arguments to methods.

class mul
{
int a;
int sqr(int a)
{
System.out.println("squre value is ");
return a*a;
}}
class exmet3
{
public static void main(String args[])
{
mul mymul=new mul(); int vol;
vol=mymul.sqr(5);
System.out.println(vol);
}}

The this keyword:

A special reference value called this is included in java. The this keyword is used inside any instance
method to refer to the current object. The value this refers to the object which the current method has been
called on. The this keyword can be used where a references to an object of the current class type is required.

Example of this keyword:

class this1
{
int x,y;
void show(int x,int y)
{
this.x=x; this.y=y;
}
void disp()
{
System.out.println(“x=”+x);
System.out.println(“y=”+y);
}}
class exthis
{
public static void maim (String args[])
{
this1 th=new this1(); th.show(4,6);
th.disp();
}}

output of the program is : x=4 y=6.

Overloading Methods:

In java it is possible to define two or more methods within the same class that share the same name, as
long as their parameter declarations are different. When this is the case, the methods are said to be
overloaded, and the process is referred to as method overloading. When we call a method in an object, java
matches up the method name first and then the number and type of parameters to decide which one of the
definitions to execute. This process is known as polymorphism.

Example of overloading method:

class exover
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a :"+a);
}
void test(int a, int b)
{
System.out.println("a and b "+a+ " "+b);
}
double test(double a)
{
System.out.println("double value is "+a); return a*a;
}
public static void main(String args[])
{
exover ex=new exover(); double d;
ex.test();
ex.test(10);
ex.test(10,20); d=ex.test(120.5);
System.out.println("double result is "+d);
}}
Constructors:

Often an object will require some form of initialization when it is created. To accommodate this, java
allows you to define constructors for your classes. A constructor is a special method that creates and
initializes an object of a particular class. It has the same name as its class and may accept arguments. In this
respect, it is similar to any other method.
However, a constructor does not have a return type. Instead, a constructor returns a reference to the
object that it creates. If you do not explicitly declare a constructor for a class, the java compiler automatically
generates a default constructor that has no arguments.
A constructor is never called directly. Instead, it is invoked via the new operator.
And allocate the memory space.

example for constructor :

class mul
{
double a,b,c; mul()
{
System.out.println("Constructor example"); a=10;
b=5; c=10;
}
double cal()
{
System.out.println("calculated value is "); return a*b*c;
}
}
class excon
{
public static void main(String args[])
{
mul mymul=new mul(); double vol;
vol=mymul.cal();
System.out.println(vol);
}}
Constructor Overloading:

A class may have several constructors. This feature is called constructor overloading. When
constructors are overloaded, each still called by the name of its class. However, it must have different
parameter list. In more precise terms, the signature of each constructor must differ.

example for constructor overloading:

class exover1
{
int a,b,c;
exover1(int x,int y,int z)
{
a=x;b=y;c=z;
}
exover1()
{ a=1;b=1;c=1;
}
exover1(int d)
{
a=d;b=d;c=d;
}
int cal()
{
return a*b*c;
}
public static void main(String args[])
{
exover1 ex=new exover1(5,5,5); exover1
ex1=new exover1(); exover1 ex2=new
exover1(2); int k;
System.out.println("first resutl"); k=ex.cal();
System.out.println(k);
System.out.println("second result"); k=ex1.cal();
System.out.println(k); System.out.println("third
result"); k=ex2.cal(); System.out.println(k);
}}
Recursion:

Java supports recursion. The method call by itself is called recursive method.

Example for recusion:

class fact
{
int fact(int n)
{
int result; if(n==1) return 1;
result=fact(n-1)*n; return result;
}
public static void main(String args[])
{
fact f=new fact();
System.out.println("factorial value is "+f.fact(4));
System.out.println("factorial value is "+f.fact(5));
System.out.println("factorial value is "+f.fact(6));
}}

Inner Classes:

It is possible to nest a class definition within another class and treat the nested class like any other
method of that class. Such a class is called nested class. As a member of its enclosing class , a nested class has
privileges to access all the members of the class enclosing it. A nested class can either be static or not-static.
While static nested classes are just called as static nested classes, non-static classes are called as inner classes.

Example for inner classes:

class inner
{
void test()
{
inn in=new inn(); in.disp();
}
class inn
{
int x=10,y=5;
void disp()
{
int z=x+y;
System.out.println("example for inner class "); System.out.println("x + y
value is : "+z);
}}

public static void main(String args[])


{
inner o=new inner(); o.test();
}}
unit 2

Arrays:

An array is a group of like-typed variables that are referred to by a common name.


Arrays of any type can be created and may have one or more dimensions.

One-Dimensional Arrays:

An one-dimensional array is , essentially, a list of like-typed variables. To create a array, you first
must create an array variable of the desired type. The general form of a one- dimensional array declaration is
Type var-name[ ];

The general form of new as it applies to one-dimensional arrays appears as follows


Array-var = new type [size];

Here type declares the base type of the array. The base type determines the data type determines the data type of
each element that comprises the array.

Example

class sort
{
public static void main(String args[])
{
int a[]=new int[10]; int j,i,n;
n=Integer.parseInt(args[0]); for(i=1;i<=n;i++)
{
a[i]=Integer.parseInt(args[i]);
}
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(a[i]>a[j])
{
int temp=a[i]; a[i]=a[j]; a[j]=temp;
}
}}
for(i=1;i<=n;i++)
{
System.out.println(a[i]);
}
}}

Multidimensional Arrays:

In java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look and
act like regular multidimensional arrays. However, as you will see, there are a couple of subtle differences. To
declare a multidimensional array variable, specify each additional index using another set of square brackets.
A two-dimensional array can be thought of as a table of rows and columns.
Syntax:
Data type array-name[][]; (Or)
data type array-name[][]=new data type [row size] [column size];

Example
: class mattra
{
public static void main (String args[])
{
int a[][]=new int[10][10];
int b[][]=new
int[10][10]; int j,i,k=0;
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
a[i][j]=Integer.parseInt(args[k]); k=k+1;
}
}
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
b[i][j]=a[j][i]; k=k+1;
}}
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
System.out.print(" "+ b[i][j]);
}
System.out.println(" ");
}
}
}

Inheritance:

Inheritance is new class derived from old class. Some modification about particular class. It should
invoke super class(base class) & sub class(derived class).

Types of inheritance:

1. Single Inheritance (only one super class).


2. Multiple Inheritance (several super class).
3. Multilevel Inheritance (derived from a derived class).
4. Hybrid Inheritance (combination of multiple and multilevel inheritance).
5. Hierarchical Inheritance ( one super class, many subclasses).

Java does not directly implement multiple inheritance. However, this concept is implemented using a
secondary inheritance path in the for of interfaces.

Defining a subclass:

class subclass name extends super class name


{
variable declaration; methods declaration;
}

The keyword extends signifies that the properties of the super class name are extended to the
subclass name. The subclass will now contain its own variables and methods as well those of the super
class. This kind of situation occurs when we want to add some more properties to an existing class without
actually modifying it.

Example for single inheritance:

class a
{
int i;
private int j;
void setval(int x,int y)
{
i=x;j=y;
System.out.println("i value is "+i +" j value is "+j);
}
}
class b extends a
{
int total,j=15; void sum()
{
total =i+j;
System.out.println("total is :"+total);
}
}
class inher1
{
public static void main(String args[])
{
b bb=new b(); bb.setval(4,6);
bb.sum();
}
}
example multilevel inheritance

class a
{
int i;
private int j;
void setval(int x,int y)
{
i=x;j=y;
System.out.println("i and j value is "+i +" "+j);
}}
class b extends a
{
int total,k=10; void sum()
{
total =i+k;
System.out.println("first subclass value is "+total);
}}
class c extends b
{
int a,b,c;
void cal(int a)
{
c=a+i+k;
System.out.println("multilevel inheritance is "+c);
}
void setval(int x)
{
b=x;
System.out.println("b value is "+b);
}
}
class inher2
{
public static void main(String args[])
{
c bb=new c(); bb.setval(10,6);
bb.setval(5);
bb.sum();
bb.cal(100);
}}
Super keyword:

A subclass constructor is used to construct the instance variable of both the subclass and the
superclass. The subclass constructor uses the keyword super to invoke the constructor method of the
super class. The keyword super is used subject to the following conditions

o Super may only be used within a subclass constructor method.


o The call to super class constructor must appear as the first statement within the super class constructor.
o The parameters in the super call must match the order and type of the instance variable declared in the
super class.

Example for super keyword:

class a
{
int i;
}
class b extends a
{
int i;
b(int a,int b)
{
super.i=a; i=b;
}
void show()
{
System.out.println("base class variable i value is " +super.i); System.out.println("sub class
variable i value is " +i);
}}
class exsuper
{
public static void main(String args[])
{
b ob=new b(4,6); ob.show();
}}
Method Overriding:

In a class hierarchy, when a method in a subclass has the same name and type signature as a method in
its superclass, then the method in the subclass is said to override the method in the superclass. When an
overridden method is called from within a subclass, it will always refer to the version of that method defined
by the subclass.

Example for overriding:

class a
{
void hello( )
{
System.out.println(“hello from a”);
}}

class b extends a
{
void hello( )
{
System.out.println(“hello from b”);
}}
class c extends b
{
void hello( )
{
System.out.println(“hello from c”);
}}
class exover
{
public static void main(String args[])
{
c ob=new c( ); ob.hello( );
}}

output from this application is shown here: hello from c


another example for overriding:

class a
{
int i,j;
a(int a,int b)
{
i=a;j=b;
}
void show()
{
System.out.println("i value is "+i); System.out.println("j
value is "+j);
}}
class b extends a
{
int k;
b(int a,int b,int c)
{
super(a,b); k=c;
}

void show()
{
super.i=10;
System.out.println("k value is "+k); super.show();
}
}
class supers
{
public static void main(String args[])
{
b ob=new b(1,2,3);
ob.show();
}}
Hierarchical inheritance:

It is one base class many sub class.

Example of Hierarchical inheritance:

class a
{
int i; int j;
void setval(int x,int y)
{
i=x; j=y;
System.out.println("i and j value is "+i +" "+j);
}}
class b extends a
{
int total; void sum()
{
total =i+j;
System.out.println("first subclass add value is "+total);
}}
class c extends a
{
int c; void cal()
{
System.out.println(" i value is "+i);
System.out.println(" j value is "+j); c=i-j; In this program save as file name is
System.out.println("Second subclass sub vlaue is "+c); inher3. This program base class is
}} “a” . Then “b” and “c “ class are
the subclass of “a” class. These
class inher3 two class are different operation
{ this program to satisfy the one base
public static void main(String args[]) class more than one sub class so
{ it’s hierarchical inheritance
b bb=new b(); bb.setval(10,6); program.
bb.sum();
c cc=new c(); cc.setval(15,6);
cc.cal();
}}
Interfaces:
Using the keyword interfaceyou can fully abstract a class interface from its implementation. That is,
using interface you can specify what a class must do, but not how it does it.
Like classes, interfaces contain methods and variables but with a major difference. The difference is
that interfaces define only abstract methods and final fields. This means that interfaces do not specify and
code to implement these methods and data fields contain only constants.
Therefore, it is the responsibility of the class that implements an interface to define the code for
implementation of these methods.
The syntax for defining an interface is very similar to that for defining a class. The general form of an
interface definition is:
interface Interfacename
{
variable declaration; methods declaration;
}

Here, interface is the key word and Interface name is any valid java variable(just like class names).
Variables are declared as follows:
Type final-variable-name1=value; Type final-variable-
name2=value;

Note that all variables are declared as constants. Methods declaration will contain only a list of
methods without any body statements. Example
return-type methodname1(parameter-list);
return-type methodname2(parameter-list);
Here is an example of an interface definition that contains two variables and one method
interface
area
{ final float pi=3.142f;
float compute (float x, float y);
void show( );

}
here pi is the float type variable it will be declare as final suppose you declare simply float pi=3.142f that will
be consider as final type.

Extending interfaces:

Like classes, interfaces can also be extended. That is , an interface can be sub interfaced from other
interfaces. The new sub interface will inhert all the members of the super interface in the manner similar to
subclasses. This is achieved using the keyword extends as shown below:
Interface name2 extends name1
{
body of name2;
}

Example:
interface itemconstant
{
int code= 1001; String name=”fan”;
}
interface item extends itemconstant
{
void display( );
}

while interfaces are allowed to extend to other interfaces, sub interfaces cannot define the methods
declared in the super interfaces. After all, sub interfaces are still interfaces, not classes. Note that when an
interface extends two or more interfaces, they are separated by commas.
It is important to remember that an interface cannot extend classes. This would violate the rule that an
interface can have only abstract methods and constants.
Implementing interface:

Interfaces are used as “super classes” whose properties are inherited by classes. It is therefore
necessary to create a class that inherits the given interface. This is done as follows:
Class classname implements interfacename
{
body of classname;
}

Here the class classname “implements” the interface interfacename. A more general form of implementation
may look like this:

Class classname extends superclass implements interface1,interface2,…


{
body of classname;
}

This is shows that a class can extend another class while implementing interfaces. When a class implements

more than one interface, they are separated by a comma.

Example of Interface with implements (Multiple inheritance)

class onee
{
int a,b,c;
void setval(int x,int y)
{
a=x; b=y;
}

void cal()
{
c=a+b;
System.out.println("base class 1 " + c);
}
}

interface two
{
int x = 10;
}

class three extends onee implements two


{
int y= 20; void cal1()
{
c=a+x+y;
System.out.println("multiple inheritance c value is"+c);
}
}

class mulpinh
{
public static void main(String args[])
{
three t=new three();
t.setval(4,6);
t.cal();
al1();
}
}
Hybrid inheritance:

Combination of multiple and multiple inheritance is called hybrid inheritance.


Example of hybrid inheritance is:

class student
{
int rollno;
void getnumber(int n)
{
rollno=n;
}
void putnumber()
{
System.out.println("Roll Number :"+rollno);
}
}
class mark extends student
{
int ma1,ma2;
void getmarks(int m1,int m2)
{
ma1=m1; ma2=m2;
}
void putmarks()
{
System.out.println("marks obtained"); System.out.println("mark1
:"+ma1); System.out.println("mark2 :"+ma2);
}
}

interface clas
{
String cla="iii cs b"; void
putclas();
int ma3=100;
}

class result extends mark implements clas


{
int total;
public void putclas()
{
System.out.println("class :"+cla);
}
void display()
{
total=ma1+ma2+ma3; putnumber();
putmarks();
System.out.println(“mark3: “+ma3); putclas();
System.out.println("total mark:"+total);
}}

class inter1
{
public static void main (String args[])
{
result ob=new result();
ob.getnumber(100);
ob.getmarks(45,66); ob.display();
}
}

Packages: Putting classes together

We have repeatedly stated that one of the main features of OOP is its ability to reuse the code already
created. One way achieving this is by extending the classes and implementing the interfaces we had created as
discussed. This limited to reusing the classes within a program. What if we need to use classes from other
programs without physically copying them into the program under development?. This can be accomplished
in java by using what is known as package, a concept similar to “ class libraries” in other languages. Another
way of achieving the reusability in java, therefore, is to use package.

Packages are java’s way of grouping a variety of class and/or interfaces together. The grouping is
usually done according to functionality. In fact, packages act as “containers” for classes. By organizing our
classes into packages we achieve the following benefits:

1. The classes contained in the packages of other programs can be easily reused.
2. In packages, classes can be unique compared with classes in other packages. That is, two classes in two
different packages can have the same name. They may be referred by their fully qualified name, comprising
the package name and the class name.
3. Packages provide a way to “hide” classes thus preventing other programs or packages from accessing classes
that are meant for internal use only.
4. Packages also provide a way for separating “design” from “coding”. First we can design classes and decide
their relationships, and then we can implement the java code needed for the methods. It is possible to change
the implementation of any method without affecting the rest of the design.

Java packages are therefore classified into two types. The first category is known as
Java API packages and the second is known as user defined packages.

JAVA API PACKAGES:

Java API provides a large number of classes grouped into different packages according to
functionality. Most of the time we use the packages available with the java API. Java has a six packages.

Java.lang :

Language support classes. These are classes that java compiler itself uses and therefore they are
automatically imported. They include classes for primitive types, strings, math function, threads and
exception.

Java.util :

Language utility classes such as vectors, hash tables, random numbers, date, etc.

Java.io :

Input/output support classes. They provide facilities for the input and output of data.

Java.awt :

Set of classes for implementing graphical user interface. They include classes for windows, buttons,
lists, menus and so on.

Java.net :

Classes for networking. They include classes for communicating with local computers as well as with
internet servers.
Java.applet :

Classes for creating and implementing applets.

USER DEFINED PACKAGES:

User create a packages and process is called user defined packages. Let us see how to create our own
packages. We must first declare the name of the package using the package keyword followed by a package
name. This must be the first statement in a java source file ( except for comment and white spaces). Then we
define a class, just as we normally define a class. Here is an example
package firstpackage;

public class firstclass


{

---------------- (body of class)


}

Here the package name is firstpackage. The class firstclass is now considered a part of this package.
This listing would be saved as a file called firstclass.java , and located in a directory named firstpackage.
When the source file is compiled, java will create a .class file and store it in the same directory.
Remember that the .class files must be located in a directory that has the same name as the package,
and this directory should be a subdirectory of the directory where classes that will import the package are
located.

To recap, creating our own package involves the following steps:

1. Declare the package at the beginning of a file using the form package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source files are stored.
4. Store the listing as the classname.java file in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.

Remember that case is significant and therefore the subdirectory name must match the package name exactly.
As pointed out earlier, java also supports the concept of package hierarchy. This is done by specifying
multiple names in a package statement, separated by dots.
ACCESSING A PACKAGE:
It will recalled that we have discussed earlier that a java system package can be accessed either using a
fully qualified class name or using a shortcut approach through the import statement. We use the import
statement when there are many references to a particular package or the package name is too long and
unwieldy.
The same approaches can be used to access the user-defined packages as well. The import statement
can be used to search a list of packages for a particular class. The general form of import statement for
searching a class is as follows:

Import package1 [.package2] [.package3].classname;

Here package1 is the name of the top level package, package2 is the name of the package that is
inside the package1, and so on. We can have any number of packages in a package hierarchy. Finally, the
explicit classname is specified. Note that the statement must end with a semicolon(;). The import statement
should appear before any class definitions in a source file.

USING A PACKAGE :
Let us now consider some simple programs that will use classes from other packages.
The listing below shows a package named visa containing a single class gisa.

package visa; public class gisa


{
public void show()
{
System.out.println("welcome to all by arun saran"); System.out.println("welcome to
package program");
}
}
This source file should be named gisa.java and stored in the subdirectory visa as started earlier. Now compile
this java file. The resultant gisa.class will be stored in the same subdirectory.
Now consider the listing shown below:

import visa.gisa;

public class simi


{
public static void main(String args[])
{
gisa ob=new gisa(); ob.show();
}}

This listing shows a simple program that imports the class gisa from the package visa. The source file
should be saved as simi.java and then compiled. The source file and the compiled file would be saved in the
directory of which visa was a subdirectory. Now we can run the program and obtain the results.
During the compilation of simi.java the compiler checks for the file gisa.class in the visa directory
for information it needs, but it does not actually include the code from gisa.class in the file simi.class. when
the simi program is run, java looks for the file simi.class and loads it using something called class loader.
Now the interpreter knows that it also needs the code in the file gisa.class and loads it as well.

This program compiled and run to obtain the results. The output will be as under Welcome all by arun
saran
Welcome to package program
MULTIPLE PACKAGES:

More than one package is to be created and imported and process is known as multiple packages.

Example:

package a1; public class one


{
int a=10,b=5; public void show()
{
int c=a+b;

(program 1)
System.out.println("Add value is"+c);
}

public void show1()


{
int c=a*b;
System.out.println("Mul value is"+c);
}
}

first create one folder in c: that is (c:\arun) and save this file as one.java. (program 2)

package a1;

public class two


{
int a=10,b=2; public void cal()
{
int c=a-b;
System.out.println("Sub value is "+c);
}
public void cal1()
{
int c=a/b;
System.out.println("Divide value is "+c); System.out.println(“End of
package program”);
}}

this program save as this directory and name is (two.java).


(program 3)

import a1.one; import a1.two;


public class three
{
public static void main(String args[])
{
one ob=new one(); two ob1=new
two(); ob.show();
ob.show1();
ob1.cal();
ob1.cal1();
}}
This program save as the same directory and save as file name as(three.java).

Save these three program and then compile the first two programs before set path as below.Suppose
your java software as place in your system on c: then follow the procedure as follow.

C:\arun> path = c:\jdk1.3\bin> then press enter

C:\arun> javac one.java ,, ,


,
C:\arun> javac two.java ,, ,
,
This time java to create automatically two files that is one.class , two.class .
Then to create subdirectory on package name (that is a1)
C:\arun> md a1 then press enter then copy this two class file on the subdirectory area. C:\arun>copy
one.class c:\arun\a1 then press enter
C:\arun>copy two.class c:\arun\a1 then press enter Then set class
path as follows

C:\arun> set classpath = c:\arun;%classpath%; Then compile

the third program


C:\arun> javac three.java then press enter C:\arun> java
three ,, ,, ,,

Then output as follows


Add value is 15 Mull value is 50 Sub
value is 8 Divide value is 5
End of package program
Strings, which are widely used in Java programming, are a sequence of characters. In Java programming
language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.
The most direct way to create a string is to write −
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this
case, "Hello world!'.
Example
public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}

String class in Java


 Difficulty Level : Easy
 Last Updated : 03 Nov, 2022

Read

Discuss(18)

Courses

Practice

Video
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 = “GeeksforGeeks”;
 Using new keyword
String s = new String (“GeeksforGeeks”);

Constructors
1. String(byte[] byte_arr) – Construct a new String by decoding the byte array. It uses the platform’s default
character set for decoding.
Example:
2. byte[] b_arr = {71, 101, 101, 107, 115};
3. String s_byte =new String(b_arr); //Geeks
4. String(byte[] byte_arr, Charset char_set) – Construct a new String by decoding the byte array. It uses
the char_set for decoding.
Example:
5. byte[] b_arr = {71, 101, 101, 107, 115};
6. Charset cs = Charset.defaultCharset();
7. String s_byte_char = new String(b_arr, cs); //Geeks
8. String(byte[] byte_arr, String char_set_name) – Construct a new String by decoding the byte array. It uses
the char_set_name for decoding.
It looks similar to the above constructs and they appear before similar functions but it takes the String(which
contains char_set_name) as parameter while the above constructor takes CharSet.
Example:
9. byte[] b_arr = {71, 101, 101, 107, 115};
10. String s = new String(b_arr, "US-ASCII"); //Geeks
11. String(byte[] byte_arr, int start_index, int length) – Construct a new string from the bytes array depending on
the start_index(Starting location) and length(number of characters from starting location).
Example:
12. byte[] b_arr = {71, 101, 101, 107, 115};
13. String s = new String(b_arr, 1, 3); // eek
14. String(byte[] byte_arr, int start_index, int length, Charset char_set) – Construct a new string from the bytes
array depending on the start_index(Starting location) and length(number of characters from starting
location).Uses char_set for decoding.
Example:
15. byte[] b_arr = {71, 101, 101, 107, 115};
16. Charset cs = Charset.defaultCharset();
17. String s = new String(b_arr, 1, 3, cs); // eek
18. String(byte[] byte_arr, int start_index, int length, String char_set_name) – Construct a new string from
the bytes array depending on the start_index(Starting location) and length(number of characters from starting
location).Uses char_set_name for decoding.
Example:
19. byte[] b_arr = {71, 101, 101, 107, 115};
20. String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks
21. String(char[] char_arr) – Allocates a new String from the given Character array
Example:
22. char char_arr[] = {'G', 'e', 'e', 'k', 's'};
23. String s = new String(char_arr); //Geeks
24. String(char[] char_array, int start_index, int count) – Allocates a String from a given character array but
choose count characters from the start_index.
Example:
25. char char_arr[] = {'G', 'e', 'e', 'k', 's'};
26. String s = new String(char_arr , 1, 3); //eek
27. String(int[] uni_code_points, int offset, int count) – Allocates a String from a uni_code_array but
choose count characters from the start_index.
Example:
28. int[] uni_code = {71, 101, 101, 107, 115};
29. String s = new String(uni_code, 1, 3); //eek
30. String(StringBuffer s_buffer) – Allocates a new string from the string in s_buffer
Example:
31. StringBuffer s_buffer = new StringBuffer("Geeks");
32. String s = new String(s_buffer); //Geeks
33. String(StringBuilder s_builder) – Allocates a new string from the string in s_builder
Example:
34. StringBuilder s_builder = new StringBuilder("Geeks");
35. String s = new String(s_builder); //Geeks
String Methods
int length(): Returns the number of characters in the String.
"GeeksforGeeks".length(); // returns 13
Char charAt(int i): Returns the character at ith index.
"GeeksforGeeks".charAt(3); // returns ‘k’
String substring (int i): Return the substring from the ith index character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”
String substring (int i, int j): Returns the substring from i to j-1 index.
"GeeksforGeeks".substring(2, 5); // returns “eks”
String concat( String str): Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
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 = ”Learn Share Learn”;
int output = s.lastIndexOf("a"); // returns 14
boolean equals( Object otherObj): Compares this string to the specified object.
Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false
boolean equalsIgnoreCase (String anotherString): Compares string to another string, ignoring case
considerations.
Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true
int compareTo( String anotherString): Compares two string lexicographically.
int out = s1.compareTo(s2); // where s1 and 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 and 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.
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(); // returns “hello"
String toUpperCase(): 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 = “ Learn Share Learn “;
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 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks”
unit 3
EXCEPTION HANDLING:

Introduction:

Rarely does a program run successfully at its very first attempt. It is common to make mistakes while
developing as well as typing a program. A mistake might lead to an error causing the program to produce
unexpected results. Errors are the wrongs that can make a program go wrong.
An error may produce an incorrect output or may terminate the execution of the program abruptly or
even may cause the system to crash. It is therefore important to detect and manage properly all the possible
error conditions in the program so that the program will not terminate or crash during execution.

Types of errors:

Errors may broadly be classified into two categories:

Compile-time errors Run-time errors.

Compile-time errors:

All syntax errors will be detected and displayed by the java compiler and therefore these errors are
known as compile-time errors. Whenever the compiler displays an error, it will not create the .class file. It is
therefore necessary that we fix all the errors before we can successfully compile and run the program.

Example:

/* this program contains an error */ Class a


{
public static void main(String args[])
{
System.out.pritnln(“hello soft”) //missing
}
}

The java compiler does a nice job of telling us where the errors are in the program. For example, if we have
missed the semicolon at the end of the print statement in this program.

The following message will be displayed in the screen. a.java :7: ‘;’ expected
System.out.println(“hello soft”)
^ 1 error

we can now go to the appropriate line, correct the error, and recompile the program. Most of the
compile-time error are due to typing mistakes. Typographical errors are hard to find. We may have to check
the code word by word, or even character by character.
The most common problems are:
* Missing semicolons
* Missing (or mismatch of) brackets in classes and methods.
* Misspelling of identifiers and keywords
* Missing double quotes in strings
* Use of undeclared variables
 Use of = in place of = = operator
Other errors we may encounter are related to directory paths. An error such as Javac : command not found
Means that we have not set the path correctly. We must ensure that the path includes the directory where the java
executables are stored.

Run – time errors:

Sometimes, a program may compile successfully creating the .class file but may not run properly. Such
programs may produce wrong results due to wrong logic or may terminate due to errors such as stack
overflow. Most common run-time errors are

 Dividing an integer by zero


 Accessing an element that is out of the bounds of an array
 Trying to store a value into an array of an incompatible class or type
 Trying to cast an instance of a class to one of its subclass
 Attempting to use a negative size for an array
 Converting invalid string to a number
 Accessing a character that is out of bounds of a string

When such errors are encountered, java typically generates an error message and aborts the program.

Exception:

An exception is a condition that is caused by a run-time error in the program. When the java interpreter
encounters an error such as dividing an integer by zero, it creates an exception object and throws it (i.e.,
informs us that an error has occurred).
If the exception object is not caught and handled properly, the interpreter will display an error message
and will terminate the program. If we want the program to continue with the execution of the remaining code,
then we should try to catch the exception object thrown by the error condition and then display an appropriate
message for taking corrective actions. This task is known as exception handling.
The purpose of exception handling mechanism is to provide a means to detect and report an “ exceptional
circumstance” so that appropriate action can be taken. The mechanism suggests incorporation of a separate error
handling code that performs the following tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (throw the exception)
3. Receive the error information (catch the exception)
4. Take corrective actions (Handle the exception)

The error handling code basically consists of two segments, one to detect errors and to throw
exceptions and the other to catch exceptions and to take appropriate actions.
When writing programs, we must always be on the lookout for places in the program where an
exception could be generated. Some common exception that we must watch out for catching are listed in the
table
Common java exception

Exception type cause of exception ArithmeticExceptin

Arithmetic errors such as division by zero

ArrayIndexOutOfBoundsException Array index out of bounds

ArrayStoreException Assignment to an array element of an incompatible type


ClassCastException Invalid cast

NegativeArraySizeException Array created with a negative size.

FileNotFoundException Caused by an attempt to access a nonexistent file IOException Caused

by general I/O failures, such as inability to read


from a file

NullPointerException Invalid use of null reference NumberFormatExceptoin Invalid

conversion of a string to a numeric format InterruptedException One thread has been

interrupted by another thread ClassNotFoundException class not found

Java exception handling is managed via five keywords :


try, catch, throw, throws , finally

Program statements that you want to monitor for exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown. Your code can catch this exception (using catch) and
handle it in some rational manner. System-generated exception are automatically thrown by the java run-time
system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a
method must be specified as such by a throws clause. Any code that absolutely must be executed before a
method returns is put in a finally block.
Syntax of try – catch

try
{
statement;
}
catch (Exception-type e)
{
statement;
}

Example
: class exe
{
public static void main (String args[])
{
try
{
int a = 10,b=0; int c = a /b;
System.out.println(“divide value is “+c);
}
catch(ArithmeticException e)
{
System.out.println(“Divide by zero”);
}
}}

This program to run then the output as follows Divide by zero


Note that the program did not stop at the point of exceptional condition. It catches the
error condition, prints the error message, and then continues the execution.
Multiple catch statements:

In some cases, more than one exception could be raised by a single piece of code. To handle this
type of situation, you can specify two or more catch clauses, each catching a different type of exception. When
an exception is thrown, each catch statements is inspected in order, and the first one whose type matches that
of the exception is executed. After one catch statement executes, the others are bypassed, and execution
continues after the try/catch block.

The following example traps two different exception types


class exe1
{
public static void main(String args[])
{

try
{
int a=2;

System.out.println(" a value is "+a); int b=40/a;

int c[]={ 1}; c[40]=90;

catch(ArithmeticException e)
{

System.out.println("divide by 0 :"+e);

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index obj: ");
}

System.out.println("after try / catch blocks");

}
}
Nested try statements:

The try statement can be nested. That is, a try statement can be inside the block of another try. Each
time a try statement is entered, the context of that exception is pushed on the stack. In an inner statement is
entered, the context of that exception is pushed on the stack. In an inner try statement does not have a catch
handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are
inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try
statements are exhausted. If no catch statement matches, then the java run-time system will handle the
exception. Here is an example that uses nested try statements.

class exe2
{
public static void main(String args[])
{
try
{

int a=10; int c,b;


b=Integer.parseInt(args[0]); c=a/b;
System.out.println(c);
try
{
int d,e,f; d=Integer.parseInt(args[1]);
e=Integer.parseInt(args[2]); f=d*e;
System.out.println("mul value is "+f);
}
catch(NumberFormatException e)
{
System.out.println("give only integer value");
}
}
catch(ArithmeticException e)
{
System.out.println("divide by zero ");
}
}
}
Finally

java supports another statement known as finally statement that can be used to handle an exception
that is not caught by any of the previous catch statements. finally block can be used to handle any exception
generated within a try block. It may be added immediately after the try block or after the last catch block
shown as follows
try
{
statement;
}
finally
{
statement;
}

example:
class exe3
{
public static void main(String args[])
{

int
a,b,c;
try
{

a=Integer.parseInt(args[0]
);
b=Integer.parseInt(args[1])
; c=a/b;
System.out.println("division value is"+c);
}

finally
{
System.out.println("final block");
a=10;b=20;

c=a+b;
System.out.println("adition value is"+c);
}
System.out.println("simi");
}}
throw
so far you have only been catching exceptions that are thrown by the java run-time
system. However, it is possible for your program to throw an exception explicitly, using the
throw statement. The general form of throw is shown here throw
throwableinstance;
here, throwableinstance must be an object of type throwable or a subclass of throwable. Simple types
, such as int or char, as well as non-throwable classes, such as string and object, cannot be used as
exceptions. There are two ways you can objatin a thrwoable objact: using a parameter into a catch clause, or
creating one with the new operator.
The flow of execution stops immediately after the throw statement: any subsequent statements are
not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the
type of the exception. If it does find a match, control is transferred to that statement. If not, then the next
enclosing try statements is inspected, and so on. If no matching catch is found, then the default exception
handler halts the program and prints the stack trace.
Here is a sample program that creates and throws an exception. The handler that catches the exception
rethrows it to the outer handler.

class exe112
{
public static void main(String args[])
{
try
{
int a,b,c; a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]); c=a/b;
System.out.println("divide value is"+c);
}
catch(ArithmeticException e)
{
System.out.println("main block the error is "); throw e;
}
catch(NumberFormatException e)
{
System.out.println("second type of error"); throw e;
}
}}
Throws

If a method is capable of causing an exception that it does not handle, it must specify this behavior so
that callers of the method can guard themselves against that exception. You do this by including a throws
clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.
This is necessary for all exceptions, except those of type error or RuntimeException , or any of their
subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are
not, a compile-time error will result.
This is the general form of a method declaration that includes a throws clause:

Type method-name(parameter-list) throws exception-list


{
body of method;
}
Example:

class my extends Exception


{
int x; my(int a)
{
x = a;
}
public String toString()
{
return "My exception ("+ x +") ";
}
}
class exe12
{
public static void compute(int a) throws my
{
System.out.println("given value(" + a +")"); if(a >10)

throw new my(a); System.out.println("Normal exit");


}
public static void main(String args[])
{
try
{
compute(1); compute(20);
}
catch(my e)
{
System.out.println("Exception exit "+e);
}
}
}

The Exception class does not define any methods of its own. It does, of course, inherit those methods
provided by throwable. Thus, all exceptions, including those that your create, have the methods defined by
throwable available to them. They are shown in table you may also wish to override one or more of these
methods in exception classes that you create.

Method Description
String getMessage Returns a description of the exception

Returns a String object containing a description of the exception. This method is called by println() when
outputting a throwable object.

void printStackTrace
(PrintStream stream) Sends the stack trace to the specified stream.

void printStackTrace
(PrintWriter stream) Sends the stack trace to the specified stream.

MULTITHREADING

Those who are familiar with the modern operating systems such as Windows 95 may recognize that
they can execute several programs simultaneously. This ability is known as multitasking. In system’s
terminology, it is called multithreading.
Multithreading is a conceptual programming paradigm where a program(process) is divided into two
or more subprograms (process), which can be implemented at the same time in parallel. Each part of
subprograms is called thread. For example, one subprogram can display an animation on the screen while
another may build the next animation to be displayed.

The Main Thread:

When a java program starts up, one thread begins running immediately. This is usually called the main
thread of your program, because it is the one that is executed when your program begins. The main thread is
important for two reasons
 It is the thread from which other “ child” threads will be spawned.
 Often it must be the last thread to finish execution because it performs various shutdown actions.

Although the main thread is created automatically when your program is started, it can be controlled
through a Thread object. To do so, you must obtain a reference to it by calling the method currentThread( ),
which is a public static member of Thread. Its general form is shown here,
static Thread currentThread( )

Example:

class th1
{
public static void main(String args[])
{
Thread t1=Thread.currentThread(); System.out.println("current thread
:"+t1);

t1.setName("My Thread "); System.out.println("After name


change" +t1); try
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
Thread.sleep(1000);
}}

catch(InterruptedException e)
{
System.out.println("main thread interrupted");
}}
}

In this program, a reference to the current thread ( the main thread, in this case ) is obtained by calling
currentThread( ), and this reference is stored in the local variable t1. Next, the program displays information
about the thread. The program then calls setName( ) to change the internal name of the thread. Information
about the thread is then redisplayed. Next, a loop counts 1 to 5 pausing one second between each line. The
pause is accomplished by the sleep( ) method. The argument to sleep( ) specifies the delay period in
milliseconds.
Notice the try / catch block around this loop. The sleep( ) method in Thread might throw an
InterruptedException. This would happen if some other thread wanted in interrupted this sleeping one. This
example just prints a message if it gets interrupted. Here is the output generated by this program:
Current thread: Thread[main, 5, main]
After name change: Thread[My Thread,5,main] 1
2
3
4
5
The Thread class and the Runnable Interface:

Java’s multithreading system is built upon the Thread class, its methods, and its companion interface,
Runnable. The Thread class defines several methods that help manage threads.

getName:
It obtain a thread’s Name.

getPriority:
It obtain a thread’s priority.

isAlive:
Determine if a thread is still running.

join:
Wait for a thread to terminate.

run:
Entry point for the thread.

sleep:
suspend a thread for a period of time.

start:
start a thread by calling its run method.

Life cycle of Thread:


Running:
Running state used for thread hold on particular CPU.
Ready to run:
At any time CPU free then that time get ready into thread for CPU.

Suspended:
Running thread suspended into CPU

Blocked:

A thread can be blocked when waiting for the other resources in a CPU. This happens when the thread
is suspended, sleeping, or waiting in order to satisfy certain requirements. A blocked thread is considered “not
runnable” but not dead and therefore fully qualified to run again.
Terminated:
At any time any thread can be terminated, thread can not be resources or re start.

Resumed:

Resumed used for continues thread in a particular CPU.

Creating a Thread:

In the most general sense, you create a thread by instantiating an object of type Thread.
Java defines two ways in which this can be accomplished.

Implement the Runnable interface. Extend the Thread

class, itself.

Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable
abstracts a unit of executable code. You can construct a thread on any object that implements Runnable. To
implement Runnable, a class need only implement a single method called run( ) , which is declared like this:
Public void run( )
Inside run( ) , you will define the code that constitutes the new thread. It is important to understand the
run( ) can call other methods, use other classes, and declare variables, just like the main thread .

Syntax
Class x implements Runnable
:
{
………….
………….
}

After the new thread is created, it will not start running until you call its start( )
method, which is declared within Thread. In essence, start( ) executes a call to run( ). The
start( ) method is shown here:

void start( )
Example :
class exthread implements Runnable
{
exthread()
{
Thread t=new Thread(this,"demo thread");
System.out.println("Child thread"+t); t.start();
}
public void run()
{
try
{
for(int i=1;i<5;i++)
{
System.out.println("child thread i value is "+i); Thread.sleep(500);
}}
catch(InterruptedException e)
{
System.out.println("child interrupted");
}
System.out.println("exiting the child thread");
}}
class th4
{
public static void main(String args[])
{
new exthread(); try
{
for(int i=10;i<15;i++)
{
System.out.println("main thread "+i);
Thread.sleep(1000);
}}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("exiting the main thread");
}}
Extending the thread class:

The second way to create a thread is to create a new class the extends Thread, and then to create an
instance of that class. It includes the following steps:

Declare the class as extending the Thread class.


Implement the run( ) method that is responsible for executing the sequence of code that the thread
will execute.
Create a thread object and call the start( ) method to initiate the thread execution.

Declaring the Class:

The Thread class can be extended as follows: Class MyThread

extends Thread
{
………….
………….
}
Now we have a new type of thread MyThread.

Implementing the run( ) Method:

The run( ) method has been inherited by the class MyThread. We have to override this method in
order to implement the code to be executed by our thread. The basic implementation of run( ) will look like
this:
Public void run( )
{
…………….
……………..
}
When we start the new thread, java calls the thread’s run( ) method, so it is the run( )
where all the action takes place.
Starting New Thread:

To actually create and run an instance of our thread class, we must write the following: MyThread aThread = new
MyThread( );
AThread.start( );
The first line instantiates a new object of class MyThread. Note that this statement just creates the
object. The thread that will run this object is not yet running. The thread is in a newborn state. Arun
The second line calls the start( ) method causing the thread to move into the runnable state. Then,
the java runtime will schedule the thread to run by invoking its run( ) method. Now, the thread is said to be
in the running state.

Example:

class a extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("\t from thread a :i = "+i);
}
System.out.println("exit form a");
}}

class b extends Thread


{
public void run()
{
for(int j=10;j<=15;j++)
{
System.out.println("\t from thread b :j = "+j);
}
System.out.println("exit from b");
}}

class c extends Thread


{
public void run()
{
for(int k=15;k<=20;k++)
{
System.out.println("\t from thread c :k = "+k);
}
System.out.println("Exit from c");
}}

class th3
{
public static void main(String args[])
{
new a().start();
new b().start();
new c().start();
}}
THREAD PRIORITY:

In java, each thread is assigned apriority, which affects the order in which it is scheduled for running.
The threads that we have discussed so far are of the same priority. The threads of the same priority are
given equal treatment by the java scheduler and, therefore, they share the processor on first-serve basis.
Syntax of thread priority
ThreadName.setPriority(intNumber);
The intNumber is an integer value to which the thread’s priority is set. The Thread class defines several
priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY= 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value between 1 and 10.
Note that the default setting is NORM_PRIORITY.
Most user-level processes should use NORM_PRIORITY, plus or minus. Back-ground tasks such
as network I/O and screen repainting should use a value very near to the lower limit. We should be very
cautious when trying to use very high priority values.

Example:

class a extends Thread


{
public void run()
{
System.out.println("thread a started");

for(int i=1;i<=4;i++)
{
System.out.println("\t from thread a : i="+i);
}
System.out.println("exit from a");
}}

class b extends Thread


{
public void run()
{
System.out.println("thread b started"); for(int
j=10;j<=14;j++)
{
System.out.println("\t from thread b : j="+j);
}
System.out.println("exit from b");
}}

class c extends Thread


{
public void run()
{
System.out.println("thread c started"); for(int
k=20;k<25;k++)
{
System.out.println("\t from thread c : k= "+k);
}
System.out.println("exit from c");
}}

class th13
{
public static void main(String args[])
{
a ob = new a();
b ob1 = new b(); c ob2 = new
c();

ob.setPriority(Thread.MIN_PRIORITY);
System.out.println("start thread a"); ob.start();
System.out.println("start thread b"); ob1.start();
System.out.println("start thread c"); ob2.start();
System.out.println("end of main thread");

In this program class b and class c will be work on same time but the class a will be work on after
working on b & c class. That is class a will be work on last because it will be set on lower priority.

Synchronization

When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization.

Example:

class a extends Thread


{
public void run()
{
try
{
sync.display();
Thread.sleep(250);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("exit form a");
}}
class sync
{
public static synchronized void display()
{
for(int x=200;x<203;x++)
{
System.out.println("a thread x value is"+x);
}}}
class b extends Thread
{
public void run()
{
try
{
for(int j=1;j<5;j++)
{
System.out.println("b thread j value is "+j); Thread.sleep(500);
}}

catch(InterruptedException e)
{
System.out.println("interrupted");
}
}}

class th12
{
public static void main(String args[])
{
new a().start();
new b().start();
}}

In this program first class a process completed then the class b process will be started.
Deadlock

A special type of error that you need to avoid that relates specifically to multitasking is deadlock ,
which occurs when two threads have circular dependency on a pair of synchronized objects.
For example, suppose one thread enters the monitor on object x and another thread enters the monitor on
object y. if the thread in x tries to call any synchronized method on y, it will block as expected. However, if the
thread in y, in turn, tries to call any synchronized method on x, the thread waits forever, because to complete.
Deadlock is a difficult error to debug for two reasons.

In general, it occurs only rarely, when the two threads time-slice in just the right way.
It may involve more than two threads and two synchronized objects.( that is , deadlock can occur
through a more convoluted sequence of events than just described).

class firstt
{
synchronized void display(second s)
{
System.out.println("arun"); try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("one interrupted");
}
System.out.println("kumar"); s.display1();
//here deadlock occur
}
synchronized void display1()
{
System.out.println("anbu");
}}

class second
{
synchronized void show(firstt f)
{
System.out.println("simi"); try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("first interrupted");
}
System.out.println("ammu"); f.display1();
// here dead lock occur
}
synchronized void display1()
{
System.out.println("arasan");
}}

class deadlo2 extends Thread


{
firstt f=new firstt(); second s=new second();

deadlo2()
{
start();
f.display(s);
System.out.println("back in main thread");
}
public void run()
{
s.show(f);
System.out.println("back in other thread");
}
public static void main(String args[])
{
new deadlo();
}}

output of this program is arun


simi kumar ammu

then deadlock entered then we have to press ctrl + c then control come back dos prompt.

SUSPEND, RESUME A THREAD:

//example program for suspend, resuming thread class ones extends Thread
{
boolean suspendFlag; String name;
ones(String tname)
{
name=tname; suspendFlag=false; start();
}

public void run()


{
try
{
for(int i=15;i>0;i--)
{
System.out.println(name +" : "+ i); Thread.sleep(200);
synchronized(this)
{
while(suspendFlag)
{
wait();
}}

}
}
catch(Exception e)
{
System.out.println("exit");
}
}

void mysuspend()
{
suspendFlag=true;
}

synchronized void myresume()


{suspendFlag=false;
notify(); // it is used to wake up the thread
}
}

class th161
{
public static void main(String args[])
{
ones o=new ones("arun"); ones o1=new
ones("kumar");

try
{
Thread.sleep(1000);

o.mysuspend(); System.out.println("suspending thread one");


Thread.sleep(1000);

o.myresume(); System.out.println("resuming thread one");

o1.mysuspend(); System.out.println("suspendint thread two");


Thread.sleep(1000);
o1.myresume(); System.out.println("resuming thread two");
}
catch(Exception e)
{
System.out.println("interrupted");
}
}
}

Stream I/O and Files

Java programs perform I/O through streams. A stream is an abstraction that either produces or
consumes information. A stream is linked to a physical device by the java I/O system. All streams behave in
the same manner, even if the actual physical devices to which they are linked differ.
Thus, the same I/O classes and methods can be applied to any type of device. This means that an input
stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket.
Likewise, an output stream may refer to the console, a disk file, or a network connection.

Types of Stream:

Java defines two types of Streams:


1. Byte Streams 2. Character Streams.

Byte Stream:

Byte streams provide a convenient means fro handling input and output of bytes. Byte streams are
used, for example, when reading or writing binary data. Byte streams are defined by using two classes
hierarchies.
At the top are two abstract classes : InputStream and OutputStream. Each of these abstract classes
has several concrete subclasses, that handle the differences between various devices, such as disk files,
network connections and even memory buffers.
The byte stream classes are as bellow:

Stream Classes Meaning

BufferedInputStream Buffered input stream


BufferedOutputStream Buffered output stream ByteArrayInputStream Input
stream that reads from a byte array ByteArrayOutputStream Output stream that writes to a
byte array
DataInputStream An input stream that contains methods for reading
the java standard data types
An output stream that contains methods for writing The java standard data types
FileInputStream Input stream that reads from a file.
FileOutputStream Output stream that writes to a file
InputStream Abstract class that describes stream input
OutputStream Abstract class that describes stream output
PrintStream Output stream that contains print( ) &println( )
RandomAccessFile supports random access File I/O

The abstract classes InputStream and OutputStream define several key methods that the other
stream classes implement. Two of the most implement are read( ) and write( ), which respectively, read and
write bytes of data. Both methods are declared as abstract inside InputStream & OutputStream.

Character Stream:

Character streams are defined by using two class hierarchies. At the top are two abstract classes,
Reader & Writer. These abstract classes handle Unicode character streams. Java has several concrete
subclasses of each of these. The character stream classes are below:

Stream Classes Meaning

BufferedReader Buffered input character stream


BufferedWriter Buffered output character stream
CharArrayReader Input stream that reads from a character array
CharArrayWriter Output stream that writes to a character array
FileReader Input stream that reads from a file
FileWriter Output stream that writes to a file
InputStreamReader Input stream that translates bytes to characters
PrintWriter Output stream that contains print( ) & println( )
StringReader Input stream that reads from a string
StringWriter Output stream that writes to a string
Abstract class that describes character stream Output.
Reading console Input:

In java, console input is accomplished by reading from System.in. to obtain a character- based
stream that is attached to the console, you wrap System.in in a BufferedReader object, to create character
stream. BufferedReader supports a buffered input stream. It is most commonly used constructor is shown
here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being
created. Reader is abstract class. One of its concrete subclasses is InputStreamReader, which converts
bytes to charcters. To obtain an InputStreamReader object that is linked to System.in, use the following
constructor
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting
it all together, the following line of code creates BufferedReader that is connected to the keyword:
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
After this statement executes, br is a character based stream that is linked to the console through
System.in.

Example: (String Functions)

import java.io.*; class str


{
public static void main (String args[])throws IOException
{
InputStreamReader br=new InputStreamReader(System.in); BufferedReader r=new
BufferedReader(br);
String name,a,b,c; System.out.println("Enter the first
string"); name=r.readLine();

System.out.println("Enter the string");


a=r.readLine();

System.out.println("given name is "+ name); System.out.println("given


name is "+ a);
System.out.println("comp"+name.compareTo(a));

int l; l=name.length();
System.out.println("given name length is "+l);
System.out.println(" ");
System.out.println("given name length is "+ a.length());
System.out.println(" ");

System.out.println("concat string is "+ name.concat(a));


System.out.println(" ");

System.out.println("Equal string " +name.equals(a));


System.out.println(" ");

System.out.println("Upper case letter of the given name"+name.toUpperCase());


System.out.println(" ");

System.out.println("Upper case letter of the given name"+a.toLowerCase());


System.out.println(" ");

StringBuffer x=new StringBuffer(a); x.reverse();

String y=new String(x); System.out.println("Reverse of the


string is: "+y); if(a.compareTo(y)==0)
System.out.println("Given String is polyndrome"); else
System.out.println("not polyndrome strig is ");

}}

PrintWriter Class:

Although using System.out. to write to the console is still permissible under java its use is
recommended mostly for debugging purposes. For real-world programs, the recommended method of
writing to the console when using java is through a PrintWriter stream. PrintWriter is one of the character-
based classes. Using a character based class for console output makes it easier to internationalize your
program.
PrintWriter defines several constructors. The one we will use is shown here:
PrintWriter(OutputStream outputStream, Boolean flushOnNewline)
Here , outputStream is an Object of type OutputStream, and flushOnNewline controls whether java
flushes the output stream ever time a println( ) method is called. If flushOnNewline is true, flushing
automatically takes place. If false , flushing in not automatic.

PrintWriter pw=new PrintWriter(System.out, true); Example:

import java.io.*; class pwriter


{
public static void main(String args[])
{
PrintWriter pw=new PrintWriter(System.out,true); pw.println("this is a
string");
int i=9; pw.println(i);
}}

FILES:

We have used variables and arrays for storing data inside the programs. This approach poses the
following problems.
The data is lost either when a variable goes out of scope or when the program is terminated. That is ,
the storage is temporary.
It is difficult to handle large volumes of data using variables and arrays.
We can overcome these problems by storing data on secondary storage devices such as floppy disks or hard
disks. The data is stored in these devices using the concept of files.
A file is a collection of related records placed in particular area on the disk. Storing and managing
data using files is known as file processing which includes tasks such as creating files, updating files and
manipulation of data.
USING THE FILE CLASS:

The java.io, package includes a class known as the file class that provides support for creating files
and directories. The class includes several constructors for instantiating the File objects. This class also
contains several methods for supporting the operations such as
Creating a File , Opening a File, Closing a File, Deleting a File, Getting the name of the File,
Renaming a File, checking whether the file is readable, checking whether the file is writable.

INPUT / OUTPUT EXCEPTIONS:

When creating files and performing i/o operations on them, the system may generate i/o related
exceptions. The basic i/o exception classes and their functions are given below

I/O Exception class Function

Signals that an end of the file or end of stream has been reached unexpectedly during input
FileNotFoundException Informs that a file could not found InterruptedIOException
Warns that an I/O operations has be interrupted IOException
signals that an I/O exception of some sort has occurred.
CREATION OF FILES:

If we want to create and use a disk file, we need to decide the following about the Intended purpose.
Suitable name of the file Data type to be stored
Purpose ( reading, writing, or updating) Method of creating the file.

READING / WRITING CHARACTES:

As pointed out earlier, subclasses of Reader & Writer implement streams that can handle
characters. The two subclasses used for handlingcharacters in files are FileReader (for reading characters)
and FileWriter(for writing characters).
In this program , two file stream classes to copy the contents of a file amed input.dat” into a file called
“output.dat”.

//coping charcters from one file into another import java.io.*;


class file1
{
public static void main(String args[])
{
File infile=new File("input.dat"); File outfile=new
File("output.dat"); FileReader ins=null;
FileWriter outs=null; try
{
ins=new FileReader(infile); outs=new
FileWriter(outfile); int ch;
while((ch=ins.read()) !=-1)
{
outs.write(ch);
}
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
try
{
ins.close();
outs.close();
}
catch(IOException e)
{
System.out.println("interupted");
}}}}

this program is very simple. It creates two file objects inFile & outFile and initializes them with “input.dat”,
and “output.dat” respectively using the following code.
File infile= new File(“input.dat”); File outfile=new
File(“output.dat”);
The program then creates two file stream objects ins & outs and initializes them with “null” as follows.
FileReader ins=null; FileWriter outs=null;

These Streams are then connected to the named files using the following codes ins=new
FileReader(infile);
outs=new FileWriter(outfile);

This connects infile to the FileReader stream ins and outfile to the FileWriter stream outs. This
essentially means that the files “input.dat” and “output.dat” are opened. The statements ch=ins.read( )
Reads a character from the infile through the input stream ins and assigns it to the variable ch
similarly, the statement
outs.write(ch);
writes the character stored in the variable ch to the outfile through the output stream outs. The
character-1 indicates the end of the file and therefore the code
while((ch=ins.read( )) != -1)
causes the termination of the while loop when the end of the file is reached. The statements
ins.close( ); outs.close( );
enclosed in the finally( ) clause close the files created for reading and writing. When the program catches
an I/O exception, it prints a message and then exits from execution.

Example:
FileInputStream, FileOutputStream:
import java.io.*; class file3
{
public static void main(String args[])
{
try
{
FileOutputStream fos=new FileOutputStream("arun.txt"); for(int
i=1;i<10;i++)
{
fos.write(i);
}
fos.close();
}
catch(IOException e)
{
System.out.println(e);
}}}
In this program create a new file that is “arun.txt” and write the numbers between 1 and 10 and close
that file.

import java.io.*; class file31


{
public static void main(String args[])
{
try
{
FileInputStream fis=new FileInputStream("arun.txt"); int i;
while((i=fis.read())!=-1)
{
System.out.println(i);
}
fis.close();
}
catch(IOException e)
{
System.out.println(e);
}}}

In this program to open a new file that is “arun.txt” and read the message and print the message to your
console normal screen.
SequenceInputStream:

The SequenceInputStream class allows you to concatenate multiple InputStream. The construction
of SequenceInputStream is different from any other InputStream. A SequenceInputStream constructor
use either a pair of InputStream or an Enumeration of InputStream as its argument.
SequenceInputStream(InputStream first, InputStream second)
SequenceInputStream(Enumeration stream Enum)

import java.io.*; class file5


{
public static void main(String args[])throws IOException
{
FileInputStream file1=null;
FileInputStream file2=null;

SequenceInputStream file3=null;

file1=new FileInputStream("one.txt"); file2=new


FileInputStream("two.txt"); file3=new
SequenceInputStream(file1,file2);

BufferedInputStream inb=new BufferedInputStream(file3); BufferedOutputStream


ob=new BufferedOutputStream(System.out);

int ch; while((ch=inb.read())!=-1)


{
ob.write((char)ch);
}
inb.close();
ob.close(); file1.close(); file2.close();
}}

In this program to create two file that is “one.txt” and “two.txt” and write some message. Then to store
file3 that is SequenceInputStream it includes one.txt , two.txt (that is file1,file2). Then file3 to be stored on
BufferedInputStream. Then use of BufferedOutputStream to read the character from file3 and print the
message on to the screen.

DataInpurStream , DataOutputStream:

The DataInputStream class extends FilterInputStream and implements


DataInputStream. This class provides this constructor:
DataInputStream(InputSteam is)
Here, is the input stream.
The DataInput interface defines methods that can be used to read the simple java types from a byte
input stream.

Example:

import java.io.*; class file7


{
public static void main(String args[])
{
try
{
FileOutputStream fos=new FileOutputStream("kumar.txt"); DataOutputStream dos=new

DataOutputStream(fos);

dos.writeBoolean(false);
dos.writeByte(Byte.MAX_VALUE); dos.writeChar('A');
dos.writeDouble(Double.MAX_VALUE);
dos.writeFloat(Float.MAX_VALUE);
dos.writeInt(Integer.MAX_VALUE);
dos.writeLong(Long.MAX_VALUE);
dos.writeShort(Short.MAX_VALUE);

fos.close();
}
catch(Exception e)
{
System.out.println("Exception :"+e);
}
}}
In this program to create “kumar.txt” and write the message the max value of int,float,long,short data type
values.
import java.io.*; class file71
{
public static void main(String args[])
{
try
{
FileInputStream fis=new FileInputStream("kumar.txt"); DataInputStream

dis=new DataInputStream(fis);

System.out.println(dis.readBoolean());
System.out.println(dis.readByte());
System.out.println(dis.readChar());
System.out.println(dis.readDouble());
System.out.println(dis.readFloat());
System.out.println(dis.readInt());
System.out.println(dis.readLong());
System.out.println(dis.readShort()); dis.close();
}
catch(Exception e)
{
System.out.println("Exception :"+e);
}
}}

In this program to open the file “kumar.txt” and read the message and print the message on the screen.
RANDOM ACCESS FILES:

The stream classes examined in the previous sections can only use sequential access to read and
write data in File. The RandomAccessFile class allows you to write programs that can seek to any location in
a file and read or write data at the point. It also supports positioning requests- that is, you can position the
file pointer within the file. It has two constructors:
RandomAccessFile(File fileobj, String access) throws FileNotFoundException
RandomAccessFile(String filename, String access) throws FileNotFoundException

In the first form, fileobj specifies the name of the file to open as a File object. In the second form,
the name of the file is passed in filename. In both cases, access determines what type of file access is
permitted. If it is “r” , then the file can be read, but not written. If it is “rw”
, then the file is opened in read-write mode.
The method seek( ) shown here, is used to set the current position of the file pointer within the file:
Void seek(ling newpos) throws IOException
Here , newpos specifies the new position, in bytes, of the file pointer from the beginning of the file.
After call to seek( ), the next read or write operation will occur at the new file position.

Example:

import java.io.*; class file8


{
public static void main(String args[])
{
RandomAccessFile file=null;

try
{
file=new RandomAccessFile("rand.dat","rw");

file.writeChar('x'); file.writeInt(888);
file.writeDouble(89.456);
file.seek(0);//go to the begining

System.out.println(file.readChar()); System.out.println(file.readInt());
System.out.println(file.readDouble());

file.seek(2);//go to the second item System.out.println(file.readInt());

file.seek(file.length());//go to the end and append false to the file file.writeBoolean(false);

file.seek(3); System.out.println(file.readBoolean());
file.close();
}
catch(IOException e)
{
System.out.println(e);
}
}}

In this program first to create a new file that is “rand.dat” that file is read and write file. Then to write
three message on that file. Then read on that file and print the message on the screen one by one.
Then use of the seek( ) method and print the second message. Then use of length class to add another
message on that file.
Then use of the seek method to print the new (that is fourth) message on the screen. This process is only
available on RandomAccessFile method only.

The output as follows: x


888
89.456
888
true
unit 4

APPLET
Introduction:
Applets are small java programs that are primarily used in Internet computing. They can be transported
over the Internet from one computer to another and run using the Applet Viewer or any web browser that
supports java. An applet, like any application program, can do many things for us. It can perform arithmetic
operations, display graphics, play sounds, accept user input, create animation and play interactive games.

We can embed applets into web pages in two ways.


One, we can write our own applets and embed them into web pages.
Second, we can download an applet from a remote computer system and then embed it into a web
page.

An applet developed locally and stored in a local system in known as local applet.

An remote applet is that which is developed by someone else and stored on a remote computer
connected to the internet. If our system is connected to the internet, we can download the remote applet onto
our system via the Internet and run it.
In order to locate and load a remote applet, we must know the applet’s address on the web. This
address is known as Uniform Resource Locator(URL) and must be specified in the applet’s HTML document
as the value of CODEBASEattribute.

All Applets are subclasses of Applet. Thus all applets must import java.applet. Applets must also
import java.awt. Recall the AWT Abstract Window Toolkit. Since all applets run in a window, it is necessary
to include support for the window. Applets are not executed by the console-based java run-time interpreter.
Rather, they are executed by either a web browser or an applet viewer.
Output to your applet’s window is not performed by System.out.println( ). Rather, it is handled with
various AWT methods, such as drawstring( ), which outputs a string to a specified x,y location. Once an applet
has been compiled, it is included in an HTML file using the APPLET TAG.
The applet will be executed by a java-enabled web browser when it encounters the APPLET TAG
within the HTML file. To view and test an applet more conveniently, simply include a comment at the head of
your java source code file that contains the APPLET tag. This

way, your code is documented with the necessary HTML statements needed by your applet, and you can test
the compiled applet by starting the applet viewer with your java source code file specified as the target.
HOW APPLETS DIFFER FROM APPLICATIONS:

Although both the applets and stand-alone applications are java programs, there are significant
differences between. Applets are not full-featured application program. They are usually written to
accomplish a small task or a component of a task. Since they are usually designed for use on the internet, they
impose certain limitations and restrictions in their design. Applets do not use the main( ) method for initiating
the execution of the code. Applets,
when loaded, automatically call certain methods of Applet class to start and execute the applet code.
Unlike stand-alone applications, applets cannot be run independently. They are run from inside a web
page using a special feature known as HTML tag.
Applets cannot read from or write to the files in the local computer. Applets cannot communicate
with other servers on the network.
Applets cannot run any program form the local computer.
Applets are restricted from using libraries from other languages such as c or c++.

The Applet Class:

The Applet provides all necessary support for applet execution, such as starting and stopping. It also
provides methods that load and display images, and methods that load and play audio clips. Applet extends the
AWT class Panel. In turn, Panel extends Container, which extends Component. These classes provide
support for java’s window-based, graphical interface.

LIFE CYCLE OF APPLET:

Init( ) -------→ Initialize a variable. Called when an applet begins execution. Isti the first method called for
any applet.

Start( ) ----------- → After the init( ) method the program should be started. Called by
By browser when an applet should start(or resume) execution. It Is automatically called after init( )
when an applet first begins.

Paint( ) ----→drawing, writing and color creation. The paint( ) method is caledEach time your applet’s
output must be redrawn. Paint( ) is also Called when the applet begins execution. This method has one
Parameter of type Graphics. It contain the Graphics context, which describes the graphics environment.
This context is used whenever output to the applet.

Stop( ) ---------- →Halt of the running applet. Called by browser to suspend


Execution of the applet. Once stopped , an applet is restarted When the browser calls start( ).

Destroy( ) -> terminated. Called by browser just before an applet is terminated.


Repaint( ) →call update method.

APPLET ARCHITECTURE:

An applet is a window-based program. As such, its architecture is different from the so- called normal,
console-based programs. If you are familiar with windows programming, you will be right at home writing
applets.
Applets are event driven. It is important to understand in a general way how the event- driven
architecture impacts the design of an applet. An applet resembles a set of interrupt service routines.
Here is how the process works. An applet waits until an event occurs. The AWT notifies the applet
about an event by calling an event handler that has been provided by the applet.
The user initiates interaction with an applet – not the other way around. As you know, in a non
windowed program, when the program needs input, it will prompt the user and then call some input method,
such as readLine( ). This is not the way it works in an applet. Instead, the user interacts with the applet as he
or she wants, when he or she wants.
These interactions are sent to the applet as events to which the applet a mouse-clicked event is
generated. If the user presses a key while the applet’s window has input focus, a key press event is generated.
Applets can contain various controls, such as push buttons and check boxes. When the user interacts with one
of these controls, an event is generated.
While the architecture of an applet is not as easy to understand as that of a console-based program,
java’s AWT makes it as simple as possible.

THE HTML APPLET TAG:

The APPLET tag is used to start an applet from both an HTML(Hyper Text Markup Language)
document and from an applet viewer. (The newer OBJECT tag also works, but it will use APPLET).
An applet viewer will execute each APPLET tag that if finds in a separate window, while web
browsers like Netscape Navigator, Internet Explorer, and HotJava will allow many applets on a single page.
So far, we have been using only a simplified form of the APPLET tag.
The syntax for the standard APPLET tag is shown here. Bracketed items are optional.

<APPLET
[CODEBASE = codebase URL]
CODE = applet file
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment] >
[<PARAM NAME = Attribute Name VALUE = Attribute value> ] [<PARAM NAME =
Attribute Name2 VALUE = attribute value> ]
</APPLET>

CODEBASE:
It is an optional attribute that specifies the base URL of the applet code, which is the directory that
will be searched for the applet’s executable class file. The HTML document’s URL directory is used as the
CODEBASE if this attribute is not specified.

CODE:
It is a required attribute that gives the name of the file containing your applet’s compiled
.class file. This file is relative to the code base URL of the applet, which is the directory that the HTML file
was in or the directory indicated by CODEBASE if set.

WIDTH AND HEIGHT:


WIDTH and HEIGHT are required attributes that give the size ( in pixels) of the applet display area.

ALIGN:
It is an optional attribute that specifies the alignment of the applet. This attributes is treated the same
as the HTML IMG tag with these possible values: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE,
TEXTTOP, ABSMIDDLE, and ABSBOTTOM.

PARAM NAME AND VALUE:


The PARAM tag allows you to specify applet specific arguments in an HTML page.
Applets access their attributes with the getParameter( ) method.

HANDLING BROWSERS:

The best way to design your HTML page to deal with such browsers is to include HTML text and
markup within your <applet></applet> tags. If the applet tags are not recognized by your browser, you will
see the alternate markup. If java is available, it will consume all of the markup between the <applet></applet>
tags and disregard the alternate markup.
Example of Applet program:

import java.applet.*; import


java.awt.*;
/*
<applet code="app1.java" height = 400 width = 200 >
</applet>
*/
public class app1 extends Applet
{
public void paint(Graphics g)
{
g.drawString("hello applet program",30,30);
}}

In this program save app1.java. and compile javac app1.java. Then run this program by this
command : appletviewer app1.java. The it will create a applet window and print the message “hello applet
program” .

Example two:

import java.awt.*; import


java.applet.*;
/*
<applet code="app2" width =400 height = 50>
</applet>
*/
public class app2 extends Applet
{
String msg; public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
}
public void start()
{
msg="arun";
}
public void paint(Graphics g)
{
msg+="kumar ";
g.drawString(msg,130,150);
}}
PASSING PARAMETERS IN APPLET:

The APPLET tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use
the getParameter( ) method. It returns the value of the specified parameter in the form of String object. Thus,
for numeric and Boolean values, you will need to convert their string representations into their internal formats.
Here the example of passing parameters

import java.awt.*; import


java.applet.*;
/*
<applet code="app3" width =400 height = 500>
<param name=name value="name :saran">
<param name=no value = 100>
<param name=m1 value=80>
<param name=m2 value=90>
</applet>
*/
public class app3 extends Applet
{
Font f=new Font("TimesRoman",Font.ITALIC,20); String name;
int no,m1,m2,tot; public void init()
{
name=getParameter("name"); String na,ma1,ma2;
na=getParameter("no"); no=Integer.parseInt(na);
ma1=getParameter("m1");
m1=Integer.parseInt(ma1);
ma2=getParameter("m2");
m2=Integer.parseInt(ma2); tot=m1+m2;
}
public void paint(Graphics g)
{
g.setFont(f); g.setColor(Color.red);
g.drawString(name,50,50);
g.drawString("number :"+no,50,80);
g.drawString("mark1 :"+m1,50,110);
g.drawString("mark2 :"+m2,50,140); g.drawString("total
:"+tot,50,170);
}}

AWT Classes:

The AWT contains numerous classes and methods that allow you to create and manage windows. The
AWT when creating your own applets or stand-alone programs. The main purpose of the AWT is to support
applet windows, it can also be used to create stand-alone windows that run in a GUI environment, such as
windows. Most of the examples are contained in applets, so to run them, you need to use an applet viewer or a
java-compatible web browser. The AWT classes are contained in the java.awt package. It is one of java’s largest
packages. Fortunately, because it is logically organized in a top-down, hierarchical fashion, it
is easier to understand and use than you might at first believe. Some AWT classes below:

Class Description

AWTEvent Encapsulates AWT events.


BorderLayout The border layout manager. It use five components: North, South, East, West
and Center.
Button Creates a push button control.
Canvas A blank, semantics-free window.
Checkbox Creates a check box control CheckboxGroup
Creates a group of check box controls. Choice creates
a pop-up list.
Component An abstract super class for various AWT components.
Container A subclass of Component that can hold other components.
Dialog Creates a dialog window.
FlowLayout the flow layout manager. Flow layout positions components left
to right, top to bottom.
Font Encapsulates a type font.
FontMetrics Encapsulates various information related to a font. This
information helps you display text in a window
Frame Creates a standard window that has a title bar, resize corners, and a menu bar.
Graphics encapsulates the graphics context. It is used by the various output methods to
display output in a window.
GridLayout the grid layout manager. To displays components in a two-
dimensional grid.
Image Encapsulates graphical images.
Label Creates a label that displays a string.

Class Description
List Creates a list from which the user can choose.
Menu Creates a pull-down menu.
Panel the simplest concrete subclass of Container.
Rectangle Encapsulates a rectangle.
Scrollbar Creates a scroll bar control
Textarea Creates a multi line edit control.
TextField Creates a single-line edit control.
Window Creates a window with no frame, no menu bar, and no title.

WINDOW FUNDAMENTALS:

The AWT defines windows according to a class hierarchy that adds functionality and specificity with
each level. The two most common windows are those derived from Panel, which is used by applets, and those
derived from Frame, which creates a standard window.

Component:
At the top of the AWT hierarchy is the Component class. Component is an abstract class that
encapsulates all of the attributes of a visual component. All user interface elements that are displayed on the
screen and that interact with the user are subclasses of Component.
It responsible for managing events, such as mouse and keyboard input, positioning and sizing the
window, and repainting. A Component object is responsible for remembering the current foreground and
background colors and the currently selected text font.

Container:
The Container class is a subclass of Component. It has additional methods that allow other Component
objects to be nested within it. A container is responsible for laying out ( that is, positioning ) any components that
it contains. It does this through the use of various layout managers.

Panel:
The Panel class is concrete subclass of Container. It doesn’t add any new methods; it
simply implements Container. A Panel may be thought of as a recursively nestable, concrete screen component.
Panel is the super class for Applet. When screen output is directed to an applet, it is drawn on the surface of a
Panel object. In essence, a Panel is a window that does
not contain a title bar, menu bar, or border. When you run an applet using an applet viewer, the applet viewer
provides the title and border.
Other components can be added to a Panel object by its add( ) method. Once these components have
been added, you can position and resize them manually using the setLocation( ), setSize( ), or setBounds( )
methods defined by Component.

Window:
The Window class creates a top-level window. A top-level window is not contained within any other
object; it sits directly on the desktop. Generally , you won’t create Window objects directly. Instead, you will
use a subclass of Window called Frame, described next.

Frame:
Frame encapsulates what is commonly thought of as a “window”. It is subclass of window and has a title
bar, menu bar, borders, and resizing corners.

Canvas:
Although it is not part of the hierarchy for applet or frame windows, there is one other type of window
that you will find valuable: Canvas. Canvas encapsulates a blank window upon which you can draw.

Working with Frame Windows:


After the applet, the type of window you will most often create is derived from Frame. You will use it to
create child windows with applets, and top-level or child windows for applications. Here are two of Frame’s
constructors:
Frame( )
Frame( String title)
The first form creates a standard window that does not contain a title. The second form creates a window with
the title specified by title.

Hiding and Showing a Window:


After a frame window has been created, it will not be visible until you call setVisible(
). Its signature is shown here:
void setVisible(Boolean visible flag)
The component is visible if the argument to this method is true. Otherwise, it is hidden.
Setting a Window’s Title:
You can change the title in a frame window using setTitle( ), which has this general
form:
void setTitle(String newTitle)
here, newTitle is the new title for the window.

Creating a Frame Window in an Applet:

While it is possible to simply create a window by creating an instance of Frame, you will seldom do so,
because you will not be able to do much with it. Creating a new frame window from within an applet is actually
quite easy. First, create a subclass of Frame. Next, override any of the standard window methods, such as init( ),
start( ), stop( ), and paint( ). Finally, implement the windowClosing( ) method of the WindowListener
interface, calling setVisible(false) when the window closed.

Example:

import java.awt.*; import java.applet.*;


import java.awt.event.*;

/*
<applet code= "app811" width = 300 height = 50>
</applet>
*/

class o extends Frame


{
public void paint(Graphics g)
{
g.drawString("this is a frame window",50,59);
}}

public class app811 extends Applet


{
Frame f;
public void init()
{
f=new o(); f.setSize(250,250);
f.setVisible(true);
}
public void paint(Graphics g)
{
g.drawString("this is an applet window",10,20); showStatus("this is applet
window status bar");
}
}

UNIT 5

Working with Graphics:

The AWT supports a rich assortment of graphics methods. All graphics are drawn relative to a window.
This can be the main window of an applet, a child window of an applet, or a stand-alone application window. The
origin of each window is at the top-left corner and is 0,0. coordinates are specified in pixels. All output to a
window takes place through a graphics context. A graphics context is encapsulated by the Graphics class and is
obtained in two ways: It is passes to an applet when one of its various methods, such as paint( ) or update( )
is called.
It is returned by the getGraphics( ) method of Component.
The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled.
Objects are drawn and filled in the currently selected graphics color, which is black by default.

Drawing Lines:
Lines are drawn by means of the drawLine( )method, shown here: void
drawLine(int startx, int starty, int endx, int endy)
drawLine( ) displays a line in the current drawing color that begins at startx,starty and ends at endx, endy.

Drawing Rectangle:

The drawRect( ) & fillRect( ) methods display an outlined and filled rectangle, respectively. They are
shown here:
void drawRect(int top, int left, int width, int height) void fillRect(int
top, int left, int width, int height)
The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle are specified by width and
height.
To draw a rounded rectangle, use drawRoundRect( ) or
here fillRoundRect( ),both shown

void drawRoundRect(int top, int left, int width, int height, int
xDiam, int yDiam) void fillRoundRect(int top, int left, int width,
int height, int xDiam, int yDiam)
A rounded rectangle has rounded corners. The upper-left corner of the rectangle is at top,left. The dimensions of
the rectangle are specified by width and height. The diameter of the rounding arc along the x axis is specified by
xDiam. The diameter of the rounding arc along the y axis is specified by yDiam.

Drawing Ellipses and Circles:

To draw an ellipse, use drawOval( ). To fill an ellipse, use fillObval( ). These methods as shown here:
void drawOval(int top, int left, int width, int height) void fillOval(int
top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by top,left and whose width
and height are specified by width and height.

Drawing Arcs:

Arcs can be drawn with drawArc( ) & fillArc( ), shown here:


void drawArc(int top, int left, int width, int height, int startAngle,int sweep Angle) void fillArc(int
top, int left, int width, int height, int start Angle, int sweep Angle)

The arc is bounded by the rectangle whose upper-left corner is specified by top, left and whose width and
height are specified by width and height. The arc is drawn from start angle through the angular distance
specified by sweep angle. Angles are specified in degrees. Zero degree is on the horizontal, at the three o’clock
position. The arc is drawn counterclockwise if sweep angle is positive, and clockwise if sweep angle is negative.
Therefore, to draw an arc from twelve o’clock to six o’clock , the start angle would be 90 and the sweep angle
180.

Example:
import java.awt.*; import java.applet.*;
/*
<applet code="app6" width=300 height = 200>
</applet>
*/
public class app6 extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10,10,50,50); g.drawRect(10,60,40,30);
g.setColor(Color.red); g.fillRect(60,10,30,80);
g.drawRoundRect(10,100,80,50,10,10);
g.fillRoundRect(20,110,60,30,5,5);
g.drawOval(60,190,200,120);
g.fillOval(110,200,100,100);
g.drawArc(30,170,80,80,10,95);
}}

Drawing Polygons:

It is possible to draw arbitrarily shaped figures using drawPolygon( ) & fillPolygon( ), show here:
void drawPolygon(int x[],int y[],int numpoints) void
fillPolygon(int x[],int y[], int numpoints)
The polygon’s endpoints are specified by the coordinate pairs contained within the x and y arrays. The number
of points defined by x and y is specified by numpoints. Ther are alternative forms of these methods in which the
polygon is specified by a polygon object.

Example:

import java.awt.*; import


java.applet.*;
/*
<applet code = "app21" width = 300 height = 200>
</applet>
*/
public class app21 extends Applet
{
public void paint(Graphics g)
{
int xpoints[]={30,200,30,200,30}; int
ypoints[]={30,30,200,200,30}; int num= 5;
g.drawPolygon(xpoints,ypoints,num);
}}

AWT Controls:

Controls are components that allow a user to interact with your application in various ways – for
example, a commonly used control is the push button. A layout manager automatically positions components
within a container.

Control Fundamentals:

The AWT supports the following types of controls:


Labels, Push buttons, Check boxes, Choice lists, Lists, Scroll bars, Text editing.
These controls are subclasses of Component.
Labels:
The easiest control to use is a label. A label is an object of type Label, and it contains a string, which it
displays. Labels are passive controls that do not support any interaction with the user. Label defines the following
constructors:
Label( ) , Label (String str) , Label(String str, int how)

The first version creates a blank label. The second version creates a label that contains the string
specified by str. This string is left-justified. The third version creates a label that contains the string specified by
str using the alignment specified by how. The value of how must be one of these three constants: Label.LEFT,
Label.RIGHT, Label.CENTER.
You can set or change the text in a label by using the setText( )method. You can obtain the current label
by calling getText( ). These methods are shown here:
void setText(String str) void getText( )
For setText( ), str specifies the new label. For getText( ), the current label is returned.
TextField

The TextField class implements a single-line text-entry area, usually called an edit control. Text fields
allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse selections.
TextFields is a subclass of TextComponent. TextField defines the following constructors:
TextField( ) TextField(int numchars)
TextField(String str)
TextField(String str, int numchars)

The first version creates a default text field. The second form creates a text field that is numchars
characters eide. The third form initializes the text field with the string contained in str. The fourth form
initializes text field and sets it width.
TextField (and its superclass TextComponint) provides several methods that allow you to utilize a text
field. To obtain the string currently contained in the text field, call getText( ). To set the text, call setText( ).
These methods are as follows:
String getText( )
void setText(String str) Here, str is the
new String.

Example:

import java.awt.*; import


java.applet.*;
//EXAMPLE OF LABLE AND TEXT
/*
<applet code="app9" width = 300 height = 200>
</applet>
*/
public class app9 extends Applet
{
TextField text1,text2;
Font f= new Font("TimesRoman",Font.ITALIC,20);

public void init()


{
Label one=new Label("a value"); text1=new TextField(8);
Label two=new Label("b value"); text2=new
TextField(8); add(one);
add(text1); add(two); add(text2);
text1.setText("0");
text2.setText("0");
}

public void paint(Graphics g)


{
g.setFont(f); int x,y,z=0;
String s1,s2;
g.drawString("Input a number in each box",50,100); s1=text1.getText();
x=Integer.parseInt(s1);
s2=text2.getText();
y=Integer.parseInt(s2); z=x+y;
g.drawString("sum value is = "+z,50,175);
}}

Using Buttons
The most widely used control is the push button. A push button is a component that contains a label and
the generates an event when it is pressed. Push buttons are objects of type Button. Button defines these two
constructors:
Button( ) Button(String str)
The first version creates an empty button. The second creates a button that contains str as a label.
Handling Buttons:
Each time a button is pressed, an action event is generated. Each listener implements the ActionListener
interface. That interface defines the actionPerformed( ) method, which is called when an event occurs. An
ActionEvent objects is supplied as the argument to this method.
Example:

import java.awt.*; import java.applet.*;


import java.awt.event.*;

// EXAMPLE OF BUTTON
/*
<applet code="app10" width =300 height = 200>
</applet>
*/

public class app10 extends Applet implements ActionListener


{
Label result; public void init()
{
Button b1=new Button("apple");
b1.addActionListener(this); add(b1);
Button b2= new Button("orange");
b2.addActionListener(this); add(b2);
Button b3= new Button("banana");
b3.addActionListener(this); add(b3);
result=new Label(" "); add(result);
}
public void actionPerformed(ActionEvent ae)
{
result.setText(ae.getActionCommand());
}}

Another one example:

import java.awt.*; import java.applet.*;


import java.awt.event.*;

// EXAMPLE OF BUTTON
/*
<applet code="app101" width =300 height = 200>
<param name=m1 value=80>
<param name=m2 value=90>
</applet>
*/
public class app101 extends Applet implements ActionListener
{
String ma1,ma2,a; int m1,m2;
int a1,b,c1;
TextField text1=new TextField(8); public void init()
{
ma1=getParameter("m1");
m1=Integer.parseInt(ma1);
ma2=getParameter("m2");
m2=Integer.parseInt(ma2); Button b1=new
Button("+"); b1.addActionListener(this); add(b1);
Button b2= new Button("-");
b2.addActionListener(this); add(b2);
Button b3= new Button("*");
b3.addActionListener(this); add(b3);
}
public void actionPerformed(ActionEvent ae)
{
a=ae.getActionCommand(); if(a.equals("+"))
{
b=m1+m2;
}
else if(a.equals("-"))
{
b=m1-m2;
}
else
{
b=m1*m2;
}
repaint();
}
public void paint(Graphics g)
{
g.drawString("result: "+b,200,200);
}
}
Applying Check Boxes:

A check box is a control that is used to turn an option on or off. It consists of a small box that can either
contain a check mark or not. There is a label associated with each check box that describes what option the box
represents. You change the state of check box by clicking on it. Check boxes can be used individually or as part
of a group. Check boxes are objects of the checkbox class.
Checkbox supports these constructors:
Checkbox( ) Checkbox(String str)
Checkbox(String str, Boolean on)
Checkbox(String str, Boolean on, CheckboxGroup cbgroup) Checkbox(String
str,CheckboxGroup cbgroup, Boolean on)
The first form creates a checkbox whose label is initially blank. The state of the check box in unchecked.
The second form creates a check box whose label is specified by str. The state of the check box is
unchecked.
The third form allows you to set the initial state of the check box. If on is true , the check box in initially
checked; otherwise it si cleared.
The fourth and fifth forms create a check box whose label is specified by str and whose group is specified
by cbgroup. If this check box is not part of a group, then cbgroup must be null.

Handling Check Boxes:

Each time a check box is selected or deselected, an item event is generated. This is sent to any listeners
that previously registered an interest in receiving item event notifications from that component. Each listener
implements the ItemListener interface. The interface defines the itemStateChanged( ) method.an ItemEvent
objects is supplied as the argument to this method.
CheckboxGroup:

It is possible to create a set of mutually exclusive check boxes in which one and only one check box in
the group can be checked at any one time. These check boxes are often called radio buttons, because they act like
the station selector on a car radio-only one station can be selected at any one time. Checkbox groups are objects
of type CheckboxGroup. Only the default constructor is defined, which creates an empty group.

Choice Controls:

The Choice class is used to create a pop-up lists of items from which the user may choose. Thus a
Choice control is a form of menu. When inactive, a choise component takes up only enough space to show the
currently selected item. When the user clicks on it, the whole list of choices pops up, and a new selection can be
made.
Choice only defines the default constructor, which creates an empty list. To add a selection to the list,
call addItem( ) or add( ). They have these general forms:
void addItem(String name) void add(String
name)
Here, name is the name of the item being added. Items are added to the list in the order in which calls to add( ) or
addItem( ) occur.

Handling choice list:

Each time a choice is selected, an item event is generated. This is set to any listeners that previously
registered an interest in receiving item event notifications from that component. Each listener implements the
ItemListener interface. That interface defines the itemStateChanged( )bmethod. An ItemEvent object is
supplied as the argument to this method.
Example:

import java.awt.*; import java.applet.*;


import java.awt.event.*;

//example of checkbox and choice


/*
<applet code="app11" width=300 height =200>
</applet>
*/

public class app11 extends Applet


{
Label o1=new Label(" ");
Label o2=new Label(" ");

public void init()


{

CheckboxGroup c= new CheckboxGroup();


Checkbox c1=new Checkbox("black and white",c,true); Checkbox c2=new
Checkbox("Color",c,false); c1.addMouseListener(new check1());
c2.addMouseListener(new check2());
add(c1);
add(c2);
Choice abc=new Choice(); abc.add("onida");
abc.add("bpl");
abc.add("sumsung");
abc.add("philps"); abc.addItemListener(new ch());
add(abc);
add(o1);
add(o2);
}
class check1 extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
o1.setText("you have selected : black and whit tv");
}
}
class check2 extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
o1.setText("you have selected : color tv");
}
}

class ch implements ItemListener


{
public void itemStateChanged(ItemEvent e)
{
String s= (String)e.getItem();
o2.setText("you have selected " + s + " brand");
}
}
}

Using Lists:
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice object,
which shows only the single selected item in the menu, a List object can be constructed to show any number of
choices in the visible window. It can also created allow multiple selections.
To add a selection to the list, call add( ). it has the following two forms: void add(String
name)
void add(String name, int index)
Here, name is the name of the item added to the list. The first form adds items to the end of the list. The
second form adds the item at the index specified by index. Indexing begins at zero. You can specify –1 to add he
item to the end of the list.
Given an index, you can obtain the name associated with the item at that index by calling
getItem( ) which has this general form String getItem(int
index)
Example:

import java.awt.*; import java.applet.*;


import java.awt.event.*;
/*
<applet code="app12" height = 200 width = 300>
</applet>
*/
public class app12 extends Applet
{
List ob=new List();
TextField tx=new TextField(10); Button b1=new
Button("add");
String count[]={"one","two","three"}; public void start()
{
Label one=new Label("text"); add(one);
add(tx);
for(int i=0;i<count.length;++i)
ob.addItem(count[i]); add(ob);
b1.addActionListener(new Add()); add(b1);
}
class Add implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
ob.addItem(tx.getText());
}}}

Managing Scroll Bars:


Scroll bars are used to select continuous values between a specified minimum and maximum. Scroll bars
may be oriented horizontally or vertically. A scroll bar is actually a composite of several individual parts. Each
end has an arrow that you can click to move the current value of the scroll bar one unit in the direction of the
arrow. The current value of the scroll bar relative to its minimum and maximum values is indicated by the slider
box for the scroll bar.
Scrollbar defines the following constructors: Scrollbar( )
Scrollbar( int style)
Scrollbar(int style,int initial value, int thumbsize, int min, int max) The first form
creates a vertical scroll bar.
The second and third forms allow you to specify the orientation of the scrollbar. If style is
Scrollbar.VERTICAL, a vertical scroll bar is created. If style is Scrollbar.HORIZONTAL, the scroll bar is
horizontal.
In the third form of the constructor, the initial value of the scroll bar is passed in initial value. The
number of units represented by the height of the thumb is passed int thumb size. The minimum and maximum
values for the scroll bar are specified by min and max.

Handling Scroll Bars:

To process scroll bar events, you need to implement the AdjustmentListerner interface. Each time a
user interacts with a scroll bar, an Adjustmentevent object is generated. Its getAdjustmentType() method can
be used to determinet the type of the adjustment.

Using TextArea:
Sometimes a single line of text input is not enough for a given task. To handle these situations, the AWT
includes a simple multilane editor called TextArea.
TextArea is a subclass of TextComponent. Therefore , it supports the getText( ), setText( ) methods
described in the preceding section. TextArea adds the following methods:
void append(String str)
void insert(String str, int index)
The Append( ) method appends the string specified by str to the end of the current text.
Insert ( ) inserts the string passed in str at the specified index.

Example:

import java.applet.*; import java.awt.*;


import java.awt.event.*;
/*
<applet code = "app13" width = 300 height = 200>
</applet>
*/
public class app13 extends Applet implements AdjustmentListener
{
TextArea ta; public void init()
{
Scrollbar sb=new Scrollbar(Scrollbar.VERTICAL,0,0,0,100);
sb.addAdjustmentListener(this);
add(sb);
ta=new TextArea(10,20); add(ta);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
Scrollbar sb=(Scrollbar)ae.getAdjustable();
ta.append("AdjustmentEvent :"+sb.getValue()+"\n");
}}

Layout Managers:
Each Container object has a layout manager associated with it. A layout manager is an instance of any
class that implements the LayoutManager interface. The layout manager is set by the setLayout( ) method. If no
call to setLayout( ) is made, then the default layout manager is used.
The setLayout( ) method has the following general form void
setLayout(LayoutManager layout obj)

FlowLayout:
FlowLayout is the default layout manager. This it the layout manager that the preceding examples have
used. FlowLayout implements a simple layout style, which is similar to how words flow in a text editor.
Components are laid out from the upper-left corner, left to right and top to bottom. When no more components fit
on a line, the next one appears on the next line. A small space is left between each component, above and below,
as well as left and right.

Constructor of flow layout is FlowLayout(int how)


This form lets you specify how each line is aligned. Valid values for how are as follws FlowLayout.LEFT,
FlowLayout.CENTER , FlowLayout.RIGHT.

Example:

import java.applet.*; import java.awt.*;


/*
<applet code = "app14" width = 300 height = 200>
</applet>
*/
public class app14 extends Applet
{
String str[]={"one","two","three","four","five","six","seven"}; public void init()
{
setLayout(new FlowLayout(FlowLayout.LEFT)); for(int
i=0;i<str.length;++i)
add(new Button(str[i]));
}}

BorderLayout:
The BorderLayout class implements a common layout style for top-level windows. It has four narrow,
fixed-width components at the edges and one large area in the center. The four sides are feferred to as north,
south, east, and west. The middle area is called the center. BorderLayout defines the following constants that
specify the regions:
BorderLayout.CENTER BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH
When adding components, you will use these constants with the following form of add( ) ,
which is defined by container.

Example
import java.awt.*; import java.applet.*;

/*
<applet code="app16" width = 300 height = 20>
</applet>
*/
public class app16 extends Applet
{
public void init()
{
setLayout(new BorderLayout(5,5)); Button b1=new
Button("north"); Button b2=new Button("south");
Button b3=new Button("east"); Button b4=new
Button ("west"); Button b5 = new Button("center");
add(b1,"North");
add(b2,"South");
add(b3,"East");
add(b4,"West");
add(b5,"Center");
}}
GridLayout:
GridLayout lays out components in a two-dimensional grid. When you instantiate a GidLayout, you
define the number of rows and columns. The constructors supported by gridlayout ar shown here
GridLayout(int numRows, int numColumns)
Here, this form creates a grid layout with the specified number of rows and columns.

Example:
import java.applet.*; import
java.awt.*;
//example of gridlayout
/*
<applet code = "app15" width = 300 height = 200>
</applet>
*/
public class app15 extends Applet
{
public void init()
{
setLayout(new GridLayout(3,4,10,10)); for(int
i=1;i<=12;++i)
add(new Button(" "+i));
}}

Handling Events by Extending AWT Components:


To extend an AWT component, you must call the enableEvents( ) method of
Component. Its general form is shown here:
Protected final void enableEvents(ling eventMask)
The eventMask argument is a bit mask that defines the events to be delivered to this component. The AWTEvent
class defines int constants for making the mask. Several are shown her: ACTION_EVENT_MASK
ITEM_EVENT_MASK ADJUSTMENT_EVENT_MASK
KEY_EVENT_MASK COMPONENT_EVENT_MASK
MOUSE_EVENT_MASK CONTAINER_EVENT_MASK
TEXT_EVENT_MASK INPUT_METHOD_EVENT_MASK
WINDOW_EVENT_MASK
You must also override the appropriate method from one of your superclasses in order to process the
event. Given lists the methods most commonly used and the classes that provide them.

Class processing methods:

Button processActionEvent( )
Checkbox processItemEvent( )
CheckboxMenuItem processItemEvent( ) Choice
processItemEvent( )
Component processComponentEvent( ), processKeyEvent( ),
ProcessMouseEvent( )
List processActionEvent( ), processItemEvent( )
Scrollbar processAdjustmentEvent( )
TextComponent processTextEvent( )

Extending Button:
The following program creates an applet that displays a button labeled” test Button”. When the button is
pressed, the string “action event:”, is displayed on the status line of the applet viewer or browser, followed by a
count of the number of button presses.
The program has one top-level class named app18 that extends Applet. A integer variable I is defined
and initialized to zero. The records the number of button pushes. The init(
) method instantiates MyButton and adds it to the applet.
MyButton is an inner class that extends Button. Its constructor uses super to pass the label of the buton to
the surperclass constructor. It calls enableEvents( ) so that action events may be received by this object. When an
action event is generated, processActionEvent( ) is called.
Example:

import java.awt.*; import java.applet.*;


import java.awt.event.*; arun

/*
<applet code="app18" width = 300 height = 200>
</applet>
*/

public class app18 extends Applet


{
MyButton one;

int i=0;
public void init()
{
one=new MyButton("test button"); add(one);
}
class MyButton extends Button
{
MyButton(String label)
{
super(label); enableEvents(AWTEvent.ACTION_EVENT_MASK);
}
public void processActionEvent(ActionEvent ae)
{
showStatus("action Event " + i ++);

}}}

Extending Checkbox:

The following program creates an applet that displays three check boxes labeled “apple”,
“orange”,”mango”. When a check box is selected or deselected, a string containing the name and state of the
check box is displayed on the status line of the applet viewer or browser.
The program has one top-level class named app19 that extends Applet. Its init( ) method creates three
instances of Mycheckbox and adds these to the applet. Mycheckbox is an inner class that extends checkbox.

import java.awt.*; import java.applet.*;


import java.awt.event.*;

/*
<applet code="app19" width = 300 height = 200>
</applet>
*/

public class app19 extends Applet


{
MyCheckbox cb1,cb2,cb3; public void init()
{
cb1=new MyCheckbox("apple "); add(cb1);
cb2=new MyCheckbox("orange"); add(cb2);
cb3=new MyCheckbox("mango"); add(cb3);
}
class MyCheckbox extends Checkbox
{
MyCheckbox(String label)
{
super(label); enableEvents(AWTEvent.ITEM_EVENT_MASK);
}
public void processItemEvent(ItemEvent e)
{
showStatus("Checkbox name/state: "+getLabel()+"/"+getState());
}}}

Extending Check Box Group:


This program reworks the preceding check box example so that the check boxes form a check box
group. Thus, only one of the check boxes may be selected at any time.

import java.awt.*; import java.applet.*;


import java.awt.event.*;
/*
<applet code="app20" width = 300 height = 200>
</applet>
*/

public class app20 extends Applet


{
CheckboxGroup cbg; MyCheckbox
cb1,cb2,cb3; public void init()
{
cbg=new CheckboxGroup();
cb1=new MyCheckbox("item1 ",cbg,true);
add(cb1);
cb2=new MyCheckbox("item2",cbg,false); add(cb2);
cb3=new MyCheckbox("item3",cbg,false); add(cb3);
}
class MyCheckbox extends Checkbox
{
public MyCheckbox(String label,CheckboxGroup cbg, boolean flag)
{
super(label,cbg,flag);
enableEvents(AWTEvent.ITEM_EVENT_MASK);
}
protected void processItemEvent(ItemEvent e)
{
showStatus("Checkbox name/state: "+getLabel()+"/"+getState()); super.processItemEvent(e);
}}}

Extending Choice :

The following program creates an applet that displays a choice list with items labeled “red”, ”green”, and
“blue”. When entry is selected, a string that contains the name of the color is displayed on the status line of the
applet viewer or browser.

The top class name is app22 that extends applet. Its init( ) method creates a choice element and adds it to
the applet. Mychoice is an inner class that extends choice. It calls enableEvents( ) so that item events may be
received by this object. When an item event is generated, processItemEvent( ) is called. That method displays a
string on the status line and calls processItemEvent( ) for the superclass.

import java.awt.*; import java.applet.*;


import java.awt.event.*;
//extending choice
/*
<applet code="app22" width = 300 height = 200>
</applet>
*/
public class app22 extends Applet
{
MyChoice one; public void init()
{
one = new MyChoice(); one.add("red");
one.add("green");
one.add("yellow"); add(one);
}

class MyChoice extends Choice


{
MyChoice()
{
enableEvents(AWTEvent.ITEM_EVENT_MASK);
}

public void processItemEvent(ItemEvent ie)


{
showStatus("Choice selection :"+getSelectedItem());
}
}}

Extending List:

import java.awt.*; import java.applet.*;


import java.awt.event.*;
//extending list
/*
<applet code="app23" width = 300 height = 200>
</applet>
*/

public class app23 extends Applet


{
MyList one; public void init()
{
one = new MyList(); one.add("red");
one.add("green");
one.add("yellow"); add(one);
}
class MyList extends List
{
MyList()
{
enableEvents(AWTEvent.ITEM_EVENT_MASK );
}
public void processItemEvent(ItemEvent ie)
{
showStatus("Item Event :"+getSelectedItem());
}}}

Extending Scrollbar:

import java.awt.*; import java.applet.*; import


java.awt.event.*;
//extending scrollbar
/*
<applet code="app24" width = 300 height = 200>
</applet>
*/

public class app24 extends Applet


{
MyScrollbar one; public void init()
{
one = new MyScrollbar(Scrollbar.VERTICAL,0,0,0,100); add(one);
}
class MyScrollbar extends Scrollbar
{
MyScrollbar(int style,int initial, int thumb, int min,int max)
{
enableEvents(AWTEvent.ADJUSTMENT_EVENT_MASK);
}
public void processAdjustmentEvent(AdjustmentEvent ae)
{
showStatus("Adjustment Event :"+ae.getValue());
}}}

INTRODUCTION OF SWING

The Swing-related classes are contained in javax.swing and its subpackages, such
as javax.swing.tree. Many other Swing-related classes and interfaces exist that arenot
examined in this chapter.
The remainder of this chapter examines various Swing components and illustrates
them through sample applets.

JApplet
Fundamental to Swing is the JApplet class, which extends Applet. Applets that useSwing must
be subclasses of JApplet. JApplet is rich with functionality that is notfound in
Applet. For example, JApplet supports various ―panes,‖heglass such pane, and the root pane. For theexamples in
this chapter, we will not be using most of
JApplet’s enhanced features. However,AppletandJAppletoneis diffe important to this discussion, because it
is used by the sample applets in this chapter. When
adding a component to an instance of JApplet, do not invoke the add( ) method of the applet. Instead,
call add( ) for the content pane of the JApplet object. The content pane can be obtainedvia the method
shown here:

Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane. Its form
is shown here:
void add(comp)

Here, comp is the component to be added to the content pane. Icons

and Labels

In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image. Two of
its constructors are shown here:
ImageIcon(String filename)
ImageIcon(URL url)

The first form uses the image in the file named filename. The second form uses the image in theresource
identified by url.
The ImageIcon class implements the Icon interface that declares the methods
shown here:
Method Description

int getIconHeight( ) Returns the height of theicon in


pixels.
int getIconWidth( ) Returns the width of the icon in
pixels.
void paintIcon(Component comp, Graphics g,int x,
int y)
Paints the icon at position x, y on
the graphics context g. Additional
information about the paint
operation can be provided in comp.
Swing labels are instances of the JLabel class, which extends JComponent. It can display text and/or
an icon. Some of its constructors are shown here:
JLabel(Icon i) Label(String s)
JLabel(String s, Icon i, int align)

Here, s and i are the text and icon used for the label. The align argument is either
LEFT,RIGHT, CENTER, LEADING, or TRAILING. These constants are defined in the
SwingConstants interface, along with several others used by the Swing classes.

The icon and text associated with the label can be read and written by the
following methods:
Icon getIcon( ) String
getText( ) void setIcon(Icon
i) void setText(String s)
Here, i and s are the icon and text, respectively.
The following example illustrates how to create and display a label containing bothan icon and a string.
The applet begins by getting its content pane. Next, an ImageIcon object is created for the file
france.gif. This is used as the second argument to the JLabel constructor. The first and last arguments
for the JLabel constructor are the label text and the alignment. Finally, the label is added to the content
pane.

import java.awt.*; import


javax.swing.*;
/* <applet code="JLabelDemo" width=250 height=150> </applet>*/public
class JLabelDemo extends JApplet
{ public void init() {
// Get content pane Container
contentPane =
getContentPane(); // Create an icon
ImageIcon ii = new ImageIcon("france.gif"); //
Create a label
JLabel jl = new JLabel("France", ii, JLabel.CENTER); //
Add label to the content panecontentPane.add(jl);
}
}
Output from this applet is shown here:
Text Fields

The Swing text field is encapsulated by the JTextComponent class, which extends JComponent. It
provides functionality that is common to Swing text components. One of its subclasses is JTextField,
which allows you to edit one line of text. Some of its constructors are shown here:

JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)

Here, s is the string to be presented, and cols is the number of columns in the text field.
The following example illustrates how to create a text field. The applet begins by getting its content
pane, and then a flow layout is assigned as its layout manager. Next, a JTextField object is created and is
added to the content pane.
import java.awt.*; import
javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet {
JTextField jtf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add text field to content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
}
Output from this applet is shown here:
Buttons

Swing buttons provide features that are not found in the Button class defined by theAWT. For
example, you can associate an icon with a Swing button. Swing buttons are subclasses of the
AbstractButton class, which extends JComponent. AbstractButton contains many methods that allow
you to control the behavior of buttons, check boxes, and radio buttons. For example, you can define
different icons that are displayed for the component when it is disabled, pressed, or selected. Another
icon can be used as a rollover icon, which is displayed when the mouse is positioned over that
component.

The following are the methods that control this behavior:


void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)

Here, di, pi, si, and ri are the icons to be used for these different conditions.
The text associated with a button can be read and written via the following methods:
String getText( ) void
setText(String s)

Here, s is the text to be associated with the button.

Concrete subclasses of AbstractButton generate action events when they are pressed. Listenersregister and
unregister for these events via the methods shown here:
void addActionListener(ActionListener al) void
removeActionListener(ActionListener al)Here, al is
the action listener.

AbstractButton is a superclass for push buttons, check boxes, and radio buttons. Each is
examined next.

The JButton Class

The JButton class provides the functionality of a push button. JButton allows an icon,a string, or both
to be associated with the push button. Some of its constructors are shown here: JButton(Icon i)
JButton(String s)
JButton(String s, Icon
i)
Here, s and i are the string and icon used for the button.
Check Boxes

The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of
AbstractButton. Its immediate superclass is JToggleButton, which provides support for two-state
buttons. Some of its constructors are shown here:

JCheckBox(Icon i) JCheckBox(Icon i,
boolean state) JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)

Here, i is the icon for the button. The text is specified by s. If state is true, the check box is initially
selected. Otherwise, it is not.
The state of the check box can be changed via the following method:
void setSelected(boolean state)
Here, state is true if the check box should be checked.
The following example illustrates how to create an applet that displays four checkboxesand a
text field. When a check box is pressed, its text is displayed in the text field.
The content pane for the JApplet object is obtained, and a flow layout is assigned as itslayout manager.
Next, four check boxes are added to the content pane, and icons are assigned for the normal, rollover,
and selected states. The applet is then registered to receive item events. Finally, a text field is added to
the content pane.

When a check box is selected or deselected, an item event is generated. This is handled by
itemStateChanged( ). Inside itemStateChanged( ), the getItem( ) method gets the JCheckBox
object that generated the event. The getText( ) method gets the text for that check box and uses it
to set the text inside the text field.

import java.awt.*;
import
java.awt.event.*;
import javax.swing.*;
/*

<applet code="JCheckBoxDemo" width=400 height=50>


</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener {
JTextField jtf;
public void init()
{

// Get content pane


Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Create icons
ImageIcon normal = new ImageIcon("normal.gif");
ImageIcon rollover = new ImageIcon("rollover.gif");
ImageIcon selected = new
ImageIcon("selected.gif"); // Add check boxes to the
content pane
JCheckBox cb = new JCheckBox("C", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("C++", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Java", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Perl", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
// Add text field to the content pane jtf
= new JTextField(15);
contentPane.add(jtf);
}
public void itemStateChanged(ItemEvent ie) {
JCheckBox cb = (JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}
Here is the output:

Radio Buttons

Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
AbstractButton. Its immediate superclass is JToggleButton, which provides support for two- state
buttons. Some of its constructors are shown here:

JRadioButton(Icon i) JRadioButton(Icon i,
boolean state) JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the buttonis
initially selected. Otherwise, it is not.
Radio buttons must be configured into a group. Only one of the buttons in that
group can be selected at any time. For example, if a user presses a radio button that is
in a group, any previously selected button in that group is automatically deselected.
The ButtonGroup class is instantiated to create a button group. Its default constructor is invoked for this
purpose. Elements are then added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.

Radio button presses generate action events that are handled by actionPerformed( ).The
getActionCommand( ) method gets the text that is associated with a radio button and uses
it to set the text field.

import java.awt.*;
import
java.awt.event.*;
import javax.swing.*;
/*

<applet code="JRadioButtonDemo" width=300


height=50> </applet>
*/
public class JRadioButtonDemo extends JApplet
implements ActionListener {
JTextField tf; public void
init() {
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add radio buttons to content pane
JRadioButton b1 = new
JRadioButton("A");
b1.addActionListener(this);
contentPane.add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this); contentPane.add(b2);
JRadioButton b3 = new JRadioButton("C");
b3.addActionListener(this); contentPane.add(b3);
// Define a button group
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
// Create a text field and add it
// to the content pane
tf = new JTextField(5);
contentPane.add(tf);
}
public void actionPerformed(ActionEvent ae)
{ tf.setText(ae.getActionCommand());
}
}
Output from this applet is shown here:
Combo Boxes

Swing provides a combo box (a combination of a text field and a drop-down list) through the
JComboBox class, which extends JComponent. A combo box normally displays one entry. However, it
can also display a drop-down list that allows a user to select a different entry. You
can also type your selection into the text field. Two of JComboBox’s constructors here:

JComboBox( )
JComboBox(Vector v)
Here, v is a vector that initializes the combo box.
Items are added to the list of choices via the addItem( ) method, whose signature isshown here:
void addItem(Object obj)
Here, obj is the object to be added to the combo box.

The following example contains a combo box and a label. The label displays an icon. The combo box
contains entries for ―France‖,. ―Germany‖,
When a country is selected, the label is updated to display the flag for that country.

import java.awt.*;
import
java.awt.event.*;
import javax.swing.*;
/*

<applet code="JComboBoxDemo" width=300


height=100> </applet>
*/
public class JComboBoxDemo extends JApplet
implements ItemListener {
JLabel jl;
ImageIcon france, germany, italy, japan;public
void init() {
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Create a combo box and add it
// to the panel
JComboBox jc = new JComboBox();
jc.addItem("France");
jc.addItem("Germany"); jc.addItem("Italy");
jc.addItem("Japan");
jc.addItemListener(this);
contentPane.add(jc);
// Create label
jl = new JLabel(new ImageIcon("france.gif"));
contentPane.add(jl);
}
public void itemStateChanged(ItemEvent ie) {String s
= (String)ie.getItem();
jl.setIcon(new ImageIcon(s + ".gif"));
}
}

Output from this applet is shown here:

Tabbed Panes

A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title.
When a user selects a folder, its contents become visible. Only one of the folders may be selected at a
time. Tabbed panes are commonly used for setting configuration options.
Tabbed panes are encapsulated by the JTabbedPane class, which extends JComponent. We will use
its default constructor. Tabs are defined via the following method:
void addTab(String str, Component comp)
Here, str is the title for the tab, and comp is the component that should be added to the tab.
Typically, a JPanel or a subclass of it is added.

The general procedure to use a tabbed pane in an applet is outlined here:


1. Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane. (The arguments to this method
define the title of the tab and the component it contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the content pane of the applet.

Scroll Panes

A scroll pane is a component that presents a rectangular area in which a componentmay beviewed.
Horizontal and/or vertical scroll bars may be provided if necessary.
Scroll panes are implemented in Swing by the JScrollPane class, which extendsJComponent.Some
of its constructors are shown here:
JScrollPane(Component comp) JScrollPane(int vsb, int
hsb) JScrollPane(Component comp, int vsb, int hsb)
Here, comp is the component to be added to the scroll pane. vsb and hsb are intconstants that define
when vertical and horizontal scroll bars for this scroll pane areshown. These constants are defined by the
ScrollPaneConstants interface. Some
examples of these constants are described as follows:
Constant Description
HORIZONTAL_SCROLLBAR_ALWAYS Always provide horizontal scroll bar
HORIZONTAL_SCROLLBAR_AS_NEEDED Provide horizontal scroll bar, if needed
VERTICAL_SCROLLBAR_ALWAYS Always provide vertical scroll bar VERTICAL_SCROLLBAR_AS_NEEDED
Provide vertical scroll bar, if needed

Here are the steps that you should follow to use a scroll pane in an applet:
1. Create a JComponent object.
2. Create a JScrollPane object. (The arguments to the constructor specify
the component and the policies for vertical and horizontal scroll bars.)
3. Add the scroll pane to the content pane of the applet.

The following example illustrates a scroll pane. First, the content pane of the JApplet object is obtained
and a border layout is assigned as its layout manager. Next, a JPanel object is created and four hundred
buttons are added to it, arranged into twenty columns. The panel is then added to a scroll pane, and the
scroll pane is added to the content pane. This causes vertical and horizontal scroll bars to appear. You
can use the scroll bars to scroll the buttons into view.
import java.awt.*; import
javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet
{ public void init() {
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new
BorderLayout());
// Add 400 buttons to a
panelJPanel jp = new
JPanel();
jp.setLayout(new GridLayout(20, 20));int b =
0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b;
}
}
// Add panel to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h =
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);
// Add scroll pane to the content pane
contentPane.add(jsp,
BorderLayout.CENTER);
}
}

Output from this applet is shown here:

Trees
A tree is a component that presents a hierarchical view of data. A user has the ability to expand or
collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class, which
extends JComponent. Some of its constructors are shown here:
JTree(Hashtable ht)
JTree(Object obj[ ])
JTree(TreeNode tn)
JTree(Vector v)

The first form creates a tree in which each element of the hash table ht is a child node.
Each element of the array obj is a child node in the second form. The tree node tn is the root ofthe tree
in the third form. Finally, the last form uses the elements of vector v as child nodes.

A JTree object generates events when a node is expanded or collapsed. The


addTreeExpansionListener( ) and removeTreeExpansionListener( ) methods allow listeners
to register and unregister for these notifications. The signatures of these methods are shown here:
void addTreeExpansionListener(TreeExpansionListener tel)
void removeTreeExpansionListener(TreeExpansionListener tel)

Here, tel is the listener object.


The getPathForLocation( ) method is used to translate a mouse click on a specific point of thetree to a
tree path. Its signature is shown here:
TreePath getPathForLocation(int x, int y)
Here, x and y are the coordinates at which the mouse is clicked. The return value is a TreePath
object that encapsulates information about the tree node that was selected by the user.
Tables

A table is a component that displays rows and columns of data. You can drag the cursor on column
boundaries to resize columns. You can also drag a column to a new position. Tables are implemented by
the JTable class, which extends JComponent.
One of its constructors is shown here:
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and colHeads
is a one-dimensional array with the column headings. Here are
the steps for using a table in an applet:

1. Create a JTable object.


2. Create a JScrollPane object. (The arguments to the constructor specify the
table and the policies for vertical and horizontal scroll bars.)
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane of the applet.

The following example illustrates how to create and use a table. The content pane of the JApplet object
is obtained and a border layout is assigned as its layout manager.A one-dimensional array of strings is
created for the column headings. This table has three columns. A two-dimensional array of strings is
created for the table cells. You can see that each element in the array is an array of three strings. These
arrays are passed to the JTable constructor. The table is added to a scroll pane and then the scroll pane is
added to the content pane.
import java.awt.*; import
javax.swing.*;
/*
<applet code="JTableDemo" width=400
height=200> </applet>
*/
public class JTableDemo extends JApplet {

public void init() {


// Get content pane
Container contentPane = getContentPane();
// Set layout manager
contentPane.setLayout(new
BorderLayout());
// Initialize column headings
final String[] colHeads = { "Name", "Phone", "Fax"
}; // Initialize data
final Object[][] data = {
{ "Gail", "4567", "8675" },
{ "Ken", "7566", "5555" },
{ "Viviane", "5634", "5887" },
{ "Melanie", "7345", "9222" },
{ "Anne", "1237", "3333" },
{ "John", "5656", "3144" },
{ "Matt", "5672", "2176" }, {
"Claire", "6741", "4244" }, {
"Erwin", "9023", "5159" }, {
"Ellen", "1134", "5332" },
{ "Jennifer", "5689", "1212" },
{ "Ed", "9030", "1313" },
{ "Helen", "6751", "1415"
} };
// Create the table
JTable table = new
JTable(data,colHeads); //
Add table to a scroll pane
int v =
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h =
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDE
D;JScrollPane jsp = new JScrollPane(table, v, h);
// Add scroll pane to the content pane
contentPane.add(jsp,
BorderLayout.CENTER);
}
}

Here is the output:

Java JDBC

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the
database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database.
There are four types of JDBC drivers:

o JDBC-ODBC Bridge Driver,

o Native Driver,

o Network Protocol Driver, and

o Thin Driver

We have discussed the above four drivers in the next chapter.


We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API, we can
save, update, delete and fetch data from the database. It is like Open Database Connectivity (ODBC) provided by
Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on the X/Open
SQL Call Level Interface. The java.sql package contains classes and interfaces for JDBC API. A list of
popular interfaces of JDBC API are given below:

o Driver interface

o Connection interface

o Statement interface

o PreparedStatement interface

o CallableStatement interface

o ResultSet interface

o ResultSetMetaData interface

o DatabaseMetaData interface

o RowSet interface

A list of popular classes of JDBC API are given below:

o DriverManager class

o Blob class

o Clob class

o Types class

Why Should We Use JDBC

Before JDBC, ODBC API was the database API to connect and execute the query with the database. But, ODBC
API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has
defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following activities:

1. Connect to the database

2. Execute queries and update statements to the database

3. Retrieve the result received from the database.

Introduction to JDBC (Java Database Connectivity)


JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a
specification from Sun microsystems that provides a standard abstraction(API or Protocol) for java applications to
communicate with various databases. It provides the language with java database connectivity standards. It is used to
write programs required to access databases. JDBC, along with the database driver, can access databases and
spreadsheets. The enterprise data stored in a relational database(RDB) can be accessed with the help of JDBC APIs.
Definition of JDBC(Java Database Connectivity)
JDBC is an API(Application programming interface) used in java programming to interact with
databases. The classes and interfaces of JDBC allow the application to send requests made by users to the specified
database.
Purpose of JDBC
Enterprise applications created using the JAVA EE technology need to interact with databases to store application-
specific information. So, interacting with a database requires efficient database connectivity, which can be achieved
by using the ODBC(Open database connectivity) driver. This driver is used with JDBC to interact or communicate
with various kinds of databases such as Oracle, MS Access, Mysql, and SQL server database.
Components of JDBC
There are generally four main components of JDBC through which it can interact with a database. They are as
mentioned below:
1. JDBC API: It provides various methods and interfaces for easy communication with the database. It provides two
packages as follows, which contain the java SE and Java EE platforms to exhibit WORA(write once run anywhere)
capabilities.
java.sql.*;
It also provides a standard to connect a database to a client application.
2. JDBC Driver manager: It loads a database-specific driver in an application to establish a connection with a
database. It is used to make a database-specific call to the database to process the user request.
3. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation) being performed by JDBC
Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge translates the JDBC
method call to the ODBC function call. It makes use of the sun.jdbc.odbc package which includes a native library
to access ODBC characteristics.

Architecture of JDBC
Architecture of JDBC

Description:
1. Application: It is a java applet or a servlet that communicates with a data source.
2. The JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve results. Some of
the important classes and interfaces defined in JDBC API are as follows:
3. DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific drivers to
effectively connect enterprise applications to databases.
4. JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver that intelligently
communicates with the respective data source.

JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert requests from
Java programs to a protocol that the DBMS can understand. There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver

Types of JDBC Architecture(2-tier and 3-tier)

The JDBC architecture consists of two-tier and three-tier processing models to access a database. They are as
described below:
1. Two-tier model: A java application communicates directly to the data source. The JDBC driver enables the
communication between the application and the data source. When a user sends a query to the data source, the
answers for those queries are sent back to the user in the form of results.
The data source can be located on a different machine on a network to which a user is connected. This is known
as a client/server configuration, where the user’s machine acts as a client, and the machine has the data source
running acts as the server.

2. Three-tier model: In this, the user’s queries are sent to middle-tier services, from which the commands are
again sent to the data source. The results are sent back to the middle tier, and from there to the user.
This type of model is found very useful by management information system directors.
Interfaces of JDBC API
A list of popular interfaces of JDBC API is given below:
 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface
Classes of JDBC API
A list of popular classes of JDBC API is given below:
 DriverManager class
 Blob class
 Clob class
 Types class
Working of JDBC
Java application that needs to communicate with the database has to be programmed using JDBC API. JDBC Driver
supporting data sources such as Oracle and SQL server has to be added in java application for JDBC support which
can be done dynamically at run time. This JDBC driver intelligently communicates the respective data source.
Creating a simple JDBC application

 Java

package com.vinayak.jdbc
import java.sql.*;
public class JDBCDemo {
public static void main(String args[])
throws SQLException, ClassNotFoundException
{
String driverClassName
= "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:XE";
String username = "scott";
String password = "tiger";
String query
= "insert into students values(109, 'bhatt')";

// Load driver class


Class.forName(driverClassName);

// Obtain a connection
Connection con = DriverManager.getConnection(
url, username, password);

// Obtain a statement
Statement st = con.createStatement();
// Execute the query
int count = st.executeUpdate(query);
System.out.println(
"number of rows affected by this query= "
+ count);

// Closing the connection as per the


// requirement with connection is completed
con.close();
}
} // class

The above example demonstrates the basic steps to access a database using JDBC. The application uses the JDBC-
ODBC bridge driver to connect to the database. You must import java.sql package to provide basic SQL
functionality and use the classes of the package.

Simple database connections and queries


One of the benefits of programming in the Java ecosystem is that you will likely find a stable JDBC database
connector for whatever database you choose. The steps for connecting to a database with JDBC are as follows:

1. Install or locate the database you want to access.


2. Include the JDBC library.
3. Ensure the JDBC driver you need is on your classpath.
4. Use the JDBC library to obtain a connection to the database.
5. Use the connection to issue SQL commands.
6. Close the connection when you are finished.

We'll go through these steps together.

Finding a JDBC driver


To find a driver for your chosen database, simply do a web search for your database and JDBC. For instance, typing
in "mysql jdbc driver" will turn up a driver for MySQL. I challenge you to find an enterprise-grade database without
a JDBC driver!
Step 1. Download and install SQLite
SQLite is a very compact database. It isn't intended for production use but is a great choice for quickly trying things
out. SQLite uses a file as its functional database, without requiring any service or daemon installations.

To get started with this demonstration, first download the SQLite sample database. Unzip the .db file and save it
somewhere you won't forget. This file contains both a functional file-based database and sample schema and data
that we can use.

SQL and JDBC


NoSQL is popular but relational databases remain the most used type of datastore. A relational database is a
structured repository consisting of tables with columns and rows and the relationships between the tables. SQL, or
structured query language, is the language data architects use to perform CRUD (create, read, update, and delete)
operations on records in a relational database. JDBC is an adapter layer from Java to SQL: it gives Java developers
a common interface for connecting to a database, issuing queries and commands, and managing responses.
Step 2. Import JDBC into your Java application
We could do our coding in an IDE, but coding directly in a text editor will better demonstrate JDBC's simplicity. To
begin, you will need to have a compatible JDK installation for your operating system.
Assuming you have a JDK installed, we can start by creating a simple Java program. In your text editor, paste in the
code shown in Listing 1. Call this file WhatIsJdbc.java.

Listing 1. A simple Java program

class WhatIsJdbc{

public static void main(String args[]){

System.out.println("Hello InfoWorld");

Now, compile the code by entering the command: javac WhatIsJdbc.java. Compiling will output
the WhatIsJdbc.class file. Execute this file from the command line with the call: java WhatIsJdbc.

Once you have a basic Java program, you can include the JDBC libraries. Paste in the code from Listing 2 at the
head of your simple Java program.

Listing 2. JDBC imports

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.ResultSet;

import java.sql.Statement;

Each of these imports provides access to a class that facilitates the standard Java database connection:

 Connection represents the connection to the database.


 DriverManager obtains the connection to the database. (Another option is DataSource, used for connection pooling.)
 SQLException handles SQL errors between the Java application and the database.
 ResultSet and Statement model the data result sets and SQL statements.

You'll see each of these in action shortly.

Step 3. Add the JDBC driver to your classpath


Next, you'll add the SQLite driver to your classpath. Remember, a JDBC driver is a class that implements the JDBC
API for a specific database.
Go to the GitHub page for SQLite driver and download the latest SQLite .jar. If you are using Maven or Gradle, or
something similar, you can add the driver via the Maven repository. Be sure to get the most recent .jar file and store
it somewhere you'll remember.

The next time you execute your Java program, you will pull in that .jar file via the classpath. There are several ways
to set the classpath. Listing 3 shows how to do it using a command-line switch.

Listing 3. Executing the SQLite driver on the Java classpath

java.exe -classpath /path-to-driver/sqlite-jdbc-3.23.1.jar:. WhatIsJdbc

Notice that we've set the classpath to point at the driver and the local directory; this way, Java will still find our class
file.

Step 4. Obtain a database connection


The classpath now has access to the driver. Next, change your simple Java application file to look like the program
in Listing 4.

Listing 4. Using the JDBC Connection class to connect to SQLite

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.ResultSet;

import java.sql.Statement;

String sql = "SELECT id, username FROM users WHERE id = ?";

List users = new ArrayList<>();

try (Connection con = DriverManager.getConnection(myConnectionURL);

PreparedStatement ps = con.prepareStatement(sql)) {

ps.setInt(1, userId);

try (ResultSet rs = ps.executeQuery()) {

while(rs.next()) {
users.add(new User(rs.getInt("id"), rs.getString("name")));

} catch (SQLException e) {

e.printStackTrace();

return users;

class WhatIsJdbc{

public static void main(String[] args) {

String url = "jdbc:sqlite:path-to-db/chinook/chinook.db";

try (Connection conn = DriverManager.getConnection(url){

System.out.println("Got it!");

} catch (SQLException e) {

throw new Error("Problem", e);

Compile and execute this code. Assuming all goes well, you will get an affirming message.

No suitable driver found


If you've received an error that looks like "No suitable driver found for jdbc:sqlite," then you need to revisit the
classpath and make sure it points to the driver you downloaded. Failed driver connection is the most common
stumbling block for beginners using JDBC. Don't sweat it; just fix it.
Now, we're ready for some SQL commands.

Step 5. Query the database


With the live connection object in hand, we can do something useful, like querying the database. Listing 5 shows
how to query SQLite using the JDBC Connection and Statement objects.

Listing 5. Querying the database with JDBC

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.ResultSet;

import java.sql.Statement;

class WhatIsJdbc{

public static void main(String[] args) {

String sql = "SELECT id, username FROM users WHERE id = ?";

String url = "jdbc:sqlite:path-to-db-file/chinook/chinook.db";

try (Connection conn = DriverManager.getConnection(url);

Statement stmt = conn.createStatement()) {

try {

ResultSet rs = stmt.executeQuery("select * from albums";);

while (rs.next()) {

String name = rs.getString("title");

System.out.println(name);

} catch (SQLException e ) {
throw new Error("Problem", e);

} catch (SQLException e) {

throw new Error("Problem", e);

In Listing 5 we use our Connection object to obtain a Statement object: conn.createStatement(). We then use this
object to execute an SQL query: stmt.executeQuery(query).

The executeQuery command returns a ResultSet object, which we then use to iterate over the data with while
(rs.next()). In this example, you should see the album titles we've queried on as output.

Notice that we also closed the connection, via a call to conn.close().

CREATING DATABASE

Step 1 Open a command line prompt


Change to the directory in which you have installed the files for the sample.
Step 2 Viewing your .java file
Using your text editor, view the file “HelloWorldJDBC.java”.
Step 3 Viewing your sample class
Your class must contain the same name as the .java file containing the class. It should appear as follows:
public class HelloWorldJDBC {

}
Copy
This class is a public class because it has the ability to be accessed outside the scope of this class. In this
example everything is done within this class.
Step 4 Examining the main method
The main method is the entry point for your program. For this simple example, we are only using one
.java file. Therefore, the class will contain the main method as shown below. For this example, we will
throw the outermost SQLException (The exception related to the Connection object) for simplicity.
public static void main(String[] args) throws SQLException {

}
Copy
Step 5 Creating and initializing your Connection Object
You will initialize your Connection object before you have access to any of the methods it contains. You
will retrieve the connection object by calling a method from the DriverManager class called
getConnection(). The return from this method is your Connection object.
It is good practice to start a new try block for every object that you initialize. When you are done with
the object, simply add a finally block that performs the corresponding close() method, and the outermost
block will contain your catch block to handle all possible SQLExceptions. This will be easier to see with
the full code.
*Note: The URL will change depending on the Driver you are using, in this case, the RDM JDBC driver
is being used.
Connection Conn = DriverManager.getConnection(“jdbc:raima:rdm://local”);
try {

}
} catch (SQLException exception) {

} finally {
Conn.close();
}
Copy
Step 6 Creating your Statement Object
The newly created Connection object Conn has a method in it called createStatement() that will return a
Statement object. You will then use with this Connection to the database.
Statement Stmt = Conn.createStatement();
try {

} finally {
Stmt.close();
}
Copy
Step 7 Execute Statements to Create or Open the Database
Using the Statement object Stmt you just created, you can execute several different methods depending
on the type of statement you want to execute. For example, if you would like to execute a SQL statement
such as “OPEN database_name” or “DELETE * FROM table_name” you would perform a
Statement.execute() method. You can see execute() used in the code snippet below. In this example, we
will create the database programmatically. In this example, the database is trivial, consisting of a single
table named hello_table containing a single character column named foo. The sequence will create a
database if it doesn’t yet exist, or just open it if it does exist.
*Note: This database is created programmatically. There are tools out there to create your database
separately from your program. View a quick “How to Create a Database with SQL” tutorial on how to
do this.
try {
Stmt.execute(“CREATE DATABASE hello_db”);
Stmt.execute(“CREATE TABLE hello_table (f00 char(31))”);
Conn.commit(); // now the database physically exists
} catch (SQLException exception) {
// we are here if database exists
Stmt.execute(“OPEN DATABASE hello_db”);
}
Copy
Step 8 Inserting a new Row using the Statement Object
To insert a single row into this database, we use the executeUpdate() method, which is used for complete
(unprepared) INSERT, UPDATE or DELETE statements. This implicitly starts a transaction, which
will be one unit of update work applied to the database atomically. One INSERT is shown below, but
more could be added at this point.
Stmt.executeUpdate (“INSERT INTO hello_table VALUES (”Hello World”)”);
Copy
Step 9 Committing Changes
In order to have your changes finalized in the database you must perform a transaction commit. In
JDBC this is done through a method in the Connection object. The method we will be using is
Connection.commit() and that will finalize any changes you made during a transaction.
Conn.commit(); //Commits all changes
Copy
Step 10 Creating your Result Set Object (retrieving data from the database)
In JDBC, when you want to retrieve data from the database, you perform a SQL SELECT statement
using your Statement object with an execute method that returns a Result Set object. This method is
called Statement.executeQuery(). This means it will execute the specified Query and return the Query
results in the given Result Set.
ResultSet RS = Stmt.executeQuery(“SELECT * FROM hello_table”);
try {

} finally {
RS.close();
}
Copy
Step 11 Accessing the Result Set
In order to access every piece of data in your Result Set, you must iterate through it. A method is
provided within the Result Set to check if the next result in the Result Set is NULL, meaning no more
data. If the method ResultSet.next() returns TRUE then there is data in the database and you can
retrieve it from your result set.
To access the data inside the Result Set you must perform a getter method. There are numerous getter
methods available to retrieve the specific data type from the Result Set. In this example we want a
string, therefore we use the ResultSet.getString() method, with the parameter being the column
(first/only column is 1) you are retrieving from.
Take a look at the code below to see an example of how this can be done.
while(RS.next() != false)
{
System.out.println(RS.getString(1));
}
Copy
This loop will retrieve all rows in the result set. When this sample program is run for the first time, there
will be only one row. If you run it multiple times, you will find one row for each time it has been run.
Step 12 Deallocating Resources
Here you will deallocate all of the resources you used above. In this case, your resources are each object
that you used above, being your Connection object, Statement, and Result Set objects. For each nested
try block you will have a finally block, which performs the corresponding close method. These
statements have been shown in context above, but here are the cleanup calls in sequence from the code.
} finally {
RS.close ();
}
} finally {
Stmt.close ();
}
} catch (SQLException exception) {
System.err.println (“SQLException : ” + exception.toString ());
} finally {
Conn.close ();
}
Copy
Step 13 Final Catch and Finally block
The very last block contains both a catch block and a finally block. The catch block determines what to
do if an exception was thrown in the code above. In this case just displaying the exception to standard
out is sufficient. The finally block will be executed regardless of an exception being thrown. Here we will
deallocate our Connection object. In this example, if your Connection object does throw an exception for
some reason, it is “thrown” out of the method. In a normal situation you could either add another try
catch block, or declare this program as a separate method and handle it elsewhere.

} catch (SQLException exception) {
System.err.println(“SQLException : ” + exception.toString());
} finally {
Conn.close();
}

Copy
Step 14 Compiling your application
If your JDK is installed correctly you should have access to the Java Compiler, called javac. In order to
have your program successfully compile, you must first set your CLASSPATH to contain all of your
class files, including .jar files that you are using. Since the JDBC driver is usually a .jar file, you will
need to include this in your CLASSPATH. If you are using command line you will perform operations
similar to this:
Linux:
CLASSPATH=$CLASSPATH;{Current working directory};{Direct Path to .jar file}

CLASSPATH=$CLASSPATH;/home/users/kevin/workspace/;/home/users/kevin/workspace/rdmjdbcJD
K8-14.jar
Copy
*Note: ./ can be used to signify current working directory

Windows:
set CLASSPATH=%CLASSPATH%:{Current working directory}:{Direct path to .jar file}
set CLASSPATH=%CLASSPATH%:C:userskevinworkspace:C:userskevinworkspacerdmjdbcJDK8-
14.jar
Copy
After you have set up your CLASSPATH you should be ready to compile. In order to do this, you must
use the javac compiler. The compile will be the same on all platforms. The format looks like this:
javac {main_class.java (entry point to program)}
Copy
In this case you would type:
javac HelloWorldJDBC.java
Copy
You should see no warnings, and after completion a .class file will have been generated. You directory
should contain:
HelloWorldJDBC.java
HelloWorldJDBC.class
Copy
Step 15 Running the program
Running the program is as simple as typing “java {executable name}”. In this case you would have “java
HelloWorldJDBC” as that is the entry point to your program. If everything works as expected you
should see something like the following as displayed in a Windows Command Prompt:

CREATING TABLE
Required Steps
The following steps are required to create a new Database using JDBC application −
 Import the packages − Requires that you include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice.
 Open a connection − Requires using the DriverManager.getConnection() method to create a Connection
object, which represents a physical connection with a database server.
 Execute a query − Requires using an object of type Statement for building and submitting an SQL statement
to create a table in a seleted database.
 Clean up the environment − try with resources automatically closes the resources.
Sample Code
Copy and paste the following example in TestApplication.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class TestApplication {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
){
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";

stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac TestApplication.java
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Created table in given database...
C:\>

You might also like