Introduction to Java Programming Basics
Introduction to Java Programming Basics
INTRODUCTION TO JAVA
History of JAVA:-
Around 1990 James Gosling, Bill Joy and others at Sun Microsystems began developing a
language called Oak. The wanted it primarily to control microprocessors embedded in consumer
items such as cable set-top boxes, VCR’s, toasters, and also for personal data assistants (PDA).
To serve these goals, Oak needed to be:
Platform independent (since multiple manufacturers involved)
Extremely reliable
Compact.
However, as of 1993, interactive TV and PDA markets had failed to take off. Then the Internet and
Web explosion began, so Sun shifted the target market to Internet applications and changed the
name of the project to Java.
By 1994 Sun's HotJava browser appeared. Written in Java in only a few months, it illustrated the
power of applets, programs that run within a browser, and also the capabilities of Java for speeding
program development.
Riding along with the explosion of interest and publicity in the Internet, Java quickly received
widespread recognition and expectations grew for it to become the dominant software for browser
and consumer applications.
However, the early versions of Java did not possess the breadth and depth of capabilities needed
for client (i.e. consumer) applications. For example, the graphics in Java 1.0 seemed crude and
clumsy compared to mature software developed with C and other languages.
Applets became popular and remain common but don't dominate interactive or multimedia displays
on web pages. Many other "plug-in" types of programs also run within the browser environment.
So Java has not succeeded at development of consumer applications. However, Java's capabilities
grew with the release of new and expanded versions (see below) and it became a very popular
language for development of enterprise, or middleware, applications such as on line web stores,
transactions processing, database interfaces, and so forth.
Java has also become quite common on small platforms such as cell phones and PDAs. Java is now
used in several hundred cell phone models. Over 600 million JavaCards, smart cards with
additional features provided by Java, have been sold as of the summer of 2004.
What is JAVA?
The term Java actual refers to more than just a particular language like C or Pascal. Java
encompasses several parts, including :
A high level language:- The Java language is a high level one that at a glance looks very
similar to C and C++ but offers many unique features of its own.
Java bytecode:- a compiler, such as Sun's javac, transforms the Java language source code to
bytecode that runs in the JVM.
Java Virtual Machine (JVM):- A program, such as Sun's java, that runs on a given platform and
takes the bytecode programs as input and interprets them just as if it were a physical processor
executing machine code.
Sun provides a set of programming tools such as javac, java and others in a bundle that it calls a
Java Software Development Kit for each version of the language and for different platforms such
as Windows, Linux, etc.
Sun also provides a runtime bundle with just the JVM when the programming tools are not needed.
Java Virtual Machine or JVM as its name suggest it is a “virtual” machine that resides in the “real”
computer as a software.
JVM gives Java the flexibility of platform independence. Let us see first how exactly Java program
is created, compiled and executed.
Java code is written in .java file.
This code contains one or more Java language attributes like Classes, Methods, Variable, Objects
etc.
Javac is used to compile this code and to generate .class file. Class file is also known as “byte
code“.
The name byte code is given may be because of the structure of the instruction set of Java
program.
Java byte code is an input to Java Virtual Machine. JVM read this code and interpret it and
executes the program
Java Virtual Machine like its real counterpart, executes the program and generate output. To
execute any code, JVM utilizes different components.
JVM is divided into several components like the stack, the garbage-collected heap, the registers
and the method area. Let us see diagram representation of JVM.
Features of JAVA:
Simple
Object oriented
Compiled and interpreted
2
[Link] Institute of Technology-560056
Platform independent
Robust and secure
Distributed
Multithreaded
High performance
Dynamic
Simple:-
Java is a small and simple language. Java doesn’t use pointers, preprocessor header files,
GOTO statement and many others. It also eliminates operator overloading and multiple
inheritance.
Object oriented:-
Java is a true object oriented language. All program code and data reside within objects and
[Link] becomes extensive set of class.
Advantage of Object oriented programming:
Simpler, easier to read programs
More efficient reuse of code
Faster time to market
More robust, error-free code
Distributed:-
Java is designed as a distributed language for creating applications on networks. It has ability
to share both data and programs.
Multithreaded:-
High performance:-
Java performance is impressive for an interpreted language, due to the use of intermediate byte
code.
Dynamic:-
Java is a dynamic language. Java is capable of dynamically linking new class libraries,
methods, and objects.
TOOL DESCRIPTION
Appletviewe Enables us to run java applets
Javac The java compiler, which translates java source code to bytecode file.
Java Java interpreter that interpreting bytecode files.
Javadoc Creates HTML –format document from java source code files.
javah Produces header files
javap Java disassembler, which enables us to convert bytecode into program description.
Jdb Java debugger, which helps us to find errors in our programs.
The JDK. It consists of a framework of about 3700 classes. These classes must be implemented
according to this specification in every JDK. Sun defines this specification.
The Java Platform, or JDK, has evolved over time so there are several versions of it.
The latest major version is Java SE 7 or JDK 7.
Our applications are mostly written against either version 1.4 or 5, which are both still supported
by Sun.
Even though the Java Platform is often called the JDK, the correct definition is very different.
As originally defined, the Java Development Kit (JDK) is actually a combination of Java
compilation tools and API implementation for a particular version of the Java Platform.
It also typically includes a Java runtime (JRE), so that you can run the programs you compile.
4
[Link] Institute of Technology-560056
Documentation Section
The documentation section comprises a set of comment lines giving the name of the program,
the author and other details, which the programmer would like to refer to at a later stage. We
use comment for documentation.
Package Statement
The first statement allowed in a Java file is a package statement.
This statement declares a package name and informs the compiler that the classes defined here
belong to this package.
The package statement is optional. That is, our classes do not have to be part of a package.
Import Statements
The next thing after a package statement (but before any class definitions) may be a number of import
statements. This is similar to the #include statement in C.
Interface Statement
An interface is like a class but includes a group of method declarations.
It is new concept in java. This is also an optional section and is used only when we wish to
implement the multiple inheritance features in the program.
Class Definitions
A Java program may contain multiple class definitions. Classes are the primary and essential
elements of a Java program. These classes are used to map the objects of real-world problems.
The number of classes used depends on the complexity of the problem.
Let us see now how the simple java program will look like. You can use any editor like notepad or
any Java IDE for writing java programs.
class Sample
{
public static void main (String args[])
{
[Link] (“JAVA IS BETTER”);
}
}
public The keyword public is an access specifier that declares the main method as
unprotected & therefore making it accessible to all other classes.
static The keyword Static, which declares this method as one that belongs to the
entire class and not a part of any object
void The type modifier void states that the main method does not return any value.
DATA TYPES:
Every variable in java has a data type. Data types specify the size and type of values that can be
stored. The variety of data types available allows the programmer to select appropriate types.
There are two data types available in Java:
Primitive Data Types
Reference/Object Data Types
Primitive Data Types:
There are eight primitive data types supported by Java.
Primitive data types are predefined by the language and named by a key word. Let us now look
into detail about the eight primitive data types.
6
[Link] Institute of Technology-560056
PRIMITIVE DATA TYPES:
Java language supports few special escape sequences for String and char literals as well. They are:
Notation Character represented
\n Newline (0x0a)
\r Carriage return (0x0d)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\" Double quote
\' Single quote
\\ backslash
\ddd Octal character (ddd)
\uxxxx Hexadecimal UNICODE character (xxxx)
KEYWORDS IN JAVA
Keywords are reserved words that are predefined in the language; see the table below. All the
keywords are in lowercase.
An identifier is composed of a sequence of characters where each character can be a letter, a digit,
an underscore, or a dollar sign.
OPERATORS IN JAVA
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Conditional(ternery) operators
Bitwise operators
Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators:
Assume integer variable A =10 and variable B =20 then:
The following simple example program demonstrates the arithmetic operators. Copy and paste
following Java program in [Link] file and compile and run this program.
class Test
{
public static void main(String args[])
{
int a = 10; a + b = 30
int b = 20; a - b = -10
int c = 25; a * b = 200
int d = 25; b/a=2
[Link]("a + b = " + (a + b) ); b%a=0
[Link]("a - b = " + (a - b) ); c%a=5
[Link]("a * b = " + (a * b) ); a++ = 10
[Link]("b / a = " + (b / a) ); b-- = 11
[Link]("b % a = " + (b % a) ); d++ = 25
[Link]("c % a = " + (c % a) ); ++d = 27
[Link]("a++ = " + (a++) );
[Link]("b-- = " + (a--) );
// Check the difference in d++ and ++d
[Link]("d++ = " + (d++) );
[Link]("++d = " + (++d) );
8
[Link] Institute of Technology-560056
}
}
Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20 then:
The following simple example program demonstrates the relational operators. Copy and paste
following Java program in [Link] file and compile and run this program.
class Test
{
public static void main(String args[])
{
int a = 10;
int b = 20;
[Link]("a == b = " + (a == b) );
[Link]("a != b = " + (a != b) );
[Link]("a > b = " + (a > b) ); a == b = false
[Link]("a < b = " + (a < b) ); a != b = true
[Link]("b >= a = " + (b >= a) ); a > b = false
[Link]("b <= a = " + (b <= a) ); a < b = true
} b >= a = true
} b <= a = false
Logical Operators:
class Test
{
public static void main(String args[])
{
int a = true;
int b = false;
Bitwise Operator:
Java defines several bitwise operators which can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands.
They are summarized in the following table:
Operator Name
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
<<= Shift left assignment
Left Shift
The left shift operator, <<, shifts all of the bits in a value to the left a specified number
of times. It has this general form:
value << num
Example:
class ByteShift
{
public static void main(String args[])
{
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
[Link]("Original value of a: " + a);
[Link]("i and b: " + i + " " + b);
}
10
[Link] Institute of Technology-560056
}
OUTPUT
Original value of a: 64
i and b: 256 0
Right Shift
The right shift operator, >>, shifts all of the bits in a value to the right a specified number
of times. Its general form is shown here:
value >> num
Example:
int a = 35;
a = a >> 2; // a still contains 8
Looking at the same operation in binary shows more clearly how this happens:
00100011 35
>> 2
00001000 8
Assignment Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence
than + so it first get multiplied with 3*2 and then adds into 7.
Control statements control the order of execution in a java program, based on data values and
conditional logic. There are three main categories of control flow statements;
Selection statements: if, if-else, nested if-else, else-if ladder and switch.
Iteration statements: while, do-while and for.
We use control statements when we want to change the default sequential order of execution
Selection Statement
If Statement
if statement executes a block of code only if the specified expression is true.
If the value is false, then if block is skipped and execution continues with the rest of the
program.
You can either have a single statement or a block of code within if statement.
Note that the conditional expression must be a Boolean expression.
The simple if statement has the following syntax:
if (<condition>) <statement>
Below is an example that demonstrates conditional execution based on if statement condition.
Example:
class IfDemo
{
public static void main(String[] args)
{
int a = 67;
if(a <100)
{
[Link]("a is less than 100");
}
}
}
12
[Link] Institute of Technology-560056
If-else Statement:-
Nested If-else:-
Syntex:-
The syntax for a nested if...else is as follows:
if(condition1)
{
if(condition2)
{
Statement-1;
else
Statement-2;
}
else
Statement-3;
}
In nested if else logic if condition1 is true then check condition2 if it is true then statement1
will be execute else statement2 will be execute.
In nested if else logic if condition -1 is false then statement -3 is execute.
class NestedIfElse
{
public static void main(String args[])
{
int a=10;
int b=20;
int c=30;
if (a>b)
{
if (a>c)
{
[Link]("a is max ");
}
else
{
[Link]("c is a max");
}
}
else
{
if (b>c)
{
[Link]("b is max");
}
else
{
[Link]("c is a max");
}
}
}
}
If-else-if ladder:
In this if-else-if ladder, conditions are evaluated from top. First condition-1 will be evaluated and if
this is true, the code inside the if block will be executed. If condition-1 is false, condition-2 will be
evaluated.
If condition-2 is true, the code inside that else if block will be executed. If condition-2 is false,
condition-3 will be evaluated. This will go on like this.
If none of the conditions are true, the code inside the else block will be executed.
Syntex:
if(condition-1)
{
Statement1;
}
else if (condition-2)
{
Statement2;
14
[Link] Institute of Technology-560056
}
.
.
.
else if (condition-n)
{
Statement n-1;
}
else
{
Statement n;
}
Example:-
public class IfElseIfLadderDemo1
{
public static void main(String args[])
{
int test=2;
if(test==1)
{
[Link]("Hello");
}
else if(test==2)
{
[Link]("Hi");
}
else if(test==3)
{
[Link]("Good");
}
else
{
[Link]("No Match Found");
}
}
}
Loop is the control statement of any language in which whenever you want to perform the
repetitious work then you use the Loop control statement.
There are mainly three types of loops.
Loop repeats a statement or a process multiple times according to the specified conditions.
It allows the multiple statements or process to be run for the specified time or it also follows
the certain conditions.
Loop makes your program readable, flexible and reliable.
Initialization;
while(condition)
{
statements;
}
In this program you will see how to use the while loop statement.
This program takes the 1 to 10 number.
class test
{
public static void main(String[] args)
{
int i = 1;
while(i<=10)
{
[Link](i);
i++;
}
[Link](“Loop Complete”);
}
}
do-while:
In do-while loop, compiler executes some statements and processes once at least.
do-while loop is same as the while loop statement but while loop checks the condition is first
and in do-while loop executes all the statements first at once and then check the condition if the
condition is true then all the statements are also executed second times otherwise loop
terminates.
Syntax :
Initialization;
do
{
statements;
}while(condition);
In this example you will see how to use the do-while loop statement.
class test
{
public static void main(String[] args)
{
int i;
i=1;
do
{
[Link]("Number : " + i);
}while (i <=10);
}
16
[Link] Institute of Technology-560056
}
for loop:
for loop is often used when you want to repeat a section of a program for a fixed number of
times.
Syntax:
for( initialization; condition; increment/decrement)
{
statements;
}
Initialization: It allows the variable to be initialize. Such as:
int i = 1;
int j = 1;
condition: It allows to check the certain condition. If condition is true then all statements and
processes written in the for block will be executed otherwise ignored
Condition such as:
i <= 5;
j <= i;
Increment: It allows the how much increase the given variable. Such as:
i++;
j++;
Example:-
class test
{
public static void main(String[] args)
{
int i;
for(i=1;i<=10,i++)
{
[Link]("Number : " + i);
}
[Link](“Loop Complete”);
}
}
switch statement:
Example:
class test
{
public static void main(String[] args)
{
int i = 1;
switch (i)
{
case 1 :
[Link]("One.");
break;
case 2 :
[Link]("Two.");
break;
case 3 :
[Link]("Three.");
break;
default:
[Link]("You did not enter a valid value.");
}
}
}
Break statement:
The break statement is used to break from an enclosing do, while, for, or switch statement.
It is compile errors to use break anywhere else.
'break' breaks the loop without executing the rest of the statements in the block.
For example, consider the following code
class test
{
public static void main(String[] args)
{
int i = 0;
while (i<100)
{
if (i > 3)break;
[Link](i);
}
}
}
18
[Link] Institute of Technology-560056
continue statement:
The continue statement stops the execution of the current iteration and causes control to begin with
the next iteration.
For example, the following code prints the number 0 to 9, except 5.
class test
{
public static void main(String[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
continue;
}
[Link](i);
}
}
}
Array:
An array is a very common type of data structure where in all elements must be of the same data
type.
Once defined, the size of an array is fixed and cannot increase to accommodate more elements.
The first element of an array starts with zero
Using and array in your program is a 3 step process -
Declaring your Array
Constructing your Array
Initializing your Array
Syntax for Declaring Array Variables is
<elementType>[] <arrayName>;
Example:
int a[];
int []a;
Constructing an Array
= new [];
Example:
a = new int[10]; // Defines that intArray will store 10 integer values
Multidimensional arrays:
Multidimensional arrays, are arrays of arrays.
To declare a multidimensional array variable, specify each additional index using another set of
square brackets.
int twoD[ ][ ] = new int[4][5] ;
When you allocate memory for a multidimensional array, you need only specify the memory
for the first (leftmost) dimension.
You can allocate the remaining dimensions separately.
Example:-1
class test
{
public static void main(String args[])
{
int a[ ][ ];
a=new int[3][3];
int i,j,k=0;
for (i=0; i<3; i++)
{
for(j=0;j<i;j++)
{
a[i][j] = k;
k++;
}
}
for (i=0; i<3; i++)
{
for(j=0;j<i;j++)
{
[Link](a[i][j]);
}
}
}
}
Example:-2
class test
{
public static void main(String args[])
{
int a[ ][ ] = { { 2, 1, 3 }, { 1, 3, 2 }, { 3, 2, 1 } };
int I,j;
20
[Link] Institute of Technology-560056
for (i=0; i<3; i++)
{
for(j=0;j<i;j++)
{
[Link](a[ I ][ j ]);
}
}
}
}
In short here are few differences between JRE, JDK and JVM:
JRE and JDK come as installer while JVM are bundled with them.
JRE only contain environment to execute java program but doesn’t contain other tool for
compiling java program.
JVM comes along with both JDK and JRE and created when you execute Java program by
giving “java” command.
JAVA C
Java is object-oriented language. C is procedure oriented language.
Java does not support structure, union. C supports structure,union,enum.
enum.
Java does not support Pointer. C supports pointer.
JAVA C++
Java does not support Operator C++ supports Operator overloading.
overloading.
Java does not support Template class. C++ support Template class.
Java does not support Multiple C++ supports Multiple inheritance.
inheritance but it supports interface.
Java does not support Global variable C++ support Global variable
Java does not use Pointer. C++ use Pointer.
There are no header files in java There is no. of header files In C++.
Java has replace destructor Function C++ has a constructor & also Destructor
with finalize ( ). Function.
Java does not support Pre-processor. C++ support Pre-processor.
22
[Link] Institute of Technology-560056
2. INTRODUCTION TO CLASSES
CLASS FUNDAMENTALS:-
A class can be defined as a template/ blue print that describe the behaviors/states
that object of its type support.
A class is a user-defined data type with a template that serves to define its properties.
once the class type has been defined, we can create “variable s” of that type using declarations
that are similar to the basic type declarations.
In java, these variables are termed as instances of classes, which are the actual objects.
The basic form of a class definition is:
Class Syntax:-
class classname
{
type instance-variable1 ;
type instance-variable2 ;
…..
…..
type instance-variableN ;
Here is a class called Box that defines three instance variables: width, height, and depth.
Currently, Box does not contain any methods.
class Box
{
double width;
double height;
double depth;
}
As stated, a class defines a new type of data.
It is important to remember that a class declaration only creates a template; it does not create an
actual object.
DECLARING OBJECTS:
Object reference variables act differently than you might expect when an assignment takes place.
For example, what do you think the following fragment does?
Box b1 = new Box();
Box b2 = b1;
after this fragment executes, b1 and b2 will both refer to the same object.
The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It
simply makes b2 refer to the same object as does b1.
Thus, any changes made to the object through b2 will affect the object to which b1 is referring,
since they are the same object.
This situation is depicted here:
INTRODUCING METHODS:
Example:
// This program includes a method inside the box class.
class Box
{
double width;
double height;
double depth;
void volume()
{
[Link]("Volume is ");
[Link](width * height * depth);
}
}
class BoxClass
{
public static void main(String args[])
{
Box b = new Box();
[Link] = 10;
[Link] = 20;
[Link] = 15;
[Link]();
}
}
Example:
// Now, volume() returns the volume of a box.
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class BoxClass
{
public static void main(String args[])
{
Box b = new Box();
4
CONSTRUCTORS:
vol = [Link]();
[Link]("Volume is " + vol);
vol = [Link]();
[Link]("Volume is " + vol);
}
}
OUTPUT:-
Volume is 1000.0
Volume is 1000.0
PARAMETERIZED CONSTRUCTORS
this can be used inside any method to refer to the current object.
That is, this is always a reference to the object on which the method was invoked.
You can use this anywhere a reference to an object of the current class’ type is permitted.
To better understand what this refers to, consider the following version of Box( ):
// A redundant use of this.
Box(double w, double h, double d)
{
[Link] = w;
[Link] = h;
[Link] = d;
}
This version of Box( ) operates exactly like the earlier version.
7
int a,b,c;
this.a=a;
this.b=b;
int mul()
return a*b;
class This1
A a=new A();
[Link](2,3);
int x;
x=[Link]();
[Link]("X Value:"+x);
GARBAGE COLLECTION:
[Link]();
Finalize method will use when object will need to perform some action when it is destroyed.
For example, if an object has some non-java resource such as a file handle or window character
font, then you have free those resources for future use.
Right before an asset is freed, the java run time calls the finalize() method on the object.
Here, the keyword protected is a specifier that prevents access to finalize() by code defined
outside its class.
It is not called when an object goes out-of-scope, for example. This means program should
provide other means of releasing system resources, etc., used by the object. It must not rely on
finalize() for normal program operation.
Wrapper Class
Java is an object-oriented language and can view everything as an object. A simple file can be
treated as an object (with [Link]), an address of a system can be seen as an object (with
[Link]), an image can be treated as an object (with [Link]) and a simple data type
can be converted into an object (with wrapper classes). This tutorial discusses wrapper classes.
Wrapper classes are used to convert any data type into an object
As the name says, a wrapper class wraps (encloses) around a data type and gives it an object
appearance. Wherever, the data type is required as an object, this object can be used. Wrapper
classes include methods to unwrap the object and give back the data type. It can be compared with a
chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution.
The user takes the chocolate, removes and throws the wrapper and eats it.
The name of the wrapper class corresponding to each primitive data type, along with the arguments
its constructor accepts, is listed below:
Example
public class WrappingUnwrapping
{
public static void main(String args[])
{
int marks = 50;
Integer m1 = new Integer(marks);
[Link]("Integer object m1: " + m1);
int iv = [Link]();
[Link]("int value, iv: " + iv);
}
}
OUTPUT:
10
11
Overloading Methods
Class have multiple methods(functions) by same name but different parameters,it is known as
method overloading.
Method overloading is one of the ways that Java supports polymorphism.
But as you will see, method overloading is one of Java’s most exciting and useful features.
When an overloaded method is called, Java uses the type and/or number of arguments as its guide
to determine which version of the overloaded method to actually call.
Thus, overloaded methods must differ in the type and/or number of their parameters.
While overloaded methods may have different return types, the return type alone is insufficient to
distinguish two versions of a method.
Here is a simple example that illustrates method overloading:
EXAMPLE: Sum of two numbers using method overloading.
//Demonstrate method overloading.
class sumoftwo
{
void sum(int a,int b)
{
[Link](a+b);
}
void sum(int a,int b,int c)
{
[Link](a+b+c);
}
}
class sum
{
public static void main(String args[])
{
sumoftwo ob=new sumoftwo();
[Link](10,20,30);
[Link](20,50);
}
}
EXAMPLE:
// Demonstrate method overloading.
class one
{
void test()
{
[Link]("No parameters");
}
void test(int a)
{
[Link]("a: " + a);
OUTPUT:
No parameters
a: 10
a and b: 10 20
Overloading Constructors
Constructor is special type of method which called at the time of object creation.
In addition to overloading normal methods, you can also overload constructor.
There is two types of constructor:
(1) Default constructor (Constructor have no-parameter)
(2) Parameterized constructor (Constructor have parameter)
EXAMPLE:
//Demonstrate constructor(default constructor) overloading.
class display
{
display()
{
[Link](“Hello world”);
}
}
class read_display
{
public static void main(String args[])
{
display ob=new display();
}
}
/* Here, Box defines three constructors to initialize the dimensions of a box various ways.*/
//Demonstrate constructor overloading.
class Box
OUTPUT:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
OUTPUT:
ob1 == ob2: true
ob1 == ob3: false
As you can see, the equals( ) method inside Test compares two objects for equality and returns the
result.
That is, it compares the invoking object with the one that it is passed.
If they contain the same values, then the method returns true .
Otherwise, it returns false.
Notice that the parameter object in equals( ) specifies Test as its type. Although Test is a class type
created by the program, it is used in just the same way as Java’s built-in types.
Call-By-Value
If we call a method passing a value, it is known as call by value. The changes being done in the
called method, is not affected in the calling method.
This approach copies the value of an argument into the formal parameter of the subroutine.
Therefore, changes made to the parameter of the subroutine have no effect on the argument.
Inside the subroutine, this reference is used to access the actual argument specified in the call.
This means that changes made to the parameter will affect the argument used to call the
subroutine.
In Java, when you pass a primitive type to a method, it is passed by value. Thus, what occurs to the
parameter that receives the argument has no effect outside the method.
EXAMPLE:
// Primitive types are passed by value.
OUTPUT:
a and b before call: 15 20
a and b after call: 15 20
Call-By-Reference
This concept is not correct for java.
In this approach, a reference to an argument (not the value of the argument) is passed to the
parameter.
Thus, when you pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument.
This effectively means that objects are passed to methods by use of call-by-reference.
Changes to the object inside the method do affect the object used as an argument.
EXAMPLE
// Objects are passed by reference.
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// pass an object
void abc(Test o)
{
o.a = 2;
o.b = 4;
}
Returning an object
A method can return any type of data, including class types that you create.
For example, in the following program, the abc( ) method returns an object in which the value of a
is ten greater than it is in the invoking object.
EXAMPLE:
class Test
{
int a;
Test(int i)
{
a = i;
}
Test abc()
{
Test temp = new Test(a+10);
return temp;
}
}
class two
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;
ob2 = [Link]();
[Link]("ob1.a: " + ob1.a);
[Link]("ob2.a: " + ob2.a);
ob2 = [Link]();
[Link]("ob2.a after second increase: "+ ob2.a);
}
Recursion
Recursion is a basic programming technique you can use in Java, in which a method calls itself
A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number.
The factorial of a number N is the product of all the whole numbers between 1 and [Link]
example, 3 factorial is 1 × 2 × 3 , or 6.
Here is how a factorial can be computed by use of a recursive method:
EXAMPLE:-
class Factorial
{
// this is a recursive method
int fact(int n)
{
int result;
if(n==0 || n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
[Link]("Factorial of 3 is " + [Link](3));
}
}
OUTPUT:
Factorial of 3 is 6
final KEYWORD:
A variable can be declared as final.
The Java final keyword is used to indicate that something "cannot change".
Use of Final keyword:
It is used to indicate that a class cannot be extended.
It is used to indicate that a method cannot be overridden.
It is used to indicate that a local variable cannot be changed once its value is set.
It is used to indicate that a static variable cannot be changed once set, in effect
implementing "constants".
For example:
final int I= 1;
Subsequent parts of your program can now use i, etc., as if they were constants, without fear that a
value has been changed.
EXAMPLE:
public class Demo
{
final int I=10;
void abc()
{
[Link]("Final variable value : "+i);
}
public static void main(String[] args)
{
Demo f=new Demo();
[Link]();
}
}
OUTPUT:-
Final variable value :10
Inner Classes
As with instance methods and variables, an inner class is associated with an instance of its
enclosing class and has direct access to that object's methods and fields.
Also, because an inner class is associated with an instance, it cannot define any static members
itself.
Objects that are instances of an inner class exist within an instance of the outer class.
Consider the following classes:
class OuterClass
{
...
class InnerClass
{
...
}
}
An instance of InnerClass can exist only within an instance of OuterClass and has direct access
to the methods and fields of its enclosing instance.
The next figure illustrates this idea.
Example:
class Outer
{
int outer_x = 100;
The user enters command-line arguments at the time of application run and specifies them after the
name of the class to be run.
For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file
named [Link], a user would enter:
java Sort [Link]
When an application is launched, the runtime system passes the command-line arguments to the
application's main method via an array of Strings.
In the previous example, the command-line arguments passed to the Sort application in an array
that contains a single String: "[Link]".
EXAMPLE:
public class Test2
{
public static void main(String[] args)
{
int num=[Link];
String s[]=new String[num];
if(num>0)
{
[Link]("The values enter at argument command line are:");
for(int i=0;i<num;i++)
{
[Link]("Argument"+(i+1)+"="+args[i]);
OUTPUT:
Types of Inheritance:
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
Single Inheritance
Sub class can be deriving from super class this mechanism is known as single inheritance.
Syntax:
Class A
{
----
----
}
Multilevel Inheritance
C class is derived from B class & B class is derived from A class this type of mechanism is called
multilevel inheritance.
Sub class can be derived from another super class.
Class B Intermediate
class
Hierarchical Inheritance
One super class and more than one sub class it’s called hierarchical inheritance.
Class B Class C
Sub class
Syntax:
class A
{
----
----
}
class B extends A
{
----
----
}
class C extends A
{
----
----
}
class hierarchical
{
----
----
}
Example:-Program for hierarchical inheritance.
class A
{
void add()
{
int a, b, c;
a=2;
Super keyword:
Method overriding
When method in sub class has same name as a method in super class then method in sub class is
said to override the method in super class.
Advantage of Method Overriding
Method Overriding is used to provide specific implementation of a method that is already
provided by its super class.
Method Overriding is used for Runtime Polymorphism
Rules for Method Overriding:
method must have same name as in the parent class
Method must have same parameter as in the parent class.
class Superclass
{
void print()
{
[Link]("Printed in Superclass.");
}
}
class Subclass extends Superclass
{ Overriding
void print() method
{
[Link]();
[Link]("Printed in Subclass");
Packages:
A package is a group of classes and interfaces.
Package can be categorized in two form:
built-in package such as java, lang, awt, javax, swing, net, io, util, sql etc.
user-defined package which is created by user.
Advantages of Packages:
Package is used to categorize the classes and interfaces so that they can be easily
maintained.
Package provides access protection.
Package removes naming collision.
Access Description
protection
No modifier The classes and members specified in the same package are accessible to
(default) all the classes inside the same package.
public The classes, methods and member variables under this specifier can be accessed
from anywhere.
Importing package
In a Java source file, import statements occur immediately following the package statement (if it
exists) and before any class definitions.
This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package
inside the outer package separated by a dot (.).
There is no practical limit on the depth of a package hierarchy, except that imposed by the file
system.
Finally, you specify either an explicit classname or a star (*), which indicates that the Java
compiler should import the entire package.
This code fragment shows both forms in use:
import [Link];
import [Link].*;
Example:
package pack;
public class A
{
int a;
int b;
A(int i,int j)
{
a=i;
b=j;
}
public void display()
{
[Link](a + "&" + b);
}
}
Interfaces
Interface is just like a class.
Interface declares with interface keyword.
Interface does not have any implementation of method.
In Java Interface defines the methods but does not implement them.
Interface is collection of methods and variables.
In interface variable consider as a constant and method consider as abstract.
More than one class can be implement interface.
Interface extends two or more interfaces.
It means using interface we can create multiple inheritance.
Syntax:
[access] interface InterfaceName [extends OtherInterface]
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface.
To implement an interface, include the implements keyword in a class definition, and then
create the methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
An exception is a problem that arises during the execution of a program. An exception can occur
for many different reasons, including the following:
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications, or the JVM has run out of
memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories of
exceptions:
Checked exceptions:
A checked exception is an exception that is typically a user error or a problem that cannot be
foreseen by the programmer.
For example, if a file is to be opened, but the file cannot be found, an exception occurs.
These exceptions cannot simply be ignored at the time of compilation.
Runtime exceptions:
A runtime exception is an exception that occurs that probably could have been avoided by the
programmer.
As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
Errors:
These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer.
Errors are typically ignored in your code because you can rarely do anything about an error.
For example, if a stack overflow occurs, an error will arise. They are also ignored at the time
of compilation.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Program statements that you want to check 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 normal manner.
System-generated exceptions are automatically thrown by the Java run-time [Link] manually
throw an exception, use the keyword throw.
Any exception that is thrown out of a method must be specified as such by a throws clause.
Any code that absolutely must be executed after a try block completes is put in a finally block.
Syntax:
try
{
// block of code to check for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
Example:
1) int a=50/0; //ArithmeticException
2) String s="abc";
int i=[Link](s); //NumberFormatException
3) String s=null;
[Link]([Link]());//NullPointerException
4) int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
The try/catch statement encloses some code and is used to handle errors and exceptions that might
occur in that code.
Example:-
class Trycatch
{
public static void main(String[] args)
{
try
{
int a,b,c;
a=12;
b=0;
c=a/b;
[Link](c);
}
catch(Exception e)
{
[Link](e);
}
}
}
Uncaught exceptions
This small program includes an expression that intentionally causes a divide-by-zero error:
class Test
{
public static void main(String args[])
Syntax:-
try
{
try
{
// ...
}
catch (Exception1 e)
{
//statements to handle the exception
}
}
catch (Exception2 e2)
{
//statements to handle the exception
}
Example:-
class NestedTry
{
public static void main (String args [ ] )
{
try
{
int a = [Link](args [0]);
int b = [Link](args [1]);
int c = 0;
try
{
c = a / b;
[Link](c);
}
catch (ArithmeticException e)
Throw
The throw keyword is used to explictily throw an exception.
We can throw either checked or uncheked exception. The throw keyword is mainly used to
throw custom exception
Syntax:-
throw someThrowableObject;
All the classes are children of the Throwable class, and all allow programs to differentiate
among the various types of exceptions that can occur during the execution of a program.
Used in program:
try
{
// statements
throw new UserDefinedException( );
// statements
}
catch (UserDefinedException e)
{
[Link] (“User defined exception caught”);
}
Example:-
class Throwclause
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[])
{
Throws
Example:-
class Throwsclause
{
static void abc( ) throws IllegalAccessException
{
try
{
throw new IllegalAccessException( ); // exception thrown
}
catch (IllegalAccessException e)// exception caught
{
[Link] ("catch block");
throw new IllegalAccessException( );
// exception thrown again
}
}
public static void main (String args [ ])
{
try
{
abc( );
}
catch (IllegalAccessException e)
{
[Link] ("Exception caught");
}
}
}
Finally
Java support 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 follow.
When a finally block is defined, this is guaranteed to execute.
As a result, we can use it to perform certain house-keeping operations such as closing file and
releasing system resource.
Syntax:
try
{
// statements
}
catch (<exception> obj)
{
// statements
}
finally
{
//statements
}
Example:-
class Finally
{
public static void main(String[] args)
{
try
{
int a,b,c;
a=2;
b=0;
c=a/b;
[Link](c);
}
catch (Exception e)
You can create your own exception class by defining a subclass of Exception.
The Exception class does not define any methods of its own. It inherits methods provided by
Throwable.
All exceptions have the methods defined by Throwable available to them.
They are shown in the following list.
Throwable fillInStackTrace( )
Returns a Throwable object that contains a completed stack trace.
Throwable getCause( )
Returns the exception that underlies the current exception.
String getLocalizedMessage( )
Returns a localized description.
String getMessage( )
Returns a description of the exception.
StackTraceElement[ ] getStackTrace( )
Returns an array that contains the stack trace.
Throwable initCause(Throwable causeExc)
Associates causeExc with the invoking exception as a cause of the invoking exception.
void printStackTrace( )
Displays the stack trace.
void printStackTrace(PrintStream stream)
Sends the stack trace to the stream.
void printStackTrace(PrintWriter stream)
Sends the stack trace to the stream.
void setStackTrace(StackTraceElement elements[ ])
Sets the stack trace to the elements passed in elements.
String toString( )
Returns a String object containing a description of the exception.
Example:-
class MyException extends Exception
{
private int b;
MyException(int a)
{
b = a;
}
public String toString()
7. MULTITHREDED PROGRAMMING
What is thread?
A thread is a single sequential flow of control within a program.
Thread is a path of the execution in a program.
Muti-Threading:
Executing more than one thread (part of a task) parallel using a single processor is called
multithreading
Thread: A thread can be loosely defined as a separate stream of execution that takes place
simultaneously with and independently of everything else that might be happening.
A thread is like a classic program that starts at point A and executes until it reaches point B.
It does not have an event loop. A thread runs independently of anything else happening in the
computer.
Without threads an entire program can be held up by one CPU intensive task or one infinite
loop, intentional or otherwise.
With threads the other tasks that don't get stuck in the loop can continue processing without
waiting for the stuck task to finish.
It turns out that implementing threading is harder than implementing multitasking in an
operating system
The reason it's relatively easy to implement multitasking is that individual programs are
isolated from each other. Individual threads, however, are not.
To return to the printing example, suppose that while the printing is happening in one thread,
the user deletes a large chunk of text in another thread.
What's printed? The document as it was before the deletion? The document as it was after the
deletion? The document with some but not all of the deleted text? Or does the whole system
go down in flames? Most often in a non-threaded or poorly threaded system, it's the latter.
Threaded environments like Java allow a thread to put locks on shared resources so that while
one thread is using data no other thread can touch that data.
This is done with synchronization. Synchronization should be used sparingly since the purpose
of threading is defeated if the entire system gets stopped waiting for a lock to be released.
The proper choice of objects and methods to synchronize is one of the more difficult things to
learn about threaded programming
Creating threads using the thread class
New state:
After the creations of Thread instance the thread is in this state but before the start() method
invocation.
At this point, the thread is considered not alive.
Runnable (Ready-to-run) state:
A thread start its life from Runnable state.
A thread first enters runnable state after the invoking of start() method but a thread can return to
this state after either running, waiting, sleeping or coming back from blocked state also.
On this state a thread is waiting for a turn on the processor.
Running state:
A thread is in running state that means the thread is currently executing.
There are several ways to enter in Runnable state but there is only one way to enter in Running
state: the scheduler select a thread from runnable pool.
Dead state:
A thread can be considered dead when its run() method completes.
If any thread comes on this state that means it cannot ever run again.
Blocked:
A thread can enter in this state because of waiting the resources that are hold by another thread.
Process
A process is an instance of a computer program that is executed sequentially.
It is a collection of instructions which are executed simultaneously at the rum time.
Thus several processes may be associated with the same program.
For example, to check the spelling is a single process in the Word Processor program and you can
also use other processes like printing, formatting, drawing, etc. associated with this program
Features of Threads:
1. Creating a Thread
2. Context Switch
3. Priorities
4. Synchronization
5. Messaging
Creating a thread
In Java, an object of the Thread class can represent a thread.
Thread can be implemented through any one of two ways:
Extending the [Link] Class
Implementing the [Link] Interface
start();
}
public void run()
{
[Link](s);
}
}
public class RunThread
{
public static void main(String args[])
{
MyThread m1=new MyThread("Thread started. .. ");
}
}
This join method accepts two arguments. First as timeout in milliseconds and second an integer
value for nanoseconds. The amount of timeout in milliseconds is along with the nanoseconds.
This method also forces the thread to wait for the given time.
Example:
public class Join1 implements Runnable
{
public void run()
{
Thread t = [Link]();
//Tests if this thread is alive
[Link]([Link]()+" is alive "+[Link]());
}
public static void main(String args[]) throws Exception
{
Thread t = new Thread(new Join1());
[Link]();
//Waits for this thread to die.
[Link]();
//Tests if this thread is alive
[Link]([Link]()+" is alive "+[Link]());
}
}
Thread priorities
Every thread created has some priority.
Threads are executed according to their priority.
Threads with higher priority are executed before threads with lower priority. A newly created thread
has same priority as the thread that creates it.
Java thread priorities are integer values ranging from 1 to 10.
1 is the lowest priority and 10 is the highest priority.
The default priority of a thread is 5.
The thread priorities are assigned to some constant literals as follows,
Thread.MIN_PRIORITY : It is the minimum priority of any thread i.e. 1
Thread.MAX_PRIORITY : It is the maximum priority of any thread i.e. 10
Thread.NORM_PRIORITY : It is the normal and default priority of any thread i.e. 5
To set the thread priorities we can use setPriority() method. Its syntax is,
final void setPriority(int level);
To obtain the current priority of a thread we can use getPriority() method. Its syntax is,
final int getPriority();
Example:
public class priority implements Runnable
{
public void run()
{
for (int i=1;i<=3;i++)
{
[Link](i + " This is thread " +
[Link]().getName());
}
}
public static void main(String[] args)
{
Thread t1 = new Thread(new priority(), "Thread A");
Thread t2 = new Thread(new priority(), "Thread B");
Thread t3 = new Thread(new priority(), "Thread C");
[Link](10);
[Link]();
[Link]();
[Link]();
}
}
Synchronization
Synchronization is the capabilility of control the access of multiple threads to any shared resource.
Synchronization is better in case we want only one thread can access the shared resource at a time.
Why use Synchronization?
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
Here we will learn Thread Synchronization
Only methods (or blocks) can be synchronized, Classes and variable cannot be synchronized.
Each object has just one lock.
All methods in a class need not to be synchronized. A class can have both synchronized and
non-synchronized methods.
If two threads wants to execute a synchronized method in a class, and both threads are using the
same instance of the class to invoke the method then only one thread can execute the method at a
time.
If a class has both synchronized and non-synchronized methods, multiple threads can still access
the class's non-synchronized methods. If you have methods that don't access the data you're
trying to protect, then you don't need to synchronize them.
Synchronization can cause a hit in some cases (or even deadlock if used incorrectly), so you
should be careful not to overuse it.
If a thread goes to sleep, it holds any locks it [Link] doesn't release them.
A thread can acquire more than one lock. For example, a thread can enter a synchronized
method, thus acquiring a lock, and then immediately invoke a synchronized method on a
different object, thus acquiring that lock as well. As the stack unwinds, locks are released again.
You can synchronize a block of code rather than a method.
Constructors cannot be synchronized
In non synchronized multithreaded application, it is possible for one thread to modify a shared
object while another thread is in the process of using or updating the object's value.
There are two ways to synchronized the execution of code:
Example: Synchronized Methods
class A extends Thread
{
public void run()
{
display();
}
public static synchronized void display()
{
int i;
for( i=0;i<10;i++)
{
try
{
sleep(1000);
[Link]([Link]().getName()+" "+i);
}
catch (Exception e)
{
[Link](e);
}
}
}
}
class Sn1
{
public static void main(String[] args)
{
A a=new A();
Thread t1=new Thread(a);
Thread t2=new Thread(a);
[Link]();
[Link]();
}
}
Example:
class A extends Thread
{
public void run()
{
synchronized(this) // synchronized block
{
int i;
for( i=0;i<10;i++)
{
try
{
sleep(1000);
[Link]([Link]().getName()+" "+i);
}
catch (Exception e)
{
}
}
}
}
}
class Sn
{
public static void main(String[] args)
{
A a=new A();
Thread t1=new Thread(a);
Thread t2=new Thread(a);
[Link]();
[Link]();
}
}
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
catch (InterruptedException e)
{
[Link]();
}
}
}
Example:
class MyThread implements Runnable
{
Thread t;
boolean suspended;
boolean stopped;
MyThread(String name)
{
t = new Thread(this, name);
suspended = false;
stopped = false;
[Link]();
}
public void run()
{
try
{
for (int i = 1; i < 10; i++)
{
[Link]("\t$");
[Link](50);
synchronized (this)
{
while (suspended)
wait();
if (stopped)
break;
}
}
}
catch (InterruptedException exc)
{
[Link]([Link]() + " interrupted.");
}
[Link]("\n" + [Link]() + " exiting.");
}
}
}
public class Main
{
public static void main(String args[]) throws Exception
{
MyThread mt = new MyThread("MyThread");
[Link](100);
[Link]();
[Link](100);
[Link]();
[Link](100);
[Link]();
[Link](100);
[Link]();
[Link](100);
[Link]();
}
}
8. STRING HANDLING
}
}
OUTPUT: Java
String length
length()-To find a length of string.
Syntax:- String [Link] ( );
Example:-
class length
{
public static void main(String[] args)
{
String s1=new String ("HELLO");
[Link]([Link]());
}
}
OUTPUT:5
Character Extraction
charAt ( ) :- To abstract single character from a string.
Syntax :- String [Link] (Position of character);
Example
class strcharat
{
public static void main(String[] args)
{
String s1=new String("Hello");
[Link]([Link](3));
}
}
getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of
bytes.
This method is called getBytes( ), and it uses the default character-to-byte
conversions provided by the platform.
Syntax:
byte[ ] getBytes( )
getChars( )
If you need to extract more than one character at a time, you can use the getChars( )
method.
Syntax
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
sourceStart:- specifies the index of the beginning of the substring
sourceEnd:- specifies an index that is end of the desired substring.
The array that will receive the characters is specified by target.
The index within target at which the substring will be copied is passed in
targetStart.
Example:
class getCharsDemo
{
public static void main(String args[])
{
String name= "This is a demo of the getChars method.";
int s=10;
int e=14;
char n[] = new char[e - s];
[Link](s, e, n, 0);
[Link](n);
}
}
toCharArray( )
If you want to convert all the characters in a String object into a character array, the
easiest way is to call toCharArray( ).
It returns an array of characters for the entire string.
Syntax:
char[ ] toCharArray( )
This function is provided as a convenience, since it is possible to use getChars( ) to
achieve the same result.
String comparison
equals ( )
The equal’s methods compare the character inside string of.
It returns true if the string contains same character in the same order & otherwise false.
The comparison is case sensitive.
Syntax
String [Link] (string object2);
Example:-1
class equals
{
public static void main(String[] args)
{
String s1=new String("Java");
String s2=new String("Java");
[Link]([Link](s2));
}
}
Example 2:-
class equals1
{
public static void main(String[] args)
{
String s1=new String ("Hello");
String s2=new String ("Hello");
if([Link](s2))
{
[Link] ("strings are equal");
}
else
{
[Link] ("strings are not equal");
}
}
}
compare To( )
It compares weather two string are less then, greater than or equal.
Returns negative if s1<s2 Returns positive if s1>s2 Returns zero if s1=s2.
Syntax
String [Link] (string object2);
Example:-
class strcompare
{
public static void main(String[] args)
{
String s1=new String("Hello");
String s2=new String("Hello");
[Link]([Link](s2));
}
}
Searching strings
The String class provides two methods that allow you to search a string for a
specified character or substring:
indexOf( ) Searches for the first occurrence of a character or substring.
lastIndexOf( ) Searches for the last occurrence of a character or substring.
indexOf ( )
Gives the position of first occurrence of ‘h’ in the string s1.
Syntax
String [Link](‘h’);
Example:-
class indexof
{
public static void main (String [] args)
{
String s1=new String ("Hello");
[Link] ([Link] ('h'));
}
} Page 4 K.A. Prajapati
Modifying a string
substring( )
You can extract a substring using substring( ). It has two forms.
Syntax:
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin.
This form returns a copy of the substring that begins at startIndex and runs to the
end of the invoking string.
The second form of substring( ) allows you to specify both the beginning and
ending index of the substring:
String substring(int startIndex, int endIndex)
startIndex specifies the beginning index
endIndex specifies the stopping point.
Example:-
class substring
{
public static void main(String[] args)
{
String s1=new String("Hello");
[Link]([Link](2,5));
}
}
concat ( )
This method is use to concatenate two string s1 & s2.
Syntax:
String [Link](string object2);
Example:-
class concat
{
public static void main(String[] args)
{
String s1=new String ("Hello");
String s2=new String ("BSPP");
[Link]([Link](s2));
}
}
replace ( )
Replace method replaces all occurrence of one character in the string with
another characters.
Syntax
String [Link] (‘old character’,’ new character’);
Example:-
class replace
{
public static void main(String[] args)
{
String s1=new String("Java");
[Link]([Link]('J','h'));
}
}
Page 5 K.A. Prajapati
trim( )
Remove white space at beginning & end of the string.
Syntax
String [Link]( );
Example:-
class strtrim2
{
public static void main(String[] args)
{
String s1=new String(" Hello");
[Link] ([Link]());
}
}
toUpperCase ( )
toLowerCase ( )
valueOf( )
String buffer
String buffer is used to create modifiable(mutable) string.
It allows character or substring to be inserted in the middle or append at the end.
length( ) : To find a length of string buffer.
Syntax
[Link]();
Example:-
class length
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Hello");
[Link] ([Link] ());
}
}
capacity()
The capacity() method of StringBuffer class returns the current capacity of the buffer.
The default capacity of the buffer is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
Syntax
[Link]();
Example:-
class capacityofstring
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
append()
Append string s2 to s1 at the end.
Syntax
[Link]();
Example:-
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java"); //now original string is changed
[Link](sb); //prints Hello Java
}
}
insert ( )
Insert the string s2 at the position of index s1.
‘N’=character of string of index.
Syntax
[Link] (index of charecter,”string” );
Example:-
class insert
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java"); //now original string is changed
[Link](sb); //prints Hjavaello
}
}
reverse( )
You can reverse the characters within a StringBuffer object using reverse( ), shown here:
Syntax:
StringBuffer reverse( )
This method returns the reversed object on which it was called
Example:-
class ReverseDemo
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("Hello");
[Link]();
[Link](s); //prints olleH
}
}
delete( )
You can delete characters within a StringBuffer by using the methods delete( )
Syntax:
StringBuffer delete(int startIndex, int endIndex)
The delete( ) method deletes a sequence of characters from the invoking object.
Here, startIndex specifies the index of the first character to remove, and endIndex
specifies an index one past the last character to remove.
Example:-
class deleteDemo
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb); //prints Hlo
}
}
replace( )
You can replace one set of characters with another set inside a StringBuffer object by
calling replace( ).
Syntax:-
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex.
Thus, the substring at startIndex through endIndex–1 is replaced.
The replacement string is passed in str.
The resulting StringBuffer object is returned.
Example:-
class replaceDemo
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb); //prints HJavalo
}
}
Vector Class
Vector class is in [Link] package of java.
Vector is dynamic array which can grow automatically according to the required need.
Vector does not require any fix dimension like String array and int array.
Vector contains many useful methods.
To add element in Vector, we can use add() method of vector class.
To add elements at fix position, we have to use add(index, object) method.
To get value from Vector, Vector provides get() method and Vector size() method.
Size() method returns total number of elements in Vector.
Vector is synchronized, ArrayList is not
Syntax of some important method of Vector class. Given below.
add(Object o) : It adds the element in the end of the Vector.
elements() : It returns an enumeration of the element.
elementAt(int index) : It returns the element at the specified index.
firstElement() : It returns the first element of the vector.
lastElement() : It returns last element.
removeElementAt(int index) : It deletes the element from the given index.
size() : It returns total number of components available in vector.
Example:-1
import [Link].*;
public class VectorExample
{
public static void main(String[] args)
{
Vector<String> a=new Vector<String>();
[Link]("1");
[Link]("2");
[Link]("3");
[Link]("4");
[Link]("5");
[Link](3, "Element at fix position");
[Link]("Vector Size :"+[Link]());
for(int i=0;i<[Link]();i++)
{
[Link]("Vector Element "+[Link](i));
}
[Link](“Vector Array:-”+a);
}
}
Example-2:
import [Link];
import [Link];
The procedure to create and run an applet goes as follows for an applet that simply displays
Welcome to Java in its graphical window and also prints it to the Java console.
Initialization(init() method)
Initialization occurs when the applet is first loaded (or reloaded).
It is called after the param tags inside the applet tag have been processed.
Syntax :
public void init ( )
{
// Original signature over ridden
}
Starting(start() method)
After an applet is initialized, it is started.
Starting can happen many different times during an applet’s lifetime, whereas initialization
happens only once.
Starting can also occur if the applet was previously stopped.
For example, an applet is stopped if the reader follows a link to a different page, and is
started again when the reader returns back to the page.
Syntax:
public void start ( )
{
// Original signature over ridden
}
Stopping(stop() method)
Stopping occurs when the reader leaves the page that contains a currently running applet, or
by calling the stop ( ) method.
By default, when the reader leaves a page, any threads the applet had started will continue
running.
Syntax:
public void stop ( )
{
// Original signature over ridden
}
Destroying(destroy() method)
Destroying enables the applet to perform a cleanup job just before it is destroyed or the
browser exits for example, or release any other resources.
Generally the destroy( ) method is overridden if there are specific objects that need to be
released, for example threads that the applets has created .
Syntax:
public void destroy ( )
{
// Original signature over ridden
}
Painting(paint() method)
Called immediately after the start() method, and also any time the applet needs to repaint
itself in the browser. The paint() method is actually inherited from the [Link].
Painting is the way an applet actually draws something on the screen, be it text, a line, a
colored background, or an image.
Painting may occur a number of times during an applets life cycle.
The Paint( ) method gets executed every time the applet is minimized or maximized, or
when the applet is initialized and the browser is placed behind another window on the
screen, and then brought forward again.
Syntax:
public void paint (Graphics g)
{
// Original signature over ridden
}
Graphics class
The AWT(Abstract Window Toolkit) graphics class is an abstract class that is the basis for all
graphical constructions in Java.
You cannot implement this class directly.
You use the paint and update methods to implement the features in the Graphics class in your
programs.
You use the following code line to declare the paint method:
public void paint(Graphics g)
To include the different primitives of the Graphics class, be sure to import it into your program:
import [Link];
The example applet shown these ideas. The output from this applet is Figure
import [Link].*;
import [Link].*;
public class demo extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link](10, 10, 100, 100)
}
}
drawString():
The drawSring() method draws the given string as the parameter. Here is the syntax of the
drawString() method :
Syntax:
drawString(String string, int X, int Y);
X is the starting X- axis coordinate
Y is the starting Y- axis coordinate
Example:
import [Link].*;
import [Link].*;
public class HelloWorld extends Applet
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
public void paint(Graphics g)
{
[Link]("Hello world!", 50, 25);
}
}
clearRect()
The clearRect() method can be used to clear a rectangular area.
Syntax:
[Link] (int X, int Y, int Width, int Height)
Height: The vertical size of the rectangle in pixels.
Width: The horizontal size of the rectangle in pixels.
X: Horizontal location of the upper left corner of the rectangle, in pixels.
Y: Vertical location of the upper left corner of the rectangle, in pixels.
Example:-
import [Link];
import [Link].*;
public class Clear1 extends Applet
{
public void paint (Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link] (20, 20, 180, 180);
[Link] (50, 70, 120, 80);
}
}
drawLine()
You use the drawLine() method to draw a line.
Syntax:-
[Link] (int startX, into startY, into endX, into endY );
startX is the starting X- axis coordinate
startY is the starting Y- axis coordinate
endX is the ending X- axis coordinate
endY is the ending Y- axis coordinate
Example:-
import [Link].*;
import [Link].*;
public class line1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link](10,20,30,40) ;
}
}
Syntax:-
g. drawRoundRect(int X, int Y, int Width, int Height, int arcWidth, int arcHeight);
[Link](int X, int Y, int Width, int Height, int arcWidth, int arcHeight);
X is the starting X- axis coordinate, counting from the left edge of the screen
Y is the starting Y- axis coordinate, counting from top edge of the screen
width is the widths of the rectangle
height is the height of the rectangle
The curvature of the corners is specified by the two arguments, arcWidth and arcHeight.
You can also use the fillRoundRect() method to draw a color-filled of rounded rectangle.
Example:-
import [Link].*;
import [Link].*;
public class RoundRect1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link](10,50,100,150,68,120) ;
[Link](50,50,100,150,68,120) ;
}
}
The drawOval() and fillOval() methods to draw circles and ellipses. The difference between
drawing circles and ellipses lies in the coordinates specified in the drawOval() method.
Syntax:
g. drawOval (int X, int Y, int Width , int Height);
g. fillOval (int X, int Y, int Width , int Height);
X and Y represent the top-left screen coordinates
width and height represent the width and the height of the circle or ellipse
In the case of a circle, the width and height should be same.
Example:
import [Link].*;
import [Link].*;
public class Oval1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link](50,50,100,150);
[Link] (100,150,100,150);
}
}
drawArc():
Description:
Used to draw an arc, which is similar to an incomplete oval.
The first parameters are similar to those for drawing an oval.
The last two parameters specify the starting and ending angles of the arc.
Example:
import [Link].*;
import [Link].*;
public class Arc1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
setBackground([Link]);
[Link]([Link]);
[Link](150,150,100,150,190,200);
}
}
drawPolygon():
drawPolygon() and fillpolygon() methods of the graphics class. In the case of a polygon,
the coordinates are specified as a part of two array variables.
Syntax:
[Link] (int x[] , int y[] , int points) ;
In the give syntax
x [] is an array of x-axis coordinates
y [] is an array of y-axis coordinates
points is the number of points defined by the (x, y) coordinates
Example:
import [Link].*;
import [Link].*;
public class Polygon1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
int x[]={20,100,150};
int y[]={230,220,280};
int n=3;
[Link](x,y,n);
[Link](x,y,n);
}
}
Paint():
The paint() method is called each time your applet's output must be redrawn.
For example, the window in which the applet is running may be overwritten by another
window and then uncovered.
Or the applet window was resized.
paint() is also called when the applet begins execution.
Whatever the cause, whenever the applet must redraw its output, paint() is called.
The paint() method has one parameter of type Graphics.
This is needed for the applet to know where the applet should paint its output.
public void paint(Graphics g)
{
//Body.
}
Example:-
import [Link].*;
import [Link].*;
public class Paint1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link]([Link]);
[Link]("KAP",100,50);
}
}
repaint():
The repaint() method is defined by the AWT. It causes the AWT run time system to call to
your applet's update() method, which in its default implementation, calls paint().
Again for example if a part of your applet needs to output a string, it can store this string in a
variable and then call repaint()
Inside paint(), you can output the string using drawstring().
The repaint method has two forms.
void repaint()
void repaint(int left, int top, int width, int height)
Let's look at each one –
void repaint()
This causes the entire window to be repainted
void repaint(int left, int top, int width, int height)
This specifies a region that will be repainted. integers left, top, width and height are in
pixels. You save time by specifying a region to repaint instead of the whole window.
Layout Manager:
A layout manager is an object that is used to organize components in a container.
Layout managers are objects that determine how the components are organized in a
container.
Every container has a default layout manager.
There are types of layout manager:
Flow layout
Grid layout
Border layout
Card layout
A class of the same name represents each layout manager.
To use a layout manager in a Java program, you need to use an object of the
corresponding layout manager class.
To use a layout manager for a container, create an object of the appropriate layout
manager class, and use the setLayout ( ) method to specify the type of the layout to be
used.
Flow Layout
The flow layout manager is the default layout manager for applets and panels.
It places controls linearly from left to right and from top to bottom in horizontal and vertical
rows.
For example, when the layout manager reaches the right border of the container, it positions the
components in the next row.
The flow layout manager places the controls centrally aligned in each row.
Example:-
import [Link].*;
import [Link].*;
public class Aptflow1 extends Applet
{
public void init()
{
/*
import [Link].*;
public class AptBorder extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Button bt1=new Button("ok");
Button bt2=new Button("cancel");
BorderLayout bl=new BorderLayout(2,2);
setLayout(bl);
add(bt1,[Link]);
add(bt2,[Link]);
}
}
Card Layout
The CardLayout layout manager is significantly different from the other layouts.
The CardLayout is unusual.
It breaks the applet into a deck of cards, each of which will normally have a panel with its own
LayoutManager.
Only one card appears on the screen at a time.
You then flip between cards, each of which shows a different set of components.
The common analogy is with an installer wizard.
This might be used for a series of data input screens, where more input is needed than can
comfortably be fit on one screen.
Conversely, you can use a CardLayout for a slide show, where there's more data to be presented
than will fit on one screen.
Example:
import [Link].*;
import [Link].*;
public class CardExample extends Applet
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
CardLayout cl=new CardLayout();
public void init()
{
setLayout(cl);
Panel pA = new Panel();
Panel pC = new Panel();
setLayout(new GridLayout(3,1));
List l =new List(3,false);
Choice c=new Choice();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("Male");
[Link]("Female");
[Link](l);
[Link](c);
add("One",pA);
add("Two",new Button("Click Here"));
add("Three",pC);
}
}
Panel:
To make Applet or Frame layout easier, you break a frame up into regions and compose each of
them separately. Each region is called a Panel
Each can have its own different LayoutManager. Panels don’t have any visible bounding lines.
You can delimit them with differing background colours.
Example:
import [Link].*;
import [Link].*;
public class PanelExample extends Applet
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
public void init()
{
Button bt1=new Button("ok");
Panel p1=new Panel();
[Link](bt1);
add(p1);
}
}
Canvas
The [Link] class is a rectangular area on which you can draw using the methods of
[Link].
The Canvas class has only three methods:
public Canvas()
public void addNotify()
public void paint(Graphics g)
Example:-import [Link].*;
import [Link].*;
public class MyCanvas extends Applet
{
/*<applet code=[Link] height=300 width=500>
</applet>*/
public MyCanvas()
{
setSize(200, 400);
}
public void paint(Graphics g)
{
[Link](0, 0, 90, 50);
[Link]("A Canvas", 15,15);
}} Page 5 [Link]
You generally won't instantiate a canvas directly. Instead you'll subclass it and override the paint()
method in your subclass to draw the picture you want.
Frame
Usage: A Frame is a top-level window with a title and a border. It is normally used as the main
window of a standalone application.
Package: [Link]
Class: [Link]
Parent Classes
[Link] implements MenuContainer
[Link] implements Accessible
[Link]
[Link] implements ImageObserver, MenuContainer, Serializable
[Link]
Common Public Methods
addWindowListener(WindowListener Handler): Configures a window event handler for the
frame.
setBackground (Color BackgroundColor): Sets the background color of the frame.
setFont (Font TextFont): Sets the font for this component.
setForeground (Color TextColor): Sets the color of the text for the frame.
setSize (int Width, int Height): Resizes this window so that it has the specified Width and
Height.
setTitle (String Text): Sets the text for the title bar.
show (): Makes the window visible.
Arguments
BackgroundColor: The color to be used for the background of the button.
Handler: The object which handles window events from this frame.
Text: The text to appear in the title bar.
TextColor: The color to be used for the text of the button.
TextFont: The font to be used for the text of the button.
Example:
import [Link].*;
import [Link].*;
public class Frame2 extends Frame
{
public static void main(String[] args)
{
Frame f=new Frame("Button Frame");
Button button = new Button("Submit");
[Link](button);
[Link](new FlowLayout());
[Link](200,100);
[Link](true);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
}
);
}}
Page 6 [Link]
Dialog box
Dialog boxes are pop-up windows on the screen that appear for a small time to take either input or
display output while a main application is running
The windows that appear for a brief time are known as transient windows.
Dialog boxes are generally used to draw special attention of the user like displaying warnings.
Dialog box is a top-level window that comes with a border including a title bar.
The dialog box can be made non-resizable and the default layout manager is BorderLayout which
can be overridden.
A dialog box works within a main program.
It cannot be created as a standalone application.
It is a child window and must be connected to a main program or to a parent window.
Frame is a parent window as it can work independently.
For example, the Find and Replace Dialog box cannot be obtained without opening MS-Word
document.
Likewise, File Deletion Confirmation box cannot appear without deleting a file.
Two commonly used constructors are shown here:
Dialog(Frame parentWindow, boolean mode)
Dialog(Frame parentWindow, String title, boolean mode)
Example:
import [Link].*;
import [Link].*;
import [Link].*;
Controls
Textbox
Usage: The TextField class can be used to add single line text input to a container.
Package: [Link]
Parent Classes:
[Link] implements Accessible
[Link] implements ImageObserver, MenuContainer, Serializable
[Link]
Example:
import [Link].*;
import [Link].*;
public class AptTextbox extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
TextField t=new TextField("Your Name");
add(t);
}
}
TextArea
Usage: The TextArea class is a GUI component which can be used to provide multiple line text
input or output.
Package: [Link]
Parent Classes:
[Link] implements Accessible
[Link] implements ImageObserver, MenuContainer, Serializable
[Link]
Common Public Methods
void addActionListener (ActionListener Handler):Configures an event handler for the
TextField.
String getText ():- Returns the text in the field.
void setBackground (Color BackgroundColor):- Sets the background color of the TextField.
void setEditable (boolean Editable):- Sets the field as being editable or fixed.
void setFont (Font TextFont):- Sets the font for this component.
void setText (String Text):- Sets the text for the field.
Arguments
BackgroundColor:- The color to be used for the background of the field.
Editable:- The state of the field as editable or fixed.
Handler:- The object which handles action events from this field.
Example:-
import [Link].*;
import [Link].*;
public class AptTextArea extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
TextArea t=new TextArea("Your Address");
add(t);
}
}
Button
Usage:- The Button class can be used to add interactive buttons to a container.
Package:- [Link]
Parent Classes
[Link] implements ImageObserver, MenuContainer, Serializable
[Link]
Common Public Methods
void addActionListener (ActionListener Handler)
void setBackground (Color BackgroundColor):- Sets the background color of the button.
void setEnabled (boolean State):- Enables or disables the button.
void setFont (Font TextFont):- Sets the font for this component.
void setForeground (Color TextColor):- Sets the color of the text for the button.
void setLabel (String Text):- Sets the text for the button.
Arguments
ActionText:- The ActionCommand text for the event associated with the button.
BackgroundColor:- The color to be used for the background of the button.
Handler:- The object which handles action events from this combo box.
State:- The enable state of the button (true or false.)
Text:- The text to appear next to the button.
TextColor:- The color to be used for the text of the button.
TextFont:- The font to be used for the text of the button.
Example:
import [Link].*;
import [Link].*;
public class AptButton extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Button b1=new Button("Submit");
add(b1);
}
}
Label
Usage: The Label class can be used to add text labels to a container.
Package: [Link]
Subclass of: [Link]
Common Methods:
void setBackground (Color BgdColor):Sets the color of the background for the label.
void setAlignment (int Alignment):Sets the alignment of the label's contents along the
X axis.
void setFont (Font TextFont):Sets the font for this component.
void setForeground (Color TextColor):Sets the color of the text for the label.
void setText (String Text):Sets the text for the label.
Arguments:
Alignment: The horiziontal position of the text within the label. One of:
[Link]: The central position in an area.
[Link]: Box-orientation constant used to specify the left side of a box.
[Link]: Box-orientation constant used to specify the right side of a box.
BgdColor:The color to be used for the background of the label.
Text:The text to appear in the label.
TextColor:The color to be used for the text of the label.
TextFont:The font to be used for the text of the label.
Example:
import [Link].*;
import [Link].*;
public class Aptlabel extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Label l1=new Label("User Name");
add(l1);
}
}
CheckBox
Usage:The CheckBox class can be used to add interactive grouped radio checkboxs to a
container.
Package: [Link]
Subclass of: [Link]
Common Methods:
void addItemListener (ItemListener Handler):- Configures an event handler for the
checkbox.
boolean isSelected ():- Returns the state (checked or not checked) of the checkbox.
void setBackground (Color BackgroundColor):- Sets the background color of the checkbox.
void setSelected (boolean State):- Sets the state (checked or not checked) of the checkbox.
void setFont (Font TextFont):- Sets the font for this component.
void setForeground (Color TextColor):- Sets the color of the text for the checkbox.
void setLabel (String Text):- Sets the text for the checkbox.
Arguments:
BackgroundColor:- The color to be used for the background of the checkbox.
Group:- A CheckboxGroup for interactive boxes to act as radiobuttons.
Handler:- The object which handles action events from this combo box.
State:- The checked state of the checkbox (true or false.)
Text:- The text to appear in the checkbox.
TextColor:- The color to be used for the text of the checkbox.
TextFont:- The font to be used for the text of the checkbox.
Example: 1(Simple CheckBox)
import [Link].*;
import [Link].*;
public class AptCheckbox extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Checkbox ch=new Checkbox("FootBall");
add(ch);
Checkbox ch1=new Checkbox("Cricket");
add(ch1);
}
}
Example:2(RadioButton)
import [Link].*;
import [Link].*;
public class AptRadio extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
CheckboxGroup cg =new CheckboxGroup();
Checkbox cmale=new Checkbox("Male",cg,false);
add(cmale);
Checkbox cfemale=new Checkbox("Female",cg,false);
add(cfemale);
}
}
Choice
Usage: The Choice(Combobox) class can be used to add a drop-down list of items to a container
Package: [Link]
Subclass of: [Link]
Common Methods:
void addItemListener (ItemListener Handler):- Configures an event handler for the choice
box.
void insert (String Item, int Index): Inserts the item into this choice at the specified position.
int getSelectedIndex (): Returns the index of the selected item.
void setBackground (Color BackgroundColor): Sets the background color of the choice box.
void setFont (Font TextFont): Sets the font for this component.
void setForeground (Color TextColor): Sets the color of the text for the choice box.
void Select (int Selection): Sets the index of the selected item.
Arguments:
BackgroundColor: The color to be used for the background of the choice box.
Index: Position where the item will be inserted.
Item: A String to be listed in the choice box.
Handler: The object which handles action events from this choice box.
Selection: The index of the selected item.
TextColor: The color to be used for the text of the choice box.
TextFont: The font to be used for the text of the choice box.
Example:-
import [Link].*;
import [Link].*;
public class AptChoice extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Choice ch=new Choice();
[Link]("India");
[Link]("USA");
add(ch);
}
}
List
Usage: The List class can be used to add a list of items with several visible rows to a container.
Package: [Link]
Class: [Link]
Parent Classes
[Link]
[Link]
[Link]
Common Public Methods
void addItemListener (ItemListener Handler) : Specifies an event handler for the list.
void add (String Item) : Inserts the item into this choice at the next position.
void add (String Item, int Index) : Inserts the item into this choice at the specified position.
Scrollbar
Usage: The Scrollbar lets the user graphically select a value by sliding a knob within a bounded
interval.
Package: [Link]
Subclass of: [Link]
Common Methods:
addAdjustmentListener (AdjustmentListener Handler): Configures an event handler for the
scrollbar.
getValue (): Returns the value of the scrollbar setting.
setBackground (Color BackgroundColor): Sets the background color of the scrollbar.
setMaximum (int Max): Sets the maximum value of the scrollbar.
setMinimum (int Min): Sets the minimum value of the scrollbar.
setValue (int Value): Sets the current value of the scrollbar.
Arguments:
BackgroundColor: The color to be used for the background of the field.
Handler: The object which handles action events from this field.
Max: The maximum value of the scrollbar.
Min: The minimum value of the scrollbar.
Extra Example:
Example 1: Write a program to Scroll the scrollbar and value display in textbox.
import [Link].*;
import [Link].*;
import [Link].*;
TextField t2;
public void init()
{
vs = new Scrollbar([Link]);
t1 = new TextField(2);
hs = new Scrollbar([Link]);
t2 = new TextField(2);
add(vs);
add(t1);
add(hs);
add(t2);
[Link](this);
[Link](this);
}
import [Link].*;
import [Link].*;
import [Link].*;
public class AptMouse extends Applet implements MouseListener,MouseMotionListener
{
// <Applet CODE="[Link]" width="100" height="100"></Applet>
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
setBackground([Link]);
}
public void mouseEntered(MouseEvent me)
{
setBackground([Link]);
}
public void mouseExited(MouseEvent me)
{
setBackground([Link]);
}
public void mousePressed(MouseEvent me)
{
setBackground([Link]);
}
public void mouseReleased(MouseEvent me)
{
setBackground([Link]);
}
public void mouseDragged(MouseEvent me)
{
setBackground([Link]);
}
public void mouseMoved(MouseEvent me)
{
setBackground([Link]);
}
}
}
else if(b<a && b<c)
{
[Link](" " +b);
}
else
{
[Link](" " +c);
}
}
public void focusLost(FocusEvent e)
{
int a,b,c;
a=[Link]([Link]());
b=[Link]([Link]());
c=[Link]([Link]());
if(a>b && a>c)
{
[Link](" "+a);
}
else if(b>a && b>c)
{
[Link](" " +b);
}
else
{
[Link](" " +c);
}
}
}
bt1=new Button("Add");
bt2=new Button("Sub");
bt3=new Button("Mul");
bt4=new Button("Div");
add(bt1);
add(bt2);
add(bt3);
add(bt4);
add(t1);
add(t2);
add(t3);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
int a,b,c;
a=[Link]([Link]());
b=[Link]([Link]());
if([Link]()==bt1)
{
c=a+b;
[Link](" "+ c);
}
else if([Link]()==bt2)
{
c=a-b;
[Link](" "+ c);
}
else if([Link]()==bt3)
{
c=a*b;
[Link](" "+ c);
}
else
{
c=a/b;
[Link](" "+ c);
}
}
}
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Pressed");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Realeased");
}
public void keyTyped(KeyEvent ke)
{
msg +=[Link]() ;
repaint();
}
public void paint(Graphics g)
{
[Link](msg,100,200);
}
}
import [Link].*;
import [Link].*;
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
[Link]("A Simple Applet", 20, 20);
}
}
Program explanation:
• Applet must be declared as public, because it will be accessed by code that is outside
the program.
• Inside SimpleApplet, paint( ) is declared.
• This method is defined by the AWT and must be overridden by the applet.
• paint( ) is called each time that the applet must redisplay its output.
void drawString(String message, int x, int y)
• Notice that the applet does not have a main( ) method.
• Unlike Java programs, applets do not begin execution at main( ).
• In fact, most applets don’t even have a main( ) method.
• Instead, an applet begins execution when the name of its class is passed to an applet viewer
or to a network browser.
• An applet viewer executes your applet in a window. This is generally the fastest and
easiest way to test your applet.
• To execute an applet in a web browser, you need to write a short HTML text file that contains
a tag that loads the applet.
• Currently, Sun recommends using the APPLET tag for this purpose.
• Here is the HTML file that executes SimpleApplet:
import [Link].*;
import [Link].*;
/* Execution procedure:
<applet code="SimpleApplet" width=200 1) Compile your program.
height=60> </applet> 2) Execution :
*/ C:\AppletViewer [Link]
public class SimpleApplet extends Applet
{ public void paint(Graphics g) {
[Link]("A Simple Applet", 20, 20);
}
}
1) Applet:-These applets use the Abstract Window Toolkit(AWT) to provide the graphic
user interface
2) JApplet:-The second type of applet is JApplet are those based on the Swing
[Link] applet use the Swing classes to provide the GUI.
Because JApplet inherits Applet ,all the features of Applet are also available in JApplet .
Applet Basics
• All applets are subclasses (either directly or indirectly) of Applet.
• Applets are not stand-alone programs. Instead, they run within either a web browser or
an applet viewer.
• Execution of an applet does not begin at main().
• Output to your applet’s window is not performed by [Link].
• Rather, in non-Swing applets, output is handled with various AWT methods, such as
drawString(),Which outputs a string to a specified X,Y location.
Method Description
void destroy( ) Called by the browser just before an applet is terminated.
Your applet will override this method if it needs to perform
any cleanup prior to its destruction.
AudioClip getAudioClip(URL url) Returns an AudioClip object that encapsulates the audio clip
found at the location specified by url.
URL getCodeBase( ) Returns the URL associated with the invoking applet.
URL getDocumentBase( ) Returns the URL of the HTML document that invokes the
applet.
Image getImage(URL url) Returns an Image object that encapsulates the image found at
the location specified by url.
String getParameter(String paramName) Returns the parameter associated with paramName.
null is returned if the specified parameter is not found.
void init( ) Called when an applet begins execution. It is the first method
called for any applet.
boolean isActive( ) Returns true if the applet has been started. It returns false if
the applet has been stopped.
void play(URL url) If an audio clip is found at the location specified by url, the
clip is played.
void play(URL url, String clipName) If an audio clip is found at the location specified by url with
the name specified by clipName, the clip is played.
void resize(int width, int height) Resizes the applet according to the dimensions specified by
width and height.
Applet Architecture
• An applet is a window-based program. As such, its architecture is different from the so called
Normal, console-based programs.
There are a few key concepts you must understand:
• First, applets are event driven. An applet waits until an event occurs.
• The AWT notifies the applet about an event by calling an event handler that has been
provided by the applet. Once this happens, the applet must take appropriate action and then
quickly return control to the AWT.
• Second, the user initiates interaction with an applet.
• 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 must respond.
• For example, when the user clicks a mouse inside the applet's window, a mouse-clicked
event is generated.
• If the user presses a key while the applet's window has input focus, a keypress event
is generated.
An Applet Skeleton
• All but the most trivial applets override a set of methods that provides the basic mechanism by
which the browser or applet viewer interfaces to the applet and controls its execution.
• Four of these methods are init( ), start( ), stop( ), and destroy( ) these are defined
by Applet.
• Another, paint( ), is defined by the AWT Component class. Applets do not need to override
those methods because they do not use.
Here is an example of Applet program with all basic functions
• destroy( ) :- The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory.
Simple Applet Display Methods
[Link] [Link] [Link]
[Link] [Link] [Link]
[Link] [Link] [Link]
[Link] [Link] [Link]
A simple applet that sets the foreground and background colors and outputs a string:
import [Link].*; public void start() {
import [Link].*; msg += " Inside start( ) --";
/* <applet code="Sample" width=300 height=50> }
</applet> */ // Display msg in applet window.
public class Sample extends Applet{ public void paint(Graphics g) {
String msg; msg += " Inside paint( ).";
public void init() { [Link](msg, 10, 30);
setBackground([Link]); }
setForeground([Link]); }
msg = "Inside init( ) --";
}
Requesting Repainting
• Whenever your applet needs to update the information displayed in its window, it simply
calls repaint( ).
• The repaint( ) method is defined by the AWT.
• It causes the AWT run-time system to execute a call to your applet's update( ) method,
which, in its default implementation, calls paint( ).
• For example, if part of your applet needs to output a string, it can store this string in a String
variable and then call repaint( ).
• Inside paint( ), you will output the string using drawString( ).
• The repaint( ) method has four forms.
import [Link].*; // Entry point for the thread that runs the
import [Link].*; banner.
/* public void run() {
<applet code="SimpleBanner" width=300 height=50> char ch;
</applet> // Display banner
*/ for( ; ; ) {
public class SimpleBanner extends Applet implements try {
Runnable repaint();
{ [Link](250);
String msg = " A Simple Moving Banner."; ch = [Link](0);
Thread t = null; msg = [Link](1, [Link]());
int state; msg += ch;
boolean stopFlag; if(stopFlag)
break;
// Start thread } catch(InterruptedException e) {}
public void start() { }// end of for
t = new Thread(this); } // end of run
stopFlag = false; // Pause the banner.
[Link](); public void stop() {
} stopFlag = true;
t = null;
}
// Display the banner.
public void paint(Graphics g) {
[Link](msg, 50, 30);
}}
• First, notice that SimpleBanner extends Applet, as expected, but it also implements Runnable.
• The AWT run-time system calls start( ) to start the applet running.
• Inside start( ), a new thread of execution is created and assigned to the Thread variable t.
• Then, the boolean variable stopFlag, which controls the execution of the applet, is set to false.
• Next, the thread is started by a call to [Link]( ).
• Remember that [Link]( ) calls a method defined by Thread, which causes run( ) to
begin executing.
• It does not cause a call to the version of start( ) defined by Applet.
• These are two separate [Link] run( ), the characters in the string contained in msg
are repeatedly rotated left.
• Between each rotation, a call to repaint( ) is made. This eventually causes the paint( )
method to be called and the current contents of msg is displayed.
• Between each iteration, run( ) sleeps for a quarter of a second.
• The net effect of run( ) is that the contents of msg is scrolled right to left in a
constantly moving display.
• The stopFlag variable is checked on each iteration. When it is true, the run( )
method terminates.
• An applet can also output a message to the status window of the browser or applet viewer on
which it is running.
• To do so, call showStatus( ) with the string that you want displayed.
The following applet demonstrates showStatus( ):
• The APPLET tag is used to start an applet from both an HTML document and from an applet
viewer.
• An applet viewer will execute each APPLET tag that it finds in a separate window, while web
browsers like Netscape Navigator, Internet Explorer, and HotJava will allow many applets on
a single page.
The syntax for the standard APPLET tag is shown here.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
CODEBASE:- CODEBASE 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 (specified by the CODE
tag).
CODE:- CODE is a required attribute that gives the name of the file containing your applet's compiled
.class file.
ALT:- The ALT tag is an optional attribute used to specify a short text message that should be
displayed if the browser understands the APPLET tag but can't currently run Java applets.
NAME:- NAME is an optional attribute used to specify a name for the applet instance. To obtain an
applet by name, use getApplet( ), which is defined by the AppletContext interface.
WIDTH and HEIGHT:- WIDTH and HEIGHT are required attributes that give the size (in pixels) of
the applet display area.
ALIGN:- ALIGN is an optional attribute that specifies the alignment of the applet.
VSPACE and HSPACE:- These attributes are optional. VSPACE specifies the space, in pixels, above
and below the applet. HSPACE specifies the space, in pixels, on each side of the applet.
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.
• You will create applets that will need to explicitly load media and text. Java will allow
the applet to load data from the directory holding the HTML file that started the applet
• (The document base) and the directory from which the applet's class file was loaded (the
code base).
• To allow your applet to transfer control to another URL, you must use the showDocument( )
method defined by the AppletContext interface.
• AppletContext is an interface that lets you get information from the applet's execution
environment.
• The context of the currently executing applet is obtained by a call to the getAppletContext(
) method defined by Applet.
• Within an applet, once you have obtained the applet's context, you can bring
another document into view by calling showDocument( ).
• The Delegation Event Model: Delegation event model, which defines standard and
consistent mechanisms to generate and process events.
Working of Delegation event model: a source generates an event and sends it to one or
more listeners. In this scheme, the listener simply waits until it receives an event.
Once an event is received, the listener processes the event and then returns.
Events
• In the delegation model, an event is an object that describes a state change in a source.
• Some of the activities that cause events to be generated are pressing a button, entering a
character via the keyboard, selecting an item in a list, and clicking the mouse.
• Many other user operations could also be cited as examples.
• Event may be generated when a timer expires, a counter exceeds a value, software
or hardware failure occurs, or an operation is completed.
• You are free to define events that are appropriate for your application.
1) Event Sources
• A source is an object that generates an event.
• Sources may generate more than one type of event.
• A source must register listeners in order for the listeners to receive notifications about
a specific type of event.
• Each type of event has its own registration method.
• For example, the method that registers a keyboard event listener is called addKeyListener( ).
• The method that registers a mouse motion listener is called addMouseMotionListener( ).
• When an event occurs, all registered listeners are notified and receive a copy of the
event object. This is known as multicasting the event.
Unregistering an Event:
• A source must also provide a method that allows a listener to unregister an interest in
a specific type of event.
The general form of such a method is this:
public void removeTypeListener(TypeListener el)
• you would call removeKeyListener( ).
2) Event Listeners
• A listener is an object that is notified when an event occurs. It has two major requirements.
• First, it must have been registered with one or more sources to receive notifications
about specific types of events.
• Second, it must implement methods to receive and process these notifications.
• For example, the MouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved.
Event Classes
• At the root of the Java event class hierarchy is EventObject, which is in [Link]. It is
the superclass for all events.
• It’s one constructor is shown here:
constructor: EventObject(Object src)
Note: Here, src is the object that generates this event.
AWTEvent:
• The class AWTEvent, defined within the [Link] package, is a subclass of EventObject.
• It is the superclass (either directly or indirectly) of all AWT-based events used by
the delegation event model.
NOTE:
To summarize:
• EventObject is a superclass of all events.
• AWTEvent is a superclass of all AWT events that are handled by the delegation event
model.
• Commonly used constructors and methods in each class are described in the
following sections:
The Action Event Class
• An Action Event is generated when a button is pressed, a list item is double-clicked, or
a menu item is selected.
• The Action Event class defines four integer constants that can be used to identify
any modifiers associated with an action event:
• ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK.
• In addition, there is an integer constant, ACTION_ PERFORMED, which can be used to
identify action events.
Classes in [Link]:
Event Class Description
Action Event Generated when a button is pressed, a list item is double-clicked, or a
menu item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized, or becomes
visible.
ContainerEvent Generated when a component is added to or removed from a container.
• For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents
of the numbers and letters.
Here are some others:
VK_ALT VK_DOWN VK_LEFT VK_RIGHT
VK_CANCEL VK_ENTER VK_PAGE_DOWN [Link]
VK_CONTROL VK_ESCAPE VK_PAGE_UP VK_UP
• The VK constants specify virtual key codes and are independent of any modifiers, such
as control, shift, or alt.
• The system time at which the key was pressed is passed in when.
• The modifiers argument indicates which modifiers were pressed when this key event
occurred. (ALT, SHIFT, CTRL)
• The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code.
• The character equivalent (if one exists) is passed in ch.
• If no valid character exists, then ch contains CHAR_UNDEFINED.
• For KEY_TYPED events, code will contain VK_UNDEFINED.
• The KeyEvent class defines several methods, but the most commonly used ones are
getKeyChar( ), which returns the character that was entered, and getKeyCode( ),
which returns the key code.
Their general forms are shown
here: char getKeyChar( )
int getKeyCode( )
• If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED.
When a KEY_TYPED event occurs when no valied key is pressed , getKeyCode( ) returns
VK_UNDEFINED.
Key board event program:
• Point getPoint( ) : It returns a Point object that contains the X,Y coordinates in its integer
members: x and y.
• The getClickCount( ) method obtains the number of mouse clicks for this event.
Its signature is shown here: int getClickCount( )
• The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on this
platform.
Its form is shown here:
boolean isPopupTrigger( )
• Java SE 6 added three methods to MouseEvent that obtain the coordinates of the
mouse relative to the screen rather than the component.
They are shown here:
1. Point getLocationOnScreen( )
2. int getXOnScreen( )
3. int getYOnScreen( )
Sources of Events: these are the classes which can be used in the place of src.
Event Source Description
Button Generates action events when the button is pressed.
Check box Generates item events when the check box is selected or deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked; generates item
events when an item is selected or deselected.
Menu Item Generates action events when a menu item is selected; generates item events
when a checkable menu item is selected or deselected.
Scroll bar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.
Window Generates window events when a window is activated, closed, deactivated,
deiconified, iconified, opened, or quit.
• The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is
pressed and released, respectively.
The general forms of these methods are shown here:
1. void mouseClicked(MouseEvent me)
2. void mouseEntered(MouseEvent me)
3. void mouseExited(MouseEvent me)
4. void mousePressed(MouseEvent me)
5. void mouseReleased(MouseEvent me)
• Now that you have learned the theory behind the delegation event model and have had
an overview of its various components, it is time to see it in practice.
Using the delegation event model is actually quite easy. Just follow these two steps:
• 1. Implement the appropriate interface in the listener so that it will receive the type
of event desired.
• 2. Implement code to register and unregister (if necessary) the listener as a recipient
for the event notifications.
Explanation of program :
• The MouseEvents class extends Applet and implements both the MouseListener and
MouseMotionListener interfaces.
• These two interfaces contain methods that receive and process the various types of
mouse events.
• Notice that the applet is both the source and the listener for these events.
• This works because Component, which supplies the addMouseListener( )
and addMouseMotionListener( ) methods, is a superclass of Applet.
• Being both the source and the listener for events is a common situation for applets.
• Inside init( ), the applet registers itself as a listener for mouse events.
• This is done by using addMouseListener( ) and addMouseMotionListener( ), which, as
mentioned, are members of Component.
Adapter Classes:
• Adapter classes are useful when you want to receive and process only some of the events
that are handled by a particular event listener interface.
• You can define a new class to act as an event listener by extending one of the adapter classes
and implementing only those events in which you are interested.
• For example, the MouseMotionAdapter class has two methods, mouseDragged( )
• and mouseMoved( ), which are the methods defined by the MouseMotionListener interface.
• If you were interested in only mouse drag events, then you could simply extend
MouseMotionAdapter and override mouseDragged( ).
• The empty implementation of mouseMoved( ) would handle the mouse motion events
for you.
Adapter Classes:
• Commonly Used Listener Interfaces Implemented by Adapter Classes
• The following example demonstrates an adapter. It displays a message in the status bar of
an applet viewer or browser when the mouse is clicked or dragged.
• However, all other mouse events are silently ignored.
• The program has three classes.
• AdapterDemo extends Applet.
• Its init( ) method creates an instance of MyMouseAdapter and registers that object to
receive notifications of mouse events.
Inner Classes:
• To understand the benefit provided by inner classes, consider the applet shown in
the following listing.
• It does not use an inner class. Its goal is to display the string “Mouse Pressed” in the status
// This applet does NOT use an inner class MyMouseAdapter extends MouseAdapter
class. import [Link].*; { MousePressedDemo mousePressedDemo;
import [Link].*; public MyMouseAdapter(MousePressedDemo
/*<applet code="MousePressedDemo" width=200 mousePressedDemo) {
height=100></applet>*/ [Link] = mousePressedDemo;
}
public class MousePressedDemo extends Applet public void mousePressed(MouseEvent me)
{ public void init() { { [Link]("Mouse
addMouseListener(new MyMouseAdapter(this)); Pressed.");
} }
} }
Swings:
• Although the AWT is still a crucial part of Java, its component set is no longer widely used
to create graphical user interfaces.
• Today, most programmers use Swing for this purpose.
• Swing is a set of classes that provides more powerful and flexible GUI components than does
the AWT.
• Simply put, Swing provides the look and feel of the modern Java GUI.
• Because containers are components, a container can also hold other containers. This
enables Swing to define what is called a containment hierarchy, at the top of which must be
a top-level container.
Components:
• Swing components are derived from the JComponent class
• JComponent provides the functionality that is common to all components. For example,
JComponent supports the pluggable look and feel.
• JComponent inherits the AWT classes Container and Component.
• All of Swing’s components are represented by classes defined within the
package [Link].
Components:
Table shows the class names for Swing components (including those used as containers).
Containers:
• Swing defines two types of containers.
• The first are top-level containers: JFrame, JApplet,
• JWindow, and JDialog.
• These containers do not inherit JComponent. They do, however, inherit the AWT classes
Component and Container.
• Unlike Swing’s other components, which are lightweight, the top-level containers are
heavyweight.
• This makes the top-level containers a special case in the Swing component library.
• Furthermore, every containment hierarchy must begin with a top-level container.
• The one most commonly used for applications is JFrame.
• The one used for applets is JApplet.
• The second type of containers supported by Swing are lightweight containers.
• Lightweight containers do inherit JComponent.
• An example of a lightweight container is JPanel, which is a general-purpose container.
import [Link].*;
class SwingDemo {
SwingDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");
[Link](275, 100); // Give the frame an initial size.
// Terminate the program when the user closes the application.
[Link](JFrame.EXIT_ON_CLOSE);
JLabel jlab = new JLabel(" Swing means powerful GUIs."); // Create a text-based label.
[Link](jlab); // Add the label to the content pane.
[Link](true); // Display the frame.
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
[Link](new Runnable() { public void run() { new SwingDemo(); }});
}
}
• Here, obj is a Runnable object that will have its run( ) method called by the event
dispatching thread.
• The difference between the two methods is that invokeLater( ) returns immediately, but
invokeAndWait( ) waits until [Link]( ) returns.
• You can use one of these methods to call a method that constructs the GUI for your Swing
application, or whenever you need to modify the state of the GUI from code not executed
by the event dispatching thread.
• You will normally want to use invokeLater( ), as the preceding program does.
• However, when constructing the initial GUI for an applet, you will need to use
invokeAndWait( ).
import [Link].*;
import [Link].*;
import [Link].*;
class EventDemo {
JLabel jlab;
EventDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");
// Specify FlowLayout for the layout
manager. [Link](new FlowLayout());
[Link](220, 90); // Give the frame an initial size.
// Terminate the program when the user closes the
application.
[Link](JFrame.EXIT_ON_CLOSE);
JButton jbtnAlpha = new JButton("Alpha"); // Button Alpha
JButton jbtnBeta = new JButton("Beta"); // Button Beta
// Add action listener for Alpha.
[Link]( new
ActionListener() {
public void actionPerformed(ActionEvent ae)
{ [Link]("Alpha was pressed."); }}
);
// Add action listener for Beta. public static void main(String args[]) {
[Link](new ActionListener() { // Create the frame on the event dispatching
public void actionPerformed(ActionEvent ae) { thread.
[Link]("Beta was pressed."); [Link](new Runnable()
} { public void run() {
}); new EventDemo();
}
// Add the buttons to the content });
pane. [Link](jbtnAlpha); }
[Link](jbtnBeta); }
Program explanation:
• The [Link] package is needed because it contains the FlowLayout class, which supports
the standard flow layout manager used to lay out components in a frame.
• JButton provides the addActionListener( ) method, which is used to add an action listener.
(JButton also provides removeActionListener( ) to remove a listener, but this method is not
used by the program.
12. NETWORKING:
INTRODUCTION TO NETWORKING.
One of the most important reasons that Java is the premier language for network programming are the
classes defined in the [Link] package.
They provide an easy-to-use means by which programmers of all skill levels can access
network resources.
It is important to emphasize that networking is a very large and at times complicated topic.
NEWORKING BASICS:
At the core of Java’s networking support is the concept of a socket.
A socket identifies an endpoint in a network.
A server process is said to “listen” to a port until a client connects to it.
A server is allowed to accept multiple clients connected to the same port number, although each session is
unique.
Socket communication takes place via a protocol. Internet Protocol (IP) is a low-level routing
protocol that breaks data into small packets and sends them to an address across a network,
which does not guarantee to deliver said packets to the destination.
Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string
together these packets, sorting and retransmitting them as necessary to reliably transmit data.
A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast,
connectionless, unreliable transport of packets.
InetAddress:
The InetAddress class is used to encapsulate both the numerical IP address and the domainname for
that address.
You interact with this class by using the name of an IP host, which is more convenient and understandable
than its IP address.
The InetAddress class hides thenumber inside. InetAddress can handle both IPv4 and IPv6 addresses.
Factory Methods:
The InetAddress class has no visible constructors.
To create an InetAddress object, you have to use one of the available factory methods. Factory
methods are merely a convention whereby static methods in a class return an instance of that
class.
The getLocalHost( ) method simply returns the InetAddress object that represents the localhost.
The getByName( ) method returns an InetAddress for a host name passed to it. If thesemethods are unable to
resolve the host name, they throw an UnknownHostException.
The getAllByName( ) factory method returns an array of InetAddresses that represent all of the addresses that
a particular name resolves to. It will also throw an
UnknownHostException
InetAddress also includes the factory method getByAddress( ), which takes an IP address and returns an
InetAddress object. Either an IPv4 or an IPv6 address can be used.
// Demonstrate InetAddress.
import [Link].*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException
{ InetAddress Address = [Link]();
[Link](Address);
Address = [Link]("[Link]");
[Link](Address);
InetAddress SW[] = [Link]("[Link]");
for (int i=0; i<[Link]; i++)
[Link](SW[i]);
}
}
Instance Methods:
The InetAddress class also has several other methods, which can be used on the objects returned by the
methods just discussed. Here are some of the most commonly used methods.
boolean equals(Object other) Returns true if this object has the same Internet address as other.
byte[ ] getAddress( ) Returns a byte array that represents the object’s IP address in
network byte order.
String getHostAddress( ) Returns a string that represents the host address associated with
the InetAddress object.
String getHostName( ) Returns a string that represents the host name associated with
the InetAddress object.
String toString( ) Returns a string that lists the host name and the IP address for
convenience.
Socket(String hostName, int port) Creates a socket connected to the named host
throws UnknownHostException,IOException and port.
Socket defines several instance methods. For example, a Socket can be examined at any time for the
address and port information associated with it, by use of the following methods:
InetAddress getInetAddress( ) Returns the InetAddress associated with the Socket
object. It returns null if the socket is not connected
int getPort( ) Returns the remote port to which the invoking Socket object is
connected. It returns 0 if the socket is not connected.
int getLocalPort( ) Returns the local port to which the invoking Socket object is
bound. It returns –1 if the socket is not bound
You can gain access to the input and output streams associated with a Socket by use of the
getInputStream( ) and getOuptutStream( ) methods, as shown here.
Each can throw an IOException if the socket has been invalidated by a loss of connection.
InputStream getInputStream( ) Returns the InputStream associated with the
throws IOException. invoking socket.
OutputStream getOutputStream( ) Returns the OutputStream associated with
throws IOException. The invoking socket.
Several other methods are available, including connect( ), which allows you to specify a new
connection; isConnected( ), which returns true if the socket is connected to a server; isBound( ), which
returns true if the socket is bound to an address; and isClosed( ), which returns true if the socket is
closed.
URL:
The World Wide Web. The Web is a loose collection of higher-level protocols and file formats, all
unified in a web browser.
One of the most important aspects of the Web is that Tim Berners-Lee devised a scaleable way to locate all
of the resources of the Net.
Once you can reliably name anything and everything, it becomes a very powerful paradigm. The Uniform
Resource Locator (URL) does exactly that.
The URL provides a reasonably intelligible form to uniquely identify or address information on the Internet.
URLs are ubiquitous; every browser uses them to identify information on the Web. Within
Java’s network class library, the URL class provides a simple, concise API to access
information across the Internet using URLs.
All URLs share the same basic format, although some variation is allowed.
Here are twoexamples:
[Link] and
[Link]
The third component, the port number, is an optional parameter, delimited on the left from the host name by a
colon (:) and on the right by a slash (/). (It defaults to port 80, the predefined
HTTP port; thus, “:80” is redundant.) .
The fourth part is the actual file path. Most HTTP servers will append a file named
[Link] or [Link] to URLs that refer directly to a directory resource. Thus,
[Link] is the same as
[Link]
Java’s URL class has several constructors; each can throw a MalformedURLException.
One commonly used form specifies the URL with a string that is identical to what you see displayed in
a browser:
URL(String urlSpecifier) throws MalformedURLException
The next two forms of the constructor allow you to break up the URL into its component parts:
URL(String protocolName, String hostName, int port, String path)
throws MalformedURLException
URL(String protocolName, String hostName, String path)
o throws MalformedURLException
Another frequently used constructor allows you to use an existing URL as a reference context and then
create a new URL from that context. Although this sounds a little contorted, it’s really quite easy and
useful.
URL(URL urlObj, String urlSpecifier) throws MalformedURLException.
The following example creates a URL to Osborne’s download page and then examines its properties:
// Demonstrate URL.
import [Link].*;
class URLDemo {
public static void main(String args[]) throws MalformedURLException {
URL hp = new URL("[Link] " +
[Link]());
[Link]("Port: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("File: " + [Link]());
[Link]("Ext:" + [Link]());
}}
URLConnection:
URLConnection is a general-purpose class for accessing the attributes of a remote resource.
Once you make a connection to a remote server, you can use URLConnection to inspect the properties of the
remote object before actually transporting it locally.
These attributes are exposed by the HTTP protocol specification and, as such, only make sense for URL
objects that are using the HTTP protocol.
URLConnection defines several methods. Here is a sampling:
int getContentLength( ) Returns the size in bytes of the content associated with the
resource. If the length is unavailable, –1 is returned.
String getContentType( ) Returns the type of content found in the [Link] is the
value of the content-type header [Link] null if the
content type is not available
long getDate( ) Returns the time and date of the response represented in
terms of milliseconds sinceJanuary 1, 1970 GMT.
long getExpiration( ) Returns the expiration time and date of the resource
represented in terms of milliseconds since January 1, 1970
GMT. Zero is returned if the expiration date is unavailable
String getHeaderField(intidx) Returns the value of the header field at index idx. (Header
field indexes begin at 0.) Returns null if the value of idx
exceeds the number of fields.
String getHeaderField(String Returns the value of header field whose name is specified
fieldName by fieldName. Returns null if the specified name is not
found.
String getHeaderFieldKey(intidx) Returns the header field key at index idx. (Header field
indexes begin at 0.) Returns null if the value of idx exceeds
the number of fields.
Map<String, List<String>> Returns a map that contains all of the header fields and
getHeaderFields( ) values.
HttpURLConnection.
Java provides a subclass of URLConnection that provides support for HTTP connections.
This class is called HttpURLConnection.
You obtain an HttpURLConnection in the same way just shown, by calling
openConnection( ) on a URL object, but you must cast the result to
HttpURLConnection. (Of course, you must make sure that you are actually opening an
HTTP connection.) Once you have obtained a reference to an HttpURLConnection
object,you can use any of the methods inherited from URLConnection.
You can also use any of the several methods defined by HttpURLConnection.
Here is a sampling:
static boolean getFollowRedirects( ) Returns true if redirects are automatically followed and
false otherwise. This feature is on by default.
String getRequestMethod( ) Returns a string representing how URL requests are
made. The default is GET. Other options, such as POST,
are available.
String getResponseMessage() Returns the response message associated with the
throws IOException response code. Returns null if no message is available.
An IOException is thrown if the connection fails.
static void setFollowRedirects If how is true, then redirects are automatically followed.
(boolean how) If how is false, redirects are not automatically followed.
By default, redirects are automatically
void setRequestMethod Sets the method by which HTTP requests are made to
(String how) that specified by how. The default method is GET, but
throws ProtocolException other options, such as POST, are available. If how is
invalid, a ProtocolException is thrown
Cookies:
The [Link] package includes classes and interfaces that help manage cookies and can be used to create a
stateful (as opposed to stateless) HTTP session.
The classes are CookieHandler, CookieManager, and HttpCookie. The interfaces are CookiePolicy
and CookieStore.
ServerSockets are quite different from normal Sockets. When you create a ServerSocket, it will register itself
withthe system as having an interest in client connections.
The constructors for ServerSocket reflect the port number that you want to accept connections on
and, optionally, how long you want the queue for said port to be.
The queue length tells the system how many client connections it can leave pending before it should simply
refuse connections.
The default is 50. The constructors might throw an IOException under adverse conditions.
ServerSocket has a method called accept( ), which is a blocking call that will wait for a
client to initiate communications and then return with a normal Socket that is then used for
communication with the client.
The stub works with the other parts of the RMI system to formulate a request that is sent to the remote
machine.
A remote method may accept arguments that are simple types or objects. In the latter case, the object may have
references to other objects.
All of this information must be sent to the remote machine. That is, an object passed as an argument to a
remote method call must be serialized and sent to the remote machine.
If a response must be returned to the client, the process works in reverse. Note that the serialization and
deserialization facilities are also used if objects are returned to a client.
To generate a stub, you use a tool called the RMI compiler, which is invoked from the command line,
as shown here:
rmic AddServerImpl
This command generates the file AddServerImpl_Stub.class. When using rmic, be sure that CLASSPATH is
set to include the current directory.
Datagrams.
TCP/IP-style networking is appropriate for most networking needs.
It provides a serialized,predictable, reliable stream of packet data.
Datagrams provide an alternative. Datagrams are bundles of information passed between machines.
Once the datagram has been released to its intended target, there is no assurance that it will arrive or even
that someone will be there to catch it.
Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in transit or that
whoever sent it is still there to receive a response.
Java implements datagrams on top of the UDP protocol by using two classes: the
DatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send or
receive the DatagramPackets.
DatagramSocket:
DatagramSocket defines four public constructors. They are shown here:
DatagramSocket( ) throws SocketException
DatagramSocket(int port) throws SocketException
DatagramSocket(int port, InetAddress ipAddress) throws SocketException
DatagramSocket(SocketAddress address) throws SocketException
The first creates a DatagramSocket bound to any unused port on the local computer.
The second creates a DatagramSocket bound to the port specified by port.
The third constructs a DatagramSocket bound to the specified port and InetAddress.
The fourth constructs a DatagramSocket bound to the specified SocketAddress.
SocketAddress is an abstract class that is implemented by the concrete class
InetSocketAddress.
InetSocketAddress encapsulates an IP address with a port number.
All can throw a SocketException if an erroroccurs while creating the socket.
DatagramPacket.
DatagramPacket defines several constructors. Four are shown here:
The first constructor specifies a buffer that will receive data and the size of a packet. It
is used for receiving data over a DatagramSocket.
The second form allows you to specify an offset into the buffer at which data will be stored.
The third form specifies a target address and port, which are used by a DatagramSocket to determine where
the data in the packet will be sent.
The fourth form transmits packets beginning at the specified offset into thedata.
Think of the first two forms as building an “in box,” and the second two forms
as stuffing and addressing an envelope.
DatagramPacket defines several methods, including those shown here.
InetAddress getAddress( ) Returns the address of the source (for datagrams being
received) or destination (for datagrams being sent).
byte[ ] getData( ) Returns the byte array of data contained in the
datagram. Mostly used to retrieve data from the
datagram after it has been received.
int getLength( ) Returns the length of the valid data contained in the
byte array that would be returned from the getData( )
A Datagram Example:
The following example implements a very simple networked communications client and server.
Messages are typed into the window at the server and written across the network to the client side,
where they are displayed.
/ Demonstrate datagrams.
import [Link].*; class
WriteServer {
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new
byte[buffer_size]; public static void TheServer()
throws Exception { int pos=0;
while (true) {
int c = [Link]();
switch (c) {
case -1:
[Link]("Server
Quits."); return;
case '\r':
break;
case '\n':
[Link](new DatagramPacket(buffer,pos,
[Link](),clientPort));
pos=0;
break;
default:
buffer[pos++] = (byte) c;
}
}
}
public static void TheClient() throws Exception {
while(true) {
DatagramPacket p = new DatagramPacket(buffer,
[Link]); [Link](p);
[Link](new String([Link](), 0, [Link]()));
}
}
public static void main(String args[]) throws Exception
{ if([Link] == 1) {
ds = new DatagramSocket(serverPort);
TheServer();
} else {
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}
java WriteServer
in one window; this will be the client. Then
run java WriteServer 1
This will be the server. Anything that is typed in the server window will be sent to the
client window after a newline is received.