Documente Academic
Documente Profesional
Documente Cultură
HISTORY OF JAVA
-
Java-programming language was only developed for the small devices but now it
can be found in a variety of devices like cell phones, e-commerce application,
PCs and almost all network or computing devices.
Java is available in different form:
JSP Like PHP and ASP, Java Server Pages based on a code with normal HTML
tags, Which helps in creating dynamic web pages.
Java Applets This is another type of Java program that used within a web page
to add many new features to a web browser. These are small program used in the
programming of instant messaging, chat service, solving some complex
calculation and for many other purposes.
J2EE The software Java 2 Enterprise Edition are used by various companies to
transfer data based on XML structured documents between one another.
JavaBeans This is something like Visual Basic and a reusable software
component that can be easily assemble to create some new and advanced
application.
Mobile Java - Java is also used for various entertainment devices especially
mobile phone. Mobile Information Devices Profile (MIDP) uses Java run time
environment in cell phones, mobile tracking systems and other traditional PDA
devices, including MP3 players, digital TV, video, 3D, simplifying games, etc.
Support to Internet Protocols: Java has a rich variety of classes that abstracts
the Internet protocols like HTTP , FTP, IP, TCP-IP, SMTP, DNS etc .
Support to Web Services : Java has a rich variety of APIs to use xml technology
in diverse applications that supports N-Tiered Enterprise applications over the
internet.
Features like JAXB , JAXM, JAX-RPC , JAXR etc enables to implement web
services in java applications. It makes java a most suited internet language.
Support to java enabled Mobile devices: Java language also works with any java
enabled mobile devices that support MIDP 1.0/2.0 including the symbian OS
mobile devices.
Java Releases
The tables given below provide information about the name and time of releases for
different versions of Java technology.
Releases Event
Month
Year
Java 1.5.0_09
October
2006
Java 1.5.0_08
August
2006
Java 1.5.0_06
December
2005
Java 1.5.0_05
October
2005
Java 1_5_0_04
July
Java 1_5_0_01
February
Java 2 Platform, Standard Edition 1.4
February
(J2SE 1.4)
Java 2 Platform, Standard Edition 1.3
May
(J2SE 1.3)
Java 2 Platform, Enterprise Edition
December
(J2EE)
Java 2 Platform, Standard Edition (J2SE) August
Java Development Kit 1.2 (JDK 1.2)
December
Java Development Kit 1.1 (JDK 1.1)
February
Java Development Kit 1.0 (JDK 1.0)
January
2005
2005
2002
2000
1999
1999
1998
1997
1996
Download JDK
-
Java Features
Platform Independent
-
Simple
-
Programs are easy to write and debug because java does not use the pointers
explicitly.
It is much harder to write the java programs that can crash the system but we can
not say about the other programming languages.
Java provides the bug free system due to the strong memory management. It also
has the automatic memory allocation and deallocation system.
Object Oriented:
If any language used classes and objects that language is called Object Oriented
Programming Language.
- Object: is anything that is existing in the real world.
- Object Properties: An instance of a class, Object is created using new operator
for memory allocation.
Method:
- A method is a function
- A function can return to anywhere
- A method can return to inside a class
- An object contains variables and methods
Class:
-
To be an Object Oriented language, any language must follow at least the four
characteristics.
Inheritance:
- It is the process of creating the new classes and using the behavior of the existing
classes by extending them just to reuse the existing code and adding the
additional features as needed.
Encapsulation
-
Polymorphism :
- As the name suggest one name multiple form.
Dynamic binding :
- It is the way of providing the maximum functionality to a program about the
specific type at runtime.
- As the languages like Objective C, C++ fulfills the above four characteristics yet
they are not fully object oriented languages because they are structured as well as
object oriented languages. But in case of java, it is a fully Object Oriented
language.
Robust
Java has the strong memory allocation and automatic garbage collection
mechanism.
- It provides the powerful exception handling and type checking mechanism as
compare to other programming languages.
- Compiler and interpreter by checking the errors makes the system secure from
crash.
Distributed
- The widely used protocols like HTTP and FTP are developed in java.
- Internet programmers can call functions on these protocols and can get access the
files from any remote machine on the internet rather than writing codes on their
local system.
Portable
- The feature Write-once-run-anywhere makes the java language portable provided
that the system must have interpreter for the JVM.
- Java also have the standard data size irrespective of operating system or the
processor. These features makes the java as a portable language.
Dynamic
- While executing the java program the user can get the required files dynamically
from a local drive or from a computer through the Internet.
Secure
- Java does not use memory pointers explicitly. Security manager determines the
accessibility options of a class like reading and writing a file to the local disk.
- Java uses the public key encryption system to allow the java applications to
transmit over the internet in the secure encrypted form.
- The bytecode Verifier checks the classes after loading.
Performance
- Java uses native code usage, and lightweight process called threads.
- In the beginning interpretation of bytecode resulted the performance slow but the
advance version of JVM uses the adaptive and just in time compilation technique
that improves the performance.
Multithreaded:
- Java is also a Multithreaded programming language.
Multithreading means a single program having different threads executing
independently at the same time.
- Multiple threads execute instructions according to the program code in a process
or a program.
Interpreted
- The interpreter program reads the source code and translates it on the fly into
computations.
- Thus, Java as an interpreted language depends on an interpreter program.
Java as an interpreted language is its error debugging quality. Due to this any
error occurring in the program gets traced.
ArchitectureNeutral
- The Java compiler by generating byte code instructions, to be easily interpreted
on any machine and to be easily translated into native machine code on the fly.
- The compiler generates an architecture-neutral object file format to enable a Java
application to execute anywhere on the network and then the compiled code is
executed on many processors, given the presence of the Java runtime system.
JVM is the main component of Java architecture and it is the part of the JRE (Java
Runtime Enviroment) .
It provides the cross platform functionality to java.
This is a software process that converts the compiled Java byte code to machine
code.
Byte code is an intermediary language between Java source and the host system.
Most programming language like C and Pascal converts the source code into
machine code for one specific type of machine as the machine language vary from
system to system .
Mostly compiler produce code for a particular system but Java compiler produce
code for a virtual machine .
JVM provides security to java.
The programs written in Java or the source code translated by Java compiler into
byte code and after that the JVM converts the byte code into machine code for the
computer one wants to run.
JVM is a part of Java Run Time Environment that is required by every operating
system requires a different JRE .
JRE consists of a number of classes based on JavaAPI and JVM, and without
JRE, it is impossible to run Java.
Execution
Engine
Heap
(create
object)
Java Stack
(execute
method)
Native Method
Interface
PC
Register
Native
method
stacks
If the free memory area is getting too small, the JVM will ask the operating
system for more and if there is no more additional memory available from the
operating system, then JVM stops the application and issues the "Out of memory
error".
The Java runtime employs a garbage collector to reclaim the memory occupied
by an object.
Java API classes: Java API classes are the predefined classes required for the
program compilation and interpretation.
Java Virtual Machine: JVM is also a part of the JRE. The Java Virtual Machine
is responsible for interpreting Java bytecode, and translating this into actions or
operating system calls .
Xyz.java--
-
Java language is the most powerful language and is widely used in the web
application. Today most of the web browser are java compatible. Few of them
are:
Internet Explorer
Netscape
HotJava
Firefox 1.0.4
Mozilla 1.6
Translator is a program that converts any computer program into machine language.
3 types of translators
i.
Interpreter
ii.
iii.
-
Compiler
Assembler
Interpretor: Converts the program one line at a time into machine language
Compiler: Converts all lines of the program at once atleast 10 times faster
than the interpreter.
Assembler: Translates assembly language to machine language Mnemonics
are used in assembly languge.
Assembler s/w Turbo Assemblers
- Macro Assemblers
- Micro Assemblers
compile
Xyz.c
program)
Java Compiler
-
10
Once the byte code is generated it can be run on any platform using
Java Interpreter
(JVM). It interprets byte code (.class file) and converts into machine
specific binary code. Then JVM runs the binary code on the host
machine.
Java Compiler
When you run javac command on the command prompt, it shows the following output.
C:\>javac
Usage: javac <options> <source files>
where possible options include:
-g
Generate all debugging info
-g:none
-g:{lines,vars,source}
-nowarn
Generate no warnings
-verbose
-deprecation
-classpath <path>
Specify where to find user class files and
annotation processors
-cp <path>
11
-sourcepath <path>
-bootclasspath <path>
-extdirs <dirs>
-endorseddirs <dirs>
-proc:{none,only}
Control whether annotation processing and/or
compilation is done.
-processor
<class1>[,<class2>,<class3>...]
Names of the annotation processors to run;
bypasses default discovery process
-processorpath <path>
-d <directory>
-s <directory>
-implicit:{none,class}
Specify whether or not to generate class files
for implicitly referenced files
-encoding <encoding>
-source <release>
release
-target <release>
-version
-help
-Akey[=value]
-X
-J<flag>
C:\>
12
Java Interpreter
-
Java interpreter translates the Java bytecode into the code that can be
understood by the Operating System.
Java applet is a compiled Java code, the Java interpreter can't directly
run them because
they are used as part of a larger applications. For this we use Java
Applet Viewer.
Java Debugger
-
Java debugger helps in finding and the fixing of bugs in Java language
programs.
The Java debugger is denoted as jdb. It works like a command-line
debugger for Java classes.
13
Java Comments
-
These comments are advantageous in the sense that they make the
programmer feel convenient to grasp the logic of the program.
Although these comments are ignored by the Java compiler, To
provide the additional information about the code, use comments.
Java Keywords
There are few keywords in Java programming language. Remember, we cannot use these
keywords as identifiers in the program.
The keywords const and goto are reserved though, they are not being currently used.
The brief description of each one of the keyword is given below.
abstract
When a class is not to be instantiated, use abstract keyword but rather extended by other
classes.
This keyword is used in a method declaration to declare a method without providing the
implementation.
assert
It is used to define an assert statement. Any boolean condition in a program is declared
with the help of assert statement.
The condition is checked at runtime if the program is running with assertions .
If the condition is false, the Java runtime system throws an AssertionError.
boolean
This keyword is used to pertain to an expression or variable that can have only a true or
falsevalue.
14
byte
This is 8-bit integer. This keyword is used to declare an expression, method return value,
or variable of type byte.
Case
This keyword is used to defines a group of statements. The value defined by the
enclosing switch statement should match with the specified value.
catch
This keyword is used to handle the exceptions that occur in a program preceding try
keyword.
char
This Java keyword is used to declare an expression, method return value, or variable of
typecharacter.
class
This keyword is used to define the implementation of a particular kind of object.
const
This keyword has been deprecated from Java programming language.
continue
This keyword is used for the continuation of the program at the end of the current loop
body.
default
If the value defined by the enclosing switch statement does not match any value specified
by a case keyword in the switch statement.
do
Used to declare a loop that will iterate a block of statements. The loop's exit condition is
specified with the while keyword. The loop will execute once before evaluating the exit
condition.
Double
A 64-bit floating point value. A Java keyword used to declare an expression, method
return value, or variable of type double-precision floating point number.
else
It is used to define a statement or block of statements that are executed in the case that the
test condition specified by the if keyword evaluates to false.
enum
Enumerations extend the base class Enum.This Java keyword is used to declare an
enumeratedtype.
15
extends
To specify the superclass in a class declaration, extends keyword is used. It is also used
in an interface declaration to specify one or more superinterfaces.
final
It is used to define an entity once that cannot be altered nor inherited later. Moreover, a
final class cannot be subclassed, a final method cannot be overridden, and a final variable
can occur at most once as a left-hand expression. All methods in a final class are
implicitly final.
finally
This keyword is used when the finally block is executed after the execution exits the try
block and any associated catch clauses regardless of whether an exception was thrown or
caught.
break
Used to resume program execution at the statement immediately following the current
enclosing block or statement. If followed by a label, the program resumes execution at
the statement immediately following the enclosing labeled statement or block.
strictfp
To get the precise results in Floating point calculations use strictfp keyword regardless of
any operating system and hardware platform.
Memory Description
Information is stored in the floppy disks as Bytes.
Byte is the basic measuring unit
Byte represents binary digits called bits.
8 bits
=
1 Byte
1024 B
=
1 KB
1024 KB
=
1 MB
1024 MB
=
1 GB
1024 GB
=
1 TB
Data is stored in the form of electric signals.
16
byte
It is an 8-bit signed two's complement integer. It ranges from -128 to127 (inclusive). We
can save memory in large arrays using byte. We can also use byte instead of int to
increase the limit of the code.
short
It is a 16-bit signed two's complement integer. It ranges from -32,768 to 32,767. short is
used to save memory in large arrays.
long
The long data type is a 64-bit signed two's complement integer. It ranges from
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger
range of values.
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from
1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a
float (instead of double) to save memory in large arrays. We do not use this data type for
the exact values such as currency. For that we have to use java.math.BigDecimal class.
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).
This data type is generally the default choice for decimal values.
boolean
The boolean data type is 1-bit and has only two values: true and false. We use this data
type for conditional statements. true and false are not the same as True and False. They
are defined constants of the language.
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to
65,535. They are not same as ints, shorts etc.
The following table shows the default values for the data types:
Keyword
Description
Size/Format
Byte
Byte-length integer
short
Short integer
Int
Integer
Long
Long integer
17
Float
32-bit IEEE
Double
64-bit IEEE
Char
A single character
boolean
true or false
Java Literals
Integer Literals
Integer literals is a sequence of digits and a suffix as L. To represent the type as long
integer we use L as a suffix. We can specify the integers either in decimal, hexadecimal or
octal format. To indicate a decimal format put the left most digit as nonzero. Similarly put
the characters as ox to the left of at least one hexadecimal digit to indicate hexadecimal
format.
659L
0x4a
057L
Character Literals
18
We can specify a character literal as a single printable character in a pair of single quote
characters such as 'a', '#', and '3'.
The table below shows the codes that can represent these special characters. The letter d
such as in the octal, hex etc represents a number.
Escape
\n
\t
\b
Meaning
New line
Tab
Backspace
\r
Carriage return
\f
\\
Formfeed
Backslash
\'
\"
\d
\xd
Octal
Hexadecimal
\ud
Unicode character
Size
Range
Precision
32
Double 8
64
Float
19
7D
.01f
Floating-point literal
String Literals
The string of characters is represented as String literals in Java. In Java a string is not a
basic data type, rather it is an object.
We represent string literals as
String myString = "How are you?";
Null Literals
We specify the Null literal in the source code as 'null'. To reduce the number of references
to an object, use null literal. The type of the null literal is always null. We typically assign
null literals to object reference variables. For instance
s = null;
In this example an object is referenced by s. We reduce the number of references to an
object by assigning null to s. Now, as in this example the object is no longer referenced
so it will be available for the garbage collection i.e. the compiler will destroy it and the
free memory will be allocated to the other object.
Operators
Operators are symbols that performs some operations on one or more than one operands.
SimpleAssignmentOperator =
Simple assignment operator
Arithmetic Operators
+
*
/
%
20
21
X
0
0
1
1
Y
0
1
0
1
X&Y
0
0
0
1
Truth table is table showing the relationship between input and output
X=10
Y=11
X+Y=?(output=10)
0000 1010
0000 1011
_________
0000 1010
Bitwise or( | ): This operator performs oring operation on individual bits.
X
0
0
1
1
Y
0
1
0
1
X&Y
0
1
1
1
X=10
Y=11
0000 1010
0000 1011
__________
X|Y=?(output=11)
0000 1011
Y
0
1
0
1
X&Y
0
1
1
0
X=10
Y=11
0000 1010
0000 1011
__________
X^Y=?(output=1)
0000 0001
22
Bitwise Left Shift(<<): This operator shift the bits towards left a specified number of
positions
X=10
0
0
0
0
1
0
1
0
X<<2
0
Bitwise right shift(>>): This operator shifts the bit towards right a specified number
X=10
0
X>>2
Operators
Postfix
Unary
Multiplicative
Additive
Shift
Relational
Equality
bitwise AND
bitwise
exclusive OR
bitwise
inclusive OR
logical AND
logical OR
Ternary
Assignment
Precedence
expr++,, expr-++expr, --expr, +expr,
-expr ~ !
*/%
+<< >> >>>
< > , <= , >= instanceof
== , !=
&
^
|
&&
||
?:
= , +=, -=, *=, /=,
%=, &=, ^=, |=, <<=,
>>=, >>, >=
IEEEremainder()
This is the IEEEremainder() which returns you the remainder for the given dividend and
divisor.
max()
This is the max() function which distinguishes the maximum value from the two given
value.
min()
This is the min() function which distinguishes the minimum value from the two given
value.
pow()
This is the pow() function which returns you the number raised to the power of a first
given value by the another one.
random()
This is the random() function which returns you the random number. It is absolutely
system generated.
rint()
This is the rint() function which returns you a value closest to the given value.
round()
This is the round() function which returns you a value that is in the rounded form.
sqrt()
This is the sqrt() function which returns you the square root of the specified value.
package)
class First
{
Block of statements;
}
Block: A group of statements written inside left and right curly braces.
- One method is needed to execute a java program i.e main()
- A method performs a task having a group of statements
- Variables are memory locations to store values
- Amethod needs some variables.
- void main(String args[])
25
when we call the main() method the main method is executed so for
calling we need an object and for getting obj we need to run main();
class Test
{
void main(String args[])
{
Test t=new Test();
t.main();
}
}
- So to avoid this or to break the chain we use static methods.
- A static method is a method that is called and executed without an
object.
- Static void main(String args[])
-
System.out.println(welcome);
- System.out is a method provided by Java software
- We cannot create an object to print stream class
- Out is a static variable
- System.out is an object of PrintStream class that object takes the input
and gives the output on monitor.
26
For Example
hello world !=(not equal to) Hello World
Write the following code into your note pad to run the Hello World program .
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
-
Save the file and Please remember the location where you save your
file.
In this example we have saved the file in the
"C:\javatutorial\example" directory.
The file name should be match the class name and to save the file give
the .java extension. e.g. HelloWorld.java
Now open the command prompt to compile the HelloWorld.java
program.
Go to the directory where you have saved the file ( in our case
C:\javatutorial\example>) and issue the following command to
compile the program:
C:\javatutorial\example>javac HelloWorld.java
Once the compilation is successful a new file will be created with the name
HelloWorld.class. To run the program issue the following command on command
prompt:
C:\javatutorial\example>java HelloWorld
You will see the following result on the command prompt.
Hello World!
Here is the screen shot of the above steps:
27
println(): displays the result in the next line and throws the cursor to
the next line
print() : displays the result and keeps the cursor in the same line and at
the same position.
It will execute the .class file & displays the output.
Then it will quit from memory
Escape Sequences:
\n next line
\t horizontal tab space
\r enter button
\b backspace button
\\ displays \
\ displays
\ displays
Important Note:
-
28
29
Size/Format
Integers
Byte
Byte-length integer
Short
Short integer
Int
Integer
Long
Long integer
Real numbers
Float
Double
Char
A single character
boolean
Other types
We can control the program flow by using statements like decisionmaking statements (if-then, if-then-else, switch),
the looping statements (for, while, do-while),
and the branching statements (break, continue, return)
Selection
- In this section we will learn how to use if-then, if-then else and switch statements
The if statement
- This code gets executed if and only if the test evaluates to true.
- That is the if statement in Java is a test of any boolean expression.
- The statement following the if will only be executed when the boolean
expression evaluates to true.
30
if(condition)
System.out.println(AAA);
The general form of the if else statement is:
if (condition)
statement1;
else
statement2;
-
class compare{
public static void main(String[] args){
int a = 20;
int b = 40;
if (a<b){
System.out.println("a is smaller");
}
else{
d
System.out.println("b is smaller");
}
}
31
class Switch{
public static void main(String[] args){
int week = 5;
switch (week){
case 1: System.out.println("monday"); break;
case 2: System.out.println("tuesday"); break;
case 3: System.out.println("wednesday"); break;
case 4: System.out.println("thursday"); break;
case 5: System.out.println("friday"); break;
case 6: System.out.println("saturday"); break;
case 7: System.out.println("sunday"); break;
default: System.out.println("Invalid week");break;
}
32
while (expression)
{
statement(s)
}
Lets see the flow of the execution of the while statement
1. Firstly, It evaluates the condition in parentheses, yielding true or false.
in
steps:
2. Secondly, It continues to execute the next statement if the condition is false and exit
the while statement.
3. Lastly, If the condition is true it executes each of the statements between the brackets
and then go back to step 1.
For example:
class Bonjour{
public static void main (String args[]){
System.out.print("Bonjour ");
// Say Hello
int i = 0;
// Declare and initialize loop counter
while (i < args.length){
// Test and Loop
System.out.print(args[i]);
System.out.print(" ");
i = i + 1;
// Increment Loop Counter
}
System.out.println();
// Finish the line
}
}
do-while statement
Here is the syntax:
do
{
statement(s)
}
while (expression);
class DoWhileDemo
{
public static void main (String args[])
33
{
int i = 0;
do{
System.out.print("Bonjour");
// Say Bonjour
System.out.println(" ");
i = i + 1;
// Increment LoopCounter
}
while (i < 5);
In the above example, it will enter the loop without checking the
condition first and checks the condition after the execution of the
statements.
That is it will execute the statement once and then it will evaluate the
result according to the condition.
Jumping
-
Using for, while and do-while loops is not always the right idea to use
because they are cumbersome to read.
Using jumping statements like break and continue it is easier to jump
out of loops to control other areas of program flow.
The break statement has two forms: labeled and unlabeled. You saw
the labeled form in the above example i.e. a labeled break terminates
an outer statement.
However, an unlabeled break statement terminates the innermost loop
like switch, for, while, or do-
34
while statement
- Now observe the example of unlabeled form below. We have used two
loops here two print '*'. In this example, if we haven't use break
statement thus the loop will continue and it will give the output as
shown below.
class BreaklabDemo1
{
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
System.out.print("\n");
for (int j = 0; j<=i; j++)
{
System.out.print("*");
if (j==5)
{
// break;
}
}
}
35
The java array enables the user to store the values of the same type in
contiguous memory allocations.
Arrays are always a fixed length abstracted data structure which can
not be altered when required.
36
a[0]=1
a[1]=2
...
a[n-1]=n
...
a[11]=12
The figure below shows the structure of an Array more precisely.
Array Declaration
- As we declare a variable in Java, An Array variable is declared the
same way.
- Array variable has a type and a valid Java identifier i.e. the array's type
and the array's name.
- By type we mean the type of elements contained in an array.
- To represent the variable as an Array, we use [] notation.
- These two brackets are used to hold the array of a variable.
- By array's name, we mean that we can give any name to the array,
however it should follow the predefined conventions.
- Below are the examples which show how to declare an array :-
int[]array_name;
String[]names;
int[][] matrix; //this is an array of arrays
int[]
37
static
void
main(String[]
args)
{
}
Array Initialization
- After declaring an array variable, memory is allocated to it. The "new"
operator is used for the allocation of memory to the array object. The
correct way to use the "new" operator is
String names[];
names = new String[10];
-
Here, the new operator is followed by the type of variable and the
number of elements to be allocated. In this example [] operator has
been used to place the number of elements to be allocated.
Array Usage
-
38
Example:
String months[] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"July", "Aug", "Sep", "Oct", "Nov", "Dec"};
//use the length attribute to get the number
//of elements in an array
for (int i = 0; i < months.length; i++ ) {
System.out.println("month: " + month[i]);
In this loop int i = 0; indicates that the loop starts from the 0th position
of an array and goes upto the last position which is length-1, i <
months.length; indicates the length of the array and i++ is used for the
increment in the value of i which is i = i+1.
Multi-dimensional arrays
-
Two-dimensional arrays
Two-dimensional arrays are defined as "an array of arrays". Since an array type is a firstclass Java type,
The command
int[][] A = new int[3][4]
-
39
Class
-
Objects are the basic unit of object orientation with behavior, identity,
these are part of a class but are not the same.
An object is expressed by the variable and methods within the objects.
Again these variables and methods are distinguished from each other
as instant variables, instant methods and class variable and class
methods.
Object
-
Methods -
Inheritance Acquiring the properties of one class to the other is called Inheritance.
Abstraction - The process of abstraction in Java is used to hide certain details and only
show the essential features of the object.
40
Access Modifiers
Access Modifiers : Access modifiers are used to specify the visibility and accessibility of
a class.
public keyword specifies that the public class, the public fields and the public methods
can be accessed from anywhere.
private: This keyword provides the accessibility only within a class i.e. private fields
and methods can be accessed only within the same class.
protected: This modifier makes a member of the class available to all classes in the same
package and all sub classes of the class.
default : Its not a keyword. When we don't write any access modifier then default is
considered. It allows the class, fields and methods accessible within the package only.
Access Specifiers
-
Programming Structure:
package ;
class ClassName
{
Declaration of variables;
Access-specifier return-type function-name(argument-list)
{
block of statements;
}
public static void main(String[] args)
41
{
Instantiation(creating an object);
//syntax to create an object :
//ClassName object=new ClassName();
}
}
Function Prototypes:
There are 4 types of function prototypes are available in java
1.
2.
3.
4.
42
43
import java.io.*;
class Rectangle
{
int length, breadth,a;
public void Rect(int l,int b)
{
length=l;
breadth=b;
}
public int Area()
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.Rect(10,7);
System.out.println("Area of a Rectangle=" +r.Area());
}
}
// Over Loading a Method
import java.io.*;
class Rectangle
{
int length, breadth,a;
public void Rect()
{
length=8;
breadth=3;
}
public void Rect(int l)
{
length=breadth=l;
}
public void Rect(int l,int b)
{
length=l;
breadth=b;
}
public int Area()
44
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.Rect();
System.out.println("Area of a Rectangle=" +r.Area());
r.Rect(5);
System.out.println("Area of a Rectangle=" +r.Area());
r.Rect(9,4);
System.out.println("Area of a Rectangle=" +r.Area());
}
}
Constructor:
-
Types of Constructors:
1.
2.
3.
4.
45
{
int length, breadth;
public Rectangle()
{
length=8;
breadth=3;
}
public int Area()
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r1=new Rectangle();
System.out.println("Area of a Rectangle=" +r1.Area());
}
}
// Example for Parameterized Constructor
import java.io.*;
class Rectangle
{
int length, breadth;
public Rectangle(int l,int b)
{
length=l;
breadth=b;
}
public int Area()
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r1=new Rectangle(8,3);
System.out.println("Area of a Rectangle=" +r1.Area());
}
}
//Another Example:
46
import java.io.*;
class Rectangle
{
int length, breadth,a;
public Rectangle(int length,int breadth)
{
this.length=length;
this.breadth=breadth;
}
public int Area()
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r1=new Rectangle(8,3);
System.out.println("Area of a Rectangle=" +r1.Area());
}
}
Note: this is used to invoke a constructor of the same class.
// Overloading Constructor
import java.io.*;
class Rectangle
{
int length, breadth,a;
public Rectangle()
{
length=8;
breadth=3;
}
public Rectangle(int l)
{
length=breadth=l;
}
public Rectangle(int l,int b)
{
length=l;
breadth=b;
47
}
public int Area()
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r1=new Rectangle();
System.out.println("Area of a Rectangle=" +r1.Area());
Rectangle r2=new Rectangle(8);
System.out.println("Area of a Rectangle=" +r2.Area());
Rectangle r3=new Rectangle(9,3);
System.out.println("Area of a Rectangle=" +r3.Area());
}
}
Inheritance
-
48
because every car has the features of it's parent (in this case vehicle)
class.
The following kinds of inheritance are there in java.
Single Inheritance
Multilevel Inheritance
Pictorial Representation of Simple and Multilevel Inheritance
Single Inheritance
Multilevel Inheritance
Single Inheritance
When a subclass is derived simply from it's parent class then this mechanism is known
as single inheritance. In case of single inheritance there is only a sub class and it's parent
class.
eg.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}
49
Multilevel Inheritance
- When a subclass is derived from a derived class then this mechanism
is known as the multilevel inheritance.
- The derived class is called the subclass or child class for it's parent
class and this parent class works as the child class for it's just above
( parent ) class. Multilevel inheritance can go up to any number of
level.
e.g.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}
}
class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
}
Multiple Inheritance
- The mechanism of inheriting the features of more than one base class
into a single class is known as multiple inheritance.
- Java does not support multiple inheritance but the multiple inheritance
can be achieved by using the interface.
super keyword
-
class B is the subclass that also contains its own data members named
a and b. then we can access the super class (class A) variables a and b
inside the subclass class B just by calling the following command.
super.member;
-
class A{
int a;
float b;
void Show(){
System.out.println("b in super class:
}
" + b);
}
class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class:
System.out.println("a in sub class:
}
" + super.b);
" + a);
The second use of the keyword super in java is to call super class
constructor in the subclass.
This functionality can be achieved just by using the following
command.
super(param-list);
-
class A{
int a;
int b;
int c;
A(int p, int q, int r){
a=p;
b=q;
c=r;
}
}
class B extends A{
int d;
B(int l, int m, int n, int o){
super(l,m,n);
d=o;
}
void Show(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
An abstract method one that have the empty implementation. All the
methods in any interface are abstract by default.
Abstract method provides the standardization for the " name and
signature" of any method.
One can extend and implement to these methods in their own classes
according to the requirements.
e.g.
public abstract abs_value();
Abstract Class
-
abstract classes are those that works only as the parent class or the
base class.
52
e.g.
abstract class A{
public abstract abs_value();
void show(){
System.out.println("This is an abstract class");
}
Interface
-
53
Example:
-
Interface Definition
visibility mode interface interfaceName{
constant variable declarations
abstract method declarations
}
e.g.
public interface RacingCar{
public void startcar (int Obj);
public void changegear (int Obj);
public void incrrace (int Obj);
public void stopcar (int Obj);
}
Marker Interface
- Interfaces with no methods are known as marker interfaces.
Marker interfaces are Serializable, Clonable, SingleThreadModel,
Event listener.
- Marker Interfaces are implemented by the classes or their super classes
in order to add some functionality.
-
e.g. Suppose you want to persist (save) the state of an object then you
have to implement the Serializable interface otherwise the compiler
will throw an error.
Features
Interface
Abstract Class
Methods
An interface contains all theAn abstract class must have at least one
methods
with
emptymethod with empty implementation.
implementation.
Variables
Multiple In java multiple inheritance isAbstract classes does not provide this
Inheritance
achieved by using the interfacefunctionality.
(by implementing more than
one interface at a time)
Additional
Functions
String Handling
Strings: A string represents a group of characters
Note : String is a class in java.lang package
Creating a string: 1. we can create a string by directly assigning a string literal to a
string object
Ex: String str=Hello;
Object: allocating memory to store data.Internally JVM creates object
2. We can create a string class object using new operator
Ex: String str=new String(hello);
3. We can convert a character array into String class object
Ex: char ch[]={H,e,l,l,o};
String str=new String(ch);
55
Java.lang.String:
1. String concat(String str)
Concatenates the calling string with str.concat receives one string object and
returns string.
Note: + will do the same.
Ex: String s1=Hydera;
String s2=bad;
String x=s1.concat(s2);
2. int length (): length gives no of characters in a string returns the length of a string
String s1=Hydera;
Int n=s1.length();
3. char charAt(int index): returns the character at the specified location(from 0)
4. int compareTo(String str):returns a negative value if the string comes before string in
dictionary order, a positive value, if the string comes after str, or 0 if the strings are equal
Ex: String s1=apple;
String s2=grapes;
int n=s1.compareTo(s2);
n==0 if s1==s2;
n>0 if s1>s2;
n<0 if s1<s2
StringBuffer class in Java
StringBuffer is mainly used for the dynamic string concatenation which enhances the
performance. A string buffer implements a mutable sequence of characters. A string
buffer is like a String, but can be modified. At any point of time it contains some
particular sequence of characters, but the length and content of the sequence can be
changed through certain method calls. There are some functions used in the given
example.
append()
This is the append() function used for the concatenate the string in string buffer. This is
better to use for dynamic string concatenation.
insert()
This is the insert() function used to insert any string or character at the specified position
in the given string.
reverse()
This is the reverse() function used to reverse the string present in string buffer.
setCharAt()
56
This is the setCharAt() function which is used to set the specified character in buffered
string at the specified position of the string in which you have to set the given character.
charAt()
This is the charAt() function which is used to get the character at the specified position of
the given string.
substring()
This is the substring() function which is used to get the sub string from the buffered string
from the initial position to end position (these are fixed by you in the program).
deleteCharAt()
This is the deleteCharAt() function which is used to delete the specific character from the
buffered string by mentioning that's position in the string.
length()
This is the length() function is used to finding the length of the buffered string.
delete()
This is the delete() function is used to delete multiple character at once from n position to
m position (n and m are will be fixed by you.) in the buffered string.
capacity()
This is the capacity() function is used to know about the current characters kept which is
displayed like : number of characters + 6.
import java.io.*;
public class stringBuffer{
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str;
try{
System.out.print("Enter your name: ");
str = in.readLine();
str += ", This is the example of SringBuffer class and it's functions.";
//Create a object of StringBuffer class
StringBuffer strbuf = new StringBuffer();
strbuf.append(str);
System.out.println(strbuf);
strbuf.delete(0,str.length());
//append()
strbuf.append("Hello");
strbuf.append("World");
System.out.println(strbuf);
//print HelloWorld
//insert()
strbuf.insert(5,"_Java ");
System.out.println(strbuf);
//reverse()
strbuf.reverse();
System.out.print("Reversed string : ");
System.out.println(strbuf);
//print dlroW avaJ_olleH
57
strbuf.reverse();
System.out.println(strbuf);
//setCharAt()
strbuf.setCharAt(5,' ');
System.out.println(strbuf);
//charAt()
System.out.print("Character at 6th position : ");
System.out.println(strbuf.charAt(6));
//print J
//substring()
System.out.print("Substring from position 3 to 6 : ");
System.out.println(strbuf.substring(3,7));
//print lo J
//deleteCharAt()
strbuf.deleteCharAt(3);
System.out.println(strbuf);
//capacity()
System.out.print("Capacity of StringBuffer object : ");
System.out.println(strbuf.capacity());
//print 21
//delete() and length()
strbuf.delete(6,strbuf.length());
System.out.println(strbuf);
//no anything
}
catch(StringIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}
58
Description of code:
StringBuffer(int len):
This is the constructor of StringBuffer class that implements multiple sequence of
characters. This constructor constructs a string buffer that have no characters. It
takes initial capacity that have to initialized.
insert(int pos, String str):
This method inserts the string into the object of StringBuffer. It takes following
parameters:
59
pos: This is the position that have to be used for inserting the data.
str: This is the string that have to inserted.
append(String str):
This is the method that inserts the string into string buffer. It always inserts a string at last
position.
Here is the code of program
import java.lang.*;
public class AppendInsert{
public static void main(String[] args) {
System.out.println("StringBuffer insert and append example!");
StringBuffer sb = new StringBuffer(0);
//First position
System.out.println(sb.insert(0, "vinod"));
int len = sb.length();
//last position
System.out.println(sb.insert(len, "Deepak"));
//Six position
System.out.println(sb.insert(6, "Raj"));
//Always last
System.out.println(sb.append("Mohit"));
}
}
60
Util Packages:
A collection sometimes called a container is simply an object that groups multiple
elements into a single unit. Collections are used to store, retrieve, manipulate, and
communicate aggregate data
Collection Framework
A collections framework is a unified architecture for representing and
manipulating collections. All collections frameworks contain the following:
Interfaces: These are abstract data types that represent collections. Interfaces
allow collections to be manipulated independently of the details of their
representation
Implementations: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.
Interface
Type
Set
SortedSet
List
Queue
Map
SortedMap
Implemented by
HashSet, LinkedHashSet, EnumSet
TreeSet
Vector, Stack, ArrayList, LinkedList
PriorityQueue, LinkedList
Hashtable, HashMap, LinkedHashMap, WeakHashMap,
IdentityHashMap
TreeMap
62
Collection
Set
List
Queue
Map
63
SortedSet
SortedMap
The add method is defined generally enough so that it makes sense for
collections that allow duplicates as well as those that don't.
64
Traversing Collections
There are two ways to traverse collections: (1) with the for-each construct and
(2) by using Iterators.
for-each Construct
The for-each construct allows you to concisely traverse a collection or array
using a for loop
for (Object o : collection)
System.out.println(o);
Iterators
An Iterator is an object that enables you to traverse through a collection and
to remove elements from the collection selectively,
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional
}
- The hasNext method returns true if the iteration has more elements,
and the next method returns the next element in the iteration.
- The remove method removes the last element that was returned by next
from the underlying Collection.
- Iterator.remove is the only safe way to modify a collection during
iteration;
Use Iterator instead of the for-each construct when you need to:
Remove the current element. The for-each construct hides the iterator,
so you cannot call remove.
Therefore, the for-each construct is not usable for filtering.
Object[] a = c.toArray();
66
TreeSet,
The size operation returns the number of elements in the Set (its
cardinality).
The add method adds the specified element to the Set if it's not already
present and returns a boolean indicating whether the element was added.
Similarly, the remove method removes the specified element from the
Set if it's present and returns a boolean indicating whether the element
was present.
The iterator method returns an Iterator over the Set.
import java.util.*;
public class FindDups {
public static void main(String[] args) {
Set<String> s = new HashSet<String>();
for (String a : args)
if (!s.add(a))
System.out.println("Duplicate detected: " + a);
System.out.println(s.size() + " distinct words: " + s);
}
}
Bulk operations are particularly well suited to Sets; when applied, they
perform standard set-algebraic operations.
Suppose s1 and s2 are sets. Here's what bulk operations do:
union of two sets is the set containing all of the elements contained in either set.)
s1.retainAll(s2) transforms s1 into the intersection of s1 and s2.
(The intersection of two sets is the set containing only the elements common to
both sets.)
s1.removeAll(s2) transforms s1 into the (asymmetric) set
difference of s1 and s2. (For example, the set difference of s1 minus s2 is the
set containing all of the elements found in s1 but not in s2.)
67
import java.util.*;
public class FindDups2 {
public static void main(String[] args) {
Set<String> uniques = new HashSet<String>();
Set<String> dups
= new HashSet<String>();
for (String a : args)
if (!uniques.add(a))
dups.add(a);
// Destructive set-difference
uniques.removeAll(dups);
System.out.println("Unique words:
" + uniques);
System.out.println("Duplicate words: " + dups);
}
68
// Range-view
List<E> subList(int from, int to);
Collection Operations
The operations inherited from Collection all do about what you'd expect them
to do, assuming you're already familiar with them. If you're not familiar with
them from Collection, now would be a good time to read The Collection
Interface section. The remove operation always removes the first occurrence of
the specified element from the list. The add and addAll operations always
append the new element(s) to the end of the list. Thus, the following idiom
concatenates one list to another.
list1.addAll(list2);
Note that the idiom, in its nondestructive form, takes advantage of ArrayList's
standard conversion constructor.
Like the Set interface, List strengthens the requirements on the equals and
hashCode methods so that two List objects can be compared for logical
equality without regard to their implementation classes. Two List objects are
equal if they contain the same elements in the same order.
69
The addAll operation inserts all the elements of the specified Collection
starting at the specified position. The elements are inserted in the order they are
returned by the specified Collection's iterator. This call is the positional access
analog of Collection's addAll operation.
Here's a little method to swap two indexed values in a List. It should look
familiar from Programming 101.
public static <E> void swap(List<E> a, int i, int j) {
E tmp = a.get(i);
a.set(i, a.get(j));
a.set(j, tmp);
}
In fact, this program can be made even shorter and faster. The Arrays class has
a static factory method called asList, which allows an array to be viewed as a
List. This method does not copy the array. Changes in the List write through
to the array and vice versa. The resulting List is not a general-purpose List
implementation, because it doesn't implement the (optional) add and remove
operations: Arrays are not resizable. Taking advantage of Arrays.asList and
70
Iterators
As you'd expect, the Iterator returned by List's iterator operation returns
the elements of the list in proper sequence. List also provides a richer iterator,
called a ListIterator, which allows you to traverse the list in either direction,
modify the list during iteration, and obtain the current position of the iterator.
The ListIterator interface follows.
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove(); //optional
void set(E e); //optional
void add(E e); //optional
}
The three methods that ListIterator inherits from Iterator (hasNext, next,
and remove) do exactly the same thing in both interfaces. The hasPrevious and
the previous operations are exact analogues of hasNext and next. The former
operations refer to the element before the (implicit) cursor, whereas the latter
refer to the element after the cursor. The previous operation moves the cursor
backward, whereas next moves it forward.
Here's the standard idiom for iterating backward through a list.
for (ListIterator<Type> it =
list.listIterator(list.size());
it.hasPrevious(); ) {
Type t = it.previous();
...
}
71
Note the argument to listIterator in the preceding idiom. The List interface
has two forms of the listIterator method. The form with no arguments
returns a ListIterator positioned at the beginning of the list; the form with an
int argument returns a ListIterator positioned at the specified index. The
index refers to the element that would be returned by an initial call to next. An
initial call to previous would return the element whose index was index-1. In
a list of length n, there are n+1 valid values for index, from 0 to n, inclusive.
Intuitively speaking, the cursor is always between two elements the one that
would be returned by a call to previous and the one that would be returned by a
call to next. The n+1 valid index values correspond to the n+1 gaps between
elements, from the gap before the first element to the gap after the last one. The
following figure shows the five possible cursor positions in a list containing four
elements.
Calls to next and previous can be intermixed, but you have to be a bit careful.
The first call to previous returns the same element as the last call to next.
Similarly, the first call to next after a sequence of calls to previous returns the
same element as the last call to previous.
It should come as no surprise that the nextIndex method returns the index of
the element that would be returned by a subsequent call to next, and
previousIndex returns the index of the element that would be returned by a
subsequent call to previous. These calls are typically used either to report the
position where something was found or to record the position of the
ListIterator so that another ListIterator with identical position can be
created.
It should also come as no surprise that the number returned by nextIndex is
always one greater than the number returned by previousIndex. This implies
the behavior of the two boundary cases: (1) a call to previousIndex when the
cursor is before the initial element returns -1 and (2) a call to nextIndex when
the cursor is after the final element returns list.size(). To make all this
concrete, the following is a possible implementation of List.indexOf.
public int indexOf(E e) {
for (ListIterator<E> it = listIterator();
it.hasNext(); )
72
The only bit of trickiness in this example is the equality test between val and
it.next. You need to special-case a val value of null to prevent a
NullPointerException.
The add method inserts a new element into the list immediately before the
current cursor position. This method is illustrated in the following polymorphic
algorithm to replace all occurrences of a specified value with the sequence of
values contained in the specified list.
public static <E> void replace(List<E> list, E val,
List<? extends E> newVals)
{
for (ListIterator<E> it = list.listIterator();
it.hasNext(); ){
if (val == null ? it.next() == null :
val.equals(it.next())) {
it.remove();
for (E e : newVals)
it.add(e);
}
}
}
73
Range-View Operation
The range-view operation, subList(int fromIndex, int toIndex), returns
a List view of the portion of this list whose indices range from fromIndex,
inclusive, to toIndex, exclusive. This half-open range mirrors the typical for
loop.
for (int i = fromIndex; i < toIndex; i++) {
...
}
As the term view implies, the returned List is backed up by the List on which
subList was called, so changes in the former are reflected in the latter.
This method eliminates the need for explicit range operations (of the sort that
commonly exist for arrays). Any operation that expects a List can be used as a
range operation by passing a subList view instead of a whole List. For
example, the following idiom removes a range of elements from a List.
list.subList(fromIndex, toIndex).clear();
Note that the preceding idioms return the index of the found element in the
subList, not the index in the backing List.
Any polymorphic algorithm that operates on a List, such as the replace and
shuffle examples, works with the List returned by subList.
Here's a polymorphic algorithm whose implementation uses subList to deal a
hand from a deck. That is, it returns a new List (the "hand") containing the
specified number of elements taken from the end of the specified List (the
"deck"). The elements returned in the hand are removed from the deck.
public static <E> List<E> dealHand(List<E> deck, int n) {
int deckSize = deck.size();
List<E> handView = deck.subList(deckSize - n,
deckSize);
List<E> hand = new ArrayList<E>(handView);
handView.clear();
return hand;
}
Note that this algorithm removes the hand from the end of the deck. For many
common List implementations, such as ArrayList, the performance of
74
removing elements from the end of the list is substantially better than that of
removing elements from the beginning.
The following is a program that uses the dealHand method in combination with
Collections.shuffle to generate hands from a normal 52-card deck. The
program takes two command-line arguments: (1) the number of hands to deal
and (2) the number of cards in each hand.
import java.util.*;
class Deal {
public static void main(String[] args) {
int numHands = Integer.parseInt(args[0]);
int cardsPerHand = Integer.parseInt(args[1]);
// Make a normal 52-card deck.
String[] suit = new String[]
{"spades", "hearts", "diamonds", "clubs"};
String[] rank = new String[]
{"ace","2","3","4","5","6","7","8",
"9","10","jack","queen","king"};
List<String> deck = new ArrayList<String>();
for (int i = 0; i < suit.length; i++)
for (int j = 0; j < rank.length; j++)
deck.add(rank[j] + " of " + suit[i]);
Collections.shuffle(deck);
for (int i=0; i < numHands; i++)
System.out.println(dealHand(deck,
cardsPerHand));
}
}
one or a sequence of range operations on the backing List. The longer you use
the subList instance, the greater the probability that you'll compromise it by
modifying the backing List directly or through another subList object. Note
that it is legal to modify a sublist of a sublist and to continue using the original
sublist (though not concurrently).
List Algorithms
Most polymorphic algorithms in the Collections class apply specifically to
List. Having all these algorithms at your disposal makes it very easy to
manipulate lists. Here's a summary of these algorithms, which are described in
more detail in the Algorithms section.
76
}
}
}
Exception in Java
-
Exception Object
-
77
Sample Code
The basic syntax to handle an Exception looks like this:
String myException()
{
try
{
return myMethod();
}
catch ( IOException e )
{
return null;
}
}
There are three types of Exceptions:
Checked Exceptions
78
These are the exceptions which occur during the compile time of the
program.
The compiler checks at the compile time that whether the program
contains handlers for checked exceptions or not. These exceptions do
not extend RuntimeException class and must be handled to avoid a
compile-time error by the programmer.
These exceptions extend the java.lang.Exception class These
exceptional conditions should be anticipated and recovered by an
application.
Furthermore Checked exceptions are required to be caught. Remember
that all the exceptions are checked exceptions unless and until those
indicated by Error, RuntimeException or their subclasses.
79
Exceptions are thrown if any kind of unusual condition occurs that can
be caught.
Sometimes it also happens that the exception could not be caught and
the program may get terminated.
Remember that they are a member of Exception family and can be of
type Checked or Unchecked exception.
Exceptions
Errors
-
When any kind of serious problem occurs which could not be handled
easily like OutOfMemoryError then an error is thrown.
80
Well, errors are not something which is thrown by you rather they are
thrown by the Java API or by the Java virtual machine itself i.e. only
the exceptions are thrown by your code and not the errors.
Also Remember that they are a member of Error family.
The exception classes can be explained as well seeing the hierarchy structure:
The java.lang package defines several classes and exceptions. Some of these classes are
not checked while some other classes are checked.
EXCEPTIONS
DESCRIPTION CHECKED UNCHECKED
Arithmetic
ArithmeticException
errors such as aYES
divide by zero
Arrays index is
ArrayIndexOutOfBoundsException not
withinYES
array.length
Related Class
ClassNotFoundException
YES
not found
InputOuput
IOException
YES
field not found
Illegal argument
IllegalArgumentException
when calling aYES
method
One thread has
been interrupted
InterruptedException
YES
by
another
thread
NoSuchMethodException
Nonexistent
YES
-
81
NullPointerException
NumberFormatException
method
Invalid use of
null reference
Invalid
string
for conversionto number
YES
YES
Exceptions are Objects that means an object is thrown when you throw
an exception.
Moreover only those objects could be thrown whose classes are
derived from Throwable.
Objects of your own design could also be thrown provided that they
should be the subclass of some member of the Throwable family.
Also the throwable classes which are defined by you must extend
Exception class.
java.lang
or
create
any
of
your
own.
Such
as
IllegalArgumentException, a subclass of RuntimeException in
java.lang can be thrown if any method with an invalid argument is
thrown .
82
The three exception handler components are used to catch and handle
the exceptions.
These are try, catch and finally clause.
The mechanism to catch an exception in Java is to use try and catch
block.
Every catch block can handle only one type of exception however you
can use more than one catch clause in a single try block.
Simply a statement is surrounded by the try block that may cause the
exception to occur.
Then the try block is followed by the catch block.
And if the exception occurs then this catch block specifies a code that
should be executed.
Using try and catch:The syntax for the usage of try, catch and finally block is given below.
try{
}
catch(<exceptionclass1> <obj1>)
{
}
finally
{
}
-
83
For doing this we need to have one or more catch blocks after the try
block, where each catch block acts as an exception handler and can
handle the type of exception indicated by its arguments.
import java.io.*;
class Test
{
public static void main(String args[])throws IOException
{
FileInputStream fis=null;
try
{
fis = new FileInputStream (new File (args[0]));
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
finally
{
fis.close();
}
}
}
Using finally:
-
It is always a good practice to use finally clause after the try and catch
block because the finally block always executes even if an unexpected
exception occurs i.e. whether or not an exception thrown.
The finally block executes if and only if the try block exits.
Other than exception handling the finally clause helps you in avoiding
any cleanup code accidentally bypassed by a return etc.
The statements within the finally block gets executed by the the
runtime system without taking care of what happens within the try
block.
84
Secondly after the try block exits place the code that must be executed in a finally clause.
import java.io.*;
class Test
{
public static void main(String args[])
{
FileInputStream fis=null;
try
{
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1)
{
System.out.print ((char) ch);
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
catch (IOException e)
{
System.out.println("Unable to read file!");
}
finally{
System.out.println();
System.out.println("In finally.");
try{
if(fis!=null){
fis.close();
}
}
catch (IOException ioe)
{
System.out.println("In finally.");
}
}
}
}
-
85
If you decide that you can't handle the exception properly, then the
exception can be declared to the method header using the throws
keyword followed by the class name of the exception.
Add the throws clause to the surrounding method to pass the error up
to the next level (or else write your own catch/try handler).
While the throw keyword (note the singular form) is used to force an
exception.
import java.io.*;
class Test3
{
public static void main(String args[]) throws
FileNotFoundException,IOException
{
FileInputStream fis=null;
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1){
System.out.print ((char) ch);
}
fis.close();
}
}
How to Throw Exceptions
-
Throwable class.
throw new VeryFastException();
Note: The reference should be of type Throwable or one of its subclasses.
class MyException extends Exception
{
public MyException(String msg)
{
super(msg);
}
}
86
We can have multiple catch blocks for a particular try block to handle
many different kind of exceptions that may be generated while running
the program
}
catch(<exceptionclass_1> <obj1>){
//statements to handle the exception
}
catch(<exceptionclass_2> <obj2>){
//statements to handle the exception
}
catch(<exceptionclass_N> <objN>){
//statements to handle the exception
}
87
The multiple catch blocks can generate unreachable code error i.e. if
the first catch block contains the Exception class object then the
subsequent catch blocks are never executed.
This is known as Unreachable code problem.
To avoid this, the last catch block in multiple catch blocks must
contain the generic class object that is called the Exception class.
88
This exception class being the super class of all the exception classes
and is capable of catching any types of exception.
In Java we can have nested try and catch blocks. It means that, a try
statement can be inside the block of another try.
If an inner try statement does not have a matching catch statement for
a particular exception, the control is transferred to the next try
statements catch handlers that are expected for a matching catch
statement.
This continues until one of the catch statements succeeds, or until all
of the nested try statements are done in.
If no one catch statements match, then the Java run-time system will
handle the exception.
89
}
}
}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index is Out of bound! Argument required");
}
catch(Exception e){
System.out.println("Error.."+e);
}
The above code displays a for loop trying to divide a number by zero
in its last iteration which would result in runtime exception.
We have used try block to handle this exception and a corresponding
handler by means of a catch clause.
90
And if we won't handle the exception the program will end up with the
termination.
The disadvantage in handling the runtime exception is that we need to
put the doubtful code inside a try block.
This approach sometimes causes a mess so its always better to avoid
the problems which land you up with the troubles.
If you can't find the appropriate exception in the Java API, you can
code a class that defines an exception that is more appropriate and that
mechanism of handling exception is called Custom or User Defined
Exception.
In Java API all exception classes have two type of constructor.
First is called default constructor that doesn't accept any arguments.
Another constructor accepts a string argument that provides the
additional information about the exception.
MyException,IOException
{
String temp="";
try
{
String str="amit";
System.out.println("Enter the your name");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
temp=br.readLine();
if(!temp.equals(str))
throw new MyException();
else
System.out.println("Welcome to India");
}
catch(MyException e)
{
System.err.println(e.getMessage(temp));
}
catch(Exception e)
{
System.err.println(e);
}
}
}
92
Throwable getCause()
The methods of the Throwable class are:
METHOD
DESCRIPTION
Returns the exception followed by a message string (if
toString()
one exit) .
getMessage()
printStackTrace()
GetCause()
InitCause()
The syntax for using a chained exception is as follows in which a new TestException
exception is created with the attached cause when an IOException is caught. Thus the
chain exception is thrown to next level of exception handler.
try
{ }
catch (IOException e)
{
throw new TestException("Other IOException", e);
}
Lets see an example having the implementation of chained exceptions:
93
import java.io.*;
import java.util.*;
class MyException extends Exception{
MyException(String msg){
super(msg);
}
}
public class ChainExcep{
public static void main(String args[])throws MyException,
IOException{
try
{
int rs=10/0;
}
catch(Exception e)
{
System.err.println(e.getMessage());
System.err.println(e.getCause());
throw new MyException("Chained ArithmeticException");
}
}
}
How to Print a Stack Trace Message
-
Try {
// ......
}
catch (IOException e) {
// ...........
System.out.println("Got an IOException: " +
e.getMessage());
}
Instead of this method you can get more information about the error
process if you print a stack trace from the exception using the
printStackTrace() method
That is the method of the Throwable class and prints the stack trace to
the console and provides the line numbers of statements that called the
methods in the current stack.
94
MultiThreading
Multitasking
-
Multitasking allow to execute more than one tasks at the same time, a
task being a program.
In multitasking only one CPU is involved
Multitasking allow processes (i.e. programs) to run concurrently on the
program.
For Example running the spreadsheet program and you are working
with word processor also.
Multitasking is running heavyweight processes by a single OS.
Multithreading :
-
95
Process
-
Thread
-
Main Thread
-
96
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.
97
Blocked
-
A thread can enter in this state because of waiting the resources that
are hold by another thread.
Sleeping
-
On this state, the thread is still alive but it is not runnable, it might be
return to runnable state later, if a particular event occurs.
On this state a thread sleeps for a specified amount of time.
the method sleep( ) can be used to stop the running state of a thread.
99
100
101
if (!db.isAlive())
System.out.println("Thread B not alive.");
} catch (Exception e) { }
System.out.println("Exit from Main Thread.");
Several
constructors
are
available
for
creating
new
Thread
instances.
Thread()
Thread(String)
Thread(Runnable)
Thread(Runnable,String)
Thread(ThreadGroup,String)
Thread(ThreadGroup,Runnable)
Thread(ThreadGroup,Runnable,String)
Thread(ThreadGroup, Runnable, String, long)
ThreadGroup
-
Then the newly formed group2 comes under group1. If you want a
parent group other than default then you have to specify the parent
group at the time of creation.
102
103
Thread Priorities
- In Java, thread scheduler can use the thread priorities in the form of
integer value to each of its thread to determine the execution schedule
of threads .
- Thread gets the ready-to-run state according to their priorities.
- The thread scheduler provides the CPU time to thread of highest
priority during ready-to-run state.
- Priorities are integer values from 1 (lowest priority given by the
constant Thread.MIN_PRIORITY) to 10 (highest priority given by the
constant Thread.MAX_PRIORITY).
- The default priority is 5(Thread.NORM_PRIORITY).
Constant
Description
The methods that are used to set the priority of thread shown as:
Method
Description
104
When a Java thread is created, it inherits its priority from the thread
that created it.
when multiple threads are ready to be executed, the runtime system
chooses the runnable thread with the highest priority for execution.
In Java runtime system, preemptive scheduling algorithm is applied. If
at the execution time a thread with a higher priority and all other
threads are runnable then the runtime system chooses the new higher
priority thread for execution.
On the other hand, if two threads of the same priority are waiting to be
executed by the CPU then the round-robin algorithm is applied in
which the scheduler chooses one of them to run according to their
round of time-slice.
Thread Scheduler
-
105
}
}
DeadLock
-
In this diagram two threads having the Printing & I/O operations
respectively at a time.
But Thread1 need to printer that is hold up by the Thread2, likewise
Thread2 need the keyboard that is hold up by the Thread1.
106
In this situation the CPU becomes ideal and the deadlock condition
occurs because no one thread is executed until the hold up resources
are free.
The following program demonstrates the deadlock situation:
public class DeadDemo{
public static void main(String args[]){
String s1="Dead";
String s2="Lock";
MyThread1 m=new MyThread1(s1,s2);
MyThread2 m1=new MyThread2(s1,s2);
}
}
class MyThread1 extends Thread{
String s1;
String s2;
MyThread1(String s1, String s2){
this.s1=s1;
this.s2=s2;
start();
}
public void run(){
while(true){
synchronized(s1){
synchronized(s2){
System.out.println(s1+s2);
}
}
}
}
}
class MyThread2 extends Thread{
String s1;
String s2;
MyThread2(String s1,String s2){
this.s1=s1;
this.s2=s2;
start();
}
public void run(){
while(true){
synchronized(s2){
}
}
synchronized(s1){
System.out.println(s2+s1);
}
107
Synchronized Threads
-
When the two threads are executed to access these methods (one for
increment( ),another for decrement( )) then both will share the variable
"count". in that case, we can't be sure that what value will be returned
of variable "count".
We can see this problem in the diagram shown below:
108
Lock:
-
Lock term refers to the access granted to a particular thread that can
access the shared resources.
At any given time, only one thread can hold the lock and thereby have
access to the shared resource.
Every object in Java has build-in lock that only comes in action when
the object has synchronized method code.
By associating a shared resource with a Java object and its lock, the
object can act as a guard, ensuring synchronized access to the
resource.
Only one thread at a time can access the shared resource guarded by
the object lock.
Since there is one lock per object, if one thread has acquired the lock,
no other thread can acquire the lock until the lock is not released by
first thread.
Acquire the lock means the thread currently in synchronized method
and released the lock means exits the synchronized method.
109
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.
Note : If a thread goes to sleep, it holds any locks it has,it doesn't release them.
A thread can acquire more than one lock.
Constructors cannot be synchronized
There are two ways to synchronized the execution of code:
Synchronized Methods
Synchronized Blocks (Statements)
Synchronized Methods:
wait.
-
110
Inter-Thread Communication
-
111
Method
Description
It indicates the calling thread to give up the monitor and
Wait( ) go to sleep until some other thread enters the same monitor
and calls method notify() or notifyAll().
It wakes up the first thread that called wait() on the same
notify( )
object.
notifyAll( Wakes up (Unloack) all the threads that called wait( ) on
)
the same object. The highest priority thread will run first.
All these methods must be called within a try-catch block.
Lets see an example implementing these methods :
class Shared {
int num=0;
boolean value = false;
synchronized int get() {
if (value==false)
try {
wait();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("consume: " + num);
value=false;
notify();
return num;
}
synchronized void put(int num) {
if (value==true)
try {
wait();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.num=num;
System.out.println("Produce: " + num);
value=false;
notify();
}
}
class Producer extends Thread {
Shared s;
Producer(Shared s) {
this.s=s;
this.start();
112
}
public void run() {
int i=0;
s.put(++i);
}
}
class Consumer extends Thread{
Shared s;
Consumer(Shared s) {
this.s=s;
this.start();
}
Daemon Threads
-
113
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException x) {
}
System.out.println("In run method: woke up again");
}
} finally {
System.out.println("Leaving run Method");
}
}
public static void main(String[] args) {
System.out.println("Entering main Method");
DaemonThread t = new DaemonThread();
t.setDaemon(true);
t.start();
try {
Thread.sleep(3000);
} catch (InterruptedException x) {
}
System.out.println("Leaving main method");
}
}
Files (IOStreams)
Introduction
-
The java.io package can be categories along with its stream classes in a hierarchy
structure shown below:
114
InputStream:
-
The InputStream class is used for reading the data such as a byte and
array of bytes from an input source.
An input source can be a file, a string, or memory that may contain the
data. It is an abstract class that defines the programming interface for
all input streams that are inherited from it. An input stream is
automatically opened when you create it.
close a stream with the close( ) method,
The subclasses inherited from the InputStream class can be seen in a
hierarchy manner shown below:
115
Java uses streams to handle I/O operations through which the data is
flowed from one location to another.
For example, an InputStream can flow the data from a disk file to the
internal memory and an OutputStream can flow the data from the
internal memory to a disk file.
116
The working process of the I/O streams can be shown in the given diagram.
BufferedReader
This class provides read text from character
input stream and buffering characters. It also
reads characters, arrays and lines.
BufferedWriter
This class provides write text from character
output stream and buffering characters. It also
writes characters, arrays and lines.
ByteArrayInputStream
ByteArrayOutputStream
117
CharArrayReader
CharArrayWriter
DataInputStream
DataOutputStream
File
FileDescriptor
FileInputStream
FileOutputStream
FilePermission
FileReader
FileWriter
FilterInputStream
FilterOutputStream
FilterReader
FilterWriter
InputStream
InputStreamReader
LineNumberReader
ObjectInputStream
ObjectInputStream.GetField
ObjectOutputStream
class.
It used for char input stream and implements
a character buffer.
This class also implements a character buffer
and it uses an writer.
This class reads the primitive data types from
the input stream in a machine format.
This class writes the primitive data types
from the output stream in machine format.
This class shows a file and directory
pathnames.
This class uses for create a FileInputStream
and FileOutputStream.
It contains the input byte from a file and
implements an input stream.
It uses for writing data to a file and also
implements an output stream.
It provides the permission to access a file or
directory.
This class used for reading characters file.
This class used for writing characters files.
This class overrides all methods of
InputStream and contains some other input
stream.
This class overrides all methods of
OutputStream and contains some other output
stream.
It reads the data from the filtered character
stream.
It writes data from the filtered character
stream.
This class represents an input stream of bytes.
It reads bytes and decodes them into
characters.
This class has a line numbers
This class used for recover the object to
serialize previously.
This class access to president fields read form
input stream.
This class used for write the primitive data
types and also write the object to read by the
118
ObjectOutputStream.GetField
ObjectStreamClass
ObjectStreamField
OutputStream
OutputStreamWriter
PipedInputStream
PipedOutputStream
PipedReader
PipedWriter
PrintStream
PrintWriter
PushbackInputStream
PushbackReader
RandomAccessFile
Reader
SequenceInputStream
SerializablePermission
StreamTokenizer
StringReader
StringWriter
Writer
ObjectInputStream.
This class access to president fields write in
to ObjectOutput.
Serialization's descriptor for classes.
This class describes the serializable field.
This class represents an output stream of
bytes.
It writes bytes and decodes them into
characters.
In this class the data bytes are written into
piped output stream. This class also
connected into a piped output stream.
This class also communicates the piped input
stream into piped output stream. It creates
communication between both.
It is a piped character-input stream.
It is a piped character-output stream.
This class adds the functionality of another
output stream.
This class adds the functionality of another
input stream.
It also include the another function of input
stream. Such as: "push back" or "unread" one
byte.
This is a character stream reader and reads
the data push back into the stream.
It supports both reading and writing to a
random access file.
It used for reading character stream.
It represents the logical concatenation of
other input stream.
This is a serializable permission class.
It takes an input stream and parse it into
"tokens" . The token to be allowed at the read
time.
This is a character string class. It has
character read source.
This is also a character string class. It uses to
shows the output in the buffer.
It uses for writing to character stream.
119
Interfaces:
The following summary of Interfaces provided by the java.io package shown in the table:
Interface
Description
DataInput
This interface can be used for reading byte stream
and reconstructing the java primitive data types.
DataOutput
Externalizable
FileFilter
FilenameFilter
ObjectInput
ObjectInputValidation
ObjectOutput
ObjectStreamConstants
Serializable
in
the
Exceptions Classes:
The following summary of the exception classes provided by the java.io package shown
in the table:
Exceptions
Description
CharConversionException
It provides detail message in the catch block
to
associated
with
the
CharConversionException
EOFException
This exception indicates the end of file.
When the file input stream to be end then
EOFException to be occuted.
120
FileNotFoundException
InterruptedIOException
InvalidClassException
InvalidObjectException
IOException
NotActiveException
The
Serialization
or
deserialization
operations are not active then it occurs.
NotSerializableException
ObjectStreamException
OptionalDataException
When the reading data operations to failed
then it these exception occurs. It is
belonging to the serialized object
StreamCorruptedException
SyncFaieldException
UnsupportedEncodingException
UTFDataFormatException
WriteAbortedException
then
operating.
Java provides the standard I/O facilities for reading text from either the
file or the keyboard on the command line.
- The Reader class is used for this purpose that is available in the java.io
package.
- It acts as an abstract class for reading character streams.
- The only methods that a subclass must implement are read(char[], int,
int) and close(). the Reader class is further categorized into the
subclasses.
The following diagram shows a class-hierarchy of the java.io.Reader class.
122
However, most subclasses override some of the methods in order to provide higher
efficiency, additional functionality, or both.
InputStreamReader:
-
123
Method
Return Type
Description
read( )
read(char[] cbuf,
int len)
int
int
readLine( )
String
close( )
void
int off,
This program illustrates you how to use standard input stream to read the user input..
import java.io.*;
public class ReadStandardIO{
public static void main(String[] args) throws IOException{
InputStreamReader
inp
=
new InputStreamReader(System.in)
BufferedReader br = new BufferedReader(inp);
System.out.println("Enter text : ");
}
}
Streams don't support all the operations that are common with a disk
file
In lesson, we will learn how to work with a file using the non-stream
file I/O.
The File class deals with the machine dependent files in a machineindependent manner i.e. it is easier to write platform-independent code
that examines and manipulates files using the File class.
This class is available in the java.lang package.
The java.io.File is the central class that works with files and
directories.
When a File object is created, the system doesn't check to the existence
of a corresponding file/directory.
124
If the file exist, a program can examine its attributes and perform
various operations on the file, such as renaming it, deleting it, reading
from or writing to it.
File(path)
File(dirpath,fname)
File(dir, fname)
Create a File
Introduction
-
125
If the mentioned file for the specified directory is already exist then the
createNewFile() method returns the false otherwise the method creates
the mentioned file and return true.
import java.io.*;
public class PathFile{
public static void main(String[] args) throws IOException{
File f;
f=new File("example" + File.separator + "myfile.txt");
f.createNewFile();
System.out.println("New file \"myfile.txt\"
has been created
to the specified location");
System.out.println("The absolute path of the file is: "
+f.getAbsolutePath());
}
}
will learn how to write java program to read file line by line.
FileOutputStream
FileInputstream:
-
FileInputstream(File filename);
FileOutputStream:
-
FileOutputstream(File filename);
DataInputStream:
-
DataInputStream(FileOutputstream finp);
The following program demonstrate, how the contains are read from a file.
This program reads the bytes from file and display it to the user.
127
import java.io.*;
public class ReadFile{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()&& f.length()<0)
System.out.println("The specified file is not exist");
else{
FileInputStream finp=new FileInputStream(f);
byte b;
do{
b=(byte)finp.read();
System.out.print((char)b);
}
while(b!=-1);
finp.close();
}
}
The another program use DataInputStreams for reading textual input line by line with an
appropriate BufferedReader.
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
128
import java.io.*;
public class WriteFile{
public static void main(String[] args) throws IOException{
File f=new File("textfile1.txt");
FileOutputStream fop=new FileOutputStream(f);
if(f.exists()){
String str="This data is written through the program";
fop.write(str.getBytes());
fop.flush();
fop.close();
System.out.println("The data has been written");
}
else
System.out.println("This file is not
exist");
The another way for writing data to a file, the class FileWriter and BufferedWriter are
used.
FileWriter :
-
129
BufferedWriter :
-
Lets see an another example that writes the text input by the user using
the FileWriter and the BufferedWriter class.
import java.io.*;
public class FileWriter{
130
BufferedWriter
-
import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
If the file exists then the length( ) method of the instance of the File
class gives you size of the file.
import java.io.*;
public class FileSize{
public static void main(String[] args) throws IOException{
System.out.print("Enter file name : ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
File f = new File(in.readLine());
if(f.exists()){
long file_size = f.length();
System.out.println("Size of the file : " + file_size);
}
else{
System.out.println("File does not exists.");
}
System.exit(0);
}
}
132
FileNumberReader():
-
import java.io.*;
public class NumberOfLine{
public static void main(String[] args) {
try{
System.out.println("Getting line number of a paritcular file example!");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter file name with extension:");
String str = bf.readLine();
File file = new File(str);
if (file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader ln = new LineNumberReader(fr);
int count = 0;
while (ln.readLine() != null){
count++;
}
System.out.println("Total line no: " + count);
ln.close();
}
else{
System.out.println("File does not exists!");
}
}
catch(IOException e){
e.printStackTrace();
133
}
}
}
134
}
}
}
Applets
Introduction
-
Applet is java program that can be embedded into HTML pages. Java
applets runs on the java enabled web browsers such as mozila and
internet explorer .
Applet can't access system resources on the local computer.
Applets are used to make the web site more dynamic and entertaining.
Advantages of Applet:
Applets are cross platform and can run on Windows, Mac OS and Linux platform
Applets can work all the version of Java Plugin
Applets runs in a sandbox, so the user does not need to trust the code, so it can
work without security approval
Applets are supported by most web browsers
Applets are cached in most web browsers, so will be quick to load when returning
to a web page
User can also have full access to the machine if user allows
135
Applets are designed for the client site programming purpose while the
applications don't have such type of criteria.
Applets are designed just for handling the client site problems. while
the java applications are designed to work with the client as well as
server.
Applications and applets have much of the similarity such as both have
most of the same features and share the same resources.
Applets are not capable of communicating the server than one from
which they are originating.
There are the cases in which an encryption key is used for the
verification purpose for a particular applet to a server. But accessing a
remote server is not possible.
Applet runs in the browser and its lifecycle method are called by JVM
when it is loaded and destroyed.
Here are the lifecycle methods of an Applet:
Introduction
136
init () method: The life cycle of an applet is begin on that time when
the applet is first loaded into the browser and called the init() method.
The init() method is called only one time in the life cycle on an applet.
The init() method is basically called to read the PARAM tag in the
html file.
The init () method retrieve the passed parameter through the PARAM
tag of html file using get Parameter() method
After the initialization of the init() method user can interact with the
Applet and mostly applet contains the init() method.
This method may be called multiples time when the Applet needs to be
started or restarted.
For Example if the user wants to return to the Applet, in this situation
the start Method() of an Applet will be called by the web browser and
the user will be back on the applet.
There is only miner difference between the start() method and stop ()
method.
For example the stop() method is called by the web browser on that
time When the user leaves one applet to go another applet and the
137
start() method is called on that time when the user wants to go back
into the first program or Applet.
-
alternateHTML
If we use this <applet> tag in an HTML page to be viewed by the
browser, probably the browser will ignore the <APPLET> and
<PARAM> tags that doesn't understand the <APPLET> tag. Instead of
interpreting any other HTML code between the <APPLET> and
</APPLET> tags. Java-compatible browsers ignore this extra HTML
code.
138
1. First, add the PARAM tag (with values) to the HTML source file.
2. Second, add necessary code to the applet to retrieve these parameter values.
Lets see how to Pass Parameters to the Applet
<PARAM NAME=param_name VALUE=param_value>
Retrieving Parameters Within the Applet
-
The
method
syntax
String getParameter(String name);
is
the
following:
Don't forget that the parameter names are case-sensitive when passing
parameters to applets.
Introduction
-
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet{
public void paint(Graphics g){
g.drawString("Welcome in Java Applet.",40,20);
}
}
CODE="FirstApplet.class"
WIDTH="800"
Applet viewer is used to view or test the applet whether the applet is
running properly or not.
There are different types of methods for the Graphics class of the
java.awt.*; package have been used to draw the appropriate shape.
Graphics.drawLine():The drawLine() method has been used in the program to draw the
line in the applet. Here is the syntax for the drawLine() method
drawLine(int X_from_coordinate, int Y_from_coordinate, int X_to_coordinate, int
Y_to_coordinate);
Graphics.drawString() :The drawSring() method draws the given string as the parameter.
Here is the syntax of the drawString() method :
drawString(String string, int X_coordinate, int Y_coordinate);
Graphics.drawOval():The drawOval() method draws the circle. Here is the syntax of the
drawOval() method :
g.drawOval(int X_coordinate, int Y_coordinate, int Wdth, int height);
Graphics.drawRect()
The drawRect() method draws the rectangle. Here is the syntax of the
drawRect() method :
g.drawRect(int X_coordinate, int Y_coordinate, int Wdth, int height)
import java.applet.*;
import java.awt.*;
public class CircleLine extends Applet{
int x=300,y=100,r=50;
public void paint(Graphics g){
g.drawLine(3,300,200,10);
g.drawString("Line",100,100);
g.drawOval(x-r,y-r,100,100);
g.drawString("Circle",275,100);
140
g.drawRect(400,50,200,100);
g.drawString("Rectangel",450,100);
141
g.drawString("Line",100,100);
g.drawOval(x-r,y-r,100,100);
g.setColor(Color.yellow);
//Fill the yellow color in circle
g.fillOval( x-r,y-r, 100, 100 );
g.setColor(Color.magenta);
g.drawString("Circle",275,100);
g.drawRect(400,50,200,100);
g.setColor(Color.yellow);
//Fill the yellow color in rectangel
g.fillRect( 400, 50, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangel",450,100);
}
"CENTER"
CODE
"ShapColor.class"
WIDTH
"800">
HEIGHT
Java applet has the feature of retrieving the parameter values passed
from the html page.
So, you can pass the parameters from your html page to the applet
embedded in your page.
For the illustration about the concept of applet and passing parameter
in applet, a example is given below.
In this example, we will see what has to be done in the applet code to retrieve the value
from parameters. Value of a parameter passed to an applet can be retrieved using
getParameter() function. E.g. code:
String strParameter = this.getParameter("Message");
Then in the function paint (Graphics g), we prints the parameter value
to test the value passed from html page.
Applet will display "Hello! Java Applet" if no parameter is passed to
the applet else it will display the value passed as parameter.
In our case applet should display "Welcome in Passing parameter in
java applet example." message.
There is the advantage that if need to change the output then you will
have to change only the value of the param tag in html file not in java
code.
Compile the program :
javac appletParameter.java
143
Alternatively you can also run this example from your favorite java
enabled browser.
Applets are loaded over the internet and they are prevented to make open network
connection to any computer, except for the host, which provided the .class file.
Because the html page come from the host or the host specified codebase
parameter in the applet tag, with codebase taking precedence.
They are also prevented from starting other programs on the client. Applets are
not allowed to invoke any program to list the contents of your file system that
means it cant invoke System.exit() function to terminate you web browser. And
they are not allowed to manipulate the threads outside the applets own thread
group.
Applets are loaded over the net. A web browser uses only one class loader thats
established at start up. Then the system class loader can not be overloaded,
overridden, extended, replaced. Applet is not allowed to create the reference of
their own class loader.
They cant load the libraries or define the native method calls. But if it can define
native method calls then that would give the applet direct access to underlying
computer
The Java Swing supports the plugging between the look and feel
features.
144
The look and feel that means the dramatically changing in the
component like JFrame, JWindow, JDialog etc. for viewing it into the
several types of window.
Interfaces
Action
Descriptions
This interface performed the action with the
ActionListener where the multiple controls are
used for same purposes.
BoundedRangeModel
This interface defines the data model of components
like: sliders and progressBars.
ButtonModel
It defines the state model for the buttons like: radio
buttons, check boxes etc.
CellEditor
This interface used by the developer for creating the
new editor and it has the new components
implement interfaces. The CellEditor implements
the wrapper based approach.
ComboBoxEditor
In this interface, the editor component used to
JComboBox components.
ComboBoxModel
This interface represents the data model in a list
model with the selected items.
DesktopManager
This interface has JDesktopPane object. The
JInternalFrame implements in the JDesktopPane
with the help of DesktopManager.
Icon
This interface used to graphical representation of the
components. It has fixed size picture.
JComboBox.KeySelectionManager This interface has KeySelectionManager and used
for the combo box data model.
ListCellRenderer
This interface used for paint the cell in the list with
the help of "rubber stamps" .
ListModel
This interface used for JList components method. It
gets the value of each cell of list.
ListSelectionModel
This interface indicates the components, which are
stable or not.
MenuElement
This interface used where the any components are
implements in the menu.
MutableComboBoxModel
This interface extends from the ComboBoxModel.
It is a mutable version of ComboBoxModel.
Renderer
It defines the requirements of an object for
145
RootPaneContainer
Scrollable
ScrollPaneConstants
SingleSelectionModel
SwingConstants
UIDefaults.ActiveValue
UIDefaults.LazyValue
WindowConstants
The following classes and it's descriptions to be used by the Java swing.
Classes
AbstractAction
AbstractButton
AbstractCellEditor
AbstractListModel
ActionMap
BorderFactory
Box
Box.Filler
Descriptions
This class handles the any types of action and
provides JFC Action interface.
This class defines the nature of buttons and menu
items.
It provides a list and contents of the data model.
This class defines the data model which provides
the list with its contents.
This class works with InputMap and performs
any action when the key is pressed.
This class extends from Object and creates the
Border instance in the factory.
It provides the fixed spaces between two
components and uses the BoxLayout object of
the layout manager.
This class participates in the Layout and uses the
lightweight components.
146
BoxLayout
JApplet
Jbutton
JCheckBox
JCheckBoxMenuItem
JColorChooser
JComboBox
JComponent
JDesktopPane
Jdialog
JEditorPane
JFileChooser
Jframe
JInternalFrame
JInternalFrame.JDesktopIcon
Jlabel
JLayeredPane
Jlist
Jmenu
JMenuBar
JMenuItem
JOptionPane
Jpanel
JPassworkField
JPopupMenu
JPopupMenu.Separator
JProgressBar
JRadioButton
JRadioButtonMenuItem
JRootPane
JScrollBar
JScrollPane
JSeparator
Jslider
JSplitPane
149
JTabbedPane
Jtable
JTextArea
JTextField
JTextPane
JToggleButton
JToggleButton.ToggleButtonModel
JToolBar
JToolBar.Separator
JToolTip
Jtree
JTree.DynamicUtilTreeNode
JTree.EmptySelectionModel
JViewPort
JWindow
KeyStroke
LayoutFocusTraversalPolicy
LookAndFeel
MenuSelectionManager
OverlayLayout
ProgressMonitor
ProgressMonitorInputStream
150
RepaintManager
ScrollPaneLayout
ScrollPaneLayout.UIResource
SizeRequirements
SizeSequence
SwingUtilities
Timer
ToolTipManager
UIDefaults
UIDefaults.LazyInputMap
UIDefaults.ProxyLazyValue
UIManager
UIManager.LookAndFeelInfo
ViewportLayout
The following Exceptions and it's description to be used by the Java swing.
Exception
Descriptions
This exception occurred when the look and feel
UnsupportedLookAndFeelException
classes are not supported to user's system.
151
The most common way of creating a frame is, using single argument
constructor of the JFrame class.
The frame initially are not visible and to make it visible the
setVisible(true) function is called passing the boolean value true.
The close button of the frame by default performs the hide operation
for the JFrame.
152
Program description:
JOptionPane Class:
-
The window for showing message for input or output makes your
application very innovative.
JOptionPane class is available in the javax.swing.*; package. This class provide various
types of message dialog box as follows:
153
A simple message dialog box which has only one button i.e. "Ok". This type of
message dialog box is used only for showing the appropriate message and user
can finish the message dialog box by clicking the "Ok" button.
A message dialog box which has two or three buttons. You can set several values
for
viewing
several
message
dialog
box
as
follows:
1.) "Yes" and "No"
2.) "Yes", "No" and "Cancel"
3.) "Ok", and "Cancel"
A input dialog box which contains two buttons "Ok" and "Cancel".
import javax.swing.*;
import java.awt.event.*;
public class ShowDialogBox{
JFrame frame;
public static void main(String[] args){
ShowDialogBox db = new ShowDialogBox();
}
public ShowDialogBox(){
frame = new JFrame("Show Message Dialog");
JButton button = new JButton("Click Me");
button.addActionListener(new MyAction());
154
frame.add(button);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
When you run the given program, this shows a button labeled by "Show Input Dialog
Box" on the frame. If you click on the button then a input dialog box will open. If you
click on the "Ok" button of the input dialog button then a message dialog box is seen
which has the message "You entered the text : entered_text" otherwise it will display a
message dialog box that has the message "You pressed cancel button.".
Here is the code of the program:
import javax.swing.*;
import java.awt.event.*;
public class ShowInputDialog{
public static void main(String[] args){
JFrame frame = new JFrame("Input Dialog Box Frame");
JButton button = new JButton("Show Input Dialog Box");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String str = JOptionPane.showInputDialog(null, "Enter some text : ",
Welcome
", 1);
if(str != null)
JOptionPane.showMessageDialog(null, "You entered the text : " + str,
"
Welcome
", 1);
else
JOptionPane.showMessageDialog(null, "You pressed cancel button.",
"
Welcome
", 1);
}
});
155
156
frame.getContentPane().add(new MyComponent());
frame.setSize(400,400);
frame.setVisible(true);
}
public class MyComponent extends JComponent{
public void paint(Graphics g){
int height = 200;
int width = 120;
g.setColor(Color.red);
g.drawRect(10,10,height,width);
g.setColor(Color.gray);
g.fillRect(11,11,height,width);
g.setColor(Color.red);
g.drawOval(250,20, height,width);
g.setColor(Color.magenta);
g.fillOval(249,19,height,width);
}
}
}
157
frame.setVisible(true);
}
158
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)combo.getSelectedItem();
txt.setText(str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
159
combo box at the specified position. This specification of position the item in the combo
box is held by the getItemAt() method as a parameter.
showMessageDialog():
This the method of the JOptionPane class of javax.swing.*; package. This method
displays some messages in the special dialog box. This method holds two argument in
this program in which first is the parent object name and another is the message text
which has to be displayed.
addItem(String):
This is the method of the JComboBox class which adds items to the combo box. This
method takes a string argument which is to be used to add to the combo box.
removeItemAt(index):
This is the method of the JComboBox class which remove the item at the specified
position of the combo box. This method holds the integer value for the position number
of he of the item in combo box to remove it.
Here is the code of the program:
import javax.swing.*;
import java.awt.event.*;
public class AddRemoveItemFromCombo{
JComboBox combo;
JTextField txtBox;
public static void main(String[] args){
AddRemoveItemFromCombo ar = new AddRemoveItemFromCombo();
}
public AddRemoveItemFromCombo(){
JFrame frame = new JFrame("Add-Remove Item of a Combo Box");
String items[] = {"Java", "JSP", "PHP", "C", "C++"};
combo = new JComboBox(items);
JButton button1 = new JButton("Add");
txtBox = new JTextField(20);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (!txtBox.getText().equals("")){
int a = 0;
for(int i = 0; i < combo.getItemCount(); i++){
if(combo.getItemAt(i).equals(txtBox.getText())){
a = 1;
break;
}
}
if (a == 1)
JOptionPane.showMessageDialog(null,"Combo has already this item.");
else
combo.addItem(txtBox.getText());
}
else{
160
}
});
JButton button2 = new JButton("Remove");
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (combo.getItemCount() > 0)
combo.removeItemAt(0);
else
JOptionPane.showMessageDialog(null,"Item not available");
}
});
JPanel panel = new JPanel();
JPanel panel1 = new JPanel();
panel.add(txtBox);
panel.add(combo);
panel.add(button1);
panel.add(button2);
frame.add(panel);
frame.add(panel1);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//
ButtonGroup:
This is the class of the javax.swing.*; package, which is used to create a group of radio
buttons from which you can select only one option from that group of the radio buttons.
This is class is used by creating a instance of if using it's constructor. Radio Buttons are
added to the specified group using the add(JRadioButton) method of the ButtonGroup
class.
JRadioButton:
This is the class has been used to create a single radio button for the application.
setSelected():
This method sets the value of the radio button. This method takes a boolean value either
true or false. If you pass true value then the radio button will be selected otherwise the
radio button is not selected.
Here is the code of program:
import javax.swing.*;
import java.awt.*;
public class CreateRadioButton{
public static void main(String[] args) {
CreateRadioButton r = new CreateRadioButton();
}
public CreateRadioButton(){
JRadioButton Male,Female;
JFrame frame = new JFrame("Creating a JRadioButton Component");
JPanel panel = new JPanel();
ButtonGroup buttonGroup = new ButtonGroup();
Male = new JRadioButton("Male");
buttonGroup.add(Male);
panel.add(Male);
Female = new JRadioButton("Female");
buttonGroup.add(Female);
panel.add(Female);
Male.setSelected(true);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}
In this section, you will learn how to set the tool tip text for items present in the JList
component of the Java Swing. Tool Tip text is the help text of any component for user.
When you rest the mouse cursor on the component then at that point a message which
small font and yellow background stay there for few seconds. This text show the
information about that component.
This program has used the tool tip text for items present in the JList component in Java
Swing. In this program, you can add more and more items. You can enter the item name
in the text box and click on the "Add" button. When you move the mouse pointer around
the items in the list, it shows the specific item name as a tool tip text like the following
image:
163
getElementAt(index):
This is the method of DefaultListModel class which gets the item from the returned list
model by getModel() method according to the given integer index no. as parameter.
addElement(String):
This is the method of DefaultListModel class which adds the item into the list.
Here is the code of the program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TooltipTextOfList{
private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}
public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction extends MouseAdapter implements ActionListener{
public void actionPerformed(ActionEvent ae){
164
}
}
In this program, a Spinner component has been created and set for editing mode of the
Spinner. The Spinner has been disabled for editing using setEditable() method. Some
following methods and APIs are explained as follows:
JFormattedTextField:
This is the class of javax.swing.*; package which creates formatted text field for edit text
in the specified format. For creating a JFormattedTextField, the syntax is written like:
JFormattedTextField tf =
((JSpinner.DefaultEditor)spinner.getEditor()).getTextField();
getTextField():
This method creates a JFormattedTextField for edit in the specified format. This is
defined in the JSpinner.DefaultEditor class.
getEditor():
This is the method of JSpinner class. This method is used to get the editor which has
been using for the JSpinner component.
Here is the code of the program:
165
import javax.swing.*;
import java.awt.*;
public class DesableEditingSpinner{
public static void main(String[] args){
JFrame frame = new JFrame("Desabling editing Spinner");
JSpinner spinner = new JSpinner();
JFormattedTextField tf = ((JSpinner.DefaultEditor)spinner.getEditor())
.getTextField();
tf.setEditable(false);
spinner.setValue(new Integer(100));
JPanel panel = new JPanel();
panel.add(spinner);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
For these purposes, some methods and APIs have been used to create a JSlider
component and performs various tasks related to the slider. Methods and APIs are as
follows:
166
JSlider:
This is the class which creates the slider for the swing application. For creating the slider
this class creates a instance using it's constructor JSlider().
ChangeListener:
This is the interface of which is used to call stateChanged() method which receives the
event generated by the slider using addChangeListener() method of the JSlider class.
ChangeEvent:
This is the class which handle the event generated by the JSlider component on change
the state.
addChangeListener(object):
This is the method of the JSlider class which is used to handle event on change the
selected state of the JSlider component.
Here is the code of the program:
import
import
import
import
javax.swing.*;
javax.swing.event.*;
java.awt.*;
java.awt.event.*;
167
In this section, you can learn how to handle progress bar in java swing. This section
shows you how the progress bar starts and stops with the timer. Through the given
example you can understand how the progress bar is created for showing your work is in
progress.
This program shows you a frame in which a button labeled by the string "Start", a
progress bar and another is the label which has been used to display some messages.
When you click on the "Start" button progress bar is started to progress the completed
process in percent and the label which holds the text "Roseindia.net" is change to with the
label text "Downloading is in process......" in green color and the button is disabled.
When the value of the progress bar is become 100% then the label text of the label is
changed with the text "Downloading completed." in red color and "Start" button is
enabled.
The label display the information about the Downloading process whether completed or
not. But here, nothing is downloading through the program. This message on the label
has been used only for showing in output of the program. For completion the process,
there are some methods and APIs are used in the program has been explained as follows:
JProgressBar:
This is the class which creates the progress bar using it's constructor JProgressBar() to
show the status of your process completion. The constructor JProgressBar() takes two
argument as parameter in which, first is the initial value of the progress bar which is
shown in the starting and another argument is the counter value by which the value of the
progress bar is incremented. Here, the value of the progress bar is incremented by 20.
setStringPainted(boolean):
This is the method of the JProgressBar class which shows the complete process in
percent on the progress bar. It takes a boolean value as a parameter. If you pass the true
then the value will be seen on the progress bar otherwise not seen.
setValue():
This is the method of the JProgressBar class which sets the value to the progress bar.
168
Timer():
This the constructor of the Timer class which starts the timer for timing. This constructor
takes two argument as parameter first is the interval (in milliseconds) of the timer and
second one is the listener object. Time is started using the start() method of the Timer
class.
Here is the code of the program:
import
import
import
import
java.awt.*;
java.awt.event.*;
javax.swing.*;
javax.swing.text.html.*;
169
In this section, you will learn about creation of menus, submenus and Separators in Java
Swing. Menu bar contains a collection of menus. Each menu can have multiple menu
items these are called submenu. Similarly, all menus have multiples menu items. The
Separator divides the menu items in a separate groups like same types of menu Items are
divided into a individual parts. For pictorial representation, the image for the result of the
given program is given below:
170
This program shows how to create menu bar, menus, submenus and Separators. Here, all
items shows on a frame with the help of following methods and APIs:
JMenuBar:
This is the class which constructs a menu bar that contains several menus.
JMenu(String):
This is the constructor of JMenu class. This constructor constructs the new menu. It
takes the string type value which is the name label for the menu.
JMenuItem(String):
This is the constructor of JMenuItem class which constructs new menu items for the
specific menu. It takes string types value which is the label for the menu item.
JSeparator():
This is the constructor of JSeparator class which adds an extra line between menu items.
This line, only separates the menu items.
setJMenuBar():
This method is used to set the menu bar to the specified frame. It takes the object of the
JMenuBar class.
Here is the code of program:
import javax.swing.*;
public class SwingMenu{
public static void main(String[] args) {
SwingMenu s = new SwingMenu();
}
public SwingMenu(){
JFrame frame = new JFrame("Creating a JMenuBar, JMenu, JMenuItem and
seprator Component");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menubar = new JMenuBar();
171
172
This program illustrates you about the creation of the popup menu. Following methods
and APIs have been used in this program for getting popup menu:
JPopupMenu:
This is the class which constructs the popup menu using it's constructor. This class is
helpful to add the object of the JMenuItem class which creates a particular menu.
isPopupTrigger():
This is the method of the MouseEvent class of the java.awt.event.*; package. This
method returns a boolean type value either true or false. This method returns true if the
event is generated when the popup is triggered.
mouseReleased
This is the method of the FormView.MouseEventListener class which is imported from
the javax.swing.text.html.*; package. This method receives the generated mouse event
when the object is release by clicking the mouse.
getX():
This is the method of the MouseEvent class which is imported from the
java.awt.event.*; package. This method returns the integer type value which is the
position on the x-axis for the source component where you click the mouse.
getY():
This is also the method of the the MouseEvent class. This method returns the vertical
positions of the y-coordinate for the source component where you click the mouse.
show(me.getComponent(), me.getX(), me.getY()):
This is the method of JPopupMenu class which displays the popup menu where you
press the right mouse button on the specified location or positions. This positions
calculated by the getX() and getY().
getComponent():
This is the method of the ComponentEvent class of the java.awt.event.*; package. This
method returns the source component of the generated event.
Here is the code of program:
import javax.swing.*;
import java.awt.event.*;
public class PopUpMenu{
JPopupMenu Pmenu;
JMenuItem menuItem;
public static void main(String[] args) {
PopUpMenu p = new PopUpMenu();
}
public PopUpMenu(){
173
174
AWT in Java
-
AWT package is used to develop user interface objects like buttons, checkboxes,
radio buttons and menus etc.
ActionEvent
Adjustable
CompositeContext
ItemSelectable
KeyEventDispatcher
KeyEventPostProcessor
LayoutManager
LayoutManager2
MenuContainer
Paint
PaintContext
PaintGraphics
Shape
AWTEvent
176
AWTEventMulticaster
AWTKeyStroke
AWTPermission
BasicStroke
BorderLayout
BufferCapabilities
BufferCapabilities.FlipContents
Button
Convas
CardLayout
Chaeckbox
CheckboxGroup
CheckboxMenuItem
Choice
177
Color
Component
ComponentOritentation
Container
ContainerOrderFocusTraversalPolicy
Cursor
DefultFocusTraversalPolicy
DefultKeyboardFocusManager
Dialog
Dimension
DisplayMode
Event
178
EventQueue
It is a platform independent
class. It has both classes
underlying peer class and
trusted application class.
This class displays dialog
window. Here user can be
select the file.
This class arrange the
components and flow the left
to right. It uses to write lines
in a paragraph.
This class defines the order in
which components traverse
particular focus cycle root.
This class defines fonts and it
uses render text that is
visible.
This class defines font matrix
object.. It encapsulate the
information and rendering the
paritcular fonts.
This class defines top-level
window and it designs the any
area of border.
With the help of
GradientPaint you fill any
shapes.
This class uses to drawing all
types of graphics such as:
oval, rectangle etc.
This class controls all
geometry, coordinate
transformation, color
management etc. It extends
form the Graphics class.
This class contains a valid
GraphicConfiguration.
This class describes the
characteristics of graphics
destination such as printer and
monitor.
This class describes the
graphics devices and it
FileDialog
FlowLayout
FocusTraversalPolicy
Font
FontMetrics
Frame
GradientPaint
Graphics
Graphics2D
GraphicsConfigTemplate
GraphicsConfiguration
GraphicsDevice
179
GraphicsEnvironment
GridBagConstraints
GridBagLayout
GridLayout
Image
ImageCompabilities
Insets
JobAttributes
JonAttributes.DefaultSelectionType
JobAttributes.DestinatinType
JobAttributes.DialogType
JobAttributes.MultipleDocumentHandlingType
180
JobAttributes.SidesType
KeyboardFocusManager
Label
List
MediaTracker
Menu
MenuBar
MenuComponent
MenuItem
MenuShortcut
PageAttributes
PageAttributes.ColorType
PageAttributes.MediaType
PageAttributes.OrientationRequestedType
181
the java.awt.AttributeValue
package.
It handles the origins and
extends from the
java.awt.AttributeValue
package.
It handles the print qualities
and extends from the
java.awt.AttributeValue
package.
This is a simplest container
class. It includes components
and other panels. It extends
Container and implements to
Accessible.
The point represents the
location of coordinate (x, y)
space. It extends Point2D.
It has two dimensional region
and it bounded by the
multiple number of lines.
It extends the Menu and
specify the positions of
components.
This class executes a print job
and extends from the Object.
A rectangle object has length
and width and it also specify
an area in a coordinate space.
It extends Rectangle2D.
This class contains rendering
hints by using the Graphics2D
class.
This class used to control the
randering and imaging
pipelines.
This class used to generate
the native system input events
and it automatically test the
java platform
implementations.
This class provide the user
interface components and also
PageAttributes.OriginType
PageAttributes.PrintQualityType
Panel
Point
Polygon
PopupMenu
PrintJob
Rectangle
RenderingHints
RenderingHints.Key
Robot
Scrollbar
182
ScrollPane
ScrollPaneAdjustable
SystemColor
TextArea
TextComponent
TextField
TexturePaint
Toolkit
Window
183
This component is generally used to show the text or string in your application and
label never perform any type of action.
Label label_name = new Label ("This is the label text.");
-
2. Buttons : Used to trigger actions and other events required for your application.
The syntax of defining the button is as follows :
-
In the above code we are making three check boxes with the label "One", "Two"
and "Three". If you mention more than one true valued for checkboxes then your
program takes the last true and show the last check box as checked.
4. Text Area: This is the text container component of Java AWT package. The Text
Area contains plain text. TextArea can be declared as follows:
- TextArea txtArea_name = new TextArea();
184
Make the Text Area editable or not using the setEditable (boolean) method.
Pass the boolean valued argument false then the text area will be non-editable
otherwise it will be editable.
The text area is by default in editable mode.
Text are set in the text area using the setText(string) method of the TextArea
class.
5. Text Field: This component contains single line and limited text information.
This is declared as follows :
TextField txtfield = new TextField(20);
import java.awt.*;
import java.applet.Applet;
public class MyButton extends Applet {
public void init() {
Button button = new Button("SUBMIT");
add(button);
}
}
Scrollbar
-
Both the types of Sliders are available i.e. horizontal and vertical.
The subtraction of scrollbar width from the maximum setting gives the maximum
value of the Scrollbar.
185
In the program code, '0' is the <<<<<<< scrollbar.shtml initial value of the
scrollbar, '8' is the width of the scrollbar.
import java.awt.*;
import java.applet.Applet;
public class ScrollbarDemo extends Applet {
public void init() {
Scrollbar sb = new Scrollbar
(Scrollbar.VERTICAL, 0, 8, -100, 100);
add(sb);
}
}
TextField
-
A scrollable text display object with one row of characters is known as the
TextField.
import java.awt.*;
import java.applet.Applet;
public class TextFieldDemo extends Applet{
public void init(){
TextField tf = new TextField("Type in the box");
add(tf);
}
}
186
This Panel is known as Class Applet which is used for running the programs
within the Browser.
All the subclasses of the Container class inherit the behavior of more than 50
common methods of Container.
These subclasses of the container mostly override the method of component.
Some of the methods of container which are most widely used are as follow:
getComponents();
add();
getComponentCount();
getComponent(int);
187
ScrollPane
-
There are many types of events that are generated by your AWT Application.
These events are used to make the application more effective and efficient.
Generally, there are twelve types of event are used in Java AWT. These are as
follows :
1.
2.
3.
4.
5.
6.
7.
8.
ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent
KeyEvent
188
9. MouseEvent
10. PaintEvent
11. TextEvent
12. WindowEvent
These are twelve mentioned events are explained as follows :
1. ActionEvent:
-
2. AdjustmentEvent:
-
This is the AdjustmentEvent class extends from the AWTEvent class. When the
Adjustable Value is changed then the event is generated.
3. ComponentEvent:
-
3. ContainerEvent:
-
4. FocusEvent:
-
5. InputEvent:
-
189
6. ItemEvent:
-
7. KeyEvent:
-
8. MouseEvent:
-
9. PaintEvent:
-
10. TextEvent:
-
11. WindowEvent :
-
190
Events
-
Java awt. Events are the integral part of the java platform.
For any event to occur, the objects registers themselves as listeners.
No event takes place if there is no listener i.e. nothing happens when an event
takes place if there is no listener.
No matter how many listeners there are, each and every listener is capable of
processing an event.
Most of the times every event-type has Listener interface as Events subclass the
AWTEvent class.
PaintEvent and InputEvent don't have the Listener interface because only the
paint() method can be overriden with PaintEvent etc.
Low-level Events
191
FocusEvent
ContainerEvent
KeyEvent
WindowEvent
ComponentEvent
MouseEvent
closing,
Iconifying,
Semantic Events
-
The interaction with GUI component is represented by the Semantic events like
changing the text of a text field, selecting a button etc.
ItemEvent
ActionEvent
TextEvent
AdjustmentEvent
Event Sources
-
If a component is an event source for something then the same happens with its
subclasses.
The different event sources are represented by the following table.
Low-Level Events
192
Window
Container
Component
WindowListener
ContainerListener
ComponentListener
FocusListener
KeyListener
MouseListener
MouseMotionListener
Semantic Events
Scrollbar
TextArea
TextField
Button
List
MenuItem
TextField
Choice
Checkbox
Checkbox
CheckboxMenuItem
List
AdjustmentListener
TextListener
ActionListener
ItemListener
Event Listeners
-
WindowListener
ActionListener
Methods
windowActivated(WindowEvent e)
windowDeiconified(WindowEvent e)
windowOpened(WindowEvent e)
windowClosed(WindowEvent e)
windowClosing(WindowEvent e)
windowIconified(WindowEvent e)
windowDeactivated(WindowEvent e)
actionPerformed(ActionEvent e)
193
adjustmentValueChanged(AdjustmentEvent
e)
mouseClicked(MouseEvent e)
mouseEntered(MouseEvent e)
MouseListener
mouseExited(MouseEvent e)
mousePressed(MouseEvent e)
mouseReleased(MouseEvent e)
focusGained(FocusEvent e)
FocusListener
focusLost(FocusEvent e)
ItemListener
itemStateChanged(ItemEvent e)
KeyListener
keyReleased(KeyEvent e)
keyTyped(KeyEvent e)
keyPressed(KeyEvent e)
componentHidden(ComponentEvent e)
componentMoved(ComponentEvent e)
ComponentListener
componentShown(ComponentEvent e)
componentResized(ComponentEvent e)
MouseMotionListener mouseMoved(MouseEvent e)
mouseDragged(MouseEvent e)
TextListener
textValueChanged(TextEvent e)
ContainerListen er
componentAdded(ContainerEvent e)
componentRemoved(ContainerEvent e)
AdjustmentListener
Event Adapters
-
There are some event listeners that have multiple methods to implement.
That is some of the listener interfaces contain more than one method.
Thus, the methods which you do not want to care about can have empty bodies.
To avoid such thing, we have adapter class.
Generally an adapter class is there for each listener interface having more than
one method.
194
Hence avoiding the implementation of all the methods of the listener interface.
The following example shows the implementation of a listener interface directly.
195
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
String s = ae.getActionCommand();
if (s.equals("Exit")) {
System.exit(0);
}
else if (s.equals("Bonjour")) {
System.out.println("Good Morning");
}
else {
System.out.println(s + " clicked");
}
}
}
GUI-based Applications
-
In this section you will learn about how to create a window for your application.
Define a subclass of Frame to create a window for your application.
One point to remember here is that Applications respond to events in the same
way as applets do.
import java.awt.*;
import java.awt.event.*;
public class ApplicationWindow extends Frame{
public ApplicationWindow(){
super("ApplicationWindow");
setSize(200, 200);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
setVisible(false); dispose();
System.exit(0);
}
});
196
Menus
-
3. Now the MenuItem options can be added to the Menu from top to bottom, using
the following methods.
mi.add(new MenuItem("Open"));
mi.add(new CheckboxMenuItem("Type here"));
4.
Now you can add the Menu to the MenuBar from left to right using mi.add(m);.
5. Finally, you need to add the MenuBar to the Frame by calling the setMenuBar()
method.
The program code given below, creates an application window with a menu bar.
mport java.awt.*;
import java.awt.event.*;
public class MainWindow extends Frame {
public MainWindow() {
super("Menu Window");
setSize(400, 400);
197
198
Pop-up Menus
-
Menu class can only be added to a Frame and not to the Applet.
To add it to the Applet you need to use the Swing component set.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class PopupMenuDemo extends Applet{
Button b;
TextField msg;
PopupAppMenu m;
public PopupMenuDemo(){
setSize(200, 200);
b = new Button("Pop-up Menu");
add(b, BorderLayout.NORTH);
msg = new TextField();
msg.setEditable(false);
add(msg, BorderLayout.SOUTH);
m = new PopupAppMenu(this);
add(m);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
199
});
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
if (e.isPopupTrigger())
m.show(e.getComponent(), e.getX(), e.getY());
}
public void mouseReleased(MouseEvent e){
if (e.isPopupTrigger())
m.show(e.getComponent(), e.getX(), e.getY());
}
});
}
public static void main(String[] args){
PopupMenuDemo app = new PopupMenuDemo();
app.setVisible(true);
}
}
class PopupAppMenu extends PopupMenu
implements ActionListener{
PopupMenuDemo ref;
public PopupAppMenu(PopupMenuDemo ref){
super("File");
this.ref = ref;
MenuItem mi;
add(mi = new MenuItem("Copy"));
mi.addActionListener(this);
add(mi = new MenuItem("Open"));
mi.addActionListener(this);
add(mi = new MenuItem("Cut"));
mi.addActionListener(this);
add(mi = new MenuItem("Paste"));
mi.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
String item = e.getActionCommand();
ref.msg.setText("Option Selected: " + item);
}
}
In the Java AWT, top-level windows are represented by the Frame class. Java
supports the look and feel and decoration for the frame.
The most common method of creating a frame is by using single argument
constructor of the Frame class that contains the single string argument which is
the title of the window or frame.
200
Then you can add user interface by constructing and adding different components
to the container one by one.
The center alignment of the label has been defined by the Label.CENTER. The
frame initially invisible, so after creating the frame it need to visualize the frame
by setVisible(true) method.
add(lbl):
- This method has been used to add the label to the frame. Method add() adds a
component to it's container.
setSize (width, height):
-
This is the method of the Frame class that sets the size of the frame or window.
This method takes two arguments width (int), height (int).
setVisible(boolean):
- This is also a method of the Frame class sets the visibility of the frame. The frame will
be invisible if you pass the boolean value false otherwise frame will be visible.
import java.awt.*;
public class AwtFrame{
public static void main(String[] args){
Frame frm = new Frame("Java AWT Frame");
Label lbl = new Label("Welcome to Tutorial.",Label.CENTER);
frm.add(lbl);
frm.setSize(400,400);
frm.setVisible(true);
}
}
Toolkit class has been used to get the image and then the image is used to display
as frame icon. Toolkit class is used to bind the various components to particular
native toolkit implementations.
getDefaultToolkit():
- This method returns the default toolkit.
getImage(url or filename):
- This method retrieves the pixels data of the image which can be either in format of .gif,
.jpeg or .png. If the security manager installed then the getImage() method first check
201
whether the specified file name has the permission to use and then retrieves the image in
pixels format.
Import
java.awt.*;
If you click on the close button of the frame or window that will be cancelled
automatically. The close button of the frame has to be set for the desired operation
(i.e. closing the frame).
This is done using the addWindowListener() method of the Frame class which
passes the new instance of the WindowAdapter class that uses the
windowClosing() method for receiving the WindowEvent and close the frame or
window.
addWindowListener()
:
- This is the addWindowListener() method which adds the window listener to receive the
window event from the window. This method passes the window listener.
WindowAdapter()
:
- This is the constructor of the WindowAdapter class of the java.awt.event.*; package.
This is an abstract class used for receiving window events.
windowClosing()
:
- This is the windowClosing() method of the WindowAdapter class invoked when the
frame is attempted to close from the window's system menu or close button. This method
receives the WindowEvent object.
Import java.awt.*;
import java.awt.event.*;
public class AwtCloseButtonEvent{
public static void main(String[] args){
Frame frame = new Frame("Close Operation Frame");
202
Container contains several control or tools for develop your application. All the
controls used in your application are the container for one another.
Ex: Three buttons have been added to the panel.
The position for the panel on the frame has been specified south of the frame by
using BorderLayout.SOUTH since the position of the text area has been
specified the center of the frame using BorderLayout.CENTER. Here, the add()
203
method has been used for both operations (add buttons to the panel and add panel
and text area to the frame).
BorderLayout
:
- BorderLayout is the class of the java.awt.*; package which is used to arranging and
resizing it's components to fit in five rigions : north, south, east, west and center.
-
Each region may contain only one component. All regions are represented by the
NORTH, SOUTH, EAST, WEST and CENTER constants of the BorderLayout
class.
import java.awt.*;
import java.awt.event.*;
public class CreateContainer{
public static void main(String[] args){
Panel panel = new Panel();
panel.add(new Button("Button 1"));
panel.add(new Button("Button 2"));
panel.add(new Button("Button 3"));
Frame frame = new Frame("Container Frame");
TextArea txtArea = new TextArea();
frame.add(txtArea, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
The generated focus events are performed by the FocusListener of the object used
in your application using the addFocusListener() method.
The generated event (FocusEvent) is passed to every FocusListener objects that
receives such types of events using the addFocusListener() method of the object.
The addFocusListener() method is takes the instance of MyFcousListener class.
import java.awt.*;
import java.awt.event.*;
204
205
p.add(button, BorderLayout.NORTH);
f.add(p,BorderLayout.NORTH);
lbl = new Label("Roseindia.net");
f.add(lbl, BorderLayout.CENTER);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
f.setSize(400,400);
f.setVisible(true);
}
This example shows you how to handle events in java.awt.*; package. AwtEvent
is the main class of the program which extends from the Frame class implements
the ActionListener interface.
This program starts to run from the main method in which the object for the
AwtEvent class has been created.
The constructor of the AwtEvent class creates two buttons with adding the
addActionListener() method to it.
When you click on the button then the actionPerformed() method is called which
receives the generated event.
This method shows the text of the source of the event on the label.
Import java.awt.*;
import java.awt.event.*;
public class AwtEvent extends Frame implements ActionListener{
206
Label lbl;
public static void main(String argv[]){
AwtEvent t = new AwtEvent();
}
public AwtEvent(){
super("Event in Java awt");
setLayout(new BorderLayout());
try{
Button
button = new Button("INSERT_AN_URL_HERE");
button.addActionListener(this);
add(button, BorderLayout.NORTH);
Button button1 = new Button("INSERT_A_FILENAME_HERE");
button1.addActionListener(this);
add(button1, BorderLayout.SOUTH);
lbl = new Label("Welcome");
add(lbl, BorderLayout.CENTER);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
catch (Exception e){}
setSize(400,400);
setVisible(true);
}
207
txtField.addKeyListener(new MyKeyListener());
add(label, BorderLayout.NORTH);
panel.add(txtField, BorderLayout.CENTER);
add(panel, BorderLayout.CENTER);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setSize(400,400);
setVisible(true);
}
Handling item event through the given program in which, a combo box and a text
area have been taken.
Items of the combo box are as follows : Red, Green, Blue. If you select an item
from the combo box then the message with the item name will be displayed in the
text area.
Choice()
This is the constructor of the Choice class which creates combo box.
ItemEvent :
- This is the ItemEvent class which indicates an event on selecting or deselecting items
from the item group. This event is passed by ItemListener object. The generated event is
passed to all ItemListener objects which is registered to receive such types of event. This
is done using the addItemListener() method of the object.
getItem()
:
- This is the method of the ItemEvent class which returns the value of the selected or
deselected item.
import java.awt.*;
import java.awt.event.*;
public class AwtItemEvent extends Frame{
208
TextArea txtArea;
public AwtItemEvent(String title){
super(title);
txtArea = new TextArea();
add(txtArea, BorderLayout.CENTER);
Choice choice = new Choice();
choice.addItem("red");
choice.addItem("green");
choice.addItem("blue");
choice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
txtArea.setText("This is the " + e.getItem() + " color.\n");
}
});
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
add(choice, BorderLayout.NORTH);
setSize(400,400);
setVisible(true);
setResizable(false);
}
209
l1.setText("Key Typed");
}
public void keyPressed ( KeyEvent e){
l1.setText ( "Key Pressed" ) ;
}
public void keyReleased ( KeyEvent e ){
l1.setText( "Key Released" ) ;
}
public static void main (String[]args ){
new KeyListenerTester ( "Key Listener Tester" ) ;
}
}
In this program, program you will see that only one method of the frame is
important for the purpose.
The following program show a frame titled with "Frame Hiding". When you click
on the close button of the frame, the frame will not be closed but it will hide
certain with holding all frame data as it is.
Method's Description:
getSource(): This is the method of EventObject class. Hence, here this method is used
for the WindowEvent class so, it can return the Form's object that is done invisible by
using the setVisible() method. The getSource() method returns the source of the
generated event.
setVisible(false): This method takes a boolean valued argument which decides the form
for visible or not. If you pass the boolean value false then the form will be invisible
otherwise if you argument is true then the form object will be visible. By default Java
Awt Form is in the invisible state.
import java.awt.*;
import java.awt.event.*;
public class FrameHide{
public static void main(String[] args){
Frame fa= new Frame("Frame Hiding");
Panel p =new Panel();
Label l1=new Label("Welcome");
p.add(l1);
fa.add(p);
fa.setSize(300,200);
fa.setVisible(true);
fa.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
210
}
}
211
CheckBox(): This is the constructors for CheckBox class used for creating checkbox.
The constructor is taking here a String type parameter that is the label of checkbox.
import java.awt.*;
import java.awt.event.*;
public class CheckBoxDemo{
public static void main(String[] args){
Frame frame= new Frame("Checkbox");
Checkbox check=new Checkbox("Welcome");
Checkbox check1=new Checkbox("Roseindia");
frame.add(check);
frame.add(check1);
frame.setLayout(new FlowLayout());
frame.setSize(300,200);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
Paint an Image
- This section provides you to paint an image on the frame. Paint means draw an image
and set its on the frame to the specified location according to its x coordinate and y
coordinate.
212
213