Java
Java
The languages that follow Object Oriented Approach are called as Object
Oriented Languages such as C++, JAVA, SIMULA and SMALLTALK etc.
1. Class/Object
2. Encapsulation
3. Data Abstraction
4. Inheritance
5. Polymorphism
The above five concepts are also called as features of OOPS
1) Class/object:
Class:
A class is a user defined data type.
A class is not a physical one because no storage space created in the memory.
A class is a set of properties and actions.
Properties represent variables.
Actions represents methods
A class is a structure or model of an object
Properties and actions both are called as members of a class.
Object:
An object is a physical one because it allocates memory.
An object is an instance of a class.
An object also contains a set of properties and actions.
Advantage: Two or more classes can contain the properties with the same
names.
name
Name :
: :
:
Person Student
4) Inheritance:
Inheritance is an extraction of new software from already existing software.
According to Java extraction of new classes from already existing classes is said to
be inheritance.
F1
F2
F3
F4
5) Polymorphism:
It is a Latin word. Poly means many, morphism mean actions. i.e. one thing exhibits
in many forms or one thing performs many actions.
OOP provides several benefits to both the developer and the user. It solves the many
problems in the development of software products that improves the quality. It
improves the productivity, best quality of product and reduces the cost of the product.
Applications of OOP
Large number of systems developed using OOP techniques. OOP techniques are used to
complex and big projects.
Object-Oriented Databases
Real-Time Systems
This work was assigned to “Mr. James Gosling” and his team.
James Gosling and his team were started this project by using C++ which was
introduced in the year 1983.
After the completion of 30%, C++ was not supported. So, James Gosling and his
team were developed a new language called as “Oak” (The name of a tree which
they used to see from the window when they were developing the language).
James Gosling and his team developed the Oak language by removing all the
complicated concepts from C++.
He tested the Oak language on “Green Project” (*7 device), and it was
succeeded. He developed the Green project using “APPLETS” concept to get the
images. Up to 1993, “Internet” was CUI, which was turned to GUI because of Oak.
Later, the Oak language was renamed to “JAVA”. Since “OAK” name was
registered by some other company. Java is an Island which is famous for Tea
and Coffee plants. Mr. James Gosling and his team were very fond of tea and
coffee. Hence they given a name as “Java”.
In 1995 Sun Micro System announced Java at SunWorld conference in 1995.
Java SE- It is the Java Standard Edition that contains core java classes. It is used to develop
standard applets and applications.
Java EE- It is the Java Enterprise Edition that contains the classes to develop business
applications.
Java ME- It is Java Micro edition. It is used to develop code for portable devices such as
mobile phones etc.
Why Java?
In case of ‘C’
Unix+Motorola
Windows+Intel
The .exe file generated by ‘C’ compiler in one platform can’t be executed in different
platform.
A .class file generated in one computer can be executed in any other computer
irrespective of platform. Hence, Java is platform independent.
Java Virtual Machine (JVM): JVM is a set of programs written in ‘C’ Language.
JVM internally contains a program called “Interpreter” used to convert the byte
code to machine code line by line. Every platform has its own JVM. So, JVM converts
byte code to the platform convenient. JVM is platform dependent. Since, it is written
in ‘C’ Language.
1) Simple:
Java is Simple. Since, all the complicated concepts from C++ had been removed.
2) Object Oriented:
Java is Purely Object Oriented programming language. Since, it supports all the
features of Object Oriented Approach such as
i) Class/Object
ii) Encapsulation
iii) Data Abstraction
iv) Polymorphism
v) Inheritance
**Note: Object based language: Which supports all the Object Oriented Features
except Inheritance
C Java
‘C’ is a Procedure Oriented Language Java is an Object Oriented Language
It is Platform Dependent It is Platform Independent
‘C’ Compiler generates .exe files Java Compiler generates .class files
It supports the keywords sizeof, typedef It does not support the keywords sizeof,
typedef
It supports jumping statement goto It does not support goto
It support the pointers concept It does not support the pointers concept
Pre-processor statements #include, Pre-processor statements #include,
#define are available in ‘C’. #define are not available in Java
It supports structures and unions It does not support structures and unions
new and instanceof operators are not new and instanceof operators are available
available in ‘C’ in Java
Type modifiers auto, extern, register, Type modifiers auto, extern, register,
signed and unsigned are available in ‘C’ signed and unsigned are not available in
Java
Enumerations are available in ‘C’ Enumerations are also available in Java
C++ Java
C++ is not a purely object-oriented Java is purely an object-oriented
programming Language, since it is possible programming language, since it is not
to write c++ programs Without using a possible to write a java program using at
class or an object least one class.
Java is strongly associated with the Internet because the first application program
written in Java was HotJava, a Web Browser to run applets on internet. Internet users
can use Java to create applet programs and run them locally using Java-enabled browser
such as HotJava. They can also use a Java-enabled browser to download an applet
located on a computer anywhere in the internet and run it on his local computer.
The Internet is a vast collection of information represented in many ways and stored on
many computers. A large portion of the Internet is organized as a part of World Wide
Web which uses hypertext. Web browsers are used to navigate through the information
found on the net. They allow us to retrieve the information spread across the Internet
and display it using the Hyper Text Markup Language (HTML).
Examples:
HotJava
Netscape Navigator
Internet Explorer
HotJava
HotJava is the Web Browser developed by Sun Micro System. It was the first browser to
provide support for the Java language, which makes the web more dynamic and
interactive. It is used to locate and run applet programs on Internet.
HotJava is available for the platform Windows 95, Windows NT and Windows XP and
also available for Sun Solaris.
Netscape Navigator
Internet Explorer
Note: Both Navigator and Explorer use toolbars, icons, dialog boxes and menus for easy
navigation.
Java is supported on Windows 95, Windows NT, Windows XP, Sun Solaris, MAC
and UNIX operating systems.
JAVA ENVIRONMENT
It includes a huge number of development tools and large number of classes &
interfaces. The development tools are part of the system known as Java Development
Kit (JDK). The classes and methods are part of the Java Standard Library (JSL), also
known as Application Program interface (API).
JDK:
It is a set of tools and utilities that are used to develop Java applications.
Some of the tools are
javac
javac
javac
[Link] Header Files
javah
java
Output
An API is also called as Java Standard Library (JSL). An API is a set of classes and
interfaces. These classes and interfaces are defined in different packages based upon
their functionality. For example all the Input-Output related classes are defined in
[Link] package. Most commonly used packages are [Link], [Link], [Link], [Link]
etc
The meaning of keyword is already known to the compiler. Keywords are also called
as “Reserved words”
Ex: byte, short, int, float, final, abstract, extends, implements, package, public…..etc
Constants:
Example Algorithm:
a=10
b=20
c=a+b
print c
Note: Every word starting letter of a variable name should be capital except first
word.
Ex: monthlyIncome, annualIncome, rollNo, empNo etc.
Datatypes:
Data types are used for the creation of variables.
i) Integer category:
----------------------------------------------------------------------------------------------------------
Ex:
int a, b;
ii) Float category:
-----------------------------------------------------------------------------------------------------------
Data type no. of Range
Name bytes
------------------------------------------------------------------------------------------------------------
float 4 -3.4e38 to -1.4e-45 for negative values
Ex:
float salary;
-------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
Ex: char ch;
ASCII Range: 0-255 UNICODE Range: 256-65535
In Java character is allocated by 2 bytes since, the character variable not only store ASCII
code but also stores UNI CODE.
UNI CODE:
UNI code is a UNIVERSAL code given for the characters other than English.
boolean 1 true/false
Ex: boolean response;
Syntax:
Variablename = value;
Ex:
a = 10;
b = 20;
ch = ‘A’;
Note:
A value can be given to a variable at the time of declaration called as Initialization of a
variable.
Syntax:
Ex:
int rno = 5; // initialization
float avg = 75.5f; // initialization
The Java compiler always prefers the decimal value as double. To specify the declared
value is float to the compiler, we’ve to write ‘f’ after decimals.
A value can be accepted from keyboard using readLine() method of Integer Wrapper
class which can understood in later topics.
Identifier
An identifier is a name given to a variable or a method or a class or an interface or a
package etc.
O/P:
Good afternoon_
[Link] (“Vidyaranyapuri”);
[Link] (“HNK”);
O/P: KUVidyaranyapuriHNK_
Note: print () prints the message on the screen and the cursor remains on the same line.
[Link] ():
Prints the message and then moves the cursor to the next line.
[Link] (“Informatics”);
Output:
Venkat
Informatics
Output:
Sum =1020
Sum =30
class ProgramName
---------
---------
main() method explains the starting and ending points of a program to the JVM.
The main method’s class name and program name should be same.
In Java it is not possible to write a program without using class. Hence, Java is purely
Object Oriented language.
C :\...> cd\
C: \...bin>javac [Link]
C: \...bin>java Sum
class Area{
int a, l, b;
l=10;
b=20;
a=l*b;
Output:
Area =200
{
--------------
--------------
--------------
Comments:
Classes String
System
[Link] | |
String
. Methods length()
.
If we use the methods of a class, the corresponding class should be imported.
import [Link];
(Or)
import [Link].*;
Here, * represents to import all the classes and interfaces present in the package.
By default [Link] package will be imported.
Package declaration:
We the users can create our own packages called as user-defined package.
A user defined package can be created by the programmer using the keyword
“package”
The main method is called by JVM from command line. If we want to pass the
arguments to the main method, there is a need to pass the arguments from the
command line. Such a concept is called as command line arguments.
class CmdDemo{
[Link](args[0]);
[Link](args[1]);
>javac [Link]
Explanation:
Naming Conventions
1. Instance variables
2. Class variable(static variables)
3. Local variables
1. Instance variables:
Instance variable is declared inside a class. Instance variables are created when
the objects are instantiated. Instance variables are separate for every object.
Syntax:
class ClassName
{
Datatype variable;
:
}
2. Class Variables:
Class variable is declared inside a class using a keyword static. So, It is also called
as static variable. Class variables are common (global) to all the objects that class
creates.
Syntax:
class ClassName
{
static datatype variable;
:
}
3. Local variables:
Local variables are declared inside a method. These variables cannot be accessed
outside the method definition.
Syntax:
returntype methodName([parameters..])
{
Datatype variable;
}
Symbolic constant solves the above said problem. Symbolic constant is a name
substituted for a variable. It can be declared using the keyword final. So, it is also called
as final variable. Its value cannot be changed during the execution of a program.
Syntax:
final datatype VARIABLENAME = value;
Ex:
Note:
1. Symbolic constants are written in capital letters.
2. A value assigned to a symbolic constant cannot be changed.
An Example Program on Symbolic Constant
class FinalDemo{
[Link](“x = “+x);
//[Link](“x= “+x);
Implicit type casting is possible when the following two cases are satisfied.
Case 1: Both source variable and destination variable should belongs to same
category.
Ex:1 Ex:2
byte b = 10; long x = 10.5;
int n = b; //valid 2 cases satisfied; int y = x; /* invalid, since destination
variable size not greater than source
variable size */
Note: The cast operator and data type of destination variable should be same.
To read (accept) the values from the keyboard, we should use the methods of
BufferedReader.
int ich=[Link]();
char ch=(char)ich;
[Link](ch);
Ex2:
[Link](“Enter your gender..”);
char g= (char)[Link]();
ii) readLine():
[Link](“Enter your name…”);
String sname=[Link]();
[Link](“Enter your college name..”);
String cname=[Link]();
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Reason:
String value present in String format can’t be converted to byte format.
Note: Parsing methods throw a NumberFormatException, if the String value does not
represent a number or numeric value.
import [Link].*;
class SumTwo
{
a=[Link]([Link]());
b=[Link]([Link]());
c=a+b;
Out put:
Enter two numbers…
10
20
The sum of the given two numbers is 30
Ex: b=a+20;
Operands Symbol
Types of operators:
1) Arithmetic Operators (+,-,*, /, %):
The operators which are used for simple mathematical calculations are called
as arithmetical operators.
1 + Addition a+b 13
2 - Subtraction a-b 7
3 * Multiplication a*b 30
Ex: int a, b, c;
a =10; (constant)
b= a; (variable)
c=a+ b; (expression)
Note: Relational operators and Arithmetic operators are binary operators. Since, both
operators will use two operands.
a) Logical OR (ll):
When all the conditions are false, the result will be false; otherwise the result
will be true.
C1 C2 C1llC2 C1&&C2
T T T T
F T T F
T F T F
F F F F
Ex:
int s1=60, s2=70, s3=30;
if (s1>=35 && s2>=35 && s3>=35)
Pass
else
Fail
If any one of the conditions is false, the total result will be false.
C !C
T F
F T
a) Prefix operator:
Syntax: ++/--variable;
i) Pre-increment operator:
Increment operator will be written before a variable. Such type of operators are said to
be Pre-increment operators.
Syntax: ++variable;
Decrement operator will be written before a variable. Such type of operators are said to
be Pre-decrement operators.
Syntax: --variable;
Syntax: variable++/--;
i) Post-increment:
Increment operator will be written after a variable. Such type of operators are said to be
post-increment operator.
Syntax: variable++;
ii) Post-decrement:
Decrement operator will be written after the variable. Such type of operators are said to
be post-decrement operator.
Syntax: variable--;
Prefix Postfix
1)First most ++/-- 1)All operations will be first
2)Remaining all operations 2)++/--
int x = 10;
[Link] (++x);
O/P: 11
int y = 10;
[Link] (y++);
O/P: 10
The operator which operates on 3 operands is said to be ternary operator. First the
condition will be evaluated, if the condition is true, then value of variable1 will be stored
in variable3; otherwise value of variable2 will be stored in variable3.
Syntax:
big= (a>b)? a: b;
Ex: [Link]
8. “new” operator:
10. instanceof:
a) Decimal number system: Decimal number system uses the digits 0-9
Ex: x=12
b) Binary number system: binary number system uses the digits 0 and 1.
Ex: x=1100
We can convert decimal number system to binary number system and vice versa.
Ex: 12 = 1 1 0 0
1X23 + 1X22 + 0X21 + 0X20
8 + 4 + 0 + 0 = 12
Definition: Bitwise operator operates only on bits i.e., (0’s and 1’s)
y =11 0 0 0 0 1 0 1 1
.
Xl Y = 0 0 0 0 1 0 1 1
X Y x&y
1 1 1
1 0 0
0 1 0
0 0 0
X Y x^y
1 1 0
1 0 1
0 1 1
0 0 0
EX: x=10 0 0 0 0 1 0 1 0
y = 11 0 0 0 0 1 0 1 1
.
x^y= 0 0 0 0 0 0 0 1
.
v) Bitwise Left shift (<<):
It is used to shift n bits of a value towards left side.
It can be represented as x<<n, i.e., shift the n bits of x towards left.
EX: x=10
0 0 0 0 1 0 1 0
x<<2
0 0 1 0 1 0 0 0
Ex: x=10 0 0 0 0 1 0 1 0
x>>2
0 0 0 0 0 0 1 0
Example Program:
class BitsDemo
{
public static void main(String args[])
{
int x=10, y=11;
[Link](“complement of x=”+( x));
[Link](“x | y =”+(x | y));
[Link](“x & y =”+(x & y));
[Link](“x ^ y =”+(x ^ y));
[Link](“x << 2 =”+(x << 2));
[Link](“x >> y =”+(x >> y));
}
}
O/P:
complement of x=10
x | y=11
x& y=10
x ^ y =1
x<< 2=40
x>> 2=0
𝑎𝑏𝑐 (a*b*c)/(x+y)
𝑥+𝑦
a = 𝜋𝑟 2 a = 3.14 * r * r
Evaluation of Expressions
Expressions are evaluated using assignment operator.
Syntax:
variable = expression;
When the statement is encountered, the expression is evaluated first and the result is
placed in the variable on the left-hand side of assignment operator.
All the variables in the expression must be assigned values before the evaluation.
Ex:
int a, b, c, d;
a = 10;
b = 5;
c = 3;
The default flow of execution is every statement will be executed only once in a
sequential manner one after the other.
Those are
i) Branching statements
ii) Looping statements
iii) Jumping statements
i) Branching statements:
if:
When the condition is true, ‘if’ block statements will be executed otherwise
‘if’ block statements will not be executed.
Syntax:
if(condition)
{
---------
--------- if block statements
---------
}
--------
-------- Out of if block statements
class Biggest
{
int a, b;
[Link](“Enter two numbers…”);
a=[Link]([Link]());
b=[Link]([Link]());
if(a>b)
{
[Link](“a is bigger…”);
}
[Link](“b is bigger…”);
}
[Link](“End of the program…”);
}
}
if-else:
When the condition is true, if block statements will be executed; Otherwise else block
statements will be executed.
Syntax:
if(condition)
{
--------
--------
}
else
{
--------
--------
}
--------
--------
import [Link].*;
class EvenOdd{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
int n;
{
[Link](“ given number is even…”)
}
Nested if:
An if block present in the else block of the another if block is said to be Nested if
Syntax:
Note:
When all the conditions are false then else-block (default) statements will be executed.
switch case:
Syntax:
switch(var)
{
case 1:
Statements 1;
break;
case 2:
Statements 2;
-----
------
default:
default statements;
The ?: Operator
?: is a Conditional Operator and is also called as Ternary Operator. The operator which
operates on 3 operands is said to be ternary operator. First the condition will be
evaluated, if the condition is true, then value of variable1 will be stored in variable3;
otherwise value of variable2 will be stored in variable 3.
big= (a>b)? a: b;
Example Program:
class CondOptDemo
{
}
}
For:
The statements in the “for” block will be executed until the condition gets
false. It is an entry control loop because condition is checked before entering
into the loop.
Initialization will be executed only once where as condition, updation will be
executed for more than once.
Syntax:
for(initialization; condition; updation)
{
-----------
-----------
}
---------
---------
Flow chart:
Syntax:
initialization
while(condition)
{
----------
----------
----------
updation;
}
----------
----------
Example Program 1
Write a program to print even numbers from 1 to n:
Output:
Syntax:
It checks the condition before executing It execute the block before checking the
the block of while statement. condition.
Syntax:
init; Syntax:
while(condition) init;
{ do
---- {
---- -----
updation; -----
} updatation;
}while(condition);
Nested for:
A for block written within another for block is said to be nested for
The program should be written as follows by using the nested for loops
Output:
Output:
b) Continue:
In a loop, if the condition specified evaluates to true then all statements in the
loop executes and when it reaches to the end of loop then control goes back to
the condition. But in some situations, after executing few statements in the loop
Output:
So, the behavior of the system will not know before developing the project.
The above problems can be solved by using the new approach called as object
oriented approach.
Any language that supports these five features is called as an object oriented
language.
Ex: C++, Java, SIMULA etc…
Any language that supports all the features of OOPS except Inheritance is said to be
Object based language.
class Person
{
String name;
int age;
}
Methods Declaration:
A class with only data fields without methods that operate on that data has no life.
Methods are declared inside the body of the class but immediately after the declaration
of instance variables.
A method contains two parts
1. Method Prototype
2. Method Body
1. Method Prototype: It specifies the name of the Method (method name), the type
of the value it returns (return type) and no. of parameters.
Syntax:
returntype methodName([parameters list..]) //method prototype
{
//method body
}
Ex:
//code
}
class Person
{
//properties
String name;
int age;
//actions
void talk()
{
[Link](“I am “+name);
[Link](“My age is “+age);
}
Note: pone, ptwo are reference variables referring to Person class objects.
Example
[Link]=”Raj”; //accessing instance variables outside the class
[Link]=25;
[Link](); //accessing instance method outside the class
Once a class is provided, we can create any number of objects whose structure is
same but behavior is different. A class is of no use without creation of an object.
No objects can be created without using class.
//[Link]
class PersonDemo
{
public static void main(String agrs[])
{
Person pone, ptwo;
pone=new Person();
ptwo=new Person();
[Link]=”Raj”;
[Link]=”Ravi”;
[Link]=28;
[Link]();
[Link]();
}
}
>javac [Link]
>javac [Link]
Ex:2
//[Link]
class Book
{
int bpages;
String bname;
void setBook(int bp,String bn)
{
bpages=bp;
bname=bn;
}
void getBook()
{
[Link](bpages+”\t”+bname);
}
}
//[Link]
class BookDemo
{
public static void main(String args[])
{
Book bone;
bone=new Book();
>javac [Link]
>javac [Link]
>java BookDemo
222 Java
Advantage: Two or more classes can contain the properties with the same
names.
name
Name :
: :
:
Person Student
1)
Data abstraction:
Providing the security to the data is said to be Data abstraction. We can provide
security to the data at different levels using access specifiers.
Access specifiers: Access specifier specifies the scope of a variable.
Scope: Scope means the place or area where the member can be accessed.
//code
}
protected, default, public members can be accessed in the same class in which
they are declared and can also be accessed outside the class.
Inheritance:
Inheritance is an extraction of new software from already existing software.
According to Java extraction of new class from already existing class is said to be
inheritance.
F1
F2
F3
F4
Polymorphism:
It is a Latin word. Poly means many, morphism mean actions. i.e. one thing exhibits
many actions.
The examples of polymorphism are method overloading, constructor overloading,
method overriding, etc.
Method 2:
Constructor:
Constructor is a special method that has the same name as that of class
name.
Constructor is used to initialize the properties of an object.
Constructor shouldn’t have any return type(even we shouldn’t write void).
Constructor is automatically executed during the creation of an object. i.e.,
execution of a constructor and object creation will be done at same time.
class Book{
int bpages;
String bname;
Book(){
bpages=100;
bname=”Java”;
}
public void getBook(){
[Link](“bpages+”\t”+bname);
}
}
class UseBook{
public static void main(String args[]){
Book bone, btwo;
bone=new Book();
btwo=new Book();
[Link]();
[Link]();
}
}
Dr. V. Venkateshwarlu Page 79
Note: In zero argument constructors every object is initialized with the same values.
Parameterized constructor:
Constructor may have parameters called parameterized constructor.
class Book
{
int bpages;//instance variable
String bname;//instance variable
Book(int bp, String bn)
{
bpages=bp;
bname=bn;
}
public void getBook()//instance method
{
[Link](bpages+”\t”+bname);
}
}
class useBook
{
public static void main(String args[])
{
Book bone, btwo;
bone=new Book(111, “Java”);
btwo=new Book(222, “C++”);
[Link](“Books details..”);
[Link]();
[Link]();
}
}
Note: Every object is initialized with different values.
Output:
Books details
111 Java
222 C++
long -----0
Book
//no constructor
javac
[Link]
//zero argument constructor
(Or) default constructor.
class Book{
int bpages;// instance variable
String bname;//instance variable
// no constructor provided
public void getBook(){
[Link](bpages+”\t”+bname);
}
}
class UseBook{
public static void main(String args[]){
Book bone=new Book();
[Link](“Book details..”);
[Link]();
}
}
Book details..
0 null
javap: It is a command that provides information about .class file such as properties,
constructors, methods prototypes etc…
Ex:>javap Book
Constructor overloading:
Constructor overloading is a concept in which we can provide two or more constructors
with different signature. i.e., number of arguments or type of the arguments will be
different. The general syntax is as given below
class A
{
A()
{
//code
}
A(int n)
{
//code
}
}
Output:
Books details..
111 Java
222 C++
class Book{
int bpages;
String bname;
Book()
{
bpages=111;
bname=”Java”;
}
Book( Book b)
{
bpages=[Link];
bname=[Link];
}
public void getBook()
{
[Link](bpages+”\t”+bname);
}
}
class UseBook
{
public static void main(String args[])
{
Book bone=new Book();
Book btwo=new Book(bone);
[Link](“Books details..”);
[Link]();
[Link]();
}
}
Output:
Books details..
111 Java
111 Java
Example program:
class A
{
int x;
static int y;
public void setValues(int a, int b)
{
x=a;
y=b;
}
public void showValues()
{
[Link](“Instance variable x: “+x);
[Link](“Static variable y: ”+y);
}
}
class StaticVarDemo
{
public static void main(String args[])
{
A aone=new A();
A atwo=new A();
[Link](10,20);
[Link](“aone…”);
[Link]();
[Link](“atwo…”);
[Link]();
A.y=100; //public static variable can be accessed using class name and .
[Link](“After changing…”);
[Link](“aone…”);
[Link]();
[Link](“atwo…”);
[Link]();
}
}
Out put:
>javac [Link]
>javac [Link]
>java StaticVarDemo
aone…
Instance variable x: 10
Static variable y: 20
atwo...
Instance variable x: 0
Static variable y: 20
After changing…
aone…
Instance variable x: 10
Static variable y: 100
atwo…
Instance variable x: 0
Static variable y:100
x 10 x 0
: :
aone atwo
Static methods:
The methods that are declared using the keyword static are said to be static
methods.
Static method allocates the memory before the creation of an object
Static methods are common to all the objects.
public static methods can be accessed using the class name and . (dot).
The methods that are not declared using the keyword static are called as non-
static methods (Instance methods).
Non-static methods are created during the creation of an object (instance);
Hence, non-static methods are called as instance methods.
Instance methods can be accessed outside the class using reference variable
name and . (dot).
Static methods can access only static variables, whereas instance methods can
access both static variables and instance variables.
1. Single inheritance:
Extraction of a class from single super class is said to be single inheritance.
2. Multiple inheritance:
Extraction of a single class from two or more parent classis is said to be multiple
inheritance.
4. Hierarchical inheritance:
Extraction of two or more classes from a single super class is said to be hierarchical
inheritane.
5. Hybrid inheritance:
Combination of two or more types of inheritances is said to be hybrid inheritance.
class Student{
//code
}
class InterOne extends Student {
public void setInterOne(int m1, int m2){
s1=m1;
s2=m2;
}
public void getInterOne() {
[Link](s1+”\t”+s2);
}
}
class InterTwo extends Student{
int s1,s2;
public void setInterTwo(int m1, int m2) {
s1=m1;
s2=m2;
}
public void getInterTwo() {
[Link](s1+”\t”+s2);
}
}
class HiInhDemo{
public static void main(String args[]){
InterOne ione=new InterOne();
InterTwo itwo=new InterTwo();
[Link](1, “Hanan”);
[Link](17,18);
[Link](2, “Venkat”);
[Link](19,20);
[Link](“Students details..”);
[Link]();
[Link]();
[Link]();
[Link]();
}
}
[Link]
Student
Marks
Animals
//method applicable to all animals
Cat Dog
//methods specific to Cat //methods specific to Dog
Dog d1;
d1=new Animal(); (5)
//Animal object can’t be seen like a Dog.
[Link] o;
o=new Student();
o=new Person();
o=new Cat();
Note: A reference variable of a [Link] class can refer to any class object.
Since, [Link] class is directly or indirectly super class of every class in Java.
It is a concept in which two or more methods having same names with different
signature. i.e., number of arguments should be different or data types of the arguments
should be different.
class Adds
{
public void sum(int x, int y)
{
[Link](“Sum of 2 integers is: “+(x+y));
}
public void sum(int x, int y, int z)
{
[Link](“ Sum of 3 integers is : “+(x+y+z));
}
public void sum(float x, float y)
{
[Link](“Sum of 2 floats is :”+(x+y));
}
}
class MethodOverLoadDemo
{
public static void main(String args[])
{
Adds a= new Adds();
[Link](10.5f, 12.5f);
[Link](10,20);
[Link](10,20,30);
}
}
Output:
Example Program:
class Parent{
public void show()
{
[Link](“show of parent…”);
}
}
class Child extends Parent{
public void show()
{
[Link](“show of child…”);
}
public void display()
{
show();
show();
}
}
class OverrideDemo{
public static void main(String args[])
{
Child c=new Child();
[Link]();
}
}
Output:
show of Child…
show of Child…
Note: Re-compile & Re-execute the above app by doing the following changes
public void display()
{
[Link]();
show();
}
Output: show of Parent…
show of Child…
Keyword final:
final keyword using with a variable: A variable which is declared as final whose value
never be changed once assigned.
Class FinalDemo{
public static void main(String args[]){
final int x=10;
[Link](“x = “+x);
//x=20; will not be allowed
//[Link](“x= “+x);
}
}
final keyword using with a method: A method which is declared as final can’t be
overridden in sub classes.
class P{
public final void show()
{
[Link](“show method of P…”);
}
}
class C{
/* public void show() // final method can’t be overridden.
{
[Link] (“show method of C…”);
} */
}
A super keyword is used to call super class constructor from sub class constructor.
super should be the first statement in the sub class constructor.
class A{
int a;
A(int x)
{
a=x;
}
public void showA()
{
[Link](“a= “+a);
}
}
class B extends A
{
int b;
B(int x,int y)
{
super(x);
b=y;
}
public void showB()
{
[Link](“b= “+b);
}
}
A sub class constructor implicitly calls a super class constructor when they have no
parameters.
class A
{
A()
{
[Link](“Constructor of A”);
}
}
class B extends A
{
B()
{
[Link](“Constructor of B”);
}
}
class Demo
{
public static void main(String args[])
{
B b=new B();
}
}
Output:
Constructor of A
Constructor of B
Ex:
class A
{
int x; //instance variable
public void setV(int x)
{
this.x=x;
}
public void getV()
{
[Link](“x= “+x);
}
}
class ThisDemo
{
public static void main(String args[])
{
A a=new A();
[Link](10);
[Link]();
}
}
Output:
X=10
Incomplete method:
A method without code is said to be an incomplete method.
Ex: public abstract void sub(int x, int y);
Incomplete method should be declared as abstract such a method is said to be
abstract method.
Complete class:
A class with all complete methods is said to be complete class.
Complete class is also called as “concrete class”
Object can be created to the complete class.
Incomplete class:
A class that contains at least one incomplete method is called as incomplete
class.
Incomplete class should be declared as abstract. Such a class is also called as
abstract class.
Objects can’t be created to the abstract class, but reference variables can be
created.
Abstract classes are used to extended into sub classes.
The sub class has a responsibility to provide the code for all the incomplete
methods of an abstract classes, otherwise the sub class also becomes an abstract
class
The objects that have the same requirement will be provided as complete
methods.
The objects that have the different requirement will be provided as in complete
methods.
[Link]
public class Maruthi extends Car
{
public void steering()
{
[Link](“Maruthi uses normal steering…”);
}
public void breaking()
{
[Link](“Maruthi uses gas breaking…”);
[Link](“Apply breaks to stop the car…”);
}
}
[Link]
public class Santhro extends Car
{
public void steering()
{
[Link](“Santro uses power steering…”);
}
public void breaking()
{
[Link](“Santro uses hydralic breaks…”);
[Link](“Apply breaks to stop the car…”);
}
}
[Link](“Maruthi…”);
[Link]();
[Link]();
m. breaking();
[Link](“-------------------------“);
[Link](“Santhro…”);
[Link]();
[Link]();
[Link]();
}
}
>javac *.java
>java [Link]
Maruthi…
Fill the fuel into the tank..
Drive the car now…
Maruthi uses normal steering…
Maruthi uses gas breaking…
Apply breaks to stop the car…
-------------------------
Santhro…
Fill the fuel into the tank..
Drive the car now…
Manthro uses power steering…
Santhro uses hydralic breaking…
Apply breaks to stop the car…
// [Link]
interface InterOne
//[Link]
[Link](“Sqaure = ”+(n*n));
[Link](“Cube= ”+(n*n*n));
//[Link]
class DemoApp
[Link](5);
[Link](5);
>javac [Link]
>javac [Link]
>javac [Link]
>java DemoApp
Square = 25
Cube = 125
//[Link]
public interface Rectangle
{
void areaRect(int l, int b);
//[Link]
public interface Square extends Rectangle
{
public void areaSq(int s);
>javac [Link]
>javac [Link]
>javac [Link]
>javac [Link]
Area of Rectangle: 50
Area of Square: 36
Java cannot support multiple inheritance. i.e., two or more classes cannot be extended.
Multiple inheritance can be supported by java indirectly using interfaces.
Multiple interfaces can be implemented by a single class. i.e., two or more interfaces can
be implemented by a single class.
The following example demonstrates how multiple inheritance is achieved using interfaces
and how variable declared in an interface can be accessed.
//[Link]
class MultInh
[Link]();
>javac [Link] s
>javac [Link]
>javac [Link]
>java MultInh
Ex:
int a[ ]= {10, 20, 30}; 10 20 30
0 1 2
An array allocates the memory in a sequential manner.
For arrays the index number starts from “zero”
For n values there will be “n-1” index numbers since the index number starts from
“zero”.
Initialization of an array:
Storing the values into an array at the time of memory allocation is said to be
“initialization” of an array.
Ex:
a[ ] = {10,20,30};
10 20 30
0 1 2
The elements of an array should be accessed by using index numbers;
Hence arrays are also called as “index variables”.
The process of storing the values into an array after the allocation of memory is said to
be assigning the values into an array.
Output:
HASH code is a unique reference number given by JVM to the block of memory.
JVM takes memory address and applies Hash Code Generation Algorithm to generate
hash code.
Accepting the values into an array:
Output:
Syntax:
{value1,value2,….valuen},
{value1,value2,….valuen}
};
Ex:
int a[][]= {
{10, 20},
{30, 40}
};
Note:
2-Dimensional arrays are used in solving matrices.
Example program:
class ArrayTwo
{
public static void main(String args[])
{
int a[][]= { {10,20}, {30,40}};
int i,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
[Link](a[i][j]+” “);
}
[Link](“\n”);
}
}
Output:
>javac [Link]
>java ArrayTwo
10 20
30 40
import [Link].*;
class ArrayTwoAccept
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader( new InputStreamReader([Link]));
int i,j,m,n;
[Link](“Enter the order of matrix [mxn]:”);
m=[Link]([Link]());
n=[Link]([Link]());
int a[][]=new int[m][n];
[Link](“Enter values…”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=[Link]([Link]());
}
}
[Link](“Array elements are…”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
[Link](a[i][j]+” “);
}
[Link]();
}
}
}
Output: >javac [Link]
>java ArrayTwoAccept
Enter the order of matrix [mxn]:
2 2
Enter values… 10 20 30 40
Array elements are…
10 20
30 40
import [Link].*;
class MatrixSum
{
public static void main(String args[])throws IOException
{
BufferedReader br= new BufferedReader( new InputStreamReader([Link]));
int i,j,m,n;
[Link](“Enter order of 2 matrices…”);
m=[Link]([Link]());
n=[Link]([Link]());
int a[][]=new int[m][n], b[][]=new int[m][n], c[][]=new int[m][n];
[Link](“Enter values into matrix a…”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
a[i][j]=[Link]([Link]());
}
[Link](“Enter values into matrix b…”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
b[i][j]=[Link]([Link]());
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
}
[Link](“Result matrix is…”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
[Link](c[i][j]+” “);
[Link]();
}
}
}
3-Dimensional arrays:
In 3-d arrays every element consists of 3 dimensions
In 3-d arrays every element consists of 3 indices.
First index number represents the index of single dimensional array.
The next two indices represents row, column number of a double dimensional
array.
3-d array consists of single dimensional array and every element of a single
dimensional array consists of 2-d array.
1 2
3 4
5 6
7 8
9 10
11 12
toLowerCase():
-This method converts all characters of the string into lower case and returns it.
toUpperCase():
-This method converts all characters of the string into upper case and returns it.
equals():
-This method returns true if two strings are same, otherwise false. This is case
sensitive.
Ex: [Link](s2);
equalsIgnoreCase():
-This method returns true if two strings are same, otherwise false. This is not case
sensitive.
concat()
-This method appends(joins) two string and returns it.
Ex: [Link](s2);
compareTo():
-This method is useful to compare two strings and to know which string is bigger
or smaller. This is case sensitive.
Ex: [Link](s2);
trim():
-This method removes spaces from the beginning and ending of a string.
substring():
-This method is used to extract a sub string from a main string.
“[Link]”
public class StringTest
{
public satic void main(String args[])
{
String s1=”hello”, s2=”KU”, s3=”java”, s4=”friend”;
[Link](“Length of s1=”+[Link]());
[Link](“s2 in lower case=”+[Link]());
[Link](“s3 in upper case=”+[Link]());
[Link](“s1 concats with s4=”+[Link](s4));
}
}
Output:
Length of s1=5
S2 in lower case=ku
S3 in upper case=JAVA
S1 concats with s4=hellofriend
Example Program:
“[Link]”
Output:
add(element):
remove(int position):
clear():
size():
get(int position):
“[Link]”
import [Link].*;
[Link](“Pavan”);
[Link](“Mahesh”);
[Link](“Prabhas”);
[Link](“List: “+v);
Output:
Size of vector: 3
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Converting String Objects to Numberic Objects using the static method valueOf()
Note: parsing methods throws a NumberFormatException if the value of the str does
not represent a number.
Enumerated Types
An enum type is a type whose fields consist of a fixed set of constants. Common
examples include compass directions (values of NORTH, SOUTH, EAST and WEST) and
the days of the week.
Similar to final variables, the names of enum type’s fields are in CAPITAL letters. Since,
they are constants. We can define enumeration type by using enum keyword.
For example, we can specify the days of the week enum type as
{
enum Days
weekend(d);
}
}
}
}
Output:
SUNDAY is a holiday
According to Java programmer an API is set of classes and interfaces that perform a
specific operation.
According ‘C’ programmer an API is set of functions that perform a specific operation.
A package represents a directory that contains related group of classes and interfaces.
A package is used to isolate the classes.
For example we can import the classes of [Link] package as
import [Link].*;
Where, java is a directory name and io is another sub directory within it.
‘*’ represents all the classes and interfaces of that io sub directory.
Advantages of Packages:
Packages are useful to arrange related classes and interfaces into a group i.e. the
classes and interfaces that performs the same task will be grouped together as a
package. For example, [Link] package contains all the classes and interfaces that
perform input and output operations.
Packages allow to two classes with same names provided in two different
directories.
Packages provide a way to “hide” classes thus preventing the other programs
that are meant for internal use only.
A group of packages is called a library. The classes and interfaces of a package are
like books in a library and can be reused several times. This reusability nature of
packages makes programming easy. Just think, the packages in java are created
by JavaSoft people only once, and millions of programmers all over the world are
daily by using them in various programs.
1. Pre-defined Packages:
These are the packages which are already available in java language. These
packages provide all necessary classes, interface and methods for the
programmer. For every task there is a method available in Java and that method
can be used by the programmer without developing the logic on his own.
Some Pre-defined packages are
[Link]: uitl stands for utility. It consists of Language utility classes such as
ArrayList, Vector, Stack, LinkedList, Date etc.
[Link]: io stands for input and output. It consists of input/output support classes.
These classes used to perform input-output related tasks.
[Link]: net stands for network. Client-Server programming can be done using
this package. They include classes for communicating with local computer as well
as with internet servers.
[Link]: awt stands for abstract window toolkit. They include classes to develop
GUI applications.
[Link]: sql stands for structured query language. They include classes to deal
with databases such as Oracle, MySQL etc.
Similar to Pre-defined packages, the users of the Java language may also create their
own packages called as User-defined packages. A user defined package can be created
using the keyword “package”.
Declare the package at the beginning of a file.
Addition
Add(-,-) {….}
package mathops;
public class Addition
{
public void add(int x,int y)
{
[Link](“Addition of two integers:”+(x+y));
}
}
Steps to compile the package:
D:\Programs\Java programs>javac –d. [Link]
[Link]
import [Link];
class UseAdd{
public static void main(String args[]){
Addition a=new Addition();
[Link](10,20);
}
}
>javac [Link]
>java UseAdd
Addition of 2 integers is:30
package mathops;
public class Subtraction{
public static void main(String args[]){
[Link](“Subtraction of 2 integers is:”+(x-y));
}
}
>javac –d. [Link]
import mathops.*;
public class UseAddSub
{
public static void main(String args[])
{
Addition a=new Addition();
Subtraction s=new Subtraction();
[Link](10,20);
[Link](10,20);
}
}
>javac [Link]
>java UseAddSub
Addition of 2 integers is: 30
Subtraction of 2 integers is: 10
Creating sub packages: A package within another package is said to be sub package.
Syntax: package [Link];
Adding a class to sub package:
package [Link];
public class Wish
{
public void wishing()
{
[Link](“Good evening…”);
}
}
>javac –d . [Link]
[Link]
When we import a package using “*”, all public classes are imported. However, we may
prefer to “not import” some classes i.e. we may like to hide these classes from accessing
outside the package. Such classes should not be declared as “public”.
Example:
package pone;
class A
{
//code of A
}
>javac -d . [Link]
The class A which is not declared as public is hidden from outside of the package pone.
This class can be accessed in the same package.
class B
{
A a = new A();
..
}
>javac [Link]
When we compile [Link], the compiler will generate an error, since the class A which is
not declared as public cannot be imported.
It is a feature used to access static members of a class directly i.e. without using
ClassName and dot.
Syntax:
import static [Link];
Or
import [Link];
class A{
The above program can be written using static import which allows to access a public
static member directly without using classname or interfacename and dot.
import static [Link].*;
class A{
public static void main(String args[]){
double r = 5.5;
private members can be accessed in the same class in which they are defined.
Hence, the scope of private is class scope
protected members can be accessed in the other classes of same package and in
the sub classes.
Note: Sub classes may also be present in different package.
Hence, the scope of protected members is sub class scope.
D:\Programs\Java>javac [Link]
It gives an error as ‘javac’ is not recognized internal or external command.
So, we need to set the path by using the variable path.
>set path=C:\Program Files\Java\Jdk1.7.0\bin
Now we can compile and execute the java file
>javac [Link]
>java xxx
Note:
Since, this path setting will be applicable until we close the editor.
Example program:
class Err
{
[Link](“Hello”)
}
}
>javac [Link]
class Err{
}
}
Output:
>javac [Link]
>java Err
3. Logical Errors:
These are the errors that occur due to improper or bad logic written by the
programmer.
Logical errors are not detected either by the compiler or not by the JVM.
The programmer is solely responsible for them.
These errors does not cause any harm to the program. i.e., no loss of data.
Example Program:
class Err{
int a, s=5;
Output:
Area of Square= 20
Exception Handling:
Handling the exception at run-time such that the program should be terminated
in a normal way and there should not be any loss of data is said to be Exception
Handling.
Exceptions are of two types
1. Checked Exception
2. Unchecked Exception
1. Checked Exception:
The exceptions checked at compile-time by the java compiler are called ‘Checked
Exceptions’. The programmer should handle the checked exceptions or throw them.
public static void main(String args[]) throws IOException
2. Unchecked Exception:
The exceptions checked by the JVM are called ‘Unchecked Exceptions’.
Unchecked Exceptions may be handled or may not be handled by the programmer.
When it is occurred the program will be terminated abnormally.
Ex: ArithmeticException, NumberFormatException etc..
Class: Exception
Exception is a super class for all exceptions in java.
|
Throwable
|
Exception
|-ArrayIndedOutOfBoundsException
:
An Exception Example:
class Excep
{
public static void main(String args[])
{
[Link](“Open a file..”);
[Link](“Write some data..”);
int a, b, c;
a=[Link](args[0]);
b=[Link](args[1]);
c=a/b;
[Link](“Result=”+c);
[Link](“Close a file..”);
}
}
Output:
>javac [Link]
>java Excep
Open a file..
Write some data..
Exception in thread “main” [Link]: / by zero..
try:
tryblock scans for run-time errors.
Syntax:
Try
{
Statements to scan for a run-time error
}
catch:
The programmer should write the catch block to display the exception details. catch
block will be executed when an exception is raised.
Syntax:
catch(Exceptionclass ref)
{
Statements to handle Exception
}
finally:
finally is a block of statements that contains the code for closing the files, closing
the data base connections etc..
Syntax:
Finally
{
Statements to close the database connections
}
class ExpOne{
public static void main(String args[])
{
[Link](“Open a file..”):
[Link](“Write some data..”);
int a, b, c;
try
{
a=[Link](args[0]);
b=[Link](args[1]);
c = a / b;
[Link](“Result= “+c);
}
catch(ArithmeticException ae)
{
[Link](“Error: “+ae);
[Link](“b value shoud not be zero..”);
}
finally
{
[Link](“Close a file..”);
}
[Link](“Program terminates..”);
}
}
Output:
>javac [Link]
>java ExpOne 10 0
Open a file..
Write some data..
Error:[Link]: / by zero
b value should not be zero..
Close a file..
Program terminates..
Dr. V. Venkateshwarlu Page 149
Handling Multiple Exceptions:
Most of the times there is a possibility of getting more than one exception. In this
case, the programmer should write multiple catch blocks to handle each one of them.
class ExpTwo
{
public static void main(String args[])
{
[Link](“Open a file..”):
[Link](“Write some data..”);
int a, b, c;
try
{
a=[Link](args[0]);
b=[Link](args[1]);
c = a / b;
[Link](“Result= “+c);
}
catch(ArithmeticException ae)
{
[Link](“Error: “+ae);
[Link](“b value shoud not be zero..”);
}
catch(NumberFormatException nfe)
{
[Link](“Error: “+nfe);
[Link](“Pass only integer values..”);
}
catch(ArrayIndexOutOfBoundsException aioe)
{
[Link](“Error: “+aioe);
[Link](“Not enough values..”);
}
finally
{
[Link](“Close a file..”);
}
[Link](“Program terminates..”);
}
}
class ExpThr{
public static void main(String args[]){
[Link](“Open a file..”):
[Link](“Write some data..”);
int a, b, c;
try
{
a=[Link](args[0]);
b=[Link](args[1]);
c = a / b;
[Link](“Result= “+c);
}
catch(Exception ae)
{
[Link](“Error: “+e);
}
finally
{
[Link](“Close a file..”);
}
[Link](“Program terminates..”);
}
}
Import [Link].*;
class ExpFour
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
int a, b, c;
[Link](“Enter two values:”);
a=[Link]([Link]());
b=[Link]([Link]());
c= a+b;
[Link](“\n Sum: “+c);
}
}
Output:
>javac [Link]
>java ExpFour
Enter two values:
10
20
Sum: 30
import [Link].*;
class ExpFour
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
int a, b, c;
try
{
[Link](“Enter two values:”);
a=[Link]([Link]());
b=[Link]([Link]());
c= a+b;
[Link](“\n Sum: “+c);
}
catch(IOException e)
{
[Link](“Error:”+e);
}
}
}
Output:
>javac [Link]
>java ExpFour
Enter two values:
10
20
Sum: 30
Step 2: The user should provide a zero argument constructor in a user defined
exception.
Ex:
public MarksOutOfBoundsException( ) { }
Step 3: The user should provide a one parameterized constructor and the parameter
should be a String. It should call a super class constructor.
Ex:
Step 4: When we want to raise our own exception, we need to create an object to the
exception class and throw it using throw clause.
MarksOutOfBoundsException me = new MarksOutOfBoundsException(“Exception
details..”);
throw me;
import [Link].*;
class UserExp
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
int marks;
try
{
[Link](“Enter Marks: “);
marks=[Link]([Link]());
if(marks>100)
{
MarksOutOfBoundsException me=new
MarksOutOfBoundsException(“Marks should not be greater than 100”);
throw me;
}
[Link](“Ur Marks: “+marks);
}
catch(MarksOutOfBoundsException me)
{
[Link](“Error: “+e);
}
}
}
Output:
>javac [Link]
>java UserExp
Enter Marks: 110
Error:[Link]: Marks should not be greater than 100
Note: To create our own thread it must be a subclass or it must be extended form
Thread Class
“[Link]”
public class MThread
{
public static void main(String args[])
{
Thread t = [Link]();
[Link](“After changing..”);
[Link](“Current Thread: “+t);
}
}
Output:
>javac [Link]
>java MThread
Current Thrread: [main, 5, main]
After Changing..
Current Thread: [Venkat, 6, main]
“[Link]”
public class CThread extends Thread
{
String tname;
public CThread(String name)
{
super(name);
tname=name;
[Link](tname+” Thread Created..”);
start();
}
public void run()
{
[Link](tname+” started..”);
try
{
for(int i=1; i<=5; i++)
{
[Link](tname+” : “+i);
[Link](1000);
}
}
catch(Exception e)
{
[Link](“Error: “+e);
}
[Link](tname+” thread terminated..”);
}
}
Output:
>javac [Link]
>javac [Link]
>java MainThread
Dead Lock:
Dead Lock is an error that can be encountered in multithreaded programs
It occurs when two or more threads wait indefinitely for each other to relinquish
locks.
-An Applet is a small program that runs very fast in the net and runs as a part of web application
in the browser.
Browser:
Web application:
-A web application is a set of web pages which can be executed using the browsers.
Examples:
Internet Explorer
Mozilla Firefox
Netscape Navigator
Opera etc
init():
The init stage consists of initializing any methods and variables that applet needs to function,
such as images to be loaded. The init method is called when the applet is first loaded.
start():
The start stage starts the primary functions of an Applet. For example, if an applet plays a
sound, it could start playing during the start stage. The start method is called when the init
method has finished and the applet is ready to execute.
paint():
The paint stage occurs whenever the Applet’s display must be thrown on the screen. This
happens right after the start stage.
stop():
The stop stage can be used to stop any actions that might still be in progress from the start
stage.
destroy():
destroy is called automatically, and completes any memory cleanup or garbage collection that
needs to be done when an Applet destroyed.
Class: Graphics:
Ex:
To develop the applet based application, we should extend our class from [Link].
“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
[Link](“Hello”, 250,250);
>javac [Link]
Applet will be executed in the browser, the browser understands the scripting languages.
So, we should write a HTML(Hyper Text Mark up Language) file to provide the information
about an Applet
“[Link]”
<html>
<body>
</body>
</html>
i. Using Browser
i. Using Browser
Open internet explorer and type the URL(Uniform Resource Locator) of html file as
D:\appletapps\[Link]
ii. appletviewer
Open Command prompt (DOS Prompt) and move to the D:\appletapps using cd
command
D:\appletapps>appletviewer [Link]
“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
>javac [Link]
In command Prompt
>appletviewer [Link]
We can pass parameters from HTML file to the Applet class, Such a concept is called as
dynamic programming through applets.
Parameter can be passed to the applet using a predefined tag called as “param” in
HTML file.
Example Application
“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
public class AppCol extends Applet
{
String str;
public void init()
{
setBackground([Link]);
setForeground([Link]);
str=getParameter(“bname”);
}
public void paint(Graphics g);
{
[Link](str, 250,250);
}
}
>javac [Link]
In command prompt
>appletviwer [Link]
1. drawLine()
It is a method used to draw a line.
Syntax:
drawLine(int x1, int y1, int x2, int y2)
Example Program:
“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
public class LineDemo extends Applet
{
public void paint(Graphics g)
{
[Link](100, 100, 200, 200);
}
}
Compile [Link]
>javac [Link]
“[Link]”
<html>
<body>
<applet code=”LineDemo” width=500 height=500 >
</applet>
</body>
</html>
Syntax:
drawRect(int x1, int y1, int width, int height)
fillRect(int x1, int y1, int width, int height)
Example Program:
“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
public class RectDemo extends Applet
{
public void paint(Graphics g)
{
[Link](100, 50, 250, 200);
[Link](25, 25, 100, 100);
}
}
Compile [Link]
>javac [Link]
“[Link]”
<html>
<body>
<applet code=”RectDemo” width=500 height=500 >
</applet>
</body>
</html>
Syntax:
drawOval(int x1, int y1, int width, int height)
fillOval(int x1, int y1, int width, int height)
Example Program
“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
public class OvalDemo extends Applet
{
public void paint(Graphics g)
{
[Link](100, 50, 250, 200);
[Link](25, 25, 100, 100);
}
}
Compile [Link]
>javac [Link]
“[Link]”
<html>
<body>
<applet code=”OvalDemo” width=500 height=500 >
</applet>
</body>
</html>
Syntax:
drawRoundRect(int x1, int y1, int width, int ht, int xDiameter, int yDiameter);
5. drawArc()
It is used to draw an arc.
Syntax:
drawArc(int x1, int y1, int width, int height, int startAngle, int sweepAngle);
Example Program:
“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
public class ArcDemo extends Applet
{
public void paint(Graphics g)
{
[Link](100, 50, 250, 200, 0, 120);
}
}
Compile [Link]
>javac [Link]
“[Link]”
<html>
<body>
<applet code=”ArcDemo” width=500 height=500 >
</applet>
</body>
</html>
>appletviewer [Link]
Syntax:
Example Program:
“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
public class PolygonDemo extends Applet
{
public void paint(Graphics g)
{
int x[] = {100, 200, 100, 200, 100};
int y[] = {100, 100, 200, 200, 100};
int n = 5;
[Link](x, y, n);
}
}
Compile [Link]
>javac [Link]
“[Link]”
<html>
<body>
<applet code=”PolygonDemo” width=500 height=500 >
</applet>
</body>
</html>