OBJECT ORIENTED PROGRAMMING WITH JAVA by Ladwa, Hanumanth
OBJECT ORIENTED PROGRAMMING WITH JAVA by Ladwa, Hanumanth
with
JAVA
Hanumanth Ladwa
Dedicated to my Parents and
Sisters
Contents
Chapter
Chapter Title Page no.
no.
5 Operators 36 – 48
6 Selection and iterative statements 49 – 68
7 Class 69 – 106
Object: student
Data members
Rollno.
Name
percentage
Methods
getdata()
putdata()
Class: class is a fundamental building block of object-oriented
program which serves as a blueprint. Class is a user defined data
type. Class acts as a template using which we will be able to create
any number of objects of that type. A class is a collection of similar
objects that share common features.
Example: in the above example of objects, the group of fruit is called
class. A group of flowers is called class.
Similarly, the solar system is a class whereas, an individual planet in
a solar system is called an object.
class
Data members
Data1
Data2
…
Data-n
Methods
Method 1
Method 2
…
Method-n
Data abstraction: the act of including only essential details of an
entity without including background details about it is called data
abstraction.
Example, let us consider the mobile cell phone with attributes such
as, color, Bluetooth, mobile cell phone camera etc. we are not
considering how Bluetooth works, or how the camera works or even
how the circuit inside the mobile is designed and what is happening
inside. We are interested only in using the mobile cell phone and its
features. Therefore, it is required to know how to operate a mobile
cell phone rather than its internal working, the internal working is
hidden from the user is called abstracted data.
Data encapsulation: the process of wrapping up data and functions
into a single unit called class is called data encapsulation. Data
encapsulation makes data hidden; data hiding is an act of insulating
data from outside programs. The data is not accessible directly to
the outside world, except for the functions defined inside the class
definition. These function members provide an interface between the
data and outside world to access the data out of class.
Inheritance: it is a process of acquiring properties from an object of
one class to properties of an object of another class. The class that
inherits the properties to the other class is called base class or
parent class or super class.
The class that inherits the properties from the other class is called
derived class or child class or subclass.
The programmers can add new features to the already existing class
without modifying that class. This is achieved by deriving a new
class from the already existing class. The derived class has its base
class features, in addition to that it has its own features.
The process of two or more functions having the same name with
different return types or different number of arguments is called
function overloading.
Here paint() items are single interface and paint() furniture, paint()
vehicle, paint() building and paint() fabric are many methods.
Example:
int add (int a, int b);
float add (float x, float y) ;
Here, add is a function name which is common in both the functions
but return types of these two functions are different, one is int and
another is float. And the number of arguments is the same in both
the functions i.e. 2. Function overloading is used when we want to
perform the same operations on different data. Function overloading
has the same interface but many methods. You can observe in the
above example add is the function name i.e. interface and many
methods means we have addition operations to be performed on two
different data types.
Dynamic binding: binding is the process of providing reference
between more than one module. Dynamic binding means the code
associated with a given procedure call is not known until the time of
the call at run-time or at the time of program execution.
Message passing: message passing is a request for execution of a
procedure for an object. Therefore, a message invokes a procedure
in the receiving object to generate the desired output.
Applications of OOP:
- Computer graphic applications.
- CAD/CAM software.
- Object oriented databases.
- User interface design such as windows.
- Real-time systems.
- Simulation and modelling.
- Artificial intelligence and expert systems.
- Hypermedia, expert text and hypertext.
- Decision support systems and office automation systems.
- Parallel programming and neural networks.
EXERCISES
1. What are the features of OOP?
2. List the naming conventions used in POP and OOP.
3. Differentiate between POP and OOP.
4. Explain the basic concepts of OOP.
5. Describe the advantages of OOP.
6. List the applications of OOP.
CHAPTER 2
EVOLUTION OF JAVA
Java history:
Java is a general purpose object oriented programming language
developed by Sun Microsystems of USA in 1991. Earlier java was
called oak (because it is a symbol of strength and chosen as a
national tree of many countries) by James Gosling (One of the
inventors of the language) who is known as Father of Java. In 1995
Oak was renamed as Java. Java is an island in Indonesia.
Developed this language to make it platform independent meaning
that the programs written in java can be executed on any of the
systems irrespective of hardware and operating system. Java
programs are written and executed on any of the computer systems,
because java produces the intermediate code called bytecode that
can be interpreted by any system as it is not tied with hardware and
software configuration of the computer system. The team members
of java also known as Green Team, initiated the project to develop a
programming language for digital devices like, set-top box,
interactive television etc. It was best suited for internet programming.
Presently, Java is used in internet programming, like mobile devices.
Electronic games, electronic business solutions etc.
Features of Java:
The primary objective of developing Java programming language
was to make it portable, simple and secure programming language.
In addition to this, there are some other features of Java as
described below.
- Simple: Java is simple, easy to learn and easy to understand
because Java syntax is similar to C++ programming language.
Java is made simple by removing some complicated features of
C++ such as explicit pointers, friend functions, inline functions,
goto statements, operator overloading etc. Java allocates and
deallocates memory for the object at runtime hence, the objects
are allocated dynamically and deleted by automatic garbage
collection once the program execution terminates.
- Object Oriented: Everything in java is considered as an
object. The software is organized as a combination of different
types of objects that incorporate both data and behavior. Object
oriented methodology makes the software development
process easy and provides certain rules for maintenance.
- Platform independent: Java is not dependent on machine
hardware as well as software. It is completely independent of
any platforms. A platform is the hardware or software
environment in which a program runs. Java can be executed on
multiple platforms, for example, windows, Linux, sun Solaris,
Mac/OS, etc. Java is compiled by the compiler and converted
into byte code. This byte code is also called as intermediate
code that can be interpreted by the Java Virtual Machine
(JVM). This byte code can be executed on any of the platforms
irrespective of their configurations. Hence, java is a portable
programming language. Java programs can be easily moved
from one computer system to another. Java is architecture
neutral, in C programming, int data type takes 2 bytes of
memory for 32 bit architecture and 4 bytes for 64 bit
architecture. However, it takes 4 bytes of memory for both 32
and 64 bit architecture in Java.
- Secured: Java is known for security. As java is used to
develop internet applications called applets, java ensures that
no viruses are communicated with an applet. As java does not
support pointers, it ensures that the programs cannot gain
access to memory locations without proper authorization.
- High performance: Java is both a compiled and interpreted
programming language. Java compiler produces an
intermediate code called byte code. This byte code can be
executed on any of the computer systems. This intermediate
code of java makes the java program execute the program
faster. Hence, provides high performance.
- Robust: java has the ability to use strong memory
management. As there is no use of pointers in java avoids
security issues. It provides garbage collection which runs on
the java virtual machine to delete the unwanted objects that are
no longer required. Java strongly checks for type and has an
exception handling mechanism. Hence, makes Java a robust
programming language.
- Distributed: Java is designed to distribute the applications on
the networks. Java applications allows programmers to access
remote objects on the internet, enables multiple programmers
at remote locations to collaborate with one another and work
together on a single project.
- Multi-threaded: A thread is a sequence of finite sets of
instructions written as a separate program, executing
concurrently. If multiple threads are to be executed, then the
advantage of using multi thread is that, instead of allocating
memory for each thread, it shares the common memory
location. Threads are used for multimedia, web applications
etc.
- Dynamic: Java is capable of dynamically linking in new class
libraries, methods and objects. Java supports functions written
in C and C++ programming languages. These functions are
known as native methods. These methods are linked
dynamically at runtime. Even the objects are allocated memory
space at the time of program execution and frees up the
memory locations by the built-in system called garbage
collection, as soon as the program terminates its execution.
How does Java differ from C?
Some of the features of the C programming language that causes
problems are eliminated from java. Those features are list as below:
- The user defined data types structures and unions are not
included.
- In java, header files or preprocessor directives are not
required.
- No sizeof and typedef statements are used.
- Java does not support the type modifiers such as auto ,
extern , register , signed and unsigned .
- The goto statement is omitted.
- Java does not support explicit pointers.
- Java adds new operators such as instanceof and >>>.
- Java adds labeled break and continue statements.
- Functions in java that accept no parameters must be declared
with empty brackets and not using void .
How does Java differ from C++?
Some of the features present in C++ programming language are
eliminated in java that are listed as below.
- Java does not support operator overloading.
- Java does not use default arguments.
- Java doesn’t support multiple inheritance (instead java uses
interface).
- Java does not support global variables. Every variable and
method must be declared in a class.
- Java does not support destructor functions. Instead, java uses
a method called finalize().
- Java is both a compiled and interpreted programming
language. Java source code is converted into byte code at
compile time and the interpreter executes this bytecode at
runtime and produces output.
Java and internet: Java is associated with the internet. Web
browsers to run applets on the internet. Java programming language
is used to create applet programs and run them locally using a java
enabled browser such as hot java, used to download an applet
located on the internet and it on the local computer system. Internet
users can set their websites containing java applets that could be
used by other remote users of the internet. Because of this fact, java
is also known as an internet language.
Java and World Wide Web: java communicates with a web page
through a special tag called <applet>. Java users send a request for
an HTML document to the remote computers and browser. The web
browser is a program that accepts a request, processes the request
and sends the required documents to the local computer. The
document contains the applet tag which identifies the applet. The
corresponding applet is transferred to the local computer. The java
enabled browser on the local computer interprets the byte code and
provides output.
www is a collection of information stored on the internet. It is an
information retrieval system. www contains web pages that provide
both information and controls. Web pages contain HTML tags that
enable us to retrieve, manipulate and display documents across the
globe. Java enables web pages to display animation, graphics, and
special effects. The following figure depicts exactly how the local
computer system user communicates to the java applet on the
remote computer system.
Web browsers: web browser is an application software used to
locate, fetch and show the content on the world wide web. Web
browser acts as a client whereas the remote computer holding
information acts as a web server. Web browser sends a request
object for information to the remote web server. The web server
responds back by sending a response object to the web browser that
contains information. The information fetched from the server
contains HTML tags that are interpreted by the browser. Some of the
examples for web browsers are, hot java, Netscape navigator,
internet explorer, google chrome, firefox mozilla etc.
Java environment: java environment includes a large number of
development tools and number of classes and methods. The
development tools are present in a unit called Java Development
Kit (JDK) and the classes and methods are present in a unit called
Java Standard Library (JSL) or Application Programming
Interface (API)
Java Development Kit:
Tools Description
Applet Enables to run java applets.
viewer
Java Java interpreter which runs both
applet and application by interpreting
byte code.
Javac The java compiler which translates
java source code to byte code.
Javadoc Create HTML format documentation.
Javah Produces header files for use with
native methods.
Javap Java disassembler enables to convert
byte code into program description.
Jdb Java debugger helps to find errors in
the program.
Application Programming Interface (API): most commonly used
packages are listed below:
Language support package: it is a collection of classes and
methods required for implementing basic features of java.
Utilities package: it is a collection of classes to provide utility
functions such as, date and time functions.
Input-output package: it is a collection of classes required for input-
output manipulation.
Networking package: it is a collection of classes for communicating
with other computers via the internet.
Applet package: it is a collection of classes that allows one to
create a java applet.
The following diagram depicts the process of building and running a
java application program.
Java Runtime Environment: java runtime environment facilitates
the execution of programs. It consisting of the following:
- Java Virtual Machine (JVM): JVM interprets the byte code
and produces an output. This byte code is also called an
intermediate code that can be executed on any system. It
follows the Write Once and Read Anywhere (WORA) principle.
- Runtime class libraries: it is a collection of class libraries
used to execute java programs.
- User interface toolkits: Abstract Window Toolkit (AWT) and
swing support various input methods to interact with the
application program.
- Deployment tools: Java Runtime Environment consisting the
following tools.
Java plug-in: This plug-in enables the execution of a java
applet on the browser.
Java web start: This tool enables remote deployment of
an application.
EXERCISES
1. Explain the evolution of java.
2. Describe the features of java.
3. How does Java differ from C?
4. How does Java differ from C++?
5. Explain how java and the internet are related.
6. Explain the relation between java and www.
7. What are web browsers? Explain with examples.
8. Explain the tools available in JDK.
9. Describe API with its components.
10. Briefly explain Java Runtime Environment.
CHAPTER 3
OVERVIEW OF JAVA
Introduction: Java is a general purpose, object oriented
programming language. Java programming language is used to
develop two types of programs.
- Standalone applications
- Web applets
Standalone applications are those programs that are executed on
the local computer system whereas web applets are developed for
internet applications. An applet is a program situated on a remote
computer system (server) that can be downloaded and executed on
a local computer (client). Let us discuss java standalone applications
first.
FirstProgram.java FirstProgram.class
Unary operators: these are the operators that operate only on one
operand.
Operator Name
! Logical NOT. It is used to reverse the state of operand. If
a condition is true then logical NOT return false value.
& Address-of operator. Returns address of the operand.
~ One’s complement. Convert 0 to 1 and 1 to 0
* Pointer dereference. Represent pointer type.
+ Unary plus. Represent a positive operand.
++ Increment. Increase the value of an operand by 1.
- Unary minus. Represent a negative operand.
-- Decrement. Decrease the value of an operand by 1.
Increment operator (++): ++ is used to increment the value of the
operand by 1 and the operator can appear before or after the
operand. If the operator prefix operand is called pre-increment
operator. If the operator suffix operand is called post-increment
operator. In case of pre-increment, the value of operand is
incremented and then used. In case of post increment, the value of
operand is used then incremented.
Example, if a=5, then a++ returns 5
If a=5, then ++a return 6
Decrement operator (--): -- used to decrement the value of the
operand by 1 and the operator can appear before or after the
operand. If the operator prefix operand is called pre-decrement
operator. If the operator suffix operand is called post-decrement
operator. In case of pre decrement, the value of operand is
decremented then used. In case of post decrement, the value of
operand is used then incremented.
Example, if a=5, then a--returns 5
If a=5, then --a returns 4
Binary operators: the operator that operates on two operands is
called binary operators. Binary operators are classified as, arithmetic
operators, relational operators, logical operators, bitwise operators
and assignment operators.
Arithmetic operators: the operators supported by Java are: + - * / %
Let us consider, a=10 and b=20 then
Operator Description Example
+ Adds two or more operands a+b returns
30
- Subtract second operand from the first a-b returns
-10
* Multiply first and second operand a*b return
200
/ Performs integer division and returns a/b return 0
quotient
% Performs modular division and returns a%b return 10
remainder
// Write a program to demonstrate an arithmetic operators
class Arithmetic
{
public static void main(String args[])
{
int a =10,b=20;
System.out.println(“a=”+a);
System.out.println(“b=”+b);
System.out.println(“a+b=”+(a+b));
System.out.println(“a-b=”+(a-b));
System.out.println(“a*b=”+(a*b));
System.out.println(“a/b=”+(a/b));
System.out.println(“a%b=”+(a%b));
}
}
Output:
F:\java programs >javac Arithmetic.java
F:\java programs >java Arithmetic
a=10
b=20
a+b=30
a-b=-10
a*b=200
a/b=0
a%b=10
It is also possible to receive input from the user through the keyboard
as shown in the following programming example.
import java.util.Scanner;
class Add
{
public static void main(String args[])
{
int a,b,c;
Scanner scan=new Scanner(System.in);
System.out.println("Enter the value for a: ");
a=scan.nextInt();
System.out.println("Enter the value for b: ");
b=scan.nextInt();
c=a+b;
System.out.println("Sum of "+a+" and "+b+" = "+c);
}
}
Output:
F:\java programs>javac Add.java
F:\java programs>java Add
Enter the value for a:
10
Enter the value for b:
40
Sum of 10 and 40 = 50
Relational operators:
The relational operators supported by Java are: ==, !=, >, >=, <, <=
Let us consider, a=10 and b=20 then:
Operator Description Example
== Compares the values of two operands (a==b) return
equal or not false
!= Compares the values of two operands (a!=b) return
equal or not true
> Checks if the value of the operand on (a>b) return
the left is greater than the right false
operand.
< Checks if the value of the operand on (a<b) return
the left is less than the right operand. true
>= Checks if the value of the operand on (a>=b) return
the left is greater than or equal to the false
right operand.
<= Checks if the value of the operand on (a<=b) return
the left is less than or equal to the right true
operand.
Logical AND: the result of the logical AND is true, when both the
operands are true; otherwise the result is false.
Operand1 Operand2 Operand1 &&
Operand 2
False False False
False True False
True False False
True True True
Logical OR: the result of the logical OR is false, when both the
operands are false; otherwise the result is true.
Operand1 Operand2 Operand1||Operand2
False False False
False True True
True False True
True True True
Logical NOT: the result of the logical NOT is true when the
operand is false and vice versa.
Operand !Operand
False True
True False
The bitwise operators supported by C are listed in the following
table:
Operator Description Example
& Binary AND return bit 1 if both a&b=0000
operands bits are 1, otherwise 0. 1010
| Binary OR return bit o if both operands a|b=0000 1011
bits are 0, otherwise 1.
^ Binary eXclusive OR (XOR) returns bit a^b=0000 1110
0 if there are odd numbers of 1’s.
Otherwise 1.
~ Binary negation complements the bits. ~a=0000 0101
Converts bits 1 to 0 and vice versa.
<< Binary left shift operator shifts the a<<2=0010
number of bits specified onto the left. 1000
The right shift bitwise operator changes the content of the operand by
shifting the number of bits specified from right.
General form:
Operand right_shift_operator number_of_bits
Example: a>>2
The result of the bitwise right shift operator is,
Before right shifting of bits
0 0 0 0 1 0 1 0
After two bits shifted to right
0 0 0 0 0 0 1 0
Shorthand assignment operators:
Shorthand assignment operators are a compact way of writing
assignment statements in an expression. The shorthand assignment
operator works on both arithmetic operators and bitwise operators.
The general form of a shorthand assignment operator is,
Operand operator=expression
The following table shows the use of assignment operators:
Operator Assignment Shorthand
statements assignment
+ (plus) a=a+b a+=b
- (minus) a=a-b a-=b
* (multiplication) a=a*b a*=b
/ (integer division) a=a/b a/=b
% (modular division) a=a%b a%=b
& (bitwise AND) a=a&b a&=b
| (bitwise OR) a=a|b a|=b
^ (bitwise XOR) a=a^b a^=b
<< (bitwise left shift) a=a<<b a<<=b
>> (bitwise right a=a>>b a>>=b
shift)
x;
.sin(30);
m.out.println(“The sin of 30 is”+x);
.sqrt(4);
m.out.println(“The square root of 4 is”+x);
.abs(-19);
m.out.println(“The absolute value of -19 is”+x);
.floor(11.4);
m.out.println(“The rounded down number 11.4 is”+x);
.ceil(14.5);
m.out.println(“The rounded up number 14.5 is”+x);
programs>javac MathDemo.java
programs>java MathDemo
of 30 is-0.9880316240928618
uare root of 4 is2.0
solute value of -19 is19.0
unded down number 11.4 is11.0
unded up number 14.5 is15.0
EXERCISES
1. What is operator? explain the types of operators.
2. Explain arithmetic operators with an example for each.
3. Describe relational operators with a programming example.
4. Explain logical operators with the example using the truth
table.
5. Explain shorthand assignment operators.
6. Explain increment and decrement operators.
7. What are conditional operators? explain with an example.
8. Explain bitwise operators with an example.
9. What are the special operators used in java? Explain them.
10. How to evaluate an arithmetic expression? Explain with an
example.
11. What is the precedence of operator? give the details of
precedence of operators and their associativity.
12. What is type casting? Mention its types.
13. Define implicit type casting with an example.
14. What is explicit type conversion? Explain with an example.
15. List the uses of any five mathematical functions.
CHAPTER 6
SELECTION AND ITERATIVE
STATEMENTS
Introduction: in general instructions written are executed in a linear
fashion called sequential order. It is not mandatory that all the
instructions are to be executed in the order in which they are written,
in some situations, the control may bifurcate based on the condition,
some statements get executed repeatedly a certain number of times
based on the condition. Some statements may jump from one
statement to another based on the condition imposed.
Java provides two types of control statements:
- selection statements
- iterative statements
selection statements: selection statements are also called
conditional control statements used to check the condition, based on
the condition, the control makes decision and branching.
There are four types of selections statements,
i. if-statement
ii. if-else statement
iii. nested statement
iv. switch statement
if statement: if statement is also called a one-way branching
statement. In simple if statements, if the condition is true then the
statement or set of statements will get executed. If the condition is
false then the next statements, if any, will get executed.
The general form of if statement is,
if(condition) OR if(condition)
statement1; {
statement1;
statement2;
…
statement-n
}
Flowchart:
// Write a program to find the largest of two numbers
class Largest
{
public static void main(String args[])
{
int a=5,b=10,large;
large=a;
if(b>large)
large=b;
System.out.println(“Largest number is ”+large);
}
}
Output:
F:\java programs >javac Largest.java
ligibility
unt=0, count1=0,count2=0;
]={18,25,27,16,20};
i<5;i++)
>=21)
+=1;
=count-count1;
m.out.println("Number of people eligible for marriages are "+count1);
m.out.println("Number of people not eligible for marriages are
"+count2);
programs >javac Eligibility.java
Flowchart:
/* Write a program to count how many odd and even numbers
are present in the given list of numbers. */
class EvenOdd
{
public static void main(String args[])
{
int number[]={10,13,15,16,20};
int even=0,odd=0;
for(int i=0;i<number.length;i++)
{
if(number[i]%2==0)
{
even+=1;
}
else
{
odd+=1;
}
}
System.out.println(“Even numbers: ”+even);
System.out.println(“Odd numbers: ”+odd);
}
}
Output:
F:\java programs >javac EvenOdd.java
Flowchart:
OR
// Write a program to print even
numbers
class Even
{
public static void main(String args[])
{
int i=2;
do
{
System.out.print(i+”,”);
i=i+2;
} while(i<=10);
System.out.print(“\b.”);
}
}
Output:
F:\java programs>javac Even.java
Flowchart:
Where, IV is initial value and FV is final value
// Write a program to find the sum of n natural numbers
class Sum
{
public static void main(String args[])
{
int i, sum=0;
for(i=1;i<=10;i++)
sum=sum+i;
System.out.println(sum);
}
}
Output:
F:\java programs>javac Sum.java
*
**
***
****
*****
******
*******
********
*********
EXERCISES
1. Explain a simple if statement with an example.
2. Describe if else statement with syntax, flowchart and an
example.
3. What is a nested loop? Explain with a programming
example.
4. Define if-else-if ladder. Write a program to demonstrate if-
else-if ladder.
5. Define switch statement. Explain with a programming
example.
6. Explain while statement with general form, flowchart and an
example.
7. What is a do-while statement? Explain with an example.
8. Explain the for loop with an example.
9. What is nested for loop? Explain with a programming
example.
10. Explain jumps in loops.
CHAPTER 7
CLASS
Introduction: Java is a pure object oriented programming language
and everything represented in a java program must be encapsulated
in a class. Once a class is created, any number of objects of that
class type can be created. Objects use methods to communicate
between them. In java data items are called fields , the functions are
called methods and objects are called instances .
The general form of defining a class:
class class_name
{
Data_type1 variable1;
Data_type2 variable2;
…
Data_type-n variable-n;
Return_type method_name(parameter_list)
{
Method body;
}
}
Unlike C++, methods in java must be completely implemented within
the class. we will not define a method outside the class definition
using scope resolution operator.
Example:
class Rectangle
{
int l,w;
void getdata(int x,int y)
{
l=x;
w=y;
}
int rectArea()
{
int a=l*w;
return a;
}
}
Creating objects: in order to create an object we first declare a
variable of class type and then we use the operator new to create the
object and return a reference to the object.
Rectangle r=new Rectangle();
Or
Rectangle r;
r=new Rectangle();
Now, let us write a complete executable program,
class Rectangle
{
int l,w;
void getdata(int x,int y)
{
l=x;
w=y;
}
int rectArea()
{
int a=l*w;
return a;
}
}
class RectangleArea
{
public static void main(String args[])
{
Rectangle r=new Rectangle();
r.getdata(5,10);
int area=r.rectArea();
System.out.println("Area of a Rectangle "+area);
}
}
Output:
F:\java programs>javac RectangleArea.java
class Max
{
static int x,y;
static void max(int a, int b)
{
x=a;
y=b;
}
static int big()
{
if(x>y)
return x;
else
return y;
}
}
class MaxNumber
{
public static void main(String args[])
{
Max.max(10,20);
int big=Max.big();
System.out.println("Maximum="+big);
}
}
Output:
F:\java programs>javac MaxNumber.java
Run 2:
F:\java programs >java Sample R
Area of rectangle is 200.0
Note:
- as illustrated in the above program accessing different
implementations of an interface through an interface reference
variable is how java achieves runtime polymorphism.
- The prototype methods of an interface which are implemented
by a class must be declared as public . This is because the
default access specifier in an interface is always public and the
class which implements it cannot make the method more
restrictive.
- Signature of the methods in the interface and classes must
match.
- Since, interfaces are in a different hierarchy from classes. It is
possible for unrelated classes to implement the same interface.
Different options for extending classes and implementing
interfaces:
- One class can implement more than one interface.
- A class can extend one superclass and implement one or
more interfaces.
1. class C implements I1,I2
{
…
…
}
2. class C extends S implements I1,I2
{
…
…
}
3. One interface can extend another interface
interface I1 extends I2 // super interface
{
…
…
}
Example:
interface ItemConstants
{
int part_code=125;
String part_name=”Table Fan”;
}
interface Item extends ItemConstants
{
void display();
}
The advantage of this approach is that a class which requires only
the constants can implement the interface ItemConstants while
another class which may require the constant as well as the display
method can implement only Item.
4. One interface can extend several interface
interface I1 extends I2,I3…
{
…
…
}
For example:
interface ItemMethods
{
void display();
}
interface comb extends ItemConstants, ItemMethods
{
…
…
}
This way several interfaces can be combined into a single interface.
// Write a program to access interface variables.
class Employee
{
int empid;
void getid(int n)
{
empid=n;
}
void putid()
{
System.out.println(“Employee Id=”+empid);
}
}
class Promotion extends Employee
{
float promotion1,promotion2;
void getPromotion(float p1,float p2)
{
promotion1=p1;
promotion2=p2;
}
void putPromotion()
{
System.out.println(“Promotions Received:\n”);
System.out.println(“First Promotion=”+promotion1);
System.out.println(“Second Promotion=”+promotion2);
}
}
interface bonus
{
float bonusAmount=4500.50F;
void putBonus();
}
class Output extends Promotion implements bonus
{
float total;
public void putBonus()
{
System.out.println(“Bonus Amount=”+bonusAmount);
}
void display()
{
total=promotion1+promotion2+bonusAmount;
putid();
putPromotion();
putBonus();
System.out.println(“Total Amount=”+total);
}
}
class Mixture
{
public static void main(String args[])
{
Output employee1=new Output();
employee1.getid(1);
employee1.getPromotion(1500.50F,1200.25F);
employee1.display();
}
}
Output:
F:\java programs >javac Mixture.java
First Promotion=1500.5
Second Promotion=1200.25
Bonus Amount=4500.5
Total Amount=7201.25
EXERCISES
1. Define a class. write its syntax.
2. Explain how to do field and method declaration in a class?
3. How to access class members.
4. Define constructor. Explain with a programming example.
5. What is method overloading? Explain with a programming
example.
6. Describe static members with an example.
7. What do you mean by nesting methods? Explain with an
example.
8. What are overriding methods? Explain with a programming
example.
9. What is the use of final variables, methods and classes?
explain with an example for each.
10. What is the use of finalize() method? Explain with the
programming example.
11. Explain methods with varargs with an example.
12. What is dynamic method dispatch? Explain with a
programming example.
13. Define visibility mode. Explain all the visibility modes of
java.
14. What is the interface? Write syntax for defining interface.
15. Write a program to demonstrate interface implementation.
16. Write a program to illustrate accessing interface variables.
CHAPTER 8
ARRAYS, STRINGS AND VECTORS
Introduction: Till now, we have seen different types of variables that
hold only one value, but in some situations, we require to process
more than one data item of the same types such as int, char, float or
double. In this situation, the concept of arrays comes into picture.
Definition: “Array is a collection of homogeneous data items under
the same name”.
Array allocates memory in a contiguous way, so that each data item
can be easily accessed with the help of index numbers. Each element
is stored in a contiguous memory location on RAM. The index
numbers start from 0, 1, 2, …, n-1. These indices are also called
subscripts of an array. These indices are used to locate the positions
of elements within the array.
Let us consider, if a is the name of the array, the elements can be
accessed as a[0], a[1], a[2], … ,a[n-1]. a[0] is the name of the first
element present at position 0, a[1] is the name of the second element
present at position 1 and so on. a[i] is the element present at position
i.
10 20 30 40 50
An array is mapped in a memory as,
a
0 1 2 3 4
Here, a is the name of the array, a[0] contains the element 10, a[1]
contains the element 20, a[2] contains the element 30, a[3] contains
the element 40, a[4] contains the element 50. The subscripts always
start from 0 to n-1.
Types of arrays:
- one-dimensional array
- two-dimensional array
- multidimensional array
one-dimensional array: an array in which each element is accessed
by only one subscript is called a one-dimensional array.
Declaration:
type arrayname[];
or
type [] arrayname;
Example:
int a[]; or int [] a;
float b[]; or float [] b;
Creating arrays: We need to allow arrays to allocate memory
location for the declaration using a new operator.
arrayname =new type[size];
int a[]=new int[5];
Initialization of arrays: one-dimensional arrays can be initialized as,
arrayname[subscript]=value;
Example:
a[0]=10;
a[1]=20;
…
a[4]=50;
Arrays can be initialized automatically like normal variables as shown
below,
type arrayname[]={list of values};
Example:
int a[]={10,20,30,40,50};
Note:
- No size is given. Hence, the compiler allocates enough space
for all the elements specified in the list.
- In java, there is a strict bound checking. Means, the number of
elements must be equal to the size given in the array.
Array Length: the allocated size of the array is stored in the variable
called length. The total number of elements can be determined by
using a.length.
mple: int l=a.length; /* total number of elements of array a stores in
variable l. */
// Write a program to sort the elements using length variables.
class Sort
{
public static void main(String args[])
{
int a[]={30,10,50,20,40};
int l=a.length;
System.out.print("Given list of elements are");
for(int i=0;i<l;i++)
{
System.out.print(" "+a[i]);
}
System.out.println("");
for(int i=0;i<l;i++)
{
for(int j=i+1;j<l;j++)
{
if(a[i]>a[j])
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println("Sorted list is");
for(int i=0;i<l;i++)
{
System.out.print(" "+a[i]);
}
}
}
Output:
F:\java programs>javac Sort.java
@Inherited
@interface ForEveryone { }//Now it will be available to subclass also
@interface ForEveryone { }
class Superclass{}
EXERCISES
1. What is a one dimensional array?
2. How to declare and create a one dimensional array in java?
3. Explain initialization of arrays.
4. Write a program to demonstrate the use of array length.
5. Define a two dimensional array. Explain its initialization.
6. Explain variable size arrays in java.
7. Explain any five string methods.
8. Write a program to sort the names in alphabetical order
using some of the built-in string functions.
9. What is a string buffer class? explain its methods.
10. What are vectors? Write a program to demonstrate the use
of vectors.
11. What are wrapper classes? Name them.
12. Define autoboxing and unboxing with a programming
example.
13. What is the enumerated type? write a program to illustrate
the same.
14. What are annotations? Explain built-in annotations.
CHAPTER 9
JAVA PACKAGES
Introduction: An important feature of object oriented programming
is its ability to reuse code which has already been developed and
tested. One way of doing this is by extending the classes and
implementing interfaces. However, this is limited to reusing the
classes and interface within the same program. In order to make use
of those classes and interfaces which are stored in other packages
without physically copying them into a program.
You can import the package containing that class into your program.
This concept is similar to using class libraries in C++. Thus, a
package acts as a container for a set of related classes and
interfaces.
Benefits of packages:
- Code reusability.
- Prevents name collision.
- Two classes in a package can have the same name. They
are referred to by their fully qualified names.
packagename.classname
or
packagename.subpackagename.classname
classes can be hidden inside the package so that their data
members or functions or even the class function cannot be accessed
directly from outside the function.
classification of packages: packages in java are classified as
follows:
- Java API package: API packages are predefined packages
that are part of the Java library and stored in JDK by sun
microsystem. All these packages are available for import into
the program. Packages contain hundreds of classes and
interfaces.
- User-defined packages: The programmer can create his/her
own packages. These packages can be used by any other java
developer.
Java API packages:
java.lang: this package contains the classes and interfaces used by
the compiler. Hence, this package is automatically imported in every
program the user writes. Some of the classes of this package are,
String, Thread, Exception etc.
java.util: this package contains the utility classes for random
number generation, data handling vectors etc.
java.io: it supports both console and file I/O. For example, Data
Input Stream, Data Output Stream, File, Random Access File.
java.awt (Abstract Window Toolkit): it contains classes for
implementing GUI (Graphical User Interface) such as buttons, scroll
bars, menus, combo box etc.
java.net: it contains the classes for networking programs. i.e.
sending and receiving information between a client and server.
socket, server socket: it is used for creating and implementing
applet programs. Example: Applet.
Rules for packages:
- The source file must have the same as the name of the public
class with extension (dot) .java.
- The source file should be saved in a subdirectory with the
same name as the package name.
- When no package statement is used all the classes in that
source file will become part of an unnamed default package.
Now there is no need for a public class.
- If a package contains more than one public class then it is
split into several source files.
Accessing user defined packages: accessing user defined
packages is possible by using import statements. The restriction is
that the program containing the import statement must be stored in a
directory which is at the higher level, then the directory in which the
package is stored.
All these API packages are organized in hierarchical structure as
shown below.
EXERCISES
1. What is a java package? What are the types of packages?
2. Write the benefits of packages.
3. What are the rules for packages?
4. How to access user defined packages?
5. Explain the ways of referring to the public classes of
packages.
6. Write a program to show the current date and time.
7. Explain the naming conventions in java.
8. How do you create user defined packages? Explain with a
suitable example.
9. How to access the package?
10. How to add a class to an existing package?
11. Explain the method of making java classes hidden.
12. What is static import? Explain with a programming
example.
CHAPTER 10
PROGRAMMING THREADS
Introduction: all the programs studied so far were single threshed.
In all these programs there was a single path of execution. A
multithreaded program on the other hand is one that is divided into
more subprograms which are executed by the CPU in parallel. Each
of these subprograms are called threads . Where each thread
defines a separate path of execution when there is a single CPU in
the computer, in reality it will be executing only one instruction from
any one thread at a time. However, the CPU is able to switch
between the threads, so fast that it appears that they are being
executed simultaneously.
Advantages of multithreading:
Multithreading enables the programmer to write more efficient
programs that take maximum use of CPU by keeping its idle time to
a minimum.
Example, if one thread is performing input/output which is a slow
process. The CPU does not have to wait for it to complete. In the
meanwhile, it can execute another thread of the same program. In a
single threaded program, the CPU would have to remain idle till the
input/output operation was completed. Thus, the multi-threaded
program improves the overall execution speed.
Multitasking: An ability of the computer to execute more than one
program simultaneously is called Multitasking . There are two types
of multitasking.
- Process based
- Thread based
Process based: A process is a program in execution. Thus, process
based multitasking is the feature that allows the computer to run two
or more programs concurrently.
Example: Process based multitasking enables to run the java
compiler at the same time when using the text editor word and excel.
Thread based: In a thread based multitasking environment, the
thread is the smallest unit of dispatchable code. i.e., a single
program can perform two or more tasks simultaneously. For
instance, a text editor can format text at the same time it is printing.
These two actions are being performed by two separate threads.
Java programs that we have seen and discussed so far contain only
a single sequential flow of control. The programs can be called as
single threaded programs . A thread is similar to a program that
has a single flow of control.
A unique property of java is, it supports multithreading i.e., java
enables us to use multiple flows of control in developing programs.
Each flow of control may be thought of as a separate tiny program
known as thread that runs in parallel to others. A program that
contains a multiple flow of control is known as a multithreaded
program. In the following figure you can figure out that the java
program has four threads, one main and three others. The main
thread is the main module which is designed to create and start the
other three threads. Thread A, B and C.
Once initiated by the main thread, the threads A, B and C run
concurrently and share the resources jointly. Since, threads in java
are subprograms of a main application program and share the same
memory space they are known as light weight thread or
processes .
Creating thread: threads are implemented in the form of objects
that contain a method called run() . The run() method has the
following syntax:
public void run()
{
Statements for implementing thread
}
The run() method should be invoked by an object of the concerned
thread. This can be achieved by creating the thread and initializing it,
with the help of another thread method “ start() ”. A new thread can
be created in two ways.
- By creating a thread class: define a class that extends
Thread class and override its run method.
- By converting a class to a thread: define a class that
implements a runnable interface. The runnable interface has
only one method run() that is to be defined in the method with
the code to be executed by the thread.
Example:
class Xyz implements Runnable
{
int i;
public void run()
{
while(true)
{
System.out.println("Hello "+i++);
if(i==5)
break;
}
}
}
public class ThreadTest
{
public static void main(String args[])
{
Xyz r=new Xyz();
Thread t=new Thread(r);
t.start();
}
}
Output:
F:\java programs>javac ThreadTest.java
Life cycle of a thread: At any given time a thread can be in one the
following five states:
- New born state
- Runnable state
- Running state
- Blocked state
- Dead state
New born state: A new thread object created is in a newborn state.
This new born thread is not scheduled for running. At this stage we
can schedule it for running using start() method or kill it using stop()
method.
Runnable state: in this state the thread is ready for execution and
waiting for the availability of the processor. That means the thread
has joined the queue and is waiting for its turn. If all the threads in a
queue have equal priority then they are given a time slice for
execution in round robin (first come first serve) fashion. The thread
relinquishes control, joins the queue at the end and again waits for
its turn. If we want to relinquish control to another thread to equal
priority before its turn comes, then this can be done by using the
yield() method as shown below.
Running state: In this state the processor has given the time to the
thread for its execution. The thread executes until it relinquishes its
control on its own or it is preempted by a higher priority thread.
EXERCISES
1. What is multithreading and multitasking?
2. How to create threads? Explain with a programming
example.
3. Explain extending thread class with an example.
4. Explain the life cycle of a thread with a neat labelled
diagram.
5. Write a program to demonstrate thread methods.
6. What are thread exceptions? List the thread exception.
7. Describe thread priority with a programming example.
8. What is synchronization? Explain with a programming
example.
9. Explain how to implement the runnable interface.
CHAPTER 11
JAVA EXCEPTIONS
Introduction: it is very common to make mistakes while writing any
computer programs. Such mistakes made by the programmer are
called errors. If there are errors present in the program, the program
may produce an unintended result. Sometimes programs terminate
abruptly. It is always true that, whenever we throw a garbage, we get
garbage i.e., garbage in and garbage out (GIGO). If the input is not
proper then the output is also not proper.
There are two types of errors:
- Compile time errors
- Runtime errors
Compile time errors: these are the errors generated due to typing
mistakes of the programmer. If the programmer does not follow the
syntax of the programming language, such errors are generated.
When there is an error, the java compiler does not produce a .class
file.
Let us take a look at the program where there is a syntax error
class FirstProgram
{
public static void main(String args[])
{
System.out.println(“Welcome to the world of Java”) // missing
semicolon
}
}
The above program produces an error, showing that there is a
missing semicolon. The error is as shown below.
F:\java programs>javac FirstProgram.java
FirstProgram.java:5: error: ';' expected
System.out.println("Welcome to the world of Java") // missing
semicolon
^
1 error
Most of the common syntax errors are,
- Missing out semicolon
- Missing out closing braces
- Wrong spelling
- Not following naming conventions
- Missing quotation marks while using strings.
- Using undeclared variables and so on.
Runtime errors: These are the errors that will not be identified during
compile time and the java compiler successfully generated .class file.
But the code is still erroneous and produces an inappropriate
unintended output. This type of error will occur only when the
programmer uses wrong logic.
Most of the common runtime errors are,
- Trying to divide the number by zero.
- Accessing elements of an array which are out of bounds.
- Mismatch in typecasting.
- Writing negative size for an array.
- Converting invalid string to a number.
- Attempting to change the state of a thread illegally and so on.
Let us take an example to show the runtime error,
class RunTimeError
{
public static void main(String args[])
{
int a=5,b=0,c;
c=a/b;
System.out.println("The value of c= "+c);
}
}
F:\java programs>javac RunTimeError.java
Run 1:
F:\java programs>javac NestedTry.java
Run 2:
F:\java programs>java NestedTry one
a=1
Division by zero
Run 3:
F:\java programs>java NestedTry one two
a=2
Subscript out of range
After inner try-catch block
In case, they don’t match then the catch block of outer try will be
inspected for possible match.
Multiple catch block statements: In some cases more than one
exception could be raised by a single piece of code. To handle this
type of situation we can specify two or more catch clauses. Each
catching a different type of exception. When an exception is thrown
each catch statement is inspected in order and the first one whose
type matches that exception is executed. After one catch statement
executes the others are bypassed and execution continues after the
try-catch block.
The general form is,
try
{
Statements; //generates an exception
}
catch(Exception-type1 e)
{
Statements; // process exception type1
}
catch(Exception-type2 e)
{
Statements; // process exception type2
}
…
catch(Exception-type-n e)
{
Statements; // process exception type-n
}
…
Java does not require any processing of the exception; we can simply
have a catch statement with an empty block to avoid program
termination.
Example:
catch(Exception e);
the catch statement ends with a semicolon, this statement will catch
an exception and ignore it.
Let us have an example on multiple catch blocks.
class MultipleCatch
{
public static void main(String args[])
{
try
{
int a=args.length;
System.out.println("a:"+a);
int b=42/a;
int c[]={1};
c[42]=99;
}
catch(ArithmeticException e)
{
System.out.println("Division by zero: "+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bounds: "+e);
}
System.out.println("After try-catch block");
}
}
Output:
Run 1:
F:\java programs>javac MultipleCatch.java
Run 2:
F:\java programs>java MultipleCatch test args[]
a:2
Array index out of bounds:
java.lang.ArrayIndexOutOfBoundsException: Index 42 out of bounds
for length 1
After try-catch block
Finally block: The finally block is optional. It can be placed either
immediately after a try block or if catch blocks are present then the
finally block should be written after the last catch block.
Syntax:
try
{
…
…
}
catch(Exception-type1 e)
{
…
…
}
catch(Exception-type2 e)
{
…
…
}
finally
{
…
…
}
Note: The finally block basically contains a set of instructions that will
always get executed whether an exception is thrown or there is no
exception in the try block. In case, an exception occurs within the try
block for which there is no matching catch handler even in this
situation the finally block will get executed before the program
crashes.
Let us have a program that demonstrates the use of finally block.
class FinallyBlock
{
static void funA()
{
try
{
System.out.println("Inside function A");
throw new RuntimeException();
}
finally
{
System.out.println("Inside function A's finally block");
}
}
static void funB()
{
try
{
System.out.println("Inside function B");
return;
}
finally
{
System.out.println("Inside function B's finally block");
}
}
static void funC()
{
try
{
System.out.println("Inside function C");
}
finally
{
System.out.println("Inside function C's finally block");
}
}
public static void main(String args[])
{
try
{
funA();
}
catch(Exception e)
{
System.out.println("Manual runtime exception caught");
}
funB();
funC();
}
}
Output:
F:\java programs>javac FinallyBlock.java
F:\java programs>java FinallyBlock
Inside function A
Inside function A's finally block
Manual runtime exception caught
Inside function B
Inside function B's finally block
Inside function C
Inside function C's finally block
Note: In the above program any time a function is about to go back to
its caller either because of its uncaught exception or due to an explicit
return statement. The finally block will get executed each time before
control returns to the caller. This feature can be used for closing a
data file which may have been opened at the starting of the function
with an intention of closing it before return.
Throwing manual exception: Sometimes there may be no run time
errors as far as java is concerned but it may be AWT error as far as
our program logic is concerned.
Example: if we enter negative marks in such a situation the
programmer can manually create an object of a subclass of the class
exception and throw it using the throw statement as shown in the
following program.
import java.io.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class Test
{
public static void main(String args[])
{
int m;
try
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the marks");
String s=in.readLine();
m=Integer.parseInt(s);
if(m<0)
{
MyException obj=new MyException("Negative marks");
throw obj;
}
if(m>100)
throw new MyException("Marks above 100");
System.out.println("Valid marks, process it");
}
catch(NumberFormatException e)
{
System.out.println("Not a valid integer");
}
catch(MyException e)
{
System.out.println(e.getMessage());
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
Run 1:
F:\java programs>javac Test.java
Run 2:
F:\java programs>java Test
Enter the marks
101
Marks above 100
Throws clause: whenever a function throws an exception of the
class IOException or any of its subclasses, then the programmer has
to do one of two things.
- Place a statement that calls the function inside the try block
with the appropriate catch block as shown.
void fun1()
{
…
…
try
{
…
…
fun2()
…
…
}
catch(IOException e)
{
…
…
}
}
void fun2() throws IOException
{
…
…
}
- Suppose you don’t place the function statement inside the try
block then you must write the throws clause in the header of the
calling as shown.
void fun1() throws IOException
{
…
…
fun2()
}
void fun2() throws IOException
{
…
…
}
Note: By using the throw clause in the header of the function 1
we are informing the java compiler that catching this error
becomes the responsibility of the function that calls function 1.
Hierarchy of exception classes:
EXERCISES
1. What is an exception? Write a program to demonstrate an
exception.
2. Explain multiple catch block statements with an example.
3. Describe how to throw manual exceptions? Explain with an
example.
4. What is the use of the throws clause? Explain with
examples.
5. How to use finally block? Explain with a programming
example.
6. Explain nested try and catch blocks with an example.
CHAPTER 12
APPLET PROGRAMMING
Introduction: Java Applets are small java programs that are used in
internet programming that are transported over the internet and
executed within an HTML document. Most of the programming today
has become window based. input output is done through suitable
components like labels, textbox, buttons etc. thus, applet satisfies two
requirements.
- Networking: Having a program at one site and running it on
another site.
- Windowing: Showing the program's effect in a small
rectangular portion of the screen.
There are two types of applets:
Local applets: An applet developed locally and stored in a local
system is known as a local applet.
Remote applets: An applet developed by someone else and stored
on a remote computer connected to the internet.
Advantages of applet: Applet provides a richer browsing experience
in the following ways.
- Cartoon style animation.
- Realtime games.
- Rich 3D graphics.
- Page music that plays in the background.
- Different sounds that play in real time when the user clicks on
different buttons.
Security restrictions on applets:
Since, applets are downloaded from remote computers some of them
may come from untrusted sources so the following restrictions are
imposed on applets.
- Applets cannot open any file on the client computer’s hard
disk either for reading or for writing.
- Applet cannot execute any program from the local hard disk.
- Applet cannot communicate with another server on the
network.
Difference between applications and applets:
Applications Applets
Uses main() method to execute Do not use the main() method to
programs. execute programs.
Applications can run Applets cannot run
independently. independently. They run from
inside the web page.
Applications can read or write to Applets cannot read from or write
the files. to the files.
Can run any program from a Applet cannot run any program
local computer. from a local computer.
Applications use libraries from Applets are restricted to use
other languages such as C or libraries from other languages.
C++.
Executed by java interpreter. Executed by a java enabled
browser or a utility called applet
viewer.
User input output is User IO performs the graphical
accomplished using string IO interface provided by AWT.
class.
Let’s begin writing a first applet program.
/*<html>
<applet code="FirstApplet.class" width=200 height=200>
</applet>
</html>*/
import java.awt.*;
import java.applet.*;
public class FirstApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to the world of java applets",10,100);
}
}
Note: paint() method is called every time the applet has to re-display
its output, the paint() method gets invoked in the following situations.
- When the applet begins the application.
- The applet window is maximized and then restored.
- The applet window is resized.
- The applet window is covered by another window and then
uncovered.
- When the window if referred.
drawString() method receives a single parameter. An object of the
class graphics. This object is used to invoke the method drawString()
which is defined in the class Graphics.
void drawString(String message, int x, int y);
it will display the given message at the specified xy location.
How to execute a java applet?
- Type the source code using edit and save it in a file with the
same name as the public class with extension .java .
i.e., C:\Program Files\Java\jdk\bin> edit FirstApplet.java
- Compile the program as usual using the java compiler to
produce the .class file containing the byte code.
C:\Program Files\Java\jdk\bin>javac FirstApplet.java
- Create an HTML file using edit containing appropriate applet
tag.
<html>
<applet code="FirstApplet.class" width=200 height=200>
</applet>
</html>
This file should be stored with extension .html .
FirstApplet.html
- Execute the program either using applet viewer or through a
browser software.
C:\Program Files\Java\jdk\bin>appletviewer FirstApplet.html
Executing java applet using browser:
- Start internet explorer and in the address bar type the full path
and name of the html file.
More convenient method for testing applets: when executing an
applet program using the applet viewer, it is not compulsory to create
a separate HTML file each time. Instead you can include a comment
containing the applet tag in the source program itself as shown.
/*<html>
<applet code="FirstApplet.class" width=200 height=200>
</applet>
</html>*/
Now execute it, type the following command.
C:\Program Files\Java\jdk\bin>appletviewer FirstApplet.java
The appletviewer software now searches for the comment in the
source file. Inside the comment, it encounters the applet tag and
within it, it finds the name of the .class file which is to be executed.
Note: To run applets we have to install JDK 8 because the latest java
version doesn’t support appletviewer. I am storing all java source files
in F: drive of my PC under the folder called java programs. Hence,
the path F:\java programs> is used.
Output:
F:\java programs>javac FirstApplet.java
- fillArc(): This method will draw a shaded arc like the slice of
the pie chart.
g.fillArc(xt,yt,w,h,s,a);
g.fillArc(50,20,80,60,90,-45);
- drawPolygon(): It will draw a set of n-1 connected lines
segments joining the point whose x-coordinate values are
stored in the array x and y-coordinate values in the array y.
g.drawPolygon(x,y,n);
- fillpolygon(): This method is used to draw the polygon filled
with the current color.
/* Write a program to draw the following figure in an applet
having width of 300 and height of 250 pixels. */
import java.awt.Graphics;
import java.applet.Applet;
/*<applet code=Poly.class width=300 height=250>
</applet>*/
public class Poly extends Applet
{
public void paint(Graphics g)
{
int x1[]={20,120,220,20};
int y1[]={20,120,20,20};
int x2[]={120,220,220,120};
int y2[]={120,220,20,120};
g.drawPolygon(x1,y1,4);
g.fillPolygon(x2,y2,4);
}
}
Output:
F:\java programs>javac Poly.java
Each time the size of the applet window is changed by the user, the
point method will be called automatically from inside the paint
method, the getSize() method is called which will return the new size
of the window. The rectangle and diagonals will be now redrawn
using the new dimension.
- setSize(): This function can be used to modify the size of the
applet window (width, height) through the program.
Example: Dimension d=new Dimension(w,h);
setSize(d);
or
setSize(new Dimension(w,h));
Fonts: In order to set the font style and size we have to call the
method setFont() which is defined in the class graphics.
Example: g.setFont(f);
The object f should be created as shown below,
Font f=new Font(s,m,n);
Here, s is string, m is font style, n is font size.
Example: Font f=new Font(“Times New Roman”,Font.bold,24);
Subsequent drawString() method will use this particular font string.
Fontname=”Times New Roman”, “Helretica”, “Courier” Fontstyle:
PLAIN, BOLD, ITALIC.
These are defined in the class Font as shown below,
public static final PLAIN=0;
public static final BOLD=1;
public static final ITALIC=2;
public static final BOLD+ITALIC=3;
// Write a program to demonstrate font styles.
import java.awt.*;
import java.applet.*;
/*<applet code=TextFont width=500 height=300>
</applet>*/
public class TextFont extends Applet
{
public void paint(Graphics g)
{
Font f1=new Font("Helretica",Font.PLAIN,14);
g.setFont(f1);
g.drawString("Java for you",5,35);
Font f2=new Font("Times New Roman", Font.BOLD,24);
g.setFont(f2);
g.drawString("Java for you",5,75);
Font f3=new Font("courier",Font.ITALIC,36);
g.setFont(f3);
g.drawString("Java for you",5,155);
Font f4=new Font("Arial",3,72);
g.setColor(Color.orange);
g.setFont(f4);
g.drawString("Java for you",5,225);
}
}
Output:
F:\java programs>javac TextFont.java
g.fillArc(50,40,200,200,s,a2);
s+=a2;
g.setColor(Color.green);
g.fillArc(50,40,200,200,s,a3);
s+=a3;
g.setColor(Color.blue);
g.fillArc(50,40,200,200,s,a4);
s+=a4;
g.setColor(Color.red);
g.fillArc(50,40,200,200,s,a5);
}
}
Output:
F:\java programs>javac Pie.java
A listener has to register with the source in order to receive an event. Since, the event will be sent only
to those listeners who want to receive it. The listener waits until it receives it. The listener waits until it
receives an event when it is received it will take the appropriate action.
What is the source?
A source is an object that generates an event; it could be a user interface component such as a button,
scroll bar etc. The source could also be the applet itself for keyboard and mouse events.
What is meant by event?
An event is basically a change of state in a source. In java whenever there is such a change of state, an
object of a particular event class is automatically created depending upon the type of event.
What is a listener?
A listener is an object that gets notified when an event occurs; the listener has to do two things.
- Register the source in order to receive the event.
- Implement the necessary method or methods to process the events.
Event classes: All the event classes are defined in API sub-package java.awt event. Each different type
of event creates an object of a different event class as shown in the following table.
Class name Object of this class is created
when…
ActionEvent i) Button is clicked.
ii) Menu item is clicked.
iii) List item is double clicked.
iv) Enter key is pressed in a
textfield.
AdjustmentEvent A scroll bar is manipulated.
ItemEvent i) Checkbox is clicked.
ii) List item is clicked.
iii) A choice selection is made.
iv) Checkable menu items are
clicked.
KeyEvent A key is pressed or relaxed.
MouseEvent i) Mouse enters a
component.
ii) Mouse leaves a
component.
iii) Mouse is moved.
iv) Mouse is dragged.
v) Mouse is pressed.
vi) Mouse is clicked.
vii) Mouse is released.
TextEvent Contents of the text field are
changed.
WindowEvent i) Windows is open.
ii) Windows is closing.
iii) Window is closed.
iv) Window is activated.
v) Window is deactivated.
vi) Window is iconified.
vii) Window is de-iconified.
FocusEvent i) Components get the focus.
ii) Components leave the
focus.
Event listener interface: The methods that receive and process the events are defined in the set of
interfaces which are also stored in the sub-package.
java.awt.event
so, to override these methods the listener class must implement one or more of these interfaces
whenever an event occurs. The appropriate method gets automatically invoked and the event object is
passed to it as a parameter.
Interface Defines the methods Invoked Prototype
when
ActionListener actionPerformed() Action public void actionPerformed(ActionEven
event ae)
occurs
AdjustmentListener adjustmentValueChange() Adjustment public void
event adjustmentValueChange(AdjustmentEve
occurs ae)
ItemListener itemStateChanged Items public void itemStateChanged(ItemEven
event ie)
occurs
KeyListener keyPressed() Key event public void keyPressed(KeyEvent ke)
keyTyped() occurs public void keyTyped(KeyEvent ke)
keyRelaxed()
MouseListener mouseEntered() Mouse
mouseExited() events
mousePressed() occurs
mouseClicked()
mouseReleased()
mouseMoved()
mouseDragged()
MouseMotionListener mouseMoved() As the public void mouseMoved(MouseEvent
mouse is me)
moved.
mouseDragged() As the
public void mouseDragged(MouseEvent
mouse is
me)
dragged.
User interface components: The awt package has various classes such as,
- Label
- Textfield
- Button
- Scrollbar
- Checkbox etc.
To include any of these components in the applet we have to first create an object of the relevant class
and then add this object to the applet by calling the add() method.
Label: A label is meant for displaying messages to the user. It is a passive control which the user
cannot interact with. It cannot generate any events.
Constructors:
Label lb1=new Label(); // creates blank label
Label lb2=new Label(str) // creates a label with the given caption
Label lb3=new Label(str,alignment) creates the label with the given caption. Alignment specifies the
position of the caption inside the label following are the options,
LABEL.LEFT
LABEL.RIGHT
LABEL.CENTER
Methods:
setText(): This method can be called to change the caption on the label.
lbl.setText(str);
getText(): It returns the caption of the label.
String s=lbl.getText();
// Write a program to demonstrate the use of label
import java.awt.*;
import java.applet.*;
/*<applet code="LabelDemo.class" width=300 height=200>
</applet>*/
public class LabelDemo extends Applet
{
String s;
public void init()
{
Label l1=new Label();
Label l2=new Label("for",Label.CENTER);
Label l3=new Label("YOU");
l1.setBackground(Color.blue);
l2.setBackground(Color.red);
l3.setBackground(Color.yellow);
l1.setText("Java");
l1.setAlignment(Label.RIGHT);
add(l1);
add(l2);
add(l3);
s=l1.getText()+l2.getText()+l3.getText();
}
public void paint(Graphics g)
{
g.drawString(s,10,200);
}
}
Output:
F:\java programs>javac LabelDemo.java
Text field: Text field allows the user to enter the text data and also to edit it.
Constructors:
1. TextField t1=new TextField();
TextField t1=new TextField(n);
TextField t1=new TextField(s,n);
2. Creates text field n-characters wide.
3. Creates a text field with default text ‘s’ and with ‘n’
Methods:
1. getText(): Returns the current text of the text field.
String txt=t1.getText();
2. setText(): Assigns the specified string to the text field.
t1.setText(String);
3. getSelectedText(): Returns the part of the text which is highlighted by the user.
String txt=t1.getSelectedText();
4. setEchoChar(): For entering password that should not be displayed on the screen. This method
can be used to specify some other character which should be displayed during data entry.
setEchoChar(‘*’);
// Write a program to demonstrate the use of a text field.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=TextDemo width=500 height=300>
</applet>*/
public class TextDemo extends Applet implements ActionListener
{
TextField txtname, txtpwd;
public void init()
{
Label lblname=new Label("Enter Userid",Label.RIGHT);
Label lblpwd=new Label("Enter password",Label.RIGHT);
txtname=new TextField(12);
txtpwd=new TextField(8);
txtpwd.setEchoChar('*');
add(lblname);
add(txtname);
add(lblpwd);
add(txtpwd);
txtname.addActionListener(this);
txtpwd.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("Userid :"+txtname.getText(),6,80);
g.drawString("Selected Text :"+txtname.getText(),6,100);
g.drawString("Password is :"+txtpwd.getText(),6,120);
}
}
Output:
F:\java programs>javac TextDemo.java
sg;
ox cb1,cb2,cb3;
oid init()
w Checkbox("Car",true);
w Checkbox("Bicycle");
w Checkbox("Scooter");
);
);
);
temListener(this);
temListener(this);
temListener(this);
oid paint(Graphics g)
urrent State:";
tring(msg,5,50);
1.getLabel()+":"+cb1.getState();
tring(msg,5,70);
2.getLabel()+":"+cb2.getState();
tring(msg,5,90);
3.getLabel()+":"+cb3.getState();
tring(msg,5,110);
rograms>javac CheckboxDemo.java
rograms>appletviewer CheckboxDemo.java
checkbox:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=CheckboxArray.class width=300 height=200>
</applet>*/
public class CheckboxArray extends Applet implements ItemListener
{
String msg;
Checkbox cb[];
public void init()
{
cb=new Checkbox[3];
cb[0]=new Checkbox("Car",true);
cb[1]=new Checkbox("Bicycle");
cb[2]=new Checkbox("Scooter");
for(int i=0;i<3;i++)
{
add(cb[i]);
cb[i].addItemListener(this);
}
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current state:";
g.drawString(msg,6,80);
for(int i=0;i<3;i++)
{
msg=cb[i].getLabel()+":"+cb[i].getState();
g.drawString(msg,6,100+20*i);
}
}
}
Output:
F:\java programs>javac CheckboxArray.java
add(cb1);
add(cb2);
cb1.addItemListener(this);
cb2.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
if(cb1.getState())
{
msg="You clicked on Bold, you selected it";
g.drawString(msg,5,50);
}
else
{
msg="You clicked on Bold, you deselect it";
g.drawString(msg,5,50);
}
if(cb2.getState())
{
msg="You clicked on Italic, you selected it";
g.drawString(msg,5,70);
}
else
{
msg="You clicked on Italic, you deselect it";
g.drawString(msg,5,70);
}
}
}
Output:
F:\java programs>javac CheckboxExample.java
Option button: These are mutually exclusive options where only one of them can be selected at one
time. To create a set of option buttons we have to create an object of the class checkbox group and
pass this object as an argument while constructing the individual buttons which are created as objects of
the class Checkbox creating a set of 3 option buttons.
CheckboxGroup cbg=new CheckboxGroup();
Checkbox op1=new Checkbox(“Shutdown”,cbg,true);
Checkbox op2=new Checkbox(“Restart”,cbg,false);
Checkbox op3=new Checkbox(“Standby”,cbg,false);
Checkbox group methods:
- getSelectedCheckbox(): This method is called by using the checkbox group object to
determine which option button in the group is currently selected. It will return a reference to the
selected option buttons.
Ex: Checkbox op=cbg.getSelectedCheckbox();
- setSelectedCheckbox(): This method is used to select one particular option button in the
group through the program the previously selected option button is automatically deselected.
Ex: cbg.setSelectedCheckbox(op);
// Write a program to demonstrate option buttons
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=OptionDemo width=500 height=300>
</applet>*/
public class OptionDemo extends Applet implements ItemListener
{
String msg;
Checkbox op1,op2,op3;
CheckboxGroup cbg;
public void init()
{
cbg=new CheckboxGroup();
op1=new Checkbox("Small",true,cbg);
op2=new Checkbox("Medium",false,cbg);
op3=new Checkbox("Large",false,cbg);
add(op1);
add(op2);
add(op3);
op1.addItemListener(this);
op2.addItemListener(this);
op3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current State:";
g.drawString(msg,6,80);
msg=op1.getLabel()+":"+op1.getState();
g.drawString(msg,6,100);
msg=op2.getLabel()+":"+op2.getState();
g.drawString(msg,6,120);
msg=op3.getLabel()+":"+op3.getState();
g.drawString(msg,6,140);
}
}
Output:
F:\java programs>javac OptionDemo.java
F:\java programs>appletviewer OptionDemo.java
Combo box: The class Choice is used to create a dropdown list of items in the normal state; only the
currently selected item is shown when the user clicks on the down arrow. The list of items will drop down
from which a new selection can be made. Each item in the list is a string that appears left justified in the
order in which it is added to the choice object.
Choice ch=new Choice();
Adding items to the object:
ch.addItem(str);
Getting currently selected items: String s=ch.getSelectedItem();
This will return the string containing the name of the currently selected item.
int k=ch.getSelectedIndex();
This will return the index positions of the selected items (counting starts from zero).
Finding number of items in the list:
int n=ch.getItemCount();
selecting an item through code.
ch.select(i); // selects the item at index position
ch.select(s) // selects the item whose name matches with s
To find the item at a particular position.
String s=ch.getItem(k); // where k is of type int
Handling choice list: Each time an item in the list is clicked an item event is generated. So, the listener
must implement the ItemListener interface which defines the method itemStateChanged().
// Write a program to demonstrate a Combobox.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=ChoiceDemo.class width=500 height=300>
</applet>*/
public class ChoiceDemo extends Applet implements ItemListener
{
Choice language;
String msg;
public void init()
{
msg=" ";
language=new Choice();
language.addItem("C Programming");
language.addItem("C++ Programming");
language.addItem("Java Programming");
language.addItem("C# Programming");
add(language);
language.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Currently selected programming language: ";
msg+=language.getSelectedItem();
g.drawString(msg,6,140);
}
}
Output:
F:\java programs>javac ChoiceDemo.java
Note: Double click on list items to display the name of the selected item.
// Write a program to delete items from the list box.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=TestDemo.class width=500 height=300>
</applet>*/
public class TestDemo extends Applet implements ActionListener
{
Button b1;
List l1;
String msg;
public void init()
{
msg=" ";
b1=new Button("Delete");
l1=new List();
l1.addItem("Doctor");
l1.addItem("Engineer");
l1.addItem("Scientist");
add(b1);
add(l1);
b1.addActionListener(this);
l1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
Object obj=ae.getSource();
if(obj==b1)
{
msg="Button";
l1.delItem(0);
}
else
msg="List box";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,6,140);
}
}
Output:
F:\java programs>javac TestDemo.java
Adapter classes: Java provides a special feature called adapter classes and adapter class provides
empty implementation of all the methods in an EventListener interface. This becomes useful when you
want to process only some of the methods that are handled by a particular interface.
We can define a new class to act as an event listener by extending the appropriate adapter class and
overriding only those methods which we are interested in.
For example: the mouse adapter class which is defined in the java.awt.events packages has five
methods.
- mousePressed()
- mouseReleased()
- mouseClicked()
- mouseExited()
- mouseEntered()
The signature of all these methods are exactly as defined in the mouse listener interface. So, if we were
interested in only responding to the mouseClicked() method. Then we can extend the mouse adapter
class and write the code only for the mouseClicked() method.
Names of adapter class Listener Interface it
implements
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter WindowListener
FocusAdapter FocusListener
// Write a program to illustrate the use of the adapter class.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=AdapterDemo.class width=300 height=200>
</applet>*/
public class AdapterDemo extends Applet
{
String msg;
public void init()
{
msg=" ";
xyz m1=new xyz(this);
addMouseListener(m1);
}
public void paint(Graphics g)
{
g.drawString(msg,10,100);
}
}
class xyz extends MouseAdapter
{
AdapterDemo ad;
xyz(AdapterDemo ob)
{
ad=ob;
}
public void mouseClicked(MouseEvent me)
{
ad.showStatus("Mouse was clicked");
ad.msg="You clicked the mouse";
ad.repaint();
}
}
Output:
F:\java programs>javac AdapterDemo.java
Note: The above program responds only to the clicking of the mouse; the other four mouse events are
ignored. Entry of the mouse, its exit, pressing and releasing of the mouse.
Frame classes:
A standard child window can be created by defining a class that is derived from a frame. By creating an
object of such a class we can display a standard window with title bar, menu bar, borders resizing
corners and minimum and maximum and close buttons. The warning alerts to the user can be given
using the child window can be given that, this child window was started by an applet program and not by
a local program on this computer so the user should be careful about giving sensitive information
through this window.
Constructors:
SampleFrame sf=new SampleFrame();
SampleFrame sf1=new SampleFrame(str);
- setSize(): sf.setSize(w,h);
- setVisible(): sf.setVisible(true); // shows the child window
setVisible(): sf.setVisible(false);
- setTitle(): sf.setTitle(str);
// Write a program to illustrate frame class.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=FrameDemo.class width=500 height=200>
</applet>*/
public class FrameDemo extends Applet
{
SampleFrame sf;
public void init()
{
sf=new SampleFrame("A child window");
sf.setSize(200,200);
}
public void start()
{
sf.setVisible(true);
}
public void stop()
{
sf.setVisible(false);
}
public void paint(Graphics g)
{
g.drawString("This is an applet",10,100);
}
}
class SampleFrame extends Frame
{
SampleFrame(String title)
{
super(title);
xyz adp=new xyz(this);
addWindowListener(adp);
}
public void paint(Graphics g)
{
g.drawString("This is a child window",10,100);
}
}
class xyz extends WindowAdapter
{
SampleFrame sf;
xyz(SampleFrame ob)
{
sf=ob;
}
}
Output:
F:\java programs>javac FrameDemo.java
Designing menus: The following classes are used in designing the menu
- Menubar
- Menu
- MenuItem
- CheckboxMenuItem
A menu bar is an object of the class menu bar. It displays the list of top level menu titles each title is an
object of the class menu and has a dropdown list which may contain any or all of the following.
- MenuItem objects: Represents an option which the user can click.
- Menu object: As a right pointing arrow leading to a submenu.
- CheckboxMenuItem objects: Represents a checkable menu item. These options will show a
check mark when selected.
Creating a menu bar object:
MenuBar mb=new MenuBar();
Creating a menu object:
Menu f=new Menu(“File”);
Creating a MenuItem object:
MenuItem i1=new MenuItem(“Cut”);
MenuItem i2=new MenuItem(str,key);
Creating a checkbox MenuItem objects:
CheckboxMenuItem cb1=new CheckboxMenuItem(“Bold”,true);
CheckboxMenuItem cb2=new CheckboxMenuItem(“Italic”);
MenuItem methods:
- setEnabled(): This method is used to either enable or disable a menu item.
i1.setEnabled(b); // this method receives Boolean value
- isEnabled(): This method determines if a particular menu item is enabled or disabled.
boolean b=i1.isEnabled();
Checkbox menu item methods:
- getState(): Returns the state of the option true if it is selected otherwise false.
boolean b=cb1.getState();
- setState(): This method sets the state of the option through the program.
cb1.setState(b);
Adding options to a menu object:
f.add(obj);
Adding menu objects to the menu bar object:
mb.add(f);
Adding menu bar object to the frame window:
this.setMenuBar(mb);
Handling menus: Events are generated only when a MenuItem or a CheckboxMenuItem is clicked. No
event is generated when a menu object is clicked to display the dropdown list.
MenuItem generates ActionEvent. CheckboxMenuItem generates ItemEvent. So, the listener class must
implement both ActionListener as well as ItemListener interface in order to respond to both types of
events.
// Write a program to demonstrate menus.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=MenuDemo.class width=300 height=200>
</applet>*/
public class MenuDemo extends Applet
{
SampleFrame sf;
public void init()
{
sf=new SampleFrame("SampleFrame");
sf.setSize(200,180);
}
public void start()
{
sf.setVisible(true);
}
public void stop()
{
sf.setVisible(false);
}
}
class SampleFrame extends Frame implements ActionListener
{
int flag;
SampleFrame(String title)
{
super(title);
Menu m1=new Menu("Main");
Menu sub=new Menu("Draw") ;
MenuItem i1=new MenuItem("Rectangle");
MenuItem i2=new MenuItem("Ellipse");
MenuItem i3=new MenuItem("Line");
sub.add(i1);
sub.add(i2);
sub.add(i3);
m1.add(sub);
MenuBar mb=new MenuBar();
mb.add(m1);
this.setMenuBar(mb);
i1.addActionListener(this);
i2.addActionListener(this);
i3.addActionListener(this);
MyWindowAdapter adp=new MyWindowAdapter(this);
this.addWindowListener(adp);
}
public void actionPerformed(ActionEvent ae)
{
String arg=ae.getActionCommand();
if(arg.equals("Rectangle"))
flag=1;
else
if(arg.equals("Ellipse"))
flag=2;
else
flag=3;
repaint();
}
public void paint(Graphics g)
{
switch(flag)
{
case 1: g.drawRect(10,50,100,80);
break;
case 2: g.drawOval(10,50,100,80);
break;
case 3: g.drawLine(10,50,100,80);
break;
}
}
}
class MyWindowAdapter extends WindowAdapter
{
SampleFrame sf;
public MyWindowAdapter(SampleFrame ob)
{
sf=ob;
}
public void windowClosing(WindowEvent we)
{
sf.setVisible(false);
}
}
Output:
F:\java programs>javac MenuDemo.java
Popup menus:
// Write a program to display a popup menu.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=PopupDemo.class width=300 height=200>
</applet>*/
public class PopupDemo extends Applet implements ActionListener
{
TextField t1;
PopupMenu p;
MenuItem i1,i2,i3;
public void init()
{
p=new PopupMenu("Edit");
i1=new MenuItem("Cut");
i2=new MenuItem("Copy");
i3=new MenuItem("Paste");
p.add(i1);
p.add(i2);
p.addSeparator();
p.add(i3);
add(p);
t1=new TextField(20);
add(t1);
i1.addActionListener(this);
i2.addActionListener(this);
i3.addActionListener(this);
}
public void mousePressed(MouseEvent me)
{
if(me.getModifiers()==4)
p.show(this,me.getX(),me.getY());
}
public void mouseClicked(MouseEvent me)
{}
public void mouseReleased(MouseEvent me)
{}
public void Exited(MouseEvent me)
{}
public void Entered(MouseEvent me)
{}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==i1)
t1.setText("Cut option was clicked");
if(ae.getSource()==i2)
t1.setText("Copy option was clicked");
if(ae.getSource()==i3)
t1.setText("Paste option was clicked");
}
}
Output:
F:\java programs>javac PopupDemo.java
Images: We can display images on the applets such as .jpg.gif or .bmp by first creating an object of the
class image which is defined in the java.awt.package.
Loading an image:
getImage(URL, str);
where, URL is Uniform Resource Locator and str is name of the file (.jpg, gif, .bmp)
Displaying the image: Once an image has been loaded, you can display inside the applet window by
calling the method.
drawInage() which is defined in the class Graphics.
g.drawImage(img,x,y,obj);
// Write a program to illustrate the image.
import java.awt.*;
import java.applet.*;
/*<applet code=ImageDemo.class width=300 height=350>
<param name="picture" value="Hanumanth Ladwa.jpg"></applet>*/
public class ImageDemo extends Applet
{
Image img;
public void init()
{
img=getImage(getDocumentBase(),getParameter("picture"));
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,this);
g.drawString("My Name Is Hanumanth Ladwa",65,320);
}
}
Output:
F:\java programs>javac ImageDemo.java
t1=new JTextField(15);
cp.add(t1);
}
public void actionPerformed(ActionEvent ae)
{
String s=ae.getActionCommand();
t1.setText(s);
}
}
Output:
F:\java programs>javac JButtonDemo.java
F:\java programs>appletviewer JButtonDemo.java
The above program shows two command buttons and one text field.
Each button displays a different country’s flag whenever a button is
clicked. A name of the country will be displayed inside the text field.
JCheckbox class: It is used for creating checkboxes.
Constructors:
JCheckbox(Icon i);
JCheckbox(Icon i,Boolean b);
JCheckbox(String s);
JCheckbox(String s, boolean b);
JCheckbox(String s, Icon i);
JCheckbox(String s, Icon I, boolean b);
Methods:
- setRollOverIcon(): It specifies the icon to be displayed
whenever the mouse is moved over the checkbox at runtime.
cb.setRollOverIcon(i1);
- setSelectedIcon(): Specifies the icon to be displayed when
the checkbox is in the selected state.
cb.setSelectedIcon(i2);
// Write a program to illustrate the swing checkbox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*<applet code=JCheckboxDemo width=300 height=200>
</applet>*/
public class JCheckboxDemo extends JApplet implements
ItemListener
{
JTextField t1;
public void init()
{
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
cb=new JCheckBox("C++",r);
cb.setRolloverIcon(r);
cb.setRolloverIcon(s);
cb.addItemListener(this);
cp.add(cb);
cb=new JCheckBox("Java",s);
cb.setRolloverIcon(r);
cb.setRolloverIcon(s);
cb.addItemListener(this);
cp.add(cb);
t1=new JTextField(15);
cp.add(t1);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb=(JCheckBox) ie.getItem();
t1.setText(cb.getText());
}
}
Output:
F:\java programs>javac JCheckboxDemo.java
t1=new JTextField(15);
cp.add(t1);
}
public void actionPerformed(ActionEvent ae)
{
t1.setText(ae.getActionCommand());
}
}
Output:
F:\java programs>javac JRadioButtonDemo.java
EXERCISES
1. What is swing? Explain with a program to demonstrate the
use of JLabel class.
2. Write a program to illustrate JButton.
3. Write a program to illustrate JCheckBox.
4. Write a program to demonstrate swing checkboxes.
5. Write a program to illustrate JRadioButton class.
CHAPTER 16
FILE HANDLING
Introduction: File is an abstract data type in java. A file is a basic unit
of storage of data or information for future reference. There are
various operations on files like, creating a new file, getting information
about file, writing into a file, reading from a file and deleting a file. Java
uses Stream and File methods to perform all the above operations.
Stream: A flow of byte is referred to as a stream. Stream is classified
into two types.
- Byte stream
- Character stream
Read from a file: To read from a file we use a class called Scanner
and the opened file should be closed using a method called close() .
To get the data from the file we use hasNextLine() method nextLine()
method.
// Write a program to read data from a file.
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle
errors
import java.util.Scanner; // Import the Scanner class to read text files
Enter n Value:10
2357
//2. Write a program to print Fibonacci series.
class FibonacciSeries
{
static int n1=0,n2=1,n3=0;
static void printFibonacci(int count)
{
if(count>0)
{
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
}
}
public static void main(String args[])
{
int count=10;
System.out.print(n1+" "+n2);
printFibonacci(count-2);
}
}
Output:
F:\java programs>javac FibonacciSeries.java
Run 1:
F:\java programs>javac Quadratic.java
while(number!=0)
{
rem=number%10;
cube=(int)Math.pow(rem,3);
sum=sum+cube;
number=number/10;
}
if(sum==temp)
System.out.println(temp+" "+"is an Armstrong number");
else
System.out.println(temp+" "+"is not Armstrong number");
}
}
Output:
F:\java programs>javac Armstrong.java