Java Programming: OOP Concepts & History
Java Programming: OOP Concepts & History
ON
JAVA PROGRAMMING
OOP Concepts
Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o 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
Collection of objects is called class. It is a logical entity.
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.
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince 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.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Benefits of Inheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code
and smaller, simpler compilation units.
Inheritance can also make application code more flexible to change because classes that
inherit from a common superclass can be used interchangeably. If the return type of a
method is superclass
Reusability - facility to use public methods of base class without rewriting the same.
Extensibility - extending the base class logic as per business logic of the derived class.
JAVA PROGRAMMING PAGE 2
Data hiding - base class can decide to keep some data private so that it cannot be
The history of java starts from Green Team. Java team members (also known as
Green Team), initiated a revolutionary task to develop a language for digital
devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.
2) Originally designed for small, embedded systems in electronic appliances like set-
top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green
project.
There are many java versions that has been released. Current stable release of Java
is Java SE 8.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
11. Multithreaded
[Link]
Java Comments
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for specific time.
3. Documentation Comment
Syntax:
1. //This is single line comment
[Link](i);
Output:
10
Syntax:
/*
This
is
multi line
comment
*/
Example:
int i=10;
[Link](i);
} }
Output:
10
The documentation comment is used to create documentation API. To create documentation API, you need
to use javadoc tool.
Syntax:
/**
This
is
documentation
comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2
numbers.*/ public class Calculator {
javac [Link]
javadoc [Link]
Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML
files and see the explanation of Calculator class provided through documentation comment.
JAVA PROGRAMMING PAGE 7
Data Types
Data types represent the different values to be stored in the variable. In java, there are two types of data types:
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
class Simple{
Output:20
JAVA PROGRAMMING PAGE 8
Variables and Data Types in Java
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
There are two types of data types in java: primitive and non-primitive.
Types of Variable
o local variable
o instance variable
o static variable
1)Local Variable
2) Instance Variable
A variable which is declared inside the class but outside the method, is called instance variable . It
is not declared as static.
3) Static variable
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Constants in Java
A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.
Syntax
Instance variables
Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the
class (object) contains a copy of these variables. The scope of instance variables is determined
by the access specifier that is applied to these variables. We have already seen about it earlier.
The lifetime of these variables is the same as the lifetime of the object to which it belongs.
Object once created do not exist for ever. They are destroyed by the garbage collector of Java
when there are no more reference to that object. We shall see about Java's automatic garbage
collector later on.
Argument variables
These are the variables that are defined in the header oaf constructor or a method. The scope
of these variables is the method or constructor in which they are defined. The lifetime is
limited to the time for which the method keeps executing. Once the method finishes
execution, these variables are destroyed.
Local variables
A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the method itself.
One important distinction between these three types of variables is that access specifiers can
be applied to instance variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are defined
in bocks life an if block and an else block. The scope and is the same as that of the block
itself.
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
o Unary Operator,
o Arithmetic Operator,
o shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Assignment Operator.
Operators Hierarchy
JAVA PROGRAMMING PAGE 11
EXPRESSIONS
Expressions are essential building blocks of any Java program, usually created to produce a
new value, although sometimes an expression simply assigns a value to a variable. Expressions
are built using values, variables, operators and method calls.
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three types
of expressions in Java:
Those that have no result but might have a "side effect" because an expression can include
a wide range of elements such as method invocations or increment operators that modify
the state (i.e. memory) of a program.
Widening conversion takes place when two data types are automatically converted. This happens
when:
The two data types are compatible.
When we assign value of a smaller data type to a bigger data type.
For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.
This is useful for incompatible data types where automatic conversion cannot be done.
Here, target-type specifies the desired type to convert the specified value to.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST)
etc. The java enum constants are static and final implicitly. It is available from JDK 1.5.
Java Enums can be thought of as classes that have fixed set of constants.
class EnumExample1{
[Link](s);
}}
Output:
WINTER
SPRING
SUMMER
FALL
The control flow statements in Java allow you to run or skip blocks of code when
special conditions are met.
The “if” statement in Java works exactly like in most programming languages. With the help of
“if” you can choose to execute a specific block of code when a predefined condition is met.
The structure of the “if” statement in Java looks like this:
if (condition) {
// execute this code
9. If you're using Windows, you will need to set your path to include Java, if you haven't
done so already. This is a delicate operation. Open Explorer, and look inside
C:\ProgramFiles\Java, and you should see some version of the JDK. Open this folder, and
then open the bin folder. Select the complete path from the top of the Explorer window,
and press Ctrl-C to copy it.
Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and
select properties. Click on the Advanced tab, and then click on the Environment variables
button. Look at the variables listed for all users, and click on the Path variable. Do not delete
the contents of this variable! Instead, edit the contents by moving the cursor to the right end,
entering a semicolon (;), and pressing Ctrl-V to paste the path you copied earlier. Then go
ahead and save your changes. (If you have any Cmd windows open, you will need to close
them.)
10. If you're using Windows, go to the Start menu and type "cmd" to run a program
that brings up a command prompt window. If you're using a Mac or Linux machine,
run the Terminal program to bring up a command prompt.
11. In Windows, type dir at the command prompt to list the contents of the current directory.
On a Mac or Linux machine, type ls to do this.
cd Desktop
cd ..
Every time you change to a new directory, list the contents of that directory to see where to go
next. Continue listing and changing directories until you reach the directory that contains your
.class files.
13. If you compiled your program using Java 1.6, but plan to run it on a Mac, you'll need
to recompile your code from the command line, by typing:
14. Now we'll create a single JAR file containing all of the files needed to run your program.
Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:
or
arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate
C/C++ programmers.
Example:
JAVA PROGRAMMING PAGE 15
The following code snippets are examples of this syntax:
Creating Arrays:
You can create an array by using the new operator with the following syntax:
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to [Link]-1.
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of double
type and assigns its reference to myList:
Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.
JAVA PROGRAMMING PAGE 16
Processing Arrays:
When processing array elements, we often use either for loop or for each loop because all of the
elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
double total = 0;
total += myList[i];
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
[Link](element);
}}}
The Java Console class is be used to get input from console. It provides methods to read texts and
passwords.
If you read password using Console class, it will not be displayed to the user.
The [Link] class is attached with system console internally. The Console class is
introduced since 1.5.
1. String text=[Link]().readLine();
import [Link];
class ReadStringTest{
String n=[Link]();
[Link]("Welcome "+n); } }
Constructors
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.
2. Parameterized constructor
1. <class_name>(){}
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
class Bike1{
Bike1(){[Link]("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
} }
Output: Bike is created
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
class Student4{
int id;
String name;
Output:
111 Karan
222 Aryan
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter [Link] compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
Output:
111 Karan 0
222 Aryan 25
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the [Link]() method, for example, the system actually executes
several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, and apply method abstraction in the program design.
Creating Method
Syntax
// body
Here,
a, b − formal parameters
Method definition consists of a method header and a method body. The same is shown in the
following syntax −
Syntax
}
The syntax shown above includes −
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.
method body − The method body defines what the method does with the statements.
is known as call by value. The changes being done in the called method, is not affected in the
calling method.
In case of call by value original value is not changed. Let's take a simple example:
class Operation{
int data=50;
[Link](500);
Output:before change 50
after change 50
In Java, parameters are always passed by value. For example, following program prints
i = 10, j = 20.
// [Link]
class Test {
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class
than instance of the class.
3. block
4. nested class
o 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.
o The static variable gets memory only once in class area at the time of class loading.
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }
int rollno;
rollno = r;
name = n;
[Link]();
[Link]();
} }
If you apply static keyword with any method, it is known as static method.
o A static method can be invoked without the need for creating an instance of a class.
o static method can access static data member and can change the value of it.
class Student9{
int rollno;
String name;
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
[Link]();
[Link]();
[Link]();
} }
class A2{
static{[Link]("static block is
invoked");} public static void main(String args[]){
[Link]("Hello main");
} }
Hello main
Access Control
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor
or class.
2. default
3. protected
4. public
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is compile time error.
class A{
A obj=new A();
} }
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from outside
the package.
//save by [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
//save by [Link]
package pack;
public class A{
//save by [Link]
package mypack;
import pack.*;
class B extends A{
[Link]();
} }
Output:Hello
4) public access modifier
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
//save by [Link]
package pack;
public class A{
//save by [Link]
package mypack;
import pack.*;
class B{
[Link]();
} }
Output:Hello
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
6. this can be used to return the current class instance from the method.
class Student{
int rollno;
String name;
float fee;
[Link]=name;
[Link]=fee;
}
void display(){[Link](rollno+" "+name+" "+fee);}
}
class TestThis2{
[Link]();
}}
Output:
Constructor is used to initialize the state of an object. Method is used to expose behaviour
of an object.
Constructor must not have return type. Method must have return type.
The java compiler provides a default constructor if you Method is not provided by compiler in
don't have any constructor. any case.
Constructor name must be same as the class name. Method name may or may not be
There are many differences between constructors and methods. They are given belo
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter [Link] compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
int id;
String name;
int age;
id = i;
name = n;
id = i;
name = n;
age=a;
[Link]();
[Link]();
}
Output:
222 Aryan 25
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
class Adder{
class TestOverloading1{
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}}
Output:
22
33
if (n == 1)
return 1;
else
return(n * factorial(n-1));
} }
Output:
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
gc() method
s1=null;
s2=null;
[Link]();
} }
Java String
string is basically an object that represents sequence of char values. An array of characters works
same as java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
ssame as:
1. String s="javatpoint";
2. Java String class provides a lot of methods to perform operations on string such as
The java String is immutable i.e. it cannot be changed. Whenever we change any
string, a new instance is created. For mutable string, you can use StringBuffer and
StringBuilder classes.
1. By string literal
2. By new keyword
String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object
in heap (non pool).
java
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
} }
Output:Sachin
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=[Link](" Tendulkar");
[Link](s);
} } Output:Sachin Tendulkar
JAVA PROGRAMMING PAGE 36
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. Inheritance represents the IS-A relationship, also known as parent-
child relationship.
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
} }
File: [Link]
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
Output:
barking...
eating...
File: [Link]
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
Output:
weeping...
barking...
eating...
File: [Link]
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}
Output:
meowing...
eating...
JAVA PROGRAMMING PAGE 39
Member access and Inheritance
A subclass includes all of the members of its super class but it cannot access those members of
the super class that have been declared as private. Attempt to access a private variable would
cause compilation error as it causes access violation. The variables declared as private, is only
accessible by other members of its own class. Subclass have no access to it.
The super keyword in java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
class Animal{
String color="white";
String color="black";
void printColor(){
class TestSuper1{
public static void main(String args[]){
}}
Output:
black
white
The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
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.
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:
1. Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
JAVA PROGRAMMING PAGE 41
Usage of Java Method Overriding
Class Vehicle{
void run(){[Link]("Vehicle is running");}
}
class Bike2 extends Vehicle{
[Link]();
}
1. class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
Output:
SBI Rate of Interest: 8
A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its method
abstract method
[Link]();
1. }
running safely..
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance in
Java.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
Output:drawing circle
[Link]();
[Link]();
} }
Output:Hello
Welcome
1) Abstract class can have abstract Interface can have only abstract methods. Since
and non-abstract methods. Java 8, it can have default and static
methods also.
2) Abstract class doesn't support Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
package mypack;
public class Simple{
public static void main(String args[]){
[Link]("Welcome to package");
} }
If you are not using any IDE, you need to follow the syntax given below:
//save by [Link]
package pack;
public class A{
package mypack;
class B{
public static void main(String args[]){
}
}
Output:Hello
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.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
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
1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions [Link], 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.
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw exception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block only.
Output:
As displayed in the above example, rest of the code is not executed (in such case, rest of
the code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
}catch(ArithmeticException e){[Link](e);}
[Link]("rest of the code...");
} }
1. Output:
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Output:task1 completed
rest of the code...
class Excep6{
public static void main(String args[]){
try{
try{
[Link]("going to divide");
int b =39/0;
}catch(ArithmeticException e){[Link](e);}
try{
JAVA PROGRAMMING PAGE 51
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException
e){[Link](e);} [Link]("other statement);
}catch(Exception e){[Link]("handeled");}
[Link]("normal flow..");
}
1. }
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
Output:5
finally block is always executed
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
[Link]("welcome to vote");
}
public static void main(String args[]){
validate(13);
[Link]("rest of the code...");
} }
Output:
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
2. //method code
3. }
4.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import [Link];
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
exception handled
normal flow...
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
[Link]("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){[Link]("Exception occured: "+m);}
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
JAVA PROGRAMMING PAGE 55
How to create thread
Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
o Thread()
o Thread(String name)
o Thread(Runnable r)
2. public void start(): starts the execution of the [Link] calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
10. public Thread currentThread(): returns the reference of currently executing thread.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
o A new thread starts(with new callstack).
o When the thread gets a chance to execute, its target run() method will run.
Output:thread is running...
Output:thread is running...
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses.
When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
[Link]("going to withdraw...");
if([Link]<amount){
[Link]-=amount;
[Link]("withdraw completed...");
}
synchronized void deposit(int amount){
[Link]("going to deposit...");
[Link]+=amount;
[Link]
The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.
The [Link] package of the J2SE APIs contains a collection of classes and interfaces that provide
the low-level communication details, allowing you to write programs that focus on solving the
problem at hand.
The [Link] package provides support for the two common network protocols −
TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet Protocol,
which is referred to as TCP/IP.
UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for
packets of data to be transmitted between applications.
Socket Programming − This is the most widely used concept in Networking and it has
been explained in very detail.
[Link]
The [Link] package is necessary for every java developer to master because it has a lot of
classes that is helpful in formatting such as dates, numbers, and messages.
[Link] Classes
[table]
Class|Description
ArrayList and Vector both implements List interface and maintains insertion order.
But there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
current array size if number of size if total number of element exceeds than its
element exceeds from its capacity. capacity.
5) ArrayLis tuses Iterator interface Vector uses Enumeration interface to traverse the
Let's see a simple example of java Vector class that uses Enumeration interface.
1. import [Link].*;
2. class TestVector1{
5. [Link]("umesh");//method of Collection
6. [Link]("irfan");//method of Vector
7. [Link]("kumar");
8. //traversing elements using Enumeration
10. while([Link]()){
11. [Link]([Link]());
12. } } }
Output:
umesh
irfan
kumar
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an
input file into an output file −
Example
import [Link].*;
FileInputStream in = null;
try {
in = new FileInputStream("[Link]");
int c;
}finally {
if (in != null) {
[Link]();
if (out != null) {
[Link]();
}} }}
As a next step, compile the above program and execute it, which will result in creating [Link]
file with the same content as we have in [Link]. So let's put the above code in [Link]
$javac [Link]
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character
streams are used to perform input and output for 16-bit unicode. Though there are many classes
related to character streams but the most frequently used classes are, FileReader and
FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input
file (having unicode characters) into an output file −
Example
import [Link].*;
try {
in = new FileReader("[Link]");
int c;
[Link](c);}
}finally {
if (in != null) {
[Link]();}
if (out != null) {
[Link]();
}} }}
As a next step, compile the above program and execute it, which will result in creating [Link]
file with the same content as we have in [Link]. So let's put the above code in [Link]
$javac [Link]
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program can
take input from a keyboard and then produce an output on the computer screen. Java provides the
Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented [Link].
JAVA PROGRAMMING PAGE 79
Standard Output − This is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented as
[Link].
used to output the error data produced by the user's program
Standard Error − This is
screen is used for standard error stream and represented
and usually a computer as
[Link].
Following is a simple program, which creates InputStreamReader to read standard input stream
until the user types a "
Example
import [Link].*;
try {
char c;
do {
c = (char) [Link]();
[Link](c);
} while(c != 'q');
}finally {
if (cin != null) {
[Link]();
} }}}
This program continues to read and output the same character until we press 'q' −
$javac [Link]
$java ReadConsole
JAVA PROGRAMMING PAGE 80
Enter characters, 'q' to quit.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the keyword
new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file
−
Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
ByteArrayInputStream
DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file −
Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows −
Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.
ByteArrayOutputStream
DataOutputStream
Example
import [Link].*;
try {
[Link]();
[Link]();
} catch (IOException e) {
[Link]("Exception");
}}}
[Link] Class
The [Link] class file behaves like a large array of bytes stored in the file
[Link] of this class support both reading and writing to a random access file.
Class declaration
Following is the declaration for [Link] class −
extends Object
Class constructors
S.N. Constructor & Description
1
RandomAccessFile(File file, String mode)
This creates a random access file stream to read from, and optionally to write to, the file
specified by the File argument.
JAVA PROGRAMMING PAGE 83
2
RandomAccessFile(File file, String mode)
This creates a random access file stream to read from, and optionally to write to, a file with
the specified name.
Methods inherited
This class inherits methods from the following classes −
[Link]
A pathname, whether abstract or in string form can be either absolute or relative. The parent of
an abstract pathname may be obtained by invoking the getParent() method of this class.
First of all, we should create the File class object by passing the filename or directory name
to it. A file system may implement restrictions to certain operations on the actual file-
system object, such as reading, writing, and executing. These restrictions are collectively
known as access permissions.
Instances of the File class are immutable; that is, once created, the abstract pathname
represented by a File object will never change.
How to create a File Object?
A File object is created by passing in a String that represents the name of a file, or a String or
another File object. For example,
defines an abstract file name for the geeks file in directory /usr/local/bin. This is an absolute
abstract file name.
{
[Link]("Is writeable:"+[Link]());
[Link]("Is readable"+[Link]());
[Link]("Is a directory:"+[Link]());
[Link]("File Size in bytes "+[Link]());
}
}
}
Output:
Path: [Link]
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\[Link]
Parent:null
Exists :true
Is writeable:true
Is readabletrue
Is a directory:false
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to interact with it
by sending SQL or database commands then receiving results with Java.
JAVA PROGRAMMING PAGE 85
The [Link] package that ships with JDK, contains various classes with their behaviours defined
and their actual implementaions are done in third-party drivers. Third party vendors implements
the [Link] interface in their database driver.
When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.
JAVA PROGRAMMING PAGE 87
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's configuration
in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.
JAVA PROGRAMMING PAGE 88
The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.
For connecting java application with the mysql database, you need to follow 5 steps to perform
database connectivity.
In this example we are using MySql as the database. So we need to know following informations
for the mysql database:
1. Driver class: The driver class for the mysql database is [Link].
4. Password: Password is given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
2. use sonoo;
In this example, sonoo is the database name, root is the username and password.
import [Link].*;
class MysqlCon{
[Link]("[Link]"); Connection
con=[Link](
"jdbc:mysql://localhost:3306/sonoo","root","root");
} }
The above example will fetch all the records of emp table.
To connect java application with the mysql database [Link] file is required to be
loaded.
2. set classpath
Download the [Link] file. Go to jre/lib/ext folder and paste the jar file here.
2) set classpath:
[Link] [Link]
1. C:>set classpath=c:\folder\[Link];.;
Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the [Link] file by appending [Link];.; as
C:\folder\[Link];
JDBC-Result Sets
The SQL statements that read data from a database query, return the data in a result set. The
SELECT statement is the standard way to select rows from a database and view them in a result
set. The [Link] interface represents the result set of a database query.
JAVA PROGRAMMING PAGE 90
A ResultSet object maintains a cursor that points to the current row in the result set. The term
"result set" refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories −
Get methods: Used to view the data in the columns of the current row being pointed by
the cursor.
Update methods: Used to update the data in the columns of the current row. The updates
can then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are designated
when the corresponding Statement that generates the ResultSet is created.
JDBC provides the following connection methods to create statements with desired ResultSet −
The first argument indicates the type of a ResultSet object and the second argument is one of two
ResultSet constants for specifying whether a result set is read-only or updatable.
Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.
Type Description
Concurrency of ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type, you
will automatically get one that is CONCUR_READ_ONLY.
Concurrency Description
There is a get method for each of the possible data types, and each get method has two versions
For example, if the column you are interested in viewing contains an int, you need to use one of
the getInt() methods of ResultSet −
Returns the int in the current row in the column named columnName.
Returns the int in the current row in the specified column index. The column index starts
at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on.
JAVA PROGRAMMING PAGE 92
Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive
types, as well as common types such as [Link], [Link], and [Link].
There are also methods for getting SQL data types [Link], [Link],
[Link], [Link], and [Link]. Check the documentation for more
information about using these SQL data types.
The ResultSet interface contains a collection of update methods for updating the data of a result
set.
As with the get methods, there are two update methods for each data type −
s.
There are update methods for the eight primitive data types, as well as String, Object, URL,
and the SQL data types in the [Link] package.
Updating a row in the result set changes the columns of the current row in the ResultSet
object, but not in the underlying database. To update your changes to the row in the database,
you need to invoke one of the following methods.
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications
in java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The [Link] package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
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.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager defines the layout manager for the component.
m)
public void setVisible(boolean status) changes the visibility of the component, by default
false.
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.
import [Link].*;
First(){
}}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that
sets the position of the awt button.
Java Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
dependent. independent.
3) AWT doesn't support pluggable look Swing supports pluggable look and
Swing. componentssuchastables,lists,
scrollpanes, colorchooser, Tabbedpane
etc.
public void setLayout(LayoutManager sets the layout manager for the component.
m)
false.
We can write the code of swing inside the main(), constructor or any other method.
Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
File: [Link]
JAVA PROGRAMMING PAGE 99
import [Link].*;
}}
Layout Management
Java LayoutManagers
BorderLayout
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.
2. import [Link].*;
public class
MyGridLayout{ JFrame f;
MyGridLayout(){
f=new JFrame();
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the
default layout of applet or panel.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
f=new JFrame();
[Link](true);
}
Event Handling
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The [Link] package provides many event classes and Listener interfaces for
event handling.
Types of Event
Foreground Events - Those events which require the direct interaction of [Link] 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.
Background Events - Those events that require the interaction of end user are known as
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. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the [Link]'s have a brief introduction
to this model.
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.
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
o MenuItem
o TextField
o TextArea
o Checkbox
o Choice
o List
EventHandling Codes:
We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class
Example of event handling within class:
import [Link].*;
import [Link].*;
tf=new TextField();
[Link](60,50,170,20);
[Link](100,120,80,30);
[Link](this);
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
new AEvent();
} }
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the
above example that sets the position of the component it may be button, textfield etc.
import [Link].*;
import [Link].*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);
//register listener
[Link](this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
[Link]("Welcome"); }
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in [Link] package. It has five
methods.
import [Link].*;
import [Link].*;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
[Link](20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
}
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
} }
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in [Link] package. It has three methods.
import [Link].*;
import [Link].*;
TextArea area;
KeyListenerExample(){
l=new Label();
[Link](20,50,100,20);
area=new TextArea();
[Link](20,80,300, 300);
[Link](this);
add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
Frame f;
AdapterExample(){
[Link](); } });
[Link](400,400);
[Link](null);
[Link](true);
} }
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
o Secured
Drawback of Applet
o Plugin is required at client browser to execute applet.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
The [Link] class 4 life cycle methods and [Link] class provides 1 life
cycle methods for an applet.
[Link] class
For creating any applet [Link] 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.
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.
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.
1. //[Link]
import [Link];
import [Link];
[Link]("welcome",150,150);
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 [Link]. Now Html file is not required but it is
for testing purpose only.
1. //[Link]
import [Link];
import [Link];
[Link]("welcome to applet",150,150);
/*
*/
c:\>javac [Link]
c:\>appletviewer [Link]
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 [Link];
2. import [Link];
3. public class UseParam extends Applet
4. {
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>