67c6d8f369c6c JAVA - Notes
67c6d8f369c6c JAVA - Notes
DIGITAL NOTES
ON
JAVA PROGRAMMING
TOPIC COVERED
Object Oriented Programming Structure
Overview of Advance Java
1|Page
Java Programming
INDEX
1. OOPs Concept 03 – 54
2. Multithreading 55 - 66
3. Exception Handling 67 - 72
4. AWT 73 - 91
5. Applet 92 - 105
6. Servlets 106 - 110
7. JSP 111 - 126
Java
2|Page
Java Programming
Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling
and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box projects.
The language, initially called Oak after an oak tree that stood outside Gosling's office, also went by the name
Green and ended up later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular platforms.
…………………….
Java is:
Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the
Object model.
Platform independent: Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform independent byte code.
This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform
it is being run.
Simple:Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be
easy to master.
Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.
Architectural-neutral :Java compiler generates an architecture-neutral object file format which makes the
compiled code to be executable on many processors, with the presence of Java runtime system.
Robust:Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time
error checking and runtime checking.
Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks
simultaneously. This design feature allows developers to construct smoothly running interactive
applications.
3|Page
Java Programming
Interpreted:Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an incremental and
light weight process.
High Performance: With the use of Just-In-Time compilers, Java enables high performance.
Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry extensive amount of run-time information that can be used to verify
and resolve accesses to objects on run-time.
Before knowing about compiler and Interpreter we should know about source code.
Java source code is code that you write in the Java programming language.
File name ends with ".java" extension.
Ex: Your_class_name.java
Java source code is converted to Java bytecode by the Java compiler.
File name ends with ".class" extension.
Ex: Your_class_name.class
Machine
Phone Number
Class File
Compiler
Editor Html
Html Editor
Java compiler refers to a program which translates Java language source code into the Java Virtual Machine (JVM)
bytecodes.
"Interpreted" means that the computer looks at the language, and then turns it into native machine language.
4|Page
Java Programming
The term Java interpreter refers to a program which implements the JVM specification and actually executes the bytecodes
Compiling happens when the writing of the program is finished like calling javac.
Example: Trough command line
JAVAC Your_class_name.java
Compilation of java file will generate class file like (ex: Your_class_name.class)
Interpretation happens at runtime(which means while running the Java program),
Example: Trough command line
JAVA Your_class_name
This will take Your_class_name class file (i.e Your_class_name.class) to execute
5|Page
Java Programming
Object
Classlst
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard,
bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
6|Page
Java Programming
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convense the customer differently, to draw something e.g. shape or rectangle etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.n
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.
7|Page
Java Programming
2)OOPs provides data hiding whereas in Procedure-oriented prgramming language a global data can
be accessed from anywhere.
3)OOPs provides ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.
Object based programming language follows all the features of OOPs except Inheritance. JavaScript
and VBScript are examples of object based programming languages.
8|Page
Java Programming
In this page, we will learn about java objects and classes. In object-oriented programming technique,
we design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc.
It can be physical or logical (tengible and intengible). The example of integible object is banking
system.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance(result) of a class.
9|Page
Java Programming
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which
objects are created.
data member
method
constructor
block
class and interface
A variable that is created inside the class but outside the method, is known as instance
variable.Instance variable doesn't get memory at compile time.It gets memory at runtime when
object(instance) is created.That is why, it is known as instance variable.
Method in Java
Advantage of Method
Code Reusability
Code Optimization
new keyword
10 | P a g e
Java Programming
11 | P a g e
Java Programming
Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for
the object that is why it is known as constructor.
12 | P a g e
Java Programming
Constructor is used to initialize the state of an object. Method is used to expose behaviour of
object.
Constructor must not have return type. Method must have return type.
The java compiler provides a default constructor if you don't Method is not provided by compiler in a
have any constructor. case.
Constructor name must be same as the class name. Method name may or may not be same
class name.
There are many ways to copy the values of one object into another in java. They are:
By constructor
By assigning the values of one object into another
13 | P a g e
Java Programming
The static variable can be used to refer the common property of all objects (that is not unique
for each object) e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
14 | P a g e
Java Programming
Before learning java abstract class, let's understand the abstraction in java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
Another way, it shows only important things to the user and hides the internal details for example
sending sms, you just type the text and send the message. You don't know the internal processing
about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
15 | P a g e
Java Programming
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and multiple
inheritance in Java.
The java compiler adds public and abstract keywords before the interface method and public, static and final
keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public and
abstract.
16 | P a g e
Java Programming
17 | P a g e
Java Programming
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java
application, including the following:
18 | P a g e
Java Programming
A main() method is not invoked on an applet, and an applet class will not define main().
When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or
a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of an
applet is often referred to as sandbox security, comparing the applet to a child playing in a
sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
init: This method is intended for whatever initialization is needed for your applet. It is called
after the param tags inside the applet tag have been processed.
start: This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to
other pages.
stop: This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
destroy: This method is only called when the browser shuts down normally. Because applets
are meant to live on an HTML page, you should not normally leave resources behind after a
user leaves the page that contains the applet.
paint: Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.
19 | P a g e
Java Programming
import java.applet.*;
import java.awt.*;
These import statements bring the classes into the scope of our applet class:
java.applet.Applet.
java.awt.Graphics.
Without those import statements, the Java compiler would not recognize the classes
Applet and Graphics, which the applet class refers to.
Get the network location of the HTML file that contains the applet
Fetch an image
20 | P a g e
Java Programming
Additionally, the Applet class provides an interface by which the viewer or browser
obtains information about the applet and controls the applet's execution. The viewer
may:
request information about the author, version and copyright of the applet
The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the
paint method.
Invoking an Applet:
An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Below is an
example that invokes the "Hello, World" applet:
<html>
<hr>
21 | P a g e
Java Programming
</applet>
<hr>
</html>
Note: You can refer to HTML Applet Tag to understand more about calling applet from
HTML.
The code attribute of the <applet> tag is required. It specifies the Applet class to run.
Width and height are also required to specify the initial size of the panel in which an
applet runs. The applet directive must be closed with a </applet> tag.
If an applet takes parameters, values may be passed for the parameters by adding
<param> tags between <applet> and </applet>. The browser ignores text and other
tags between the applet tags.
The viewer or browser looks for the compiled Java code at the location of the document.
To specify otherwise, use the codebase attribute of the <applet> tag as shown:
<applet codebase="http://amrood.com/applets"
If an applet resides in a package other than the default, the holding package must be
specified in the code attribute using the period character (.) to separate package/class
components. For example:
<applet code="mypackage.subpackage.TestApplet.class"
width="320" height="120">
The second color and the size of each square may be specified as parameters to the
applet within the document.
22 | P a g e
Java Programming
CheckerApplet gets its parameters in the init() method. It may also get its parameters
in the paint() method. However, getting the values and saving the settings once at the
start of the applet, instead of at every refresh, is convenient and efficient.
The applet viewer or browser calls the init() method of each applet it runs. The viewer
calls init() once, immediately after loading the applet. (Applet.init() is implemented to
do nothing.) Override the default implementation to insert custom initialization code.
import java.applet.*;
import java.awt.*;
parseSquareSize (squareSizeParam);
setBackground (Color.black);
setForeground (fg);
23 | P a g e
Java Programming
try {
catch (Exception e) {
The applet calls parseColor() to parse the color parameter into a Color value.
parseColor() does a series of string comparisons to match the parameter value to the
name of a predefined color. You need to implement these methods to make this applet
works.
<html>
<title>Checkerboard Applet</title>
<hr>
</applet>
<hr>
</html>
24 | P a g e
Java Programming
Make an HTML page with the appropriate tag to load the applet code.
Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot
be loaded.
Eliminate the main method in the application. Do not construct a frame window for the
application. Your application will be displayed inside the browser.
Move any initialization code from the frame window constructor to the init method of the
applet. You don't need to explicitly construct the applet object.the browser instantiates it for
you and calls the init method.
Remove the call to setSize; for applets, sizing is done with the width and height parameters
in the HTML file.
If the application calls setTitle, eliminate the call to the method. Applets cannot have title
bars. (You can, of course, title the web page itself, using the HTML title tag.)
Event Handling:
Applets inherit a group of event-handling methods from the Container class. The
Container class defines several methods, such as processKeyEvent and
processMouseEvent, for handling particular types of events, and then one catch-all
method called processEvent.
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
implements MouseListener {
StringBuffer strBuffer;
addMouseListener(this);
System.out.println(word);
strBuffer.append(word);
repaint();
26 | P a g e
Java Programming
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);
<html>
<title>Event Handling</title>
<hr>
<applet code="ExampleEventHandling.class"
width="300" height="300">
</applet>
<hr>
</html>
27 | P a g e
Java Programming
Initially, the applet will display "initializing the applet. Starting the applet." Then once
you click inside the rectangle "mouse clicked" will be displayed as well.
Displaying Images:
An applet can display images of the format GIF, JPEG, BMP, and others. To display an
image within the applet, you use the drawImage() method found in the
java.awt.Graphics class.
import java.applet.*;
import java.awt.*;
import java.net.*;
context = this.getAppletContext();
if(imageURL == null)
imageURL = "java.jpg";
try
image = context.getImage(url);
}catch(MalformedURLException e)
e.printStackTrace();
28 | P a g e
Java Programming
context.showStatus("Displaying image");
<html>
<hr>
</applet>
<hr>
</html>
Playing Audio:
An applet can play an audio file represented by the AudioClip interface in the
java.applet package. The AudioClip interface has three methods, including:
public void play(): Plays the audio clip one time, from the beginning.
To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet
class. The getAudioClip() method returns immediately, whether or not the URL resolves
to an actual audio file. The audio file is not downloaded until an attempt is made to
play the audio clip.
import java.applet.*;
29 | P a g e
Java Programming
import java.awt.*;
import java.net.*;
context = this.getAppletContext();
if(audioURL == null)
audioURL = "default.au";
try
clip = context.getAudioClip(url);
}catch(MalformedURLException e)
e.printStackTrace();
if(clip != null)
clip.loop();
if(clip != null)
30 | P a g e
Java Programming
clip.stop();
<html>
<hr>
</applet>
<hr>
</html>
31 | P a g e
Java Programming
If we have to perform only one operation, having same name of the methods increases the readability of
the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments,
if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then
it may be difficult for you as well as other programmers to understand the behaviour of the method
because its name differs. So, we perform method overloading to figure out the program quickly.
In java, Methood Overloading is not possible by changing the return type of the method.
In this example, we have created two overloaded methods, first sum method performs addition of two
numbers and second sum method performs addition of three numbers.
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9.
10. }
11. }
32 | P a g e
Java Programming
Test it Now
Output:30
40
In this example, we have created two overloaded methods that differs in data type. The first sum method
receives two integer arguments and second sum method receives two double arguments.
1. class Calculation2{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(double a,double b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation2 obj=new Calculation2();
7. obj.sum(10.5,10.5);
8. obj.sum(20,20);
9.
10. }
11. }
Test it Now
Output:21.0
40
Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there
may occur ambiguity. Let's see how ambiguity may occur:
1. class Calculation3{
2. int sum(int a,int b){System.out.println(a+b);}
3. double sum(int a,int b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation3 obj=new Calculation3();
7. int result=obj.sum(20,20); //Compile Time Error
8.
9. }
10. }
Test it Now
33 | P a g e
Java Programming
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
Yes, by method overloading. You can have any number of main methods in a class by method overloading.
Let's see the simple example:
1. class Overloading1{
2. public static void main(int a){
3. System.out.println(a);
4. }
5.
6. public static void main(String args[]){
7. System.out.println("main() method invoked");
8. main(10);
9. }
10. }
Test it Now
One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept
by the figure given below:
34 | P a g e
Java Programming
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short
datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float
or double and so on.
Output:40
60
35 | P a g e
Java Programming
If there are matching type arguments in the method, type promotion is not performed.
1. class OverloadingCalculation2{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation2 obj=new OverloadingCalculation2();
7. obj.sum(20,20);//now int arg sum() method gets invoked
8. }
9. }
Test it Now
If there are no matching type arguments in the method, and each method promotes similar number of
arguments, there will be ambiguity.
1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
Test it Now
36 | P a g e
Java Programming
In other words, If subclass provides the specific implementation of the method that has been provided
by one of its parent class, it is known as method overriding.
Let's understand the problem that we may face in the program if we don't use method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5.
6. public static void main(String args[]){
7. Bike obj = new Bike();
8. obj.run();
9. }
10. }
Test it Now
Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is why we
use method overriding.
37 | P a g e
Java Programming
In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method is same and there is IS-A
relationship between the classes, so there is method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10. }
Test it Now
1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
38 | P a g e
Java Programming
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15.
16. class Test2{
17. public static void main(String args[]){
18. SBI s=new SBI();
19. ICICI i=new ICICI();
20. AXIS a=new AXIS();
21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
24. }
25. }
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?
No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it
later.
because static method is bound with class whereas instance method is bound with object. Static belongs
to class area and instance belongs to heap area.
39 | P a g e
Java Programming
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only. We will have detailed learning
of these. Let's first learn the basics of final keyword.
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
40 | P a g e
Java Programming
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
41 | P a g e
Java Programming
Ans) Yes, final method is inherited but you cannot override it. For Example:
1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Test it Now
Output:running...
A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once initialized may
not be changed, it is useful. For example PAN CARD number of an employee.
1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }
42 | P a g e
Java Programming
12. }
Test it Now
Output:70
A static final variable that is not initialized at the time of declaration is known as static blank final variable.
It can be initialized only in static block.
If you declare any parameter as final, you cannot change the value of it.
1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
Test it Now
43 | P a g e
Java Programming
String
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming
language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
Creating Strings:
The most direct way to create a string is to write:
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case,
"Hello world!'.
As with any other object, you can create String objects by using the new keyword and a constructor. The String
class has eleven constructors that allow you to provide the initial value of the string using different sources, such
as an array of characters.
System.out.println( helloString );
hello.
Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a
necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String
Builder Classes.
44 | P a g e
Java Programming
String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor method that
you can use with strings is the length() method, which returns the number of characters contained in the string
object.
After the following two lines of code have been executed, len equals 17:
String Length is : 17
Concatenating Strings:
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method
with string literals, as in:
"Hello, world!"
45 | P a g e
Java Programming
Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a
one-time print statement. For example, instead of:
String fs;
System.out.println(fs);
String Methods:
Here is the list of methods supported by String class:
46 | P a g e
Java Programming
1
char charAt(int index)
3
int compareTo(String anotherString)
5
String concat(String str)
10
boolean equals(Object anObject)
11
boolean equalsIgnoreCase(String anotherString)
47 | P a g e
Java Programming
16
int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
23
int lastIndexOf(Char ch)
Returns the index within this string of the rightmost occurrence of the specified substring.
25
int length()
29
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.
30
String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the
given replacement.
32
String[] split(String regex)
48 | P a g e
Java Programming
33
String[] split(String regex, int limit)
37
String substring(int beginIndex)
38
String substring(int beginIndex, int endIndex)
39
char[] toCharArray()
40
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default
locale.
42
String toString()
43
String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default
locale.
44
String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given
Locale.
49 | P a g e
Java Programming
45
String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
50 | P a g e
Java Programming
Methods
A Java method is a collection of statements that are grouped together to perform an
operation. Ex:- System.out.println()
Creating Method:
Considering the following example to explain the syntax of a method:
// body
Here,
a, b: formal parameters
Method definition consists of a method header and a method body. The same is shown
below:
// method body
modifier: It defines the access type of the method and it is optional to use.
nameOfMethod: This is the method name. The method signature consists of the method
name and the parameter list.
51 | P a g e
Java Programming
Parameter List: The list of parameters, it is the type, order, and number of parameters of
a method. These are optional, method may contain zero parameters.
method body: The method body defines what the method does with statements.
Method Calling:
For using a method, it should be called. There are two ways in which a method is called
i.e. method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then returns
control to the caller in two conditions, when:
System.out.println("This is tutorialspoint.com!");
52 | P a g e
Java Programming
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or
class.
1. private
2. default
3. protected
4. public
The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
53 | P a g e
Java Programming
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
54 | P a g e
Java Programming
Multithreading
Java is a multi-threaded programming language which means we can develop multi
threaded program using Java. A multi threaded program contains two or more parts
that can run concurrently and each part can handle different task at the same time
making optimal use of the available resources specially when your computer has
multiple CPUs.
Multi threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
55 | P a g e
Java Programming
New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task.A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
Terminated ( Dead ): A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order
in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot
guarantee the order in which threads execute and very much platform dependent.
Step 1:
As a first step you need to implement a run() method provided by Runnableinterface.
This method provides entry point for the thread and you will put you complete business
logic inside this method. Following is simple syntax of run() method:
56 | P a g e
Java Programming
Step 2:
At second step you will instantiate a Thread object using the following constructor:
Step 3
Once Thread object is created, you can start it by calling start( ) method, which
executes a call to run( ) method. Following is simple syntax of start() method:
void start( );
Example:
Here is an example that creates a new thread and starts it running:
57 | P a g e
Java Programming
System.out.println("Thread " + threadName + " exiting.");
}
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
58 | P a g e
Java Programming
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Step 1
You will need to override run( ) method available in Thread class. This method
provides entry point for the thread and you will put you complete business logic inside
this method. Following is simple syntax of run() method:
Step 2
Once Thread object is created, you can start it by calling start( ) method, which
executes a call to run( ) method. Following is simple syntax of start() method:
void start( );
Example:
Here is the preceding program rewritten to extend Thread:
59 | P a g e
Java Programming
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
60 | P a g e
Java Programming
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
}
}
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Thread Methods:
Following is the list of important methods available in the Thread class.
Starts the thread in a separate path of execution, then invokes the run()
method on this Thread object.
61 | P a g e
Java Programming
If this Thread object was instantiated using a separate Runnable target, the
run() method is invoked on that Runnable
object.
62 | P a g e
Java Programming
Causes the currently running thread to yield to any other threads of the same
priority that are waiting to be scheduled.
Example:
The following ThreadClassDemo program demonstrates some of thesemethods of the
Thread class. Consider a class DisplayMessage which implements Runnable:
63 | P a g e
Java Programming
System.out.println(message);
}
}
}
Following is the main program which makes use of above defined classes:
64 | P a g e
Java Programming
{
public static void main(String [] args)
{
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
65 | P a g e
Java Programming
This would produce the following result. You can try this example again and again and
you would get different result every time.
66 | P a g e
Java Programming
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked
exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
67 | P a g e
Java Programming
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked
exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java try-catch
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
68 | P a g e
Java Programming
Java try block must be followed by either catch or finally block.
Syntax of java try-catch
Try
{
//code that may throw exception
}
catch(Exception_class_Name ref)
{}
69 | P a g e
Java Programming
{
public static void main(String args[]){
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("task 2 completed");
}
catch(Exception e)
{
System.out.println("common task completed");
}
System.out.println("rest of the code...");
}
}
import java.io.IOException;
class Testthrows1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
Try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");
71 | P a g e
Java Programming
}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
class TestCustomException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
Try
{
validate(13);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}
AWT
72 | P a g e
Java Programming
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-
based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system. AWT is heavy weight i.e. its components are using the resources of underlying
operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there
are classes for each component as shown in above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.
73 | P a g e
Java Programming
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels
etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another
window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like
button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.
Method Description
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default false.
74 | P a g e
Java Programming
// creating a button
Button b = new Button("Click Me!!");
// no layout manager
setLayout(null);
// main method
public static void main(String args[]) {
Output:
75 | P a g e
Java Programming
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();
// no layout
f.setLayout(null);
// main method
public static void main(String args[]) {
AWTExample2 awt_obj = new AWTExample2();
}
} Output:
Event
Change in the state of an object is known as event i.e. event describes the change in state of source. Events
are generated as result of user interaction with the graphical user interface components.
Types of Event
The events can be broadly classified into two categories:
Foreground Events - Those events which require the direct interaction of user.They are generated as
consequences of a person interacting with the graphical components in Graphical User Interface. For
example, clicking on a button, moving the mouse, entering a character through keyboard,selecting
an item from list, scrolling the page etc.
77 | P a g e
Java Programming
Background Events - Those events that require the interaction of end user are known as background
events. Operating system interrupts, hardware or software failure, timer expires, an operation
completion are the example of background events.
Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs.
This mechanism have the code which is known as event handler that is executed when an event occurs. The
Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source object.
Listener - It is also known as event handler.Listener is responsible for generating response to an
event. From java implementation point of view the listener is also an object. Listener waits until it
receives an event. Once the event is received , the listener process the event an then returns.
78 | P a g e
Java Programming
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
For registering the component with the Listener, many classes provide the registration methods. For
example:
o Button
public void addActionListener(ActionListener a){}
o
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
79 | P a g e
Java Programming
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class
tf=new TextField();
tf.setBounds(60,50,170,20);
80 | P a g e
Java Programming
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
81 | P a g e
Java Programming
Layout Manager
The layout manager automatically positions all the components within the container. If we do not use
layout manager then also the components are positioned by the default layout manager. It is possible
to layout the controls by hand but it becomes very difficult because of the following two reasons.
It is very tedious to handle a large number of controls within the container.
Oftenly the width and height information of a component is not given when we need to arrange
them.
Java provide us with various layout manager to position the controls. The properties like size,shape
and arrangement varies from one layout manager to other layout manager. When the size of the
applet or the application window changes the size, shape and arrangement of the components also
changes in response i.e. the layout managers adapt to the dimensions of appletviewer or the
application window.
The layout manager is associated with every Container object. Each layout manager is an object of
the class that implements the LayoutManager interface.
Following are the interfaces defining functionalities of Layout Managers.
1
LayoutManager
The LayoutManager interface declares those methods which need to be
implemented by the class whose object will act as a layout manager.
2
LayoutManager2
The LayoutManager2 is the sub-interface of the LayoutManager.This
interface is for those classes that know how to layout containers based on
layout constraint object.
82 | P a g e
Java Programming
1
BorderLayout
The borderlayout arranges the components to fit in the five regions: east,
west, north, south and center.
2
CardLayout
The CardLayout object treats each component in the container as a card.
Only one card is visible at a time.
3
FlowLayout
The FlowLayout is the default layout.It layouts the components in a
directional flow.
4
GridLayout
The GridLayout manages the components in form of a rectangular grid.
5
GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout
aligns the component vertically,horizontally or along their baseline without
requiring the components of same size.
BorderLayout Manager
When you add a component to the layout, you must specify which area to place it in. BorderLayout
is one of the more unusual layouts provided. It is the default layout for Window, along with its
children, Frame and Dialog. BorderLayout provides 5 areas to hold components. These areas are
named after the four different borders of the screen, North, South, East, and West, with any
83 | P a g e
Java Programming
remaining space going into the Center area. The order in which components are added to the
screen is not important, although you can have only one component in each area. The following
shows a BorderLayout that has one button in each area, before and after resizing.
import java.awt.*;
import java.awt.event.*;
frame.add(pa);
pa.setLayout(new BorderLayout());
pa.add(new Button("India"), BorderLayout.NORTH);
pa.add(new Button("USA"), BorderLayout.SOUTH);
pa.add(new Button("Japan"), BorderLayout.EAST);
pa.add(new Button("China"), BorderLayout.WEST);
pa.add(new Button("Countries"), BorderLayout.CENTER);
frame.setSize(300,300);
frame.setVisible(true);
});
Output
84 | P a g e
Java Programming
USA
85 | P a g e
Java Programming
public class DisplayImage extends Applet
{
Image picture;
public void init()
{
picture = getImage(getDocumentBase(),"desktop.jpg");
}
public void paint(Graphics g)
{
g.drawImage(picture, 30,30, this);
}
}
In the above example, drawImage() method of Graphics class is used to display the image. The 4th argument
of drawImage() method of is ImageObserver object. The Component class implements ImageObserver
interface. So current class object would also be treated as ImageObserver because Applet class indirectly
extends the Component class.
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
Output :
86 | P a g e
Java Programming
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
87 | P a g e
Java Programming
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
Output:
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be moved.
Image picture;
88 | P a g e
Java Programming
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
try{Thread.sleep(100);}catch(Exception e){}
}
}
}
In the above example, drawImage() method of Graphics class is used to display the image. The 4th argument
of drawImage() method of is ImageObserver object. The Component class implements ImageObserver
interface. So current class object would also be treated as ImageObserver because Applet class indirectly
extends the Component class.
myapplet.html
<html>
<body>
<applet code=" AppletAnimationDemo.class" width="300" height="300">
</applet>
</body>
</html>
Output
89 | P a g e
Java Programming
demonstrates how to play a sound using an applet image using getAudioClip(), play() & stop()
methods of AudioClip() class.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
HTML Page
Output
<html>
<body>
<applet code="AppletSoundDemo.class" width="300" height="300">
</applet>
</body>
</html>
90 | P a g e
Java Programming
91 | P a g e
Java Programming
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content.
It runs inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which
is the subclass of Component.
92 | P a g e
Java Programming
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object
that can be used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
93 | P a g e
Java Programming
To execute the applet by html file, create an applet and compile it. After that create an html file and
place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
Note: class must be public because its object is created by Java Plugin software that resides
on the browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and
compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing
purpose only.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
94 | P a g e
Java Programming
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */
c:\>javac First.java
c:\>appletviewer First.java
………………………………………………………………………………………………………………………………….
95 | P a g e
Java Programming
public class GraphicsDemo extends Applet{
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
……………………………………………………………………………………………………………..
96 | P a g e
Java Programming
Image picture;
}
In the above example, drawImage() method of Graphics class is used to display the image. The 4th
argument of drawImage() method of is ImageObserver object. The Component class implements
ImageObserver interface. So current class object would also be treated as ImageObserver because
Applet class indirectly extends the Component class.
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
………………………………………………………………………………………………………..
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be moved.
97 | P a g e
Java Programming
Image picture;
try{Thread.sleep(100);}catch(Exception e){}
}
}
}
In the above example, drawImage() method of Graphics class is used to display the image. The 4th
argument of drawImage() method of is ImageObserver object. The Component class implements
ImageObserver interface. So current class object would also be treated as ImageObserver because
Applet class indirectly extends the Component class.
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
……………………………………………………………………………………………………………………
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
myapplet.html
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>
………………………………………………………………………………………………………………….
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.
99 | P a g e
Java Programming
9. }
10.
11. public void mouseDragged(MouseEvent me){
12. Graphics g=getGraphics();
13. g.setColor(Color.white);
14. g.fillOval(me.getX(),me.getY(),5,5);
15. }
16. public void mouseMoved(MouseEvent me){}
17.
18. }
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis
and y-axis. The getGraphics() method of Component class returns the object of Graphics.
myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
……………………………………………………………………………………
myapplet.html
1. <html>
2. <body>
3. <applet code="DigitalClock.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
……………………………………………………………………
Analog clock can be created by using the Math class. Let's see the simple example:
102 | P a g e
Java Programming
49. seconds = cal.get( Calendar.SECOND );
50.
51. SimpleDateFormat formatter
52. = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
53. Date date = cal.getTime();
54. timeString = formatter.format( date );
55.
56. // Now the thread checks to see if it should suspend itself
57. if ( threadSuspended ) {
58. synchronized( this ) {
59. while ( threadSuspended ) {
60. wait();
61. }
62. }
63. }
64. repaint();
65. t.sleep( 1000 ); // interval specified in milliseconds
66. }
67. }
68. catch (Exception e) { }
69. }
70.
71. void drawHand( double angle, int radius, Graphics g ) {
72. angle -= 0.5 * Math.PI;
73. int x = (int)( radius*Math.cos(angle) );
74. int y = (int)( radius*Math.sin(angle) );
75. g.drawLine( width/2, height/2, width/2 + x, height/2 + y );
76. }
77.
78. void drawWedge( double angle, int radius, Graphics g){
79. angle -= 0.5 * Math.PI;
80. int x = (int)( radius*Math.cos(angle) );
81. int y = (int)( radius*Math.sin(angle) );
82. angle += 2*Math.PI/3;
83. int x2 = (int)( 5*Math.cos(angle) );
84. int y2 = (int)( 5*Math.sin(angle) );
85. angle += 2*Math.PI/3;
86. int x3 = (int)( 5*Math.cos(angle) );
87. int y3 = (int)( 5*Math.sin(angle) );
88. g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
89. g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
90. g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
91. }
92.
93. public void paint( Graphics g ) {
94. g.setColor( Color.gray );
95. drawWedge( 2*Math.PI * hours / 12, width/5, g );
96. drawWedge( 2*Math.PI * minutes / 60, width/3, g );
97. drawHand( 2*Math.PI * seconds / 60, width/2, g );
98. g.setColor( Color.white );
99. g.drawString( timeString, 10, height-10 );
100. }
101. }
103 | P a g e
Java Programming
myapplet.html
1. <html>
2. <body>
3. <applet code="MyClock.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
…………………………………………………………………………………………….
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class provides
a method named getParameter(). Syntax:
1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class UseParam extends Applet{
5.
6. public void paint(Graphics g){
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);
9. }
10.
11. }
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>
…………………………………………………………………………………………………………….
104 | P a g e
Java Programming
Applet Communication
java.applet.AppletContext class provides the facility of communication between applets. We provide the
name of applet through the HTML file. It provides getApplet() method that returns the object of Applet.
Syntax:
105 | P a g e
Java Programming
Servlets
Java Servlets are programs that run on a Web or Application server and act as a middle
layer between a request coming from a Web browser or other HTTP client and
databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets offer several advantages in comparison
with the CGI.
Performance is significantly better.
Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
Servlets are platform-independent because they are written in Java.
Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So servlets are trusted.
The full functionality of the Java class libraries is available to a servlet. It can communicate
with applets, databases, or other software via the sockets and RMI mechanisms that you
have seen already.
Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.
Servlets Tasks:
Servlets perform the following major tasks:
Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the browsers
or other clients what type of document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.
106 | P a g e
Java Programming
Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports
the Java Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.httppackages,
which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications. At the time of writing
this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just like any other Java class. After you
install the servlet packages and add them to your computer's Classpath, you can
compile servlets with the JDK's Java compiler or any other current compiler.
108 | P a g e
Java Programming
Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
Servlets are Java classes which service HTTP requests and implement
thejavax.servlet.Servlet interface. Web application developers typically
writeservlets that extend javax.servlet.http.HttpServlet, an abstract class that
implements the Servlet interface and is specially designed to handle HTTP requests.
109 | P a g e
Java Programming
Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel
(Windows) or /usr/ServletDevel (Unix) then you would need to add these directories
as well in CLASSPATH.
Assuming your environment is setup properly, go in ServletDevel directory and
compile HelloWorld.java as follows:
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on
your CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not
using any other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to work
properly, you have to include the location of the Java SDK that you are using in the
PATH environment variable.
If everything goes fine, above compilation would produce HelloWorld.class file in the
same directory. Next section would explain how a compiled servlet would be deployed
in production.
Servlet Deployment:
By default, a servlet application is located at the path <Tomcat-installation-
directory>/webapps/ROOT and the class file would reside in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet
class must be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes and create following entries
inweb.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags available in web.xml
file. There could be various entries in this table already available, but never mind.
You are almost done, now let us start tomcat server using <Tomcat-installation-
directory>\bin\startup.bat (on windows) or <Tomcat-installation-
directory>/bin/startup.sh (on Linux/Solaris etc.) and finally
typehttp://localhost:8080/HelloWorld in browser's address box. If everything
goes fine, you would get following result:
110 | P a g e
Java Programming
JSP
JavaServer Pages (JSP) is a server-side programming technology that enables the
creation of dynamic, platform-independent method for building Web-based applications.
JSP have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases.
avaServer Pages (JSP) is a technology for developing web pages that support dynamic
content which helps developers insert java code in HTML pages by making use of special
JSP tags, most of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the
role of a user interface for a Java web application. Web developers write JSPs as text
files that combine HTML or XHTML code, XML elements, and embedded JSP actions and
commands.
Advantages of JSP:
Following is the list of other advantages of using JSP over other technologies:
vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part
is written in Java, not Visual Basic or other MS specific language, so it is more powerful and
easier to use. Second, it is portable to other operating systems and non-Microsoft Web
servers.
vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to
have plenty of println statements that generate the HTML.
vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for
"real" programs that use form data, make database connections, and the like.
vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access and image
processing etc.
vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
111 | P a g e
Java Programming
Architecture
The web server needs a JSP engine ie. container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial makes use
of Apache which has built-in JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and
other services a JSP needs. It knows how to understand the special elements that are
part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web
Application.
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and
all JSP elements are converted to Java code that implements the corresponding dynamic
behavior of the page.
112 | P a g e
Java Programming
The JSP engine compiles the servlet into an executable class and forwards the original request
to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format, which the servlet engine
passes to the web server inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally web browser handles the dynamically generated HTML page inside the HTTP response
exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists
and whether the modification date on the JSP is older than the servlet. If the JSP is
older than its generated servlet, the JSP container assumes that the JSP hasn't changed
and that the generated servlet still matches the JSP's contents. This makes the process
more efficient than with other scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to
be a Java programming wiz. Except for the translation phase, a JSP page is handled
exactly like a regular servlet
Life cycle
113 | P a g e
Java Programming
The key to understanding the low-level functionality of JSP is to understand the simple
life cycle they follow.
A JSP life cycle can be defined as the entire process from its creation till the destruction
which is similar to a servlet life cycle with an additional step which is required to compile
a JSP into servlet.
Compilation
Initialization
Execution
Cleanup
The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they
are as follows:
JSP Compilation:
114 | P a g e
Java Programming
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to
compile the page. If the page has never been compiled, or if the JSP has been modified
since it was last compiled, the JSP engine compiles the page.
JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override the jspInit()
method:
// Initialization code...
Typically initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the
jspInit method.
JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the
JSP engine invokes the _jspService() method in the JSP.
HttpServletResponse response)
115 | P a g e
Java Programming
The _jspService() method of a JSP is invoked once per a request and is responsible for
generating the response for that request and this method is also responsible for
generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed
from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Override jspDestroy when you need to perform any cleanup, such as releasing database
connections or closing open files.
JSP Declarations:
A declaration declares one or more variables or methods that you can use in Java code
later in the JSP file. You must declare the variable or method before you use it in the
JSP file.
<jsp:declaration>
code fragment
</jsp:declaration>
116 | P a g e
Java Programming
JSP Expression:
A JSP expression element contains a scripting language expression that is evaluated,
converted to a String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an expression
within a line of text, whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java
Language Specification but you cannot use a semicolon to end an expression.
<jsp:expression>
expression
</jsp:expression>
<html>
<body>
<p>
</p>
</body>
</html>
117 | P a g e
Java Programming
JSP Comments:
JSP comment marks text or statements that the JSP container should ignore. A JSP
comment is useful when you want to hide or "comment out" part of your JSP page.
<html>
<body>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
A Test of Comments
There are a small number of special constructs you can use in various cases to insert
comments or characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
118 | P a g e
Java Programming
JSP Directives:
A JSP directive affects the overall structure of the servlet class. It usually has the
following form:
Directive Description
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used in
the page
JSP Actions:
JSP actions use constructs in XML syntax to control the behavior of the servlet engine.
You can dynamically insert a file, reuse JavaBeans components, forward the user to
another page, or generate HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
Action elements are basically predefined functions and there are following JSP actions
available:
119 | P a g e
Java Programming
Syntax Purpose
Objects Description
120 | P a g e
Java Programming
page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.
We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.
Control-Flow Statements:
JSP provides full power of Java to be embedded in your web application. You can use
all the APIs and building blocks of Java in your JSP programming including decision
making statements, loops etc.
Decision-Making Statements:
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at
each line with HTML text included between Scriptlet tags.
<html>
121 | P a g e
Java Programming
<head><title>IF...ELSE Example</title></head>
<body>
<% } %>
</body>
</html>
Now look at the following switch...case block which has been written a bit differentlty
using out.println() and inside Scriptletas:
<html>
<head><title>SWITCH...CASE Example</title></head>
<body>
<%
switch(day) {
case 0:
out.println("It\'s Sunday.");
break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");
122 | P a g e
Java Programming
break;
case 4:
out.println("It\'s Thursday.");
break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It's Saturday.");
%>
</body>
</html>
It's Wednesday.
Loop Statements:
You can also use three basic types of looping blocks in Java: for, while,and
do…while blocks in your JSP programming.
<html>
<body>
JSP Tutorial
</font><br />
<%}%>
</body>
123 | P a g e
Java Programming
</html>
JSP Tutorial
JSP Tutorial
JSP Tutorial
<html>
<body>
JSP Tutorial
</font><br />
<%fontSize++;%>
<%}%>
</body>
</html>
JSP Tutorial
JSP Tutorial
124 | P a g e
Java Programming
JSP Tutorial
JSP Operators:
JSP supports all the logical and arithmetic operators supported by Java. Following table
give a list of all the operators with the highest precedence appear at the top of the
table, those with the lowest appear at the bottom.
125 | P a g e
Java Programming
JSP Literals:
The JSP expression language defines the following literals:
Integer: as in Java
String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped
as \\.
Null: null
126 | P a g e