Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
B.Tech Java
JAVA AND OOP
Computers have been with us for a long time. In the recent years computer’s hardware as well as
software has evolved quickly. Before we plunge into a discussion of Java, a quick study of how it
evolved is quite necessary.
A structured oriented programming language named C commenced the modern era of programming
language. Prior to the evolution of C, many languages such as COBOL, PASCAL, BASIC and
FORTRAN were in commonplace. All these languages were not efficient enough to be considered as
an answer to the problems that programmers faced while working with software codes.
C became the most extensively used language during the late 1970s and 1980s. Soon a need for a
better language was raised, the cause being the increasing complexity of programs.
Java was developed by a group of programmers at Sun Microsystems in 1991. Earlier it was named
Oak. The intention behind the development of this language was to create a platform independent
language that could be used in devices like microwave ovens.
Now by using this characteristic of Java the language is widely used in mobiles for developing
games, applications etc. The secret of the platform independent characteristic of Java lies in byte
code and JVM (Java Virtual machine).
OOP concept--- Java and C++ both are OOP (Object Oriented Programming) language. OOP is the crux of the two
languages, especially Java. A curiosity arises in our mind, what is OOP and objects?
Earlier we read that C++ was able to handle the increasing complexity in programs, this is all because
Java is Object Oriented unlike C which is Structured Oriented.
In OOP we take a program in terms of objects rather than methods or procedures. Characteristics of
objects are determined by data and behavior by methods or functions.
Objects, also known as instances, are an independent unit with certain characteristics. Another
important term associated with OOP is class.
Class: A class is group of objects.
In C++ we can directly work on methods without creating a class, but in Java designing a class is
binding on the programmer. A class acts as an encapsulating unit thus binding data and function in itself.
S R I Dept. of CSE
1
B.Tech Java
A real life example of class can be fruits, which has instances like Mango, Apple and Banana.
Banana
Fruit
Mango
Apple
Banana
In the above example Fruit is an class, Mango, Apple, Banana are the objects which represents the class.
The three principles of OOP –
1. Encapsulation
2. Inheritance
3. Polymorphism
Encapsulation :–.
As we studied earlier, Encapsulation is the mechanism of binding Data and function into class. This
principle enables data abstraction i.e. Hiding complexity and we can concentrate on relevant details.
Wrapping up of a data into a single unit is also called as Encapsulation.
We can understand this concept better by taking a practical example of mobile phone which forwards
hundreds of text messages every day. Although we know the application but “how our mobile connects
to network and how the network handles the traffic of thousands of such messages” is not known to most
of us. Some access keywords like private and public help us to encapsulate our data or allow it to be
accessed anywhere.
Public --- Data members declared public are available outside the class.
Private --- Data members declared private are available within the lass.
Inheritance –
Acquiring the properties of one class in to another class is called as Inheritance.
The word ‘Inheritance’ describes a lot about itself.
We inherit traits from our parents and have our own added qualities, thus we are not clones but have an
individual personality.
The same principle applies in programming. After creating a parent class we can define its child class
and hence reusing our code. The child class will have some added properties. Inheritance allows us to
create an object oriented hierarchy.
S R I Dept. of CSE
2
B.Tech Java
1.
2.
3.
A Truck is a Car with 4WD, big tires, and a bed.
A Limo is a very long luxury Car with many seats.
A Racecar is a Car with 1 seat, a very powerful engine, and a number painted on the side.
In the above example we have Three cars but all the cars have common technology which are inherited from older
or starting car technology.
Polymorphism –
If you understand the meaning of the word, the whole concept will quickly become apparent.
Polymorphism’ is a Greek word that means “many forms”.
Again taking a practical example of mobiles, we can compare polymorphism to the ringing of phone. If
you get a message from SASI the phone rings, the phone will even ring if you get a call from SRI.
The ringing capability of phone is polymorphic.
Take a look at ‘+’ i.e. addition operator; it is used to add variables and constants. This operator can also be
used to concatenate two ‘strings’ which is just a group of characters like “k3b” or “splash”. In the
upcoming chapters we will deal with method and constructor overloading that too demonstrates
polymorphism.
What is Java?
Java as a Programming Platform
As a computer language, Java is certainly a good programming language. Java has a lot of nice
language features. Java was never just a language. There are lots of programming languages out there,
and few of them make much of a splash.
Java is a whole platform, with a huge library, containing lots of reusable code, and an execution
environment that provides services such as security, portability across operating systems, and
automatic garbage collection.
A Short History of Java
Java technology was created as a computer programming tool in a small, secret effort called "the Green
Project" at Sun Microsystems in 1991. The secret "Green Team," fully staffed at 13 people and led by
James Gosling.
S R I Dept. of CSE
3
B.Tech Java
They were trying to anticipate and plan for the "next wave" in computing. Their initial conclusion was
that at least one significant trend would be the convergence of digitally controlled consumer devices and
computers.
Gosling thought C and C++could be used to develop the project .But the problem with them is that they
were System Dependent languages and hence could not be used on various processors .
So he started developing a new language, which was completely System Independent .This language
was initially called Oak. Since this name was registered by some other company, later it was changed to
JAVA.
James Gosling and his team members were consuming a lot of Tea while developing this language. They
felt they were able to develop a better language because of the good quality tea they had consumed. So
the Tea also had its own role in developing this language and hence the symbol for java is tea cup and
saucer.
In 1994 Naughton and Jonthan Payne started writing WebRunner—a java based WebBroswer, which
was later renamed as HotJava. HotJava was the first browser, having the capabilities of executing
applets.
Sun formally announced Java and Hotjava at Sun World conference in 1995.On January 23rd 1996,JDK
1.0 version was released. Today more than 4 million developers use Java and more than 1.75 billion
devices run Java. Thus Java pervaded the world.
Characteristics ( or ) Features of Java Technology
A part from being a system independent language, there are other reasons too for the immense popularity of this
language. Let us have a look at some of its features.
Simple
The syntax for Java is, indeed, a cleaned-up version of the syntax for C++. There is no need for header
files, pointer arithmetic, structures, unions, operator overloading, virtual base classes, and so on. Java did
not, however, attempt to fix all of the clumsy features of C++. For example, the syntax of the switch
statement is unchanged in Java.
Another aspect of being simple is being small. One of the goals of Java is to enable the construction of
software that can run stand-alone in small machines. The size of the basic interpreter and class support is
about 40K bytes;
Object Oriented
Simply stated, object-oriented design is a technique for programming that focuses on the data (= objects)
and on the interfaces to that object.
S R I Dept. of CSE
4
B.Tech Java
The object-oriented facilities of Java are essentially those of C++. The object-oriented features of Java
are comparable to those of C++. The major difference between Java and C++ lies in multiple
inheritances, which Java has replaced with the simpler concept of interfaces, and in the Java metaclass
model.
Robust
Java is intended for writing programs that must be reliable in a variety of ways. Java puts a lot of
emphasis on
early checking for possible problems, later dynamic (runtime) checking, and
eliminating situations that are error-prone. . . .
The single biggest difference between Java and C/C++ is that Java has a pointer model that eliminates
the possibility of overwriting memory and corrupting data.
The Java compiler detects many problems that, in other languages, would show up only at runtime. As
for the second point, anyone who has spent hours chasing memory corruption caused by a pointer bug
will be very happy with this feature of Java.
Secure
Java is intended to be used in networked/distributed environments. Toward that end, a lot of emphasis
has been placed on security. Java enables the construction of virus-free, tamper-free systems.
From the beginning, Java was designed to make certain kinds of attacks impossible, among them:
Overrunning the runtime stack—a common attack of worms and viruses
Corrupting memory outside its own process space
Reading or writing files without permission
System Independent
Java’s Byte Code is not machine dependent .It can be run on any machine with any processor and any
operating system.
The JVM will execute this byte code. The JVM has also allocating the memory to variables. Most of the
C and C++ programs crash in the middle because of not allocating sufficient memory or forgetting the
memory to be freed in a program.
In java everything i.e allocate and de allocate of memory will be taken by JVM.
Class loader subsystem of JVM will allocate the necessary memory needed by the Java program.
JVM is also capable of de allocating the memory when it is not used. This work is done by the
Garbage Collector of JVM.
Garbage Collector is a form memory management that checks the memory from time to time and marks
the variables or objects not used by the program automatically. After repeatedly identifying the same
variables or objects, Garbage Collector confirms that the variable or object is not used and hence can be
deleted.
S R I Dept. of CSE
5
B.Tech Java
Portable
If a program yields the same result on every machine, then that program is called portable. Java
programs are portable.
This is the result of JAVA’s independent nature.
Interpreted
The Java interpreter can execute Java bytecodes directly on any machine to which the interpreter has
been ported. Since linking is a more incremental and lightweight process, the development process
can be much more rapid and exploratory.
Incremental linking has advantages, but its benefit for the development process is clearly overstated.
Early Java development tools were, in fact, quite slow. Today, the bytecodes are translated into
machine code by the just-in-time compiler.
High Performance
The problem with interpreter inside is the JVM is that it is slow. Because of this, java programs used to
run slow. To overcome this problem, along with the interpreter, Java Soft people have introduced
JIT (Just-In-Time)compiler ,which enhances the speed of execution. So now in JVM both Interpreter
and JIT compiler work together to run the program.
A just-in-time compiler can monitor which code is executed frequently and optimize just that code
for speed. A more sophisticated optimization is the elimination (or “inlining”) of function calls. The
just-in-time compiler knows which classes have been loaded. It can use inlining when, based upon the
currently loaded collection of classes, a particular function is never overridden, and it can undo that
optimization later if necessary.
Multithreaded
A thread represents an individual process to execute a group of statements .
JVM uses several threads to execute different blocks of code. Creating multiple threads is called
“MultiThread”.
The benefits of multithreading are better interactive responsiveness and real-time behavior.
The ease of multithreading is one of the main reasons why Java is such an appealing language for
server-side development.
Dynamic
Before the development of Java only static text used to be displayed in the Browser. By using java’s
applets we can create animations also.
This is extremely useful for systems that need to analyze objects at runtime, such as Java GUI builders,
smart debuggers, pluggable components, and object databases.
S R I Dept. of CSE
6
B.Tech Java
Java Applets and the Internet
The idea here is simple: Users will download Java bytecodes from the Internet and run them on their
own machines. Java programs that work on web pages are called applets.
Most important, thanks to the security of the virtual machine; we need never worry about attacks from
hostile code. When the user downloads an applet, it works much like embedding an image in a web
page. The applet becomes a part of the page, and the text flows around the space used for the applet.
The point is, the image is alive. It reacts to user commands, changes its appearance, and sends data
between the computer presenting the applet and the computer serving it.
When applets first appeared, they created a huge amount of excitement. Many people believe that the
lure of applets was responsible for the astonishing popularity of Java.
Today, most web pages simply use JavaScript or Flash when dynamic effects are desired in the
browser. Java, on the other hand, has become the most popular language for developing the serverside applications that produce web pages and carry out the backend logic.
Architecture of JVM
The Java virtual machine
S R I Dept. of CSE
7
B.Tech Java
Java Virtual Machine (JVM) is the heart of entire Java program execution process.
It is responsible for taking the .class file and converting each Byte code instruction into machine
language instruction that can be executed by the microprocessor.
In the Java programming language, all source code is first written in plain text files ending with the
.java extension.
Those source files are then compiled into .class files by the javac compiler.
A .class file does not contain code that is native to your processor.
It instead contains bytecodes — the machine language of the Java Virtual Machine (Java VM).
The java launcher tool then runs your application with an instance of the Java Virtual Machine.
Java Virtual Machine
Because the Java VM is available on many different operating systems, the same .class files are
capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux,
or Mac OS.
S R I Dept. of CSE
8
B.Tech Java
Through the Java Virtual Machine, the same application is capable of running on multiple platforms.
JVM is the main component of Java architecture and it is the part of the JRE (Java Runtime
Environment). It provides the cross platform functionality to java. This is a software process that
converts the compiled Java byte code to machine code.
The programs written in Java or the source code translated by Java compiler into byte code and after that
the JVM converts the byte code into machine code for the computer one wants to run. JVM is a part of
Java Run Time Environment that is required by every operating system requires a different JRE.
Components in JVM Architecture
Class Loader
sub system
Method
Area
Java
Stacks
Heap
PC
Registers
Native
Method
Stacks
Run Time Data Areas
JIT
Interpreter
Compiler
Native
Method interface
Native
Method libraries
Execution Engine
Operating System
S R I Dept. of CSE
9
B.Tech Java
First of all .java program is converted into a .class file consisting of byte code instructions by the java
compiler.
First of all , it loads the .class file into memory.
Then it verifies whether all byte code instructions are proper or not. If it finds any instruction suspicions,
the execution is rejected immediately.
If the byte instructions are proper, then it allocates necessary memory to execute the program.
This memory is divided into 5 parts, called Run Time Data Areas, which contain the data and results
while running the program .Those are
1) Method Area
Method area is the memory block, which stores the class code, code of the variables, and
code of the methods in the java program.
This is the area where objects are created. Whenever JVM loads a class, a method and a heap
area are immediately created in it.
2) Heap
3) Java Stacks
Method code is stored on Method area. But while running a method, it needs some more
memory to store the data and results. This memory is allocated on java Stacks.
So java Stacks are memory areas where java methods are executed. While executing methods
a separate frame will be created in the Java Stack, Where the method is executed. JVM uses
a separate thread to execute each method.
4) PC (Program Counters ) Registers
These are the registers, which contain memory address of the instructions of the methods. If
there are 5 methods, 5 PC registers will be used to track the instructions of the methods.
5) Native method Stacks
S R I Dept. of CSE
Java methods are executed on Java Stacks.
Similarly, Native methods (for example C/C++ functions) are executed on Native method
stacks.
To execute the native methods, generally native methods libraries (like C/C++ Header files)
are required. These header files are located and connected to JVM by a program, called
Native Method Interface.
10
B.Tech Java
Parts of Java
Sun Micro Systems has divided Java into 3 parts-Those are
Java SE
Java EE
Java ME
Java SE
It is the Java Standard Edition that contains Basic core Java classes. This edition is used to develop
standard applets and applications.
Java EE
It is the Java Enterprise Edition and it contains classes that are beyond Java SE. In fact, we need Java
SE in order to use many of the classes in Java EE.
Java EE mainly concentrates on providing business solutions on a Network.
Java ME
Java ME stands for Java Micro Edition. Java ME is for developers who develop code for portable
devices as a PDA or a cellular phone.
Code on these devices needs to be small in size and should take less memory.
In fact, its versatility, efficiency, platform portability, and security have made it the ideal technology
for network computing, so that today, Java powers more than 4.5 billion devices:
over 800 million PCs
over 1.5 billion mobile phones and other handheld devices
2.2 billion smart cards
Plus set-top boxes, printers, web cams, games, car navigation systems, lottery terminals, medical
devices, parking payment stations, etc.
S R I Dept. of CSE
11
B.Tech Java
First Java Program
When ever we want to write a program, we should follow the syntax for follow the good Coding Standards.
Comment lines
If a program is understandable, then only can it be usable in software. If not be able to use it in the
project and will reject. So we writing comments for understand ding the program and also we know for
what purpose that program is written.
By writing the comment lines we can understand what the program is doing as well as it helps others
easily follow the our code.
By using the comment lines we can increase the Readability and understandability of a program.
There are three types of comments in java.
Single line comments
These comments are for marking a single line as a comment. These comments start with
double slash symbol // and after this, whatever is written till the ends of the line is taken
as a comment.
// This is Single line comments
Multi line comments
These comments are used for representing several lines as comments. These comments
start with /* and end with */. In between them what ever is written is treated as a
comment.
/* This is an example for Multiline comments
This is line one
………………….. */
Java Documentation comments
These comments start with /** and with */ .These comments are used to provide
description for every feature in a java program.
This description proves helpful in the creation of a .html file called API ( Application
Programming Interface ).
Java documentation comments should be used before every feature in the program as
shown below.
/** Description about a class */
Class code
/** Description about a method */
Method code
S R I Dept. of CSE
12
B.Tech Java
Importing Classes
Suppose we are writing a c/ c++ program the first line of the program would be generally be
#include <stdio.h>. This means a request made to the c / c++ compiler to include the header
file <stdio.h>
What is a header file ? A header file is a file, which contains the code of function that will be
needed in a program. In other words , to be able to use any function in a program, we must first
include the header file containing that functions’ code in our program.
What happens when we include the header file ? After we include the header file, the c/c++
compiler goes to the standard library and searches for the header file there. When it finds the
header file, it copies the entire header file content into the program where the #include statement
is written.
For example we write a program of 20 lines ,then after copying code fro, the header file, the
program size may become ,say 120 lines. (i.e) 20lines + 100 lines code form the header file. This
is causes to wastage of memory and unnecessarily increases the size of the program.
A similar but more efficient mechanism, available in case of Java is that importing classes. First
we should decide which classes are needed in our program .Generally programmers are
interested in two things.
Using the classes by creating the Objects in them.
Using the methods (functions) of the classes.
In java methods are available in classes or Interfaces. What is an Interface ? an interface is
similar to a class that contains some methods.
A group of classes and Interfaces are contained in a Package. A package is a kind of directory
that contains a group of related classes and interfaces and Java has several such packages in its
library.
Java Library
Packages
Classes and Interfaces
Methods
Import statements makes the JVM go to the Java standard library, execute the code there, and
substitute the result into the program. Here no code is copied and hence no waste of memory
or processors time.
So import is an efficient mechanism than #include
S R I Dept. of CSE
13
B.Tech Java
Writing a Class
After importing the classes into our program , the next step is write a class.
Since Java is an pure Object-Oriented programming language. We cannot write a Java program
without one class or Object.
By using the class keyword we write the class.
Class Sample
{
Statements:
Methods:
}
Writing the main( ) function….
If main( ) method is not written in a java program, JVM will not execute it. Main( ) is a starting point for
JVM to start execution of a Java program.
Public static void main( String args[] )
{
Statements
………………..
}
main( String args[] )
Inside of main( ) function we write String args[ ] . Here args[ ] is the array name it is of a String type.
This mean it can store a group of Strings , this array can also store a group of numbers but in the form of
Strings.
That is args[ ] stores the values which are enter at running a program, (i.e) command line arguments.
Static
Generally we write several methods in class. Those all methods are called using Object . Method( )
Main( ) is also an method inside a class, then how it is possible to create an object before calling the
main( ) method ? Such methods are called static methods.
Static methods are the methods , which can be called and executed without creating the Objects.
Since we want to call main( ) method without using the an object, That’s why we should declare main( )
method as static.
JVM calls main( ) method using its class name.main( ) at the time of running the program.
S R I Dept. of CSE
14
B.Tech Java
Public
JVM is a program written by JavaSoft people and main( ) is the method is written by us. Since main( )
method should be available to the JVM, That’s why we declare the main( ) method as public . If we
don’t declare main( ) method as public , then it doe’s not make itself available to JVM and JVM cnnot
execute it.
A Simple program
/*
*****************************************************
Program Name :
Purpose
:
Author
:
Version
:
Date
:
******************************************************
*/
Import java.util.*;
Import java.math.*;
public class Sample
{
public static void main(String args[])
{
System.out.println("Welcome to java..!!");
}
}
Output :-
Javac ---- This command is used for compile the .java file
Java ------This command is used to run the java program.
S R I Dept. of CSE
15
B.Tech Java
Data Types And Operators
In our daily life we receive information as stimulus from our surrounding. Then we process and
analyze it within our minds. A computer too gets input from several sources which it processes to give
an output. So data handling is a core issue of programming.
CONSTANTS
The word “constant” means anything that does not change. Constants that are also known as
“literals” have a fixed value in programming.
Let us assume a number ‘6’, this digit represents a number. If I order two shopkeepers to give me
six DVDs of a movie, both will supply me with the same number. The real world situation even
applies here. In this way we can even call alphabets ‘S’‘t’ ‘u’ ‘V’ and Strings such as “Delhi” as
constants.
A proper hierarchy will be --Constants --1. Numeric Constants-----
(1). Integer Constants
(2). Real Constants
2. Character Constants----
(1).Characters
(2).String
Data Types
Each and Every variable and constant holds a certain data. The data can be classified under any of
these types. While declaring variables we have to specify its type.
Data Type
byte
boolean
char
short
int
long
float
double
S R I Dept. of CSE
Size (byte)
1
1
2 (Unicode)
2
4
8
4
8
Range
-128 to 127
true or false
A-Z, a-z, 0-9, etc.
-32768 to 32767
(about )–2 million to 2 million
(about)-10E18 to 10E18
-3.4E38 to 3.4E18
-1.7E308 to 1.7E308
There are only eight primitive data types.
A programmer cannot create new primitive data types.
16
B.Tech Java
Integer Type
Integer (int)
Short (short)
----- Holds digits without any fractional part with 4 bytes.
------ Holds digits without any fractional part. The range of value it holds is less
If compared with int.(2 bytes).
Long (long)
------ Holds digits without any fractional part. The range of value it holds is
more if compared with “int”.(8 b ytes)
Byte (byte) ------ Holds digits without any fractional part. The range of value it holds is least.
Float Type
Float (float)
------- Holds digits with fractional part.
Double (double) ------ Holds digits with fractional part. The range of value it holds is higher in
Comparison with float.
Character Type
Char (char) -------- Holds a single character.
Boolean
It is a special data type; It holds two values either true or false.
Data Types
||
||
============================================================
||
||
||
||
Primitive (Intrinsic)
Non-Primitive (Derived)
||
||
||
====== ====================
||
||
||
||
||
Classes
Arrays
Interface
||
||
=================================
||
||
Numeric
Non-Numeric
||
||
=============
============
||
||
||
||
Integers
Float
Characters
Boolean
S R I Dept. of CSE
17
B.Tech Java
The Java Keywords
Here's a list of keywords in the Java programming language. We cannot use any of the following as
identifiers in our programs. The keywords const and goto are reserved, even though they are not
currently used. true, false, and null might seem like keywords, but they are actually literals; we cannot
use them as identifiers in our programs.
Popular Printing Characters
Newline
Horizontal Tab
Vertical Tab
\n
\t
\v
Use--- Prints a blank line.
Use---Prints a horizontal space of 5
Use---Prints a vertical space of 5
Variables
Variables are labels that describe a particular location in memory and associate it with a data type.
A declaration of a variable is where the program allocates memory for the variable.
The declaration in the example program requested a 32 bit section of memory which will use primitive
data type int and will be named states.
A variable cannot be used in a program unless it has been declared.•A variable can be declared only once
in a particular section of code.
Syntax of Variable Declaration
The first way to declare a variable: This specifies its data type, and reserves memory for it. It assigns
zero to primitive types and null to objects.
dataType variableName;
The second way to declare a variable: This specifies its data type, reserves memory for it, and puts an
initial value into that memory. The initial value must be of the correct data type.
dataType variableName = initialValue;
Names of Variables
Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character '_', and character '$'.
A name cannot contain the space character.
Do not start with a digit.
A name can be of any reasonable length.
Upper and lower case count as different characters. I.e., Java is case sensitive. So SUM and Sum
are different names.
A name cannot be a reserved word (keyword).
A name must not already be in use in this block of the program.
S R I Dept. of CSE
18
B.Tech Java
Examples: 53
12 – 3)
• x + 34
• ((rate – 3) / 45
• sum * 3 + 2
• -395.7
• (foo – 7)
• Z
• (x-5)/(y+6)+67
• x+
correct
wrong
correct
wrong
correct
correct
correct
correct
correct
wrong
OPERATORS
We widely use several operators in our daily language while working with values in
Mathematics and even our day-today life.
Definition:
Operators are certain symbols recognized by the compiler which when used with variables or constants
(popularly also known as operands) do a pre-defined action.
Types of Operators are--1.
2.
3.
4.
5.
6.
Arithmetical Operators
Increment Operators
Bitwise Operators
Logical Operators
Relational Operators
Ternary or Conditional Operator
Arithmetic Operators
An arithmetic operator is a symbol that performs some arithmetic.
The four operators ‘+’, ‘-’, ‘*’ and ‘/’ are known as arithmetic operators. They are used to perform
simple arithmetic calculation in programming as in mathematics. Certain operators require only
one operand (Example- ‘+, - ’) and are hence known as Unary operator. Other operators that are
used with two operands are known as Binary Operator (‘*, / , +, -’)
If several operators are used in an expression, there is a specific order in which the operations are
applied.
Operators of higher precedence will operate first.
S R I Dept. of CSE
19
B.Tech Java
Operator
+
*
Meaning
Unary minus
Unary plus
Multiplication
Precedence
Highest
Highest
Middle
/
%
+
-
Division
Remainder
Addition
Subtraction
Middle
Middle
Low
Low
Here is an example class
class arith_opr
{
public static void main(String args[])
{
float no1,no2;
float sum,product,difference;
float quotient;
no1=17; no2=02;
sum=no1+no2;
product=no1*no2;
quotient=no1/no2;
difference=no1-no2;
System.out.println("Two Numbers are "+no1+" "+no2);
System.out.println("Sum is " +sum); System.out.println("Product is "+product);
System.out.println("Quotient is "+quotient);
System.out.println("Difference is "+difference);
}
}
Increment and Decrement Operator
Like any other language such as C++ or C, Java too provides increment and decrement operator.
The purpose of this operator is quite simple i.e. is to increment and decrement the value of operand
by one.
Increment and Decrement operators can be in two forms.
Prefix
Postfix
Prefix Increment or Decrement Operator –
The prefix Increment or Decrement operator works on the principle “First change then use.”
The value of operand is first increased or decreased and then the value thus obtained is used
in expression for calculation.
S R I Dept. of CSE
20
B.Tech Java
Postfix Increment or Decrement Operator –
The postfix Increment or Decrement operator works on the principle “First use then change”. The
value of operand is directly used in the expression and the value is changed later.
Some examples of this Operator --class ex_inc_dcr
{
public static void main(String args[])
{
int a,b,c,d;
a=5; b=6;
c=11;
d=++a*b---c;
System.out.println(+d);
a=5; b=6;
c=11; d=0;
d=a++*b-c--;
System.out.println(+d);
}
}
As you are now familiar with the theory behind the difference in increment and decrement operator,
Let us see the working –
(1) d=++a*b---c;
a=5; b=6; c=11;
++a = 6;
b-- = 5 (value 6 will be used in expression)
c = 11;
After final calculation-6*6-11= 36-11=25
(2) a=5; b=6; c=11;
d=0;
d=a++*b-c--;
a++ =6 ( Value used in expression will be 5)
b =6
c-- =10 (value used in expression will be 11)
5*6-11
30-11=19
S R I Dept. of CSE
21
B.Tech Java
Bitwise Operator
The Bitwise operator when used with any operand works at its individual bits. It does not work with
float and double data type.
When working with any of the integer types, We have operators that can work directly with the bits
that make up the integers. This means that We can use masking techniques to get at individual bits in a
number. The bitwise operators are
&
|
(“and”)
(“or”)
^
(“xor”)
~
(“not”)
Logical Operator
Logical operators are generally used with conditional statements and are used to combine two conditions.
The three Logical Operators--
||
Logical Or
!
Logical Not
&&
Logical And
Example ---if(a= =1 && b==2)
Statements…
If both the conditions are true then only && block is successfully executed
Even if one condition out of the many is true then also the block is successfully executed.
If the condition is wrong then only the statements inside the block are executed.
Relational Operators
As the name clear illustrates the meaning, the relational operators show the relations between the
two variables.
As the name clear illustrates the meaning, the relational operators show the relations between the
two variables.
Greater Than
Less Than
Greater Than Equal To
Less Than Equal To
Equal To
Not Equal To
S R I Dept. of CSE
>
<
>
=
<
=
!
=
22
B.Tech Java
Ternary Operator
Conditional Operator is also known as Ternary Operator. It can be used to a substitute of ‘if ’
statement. Observe this program carefully.
Example:class cond_opr
{
public static void main(String args[])
{
int n1,n2,ans,ans2;
n1=5;
n2=10; ans=(n1<n2)?n1:n2;
ans2=(n1>n2)?n1:n2;
System.out.println(+ans);
System.out.println(+ans2);
}
}
Parentheses and Operator Hierarchy
In the following table shows the precedence of operators. If no parentheses are used, operations are
performed in the hierarchical order indicated. Operators on the same level are processed from left to
right, except for those that are right associative, as indicated in the table. For example, because &&
has a higher precedence than ||, the expression
a && b || c
means (a && b) || c
Operator Precedence
Operators
[ ] . ( ) (method call)
! ~ ++ -- + (unary) – (unary) ( ) (cast) new
* / %
+<< >> >>>
< <- > >- instance of
-- !&
^
|
&&
||
?:
- +--- *- /- %- &- |- ^- <<- >>- >>>-
S R I Dept. of CSE
Associativity
Left to right
Right to left
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Right to left
Right to left
23
B.Tech Java
Control Flow Statements
The statements inside Our source files are generally executed from top to bottom, in the order that they
appear. Control flow statements, however, break up the flow of execution by employing decision
making, looping, and branching, enabling Our program to conditionally execute particular blocks of
code. This section describes the decision-making statements (if-then, if-then-else, switch), the looping
statements (for, while, do-while), and the branching statements (break, continue, return) supported by
the Java programming language.
The if-then Statement
The if-then statement is the most basic of all the control flow statements. It tells our program to execute
a certain section of code only if a particular test evaluates to true.
If(condition)
{
True Block
------------}
The if-then-else Statement
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to
false.
If(condition)
{
True Block
------------}
Else
{
False Block
-------------}
Example:-
class IfElseDemo
{
public static void main(String[] args)
{
int testscore = 76;
char grade;
if (testscore >= 90)
grade = 'A';
else if (testscore >= 80)
grade = 'B';
else if (testscore >= 70)
grade = 'C';
else if (testscore >= 60)
grade = 'D';
else { grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
S R I Dept. of CSE
24
B.Tech Java
The switch Statement
Unlike if-then and if-then-else, the switch statement allows for any number of possible execution
paths. A switch works with the byte, short, char, and int primitive data types.
Example :
class SwitchDemo
{
public static void main(String[] args)
{
int month = 8;
switch (month)
{
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}}}
Iteration Statement
The while statement continually executes a block of statements while a particular condition is true. Its
syntax can be expressed as:
while (expression)
{
statement(s)
}
The while statement evaluates expression, which must return a Boolean value. If the expression
evaluates to true, the while statement executes the statement(s) in the while block. The while
statement continues testing the expression and executing its block until the expression evaluates to
false.
S R I Dept. of CSE
25
B.Tech Java
Example:class WhileDemo
{
public static void main(String[] args)
{
int count = 1;
while (count < 11)
{
System.out.println("Count is: " + count);
count++;
}
}}
Do..while
The Java programming language also provides a do-while statement, which can be expressed as
follows:
do
{
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of
the loop instead of the top. Therefore, the statements within the do block are always executed at least
once, as shown in the following DoWhileDemo program:
class DoWhileDemo
{
public static void main(String[] args)
{
int count = 1;
do
{
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}}
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to
it as the "for loop" because of the way in which it repeatedly loops until a particular condition is
satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment)
{
statement(s)
}
S R I Dept. of CSE
26
B.Tech Java
Example:
class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<11; i++)
{
System.out.println("Count is: " + i);
}
}}
The for each Statement
The for statement also has another form designed for iteration through Collections and arrays This form
is sometimes referred to as the enhanced for statement, and can be used to make Our loops more
compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1
through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10} ;
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo
{
public static void main(String[] args)
{
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers)
{
System.out.println("Count is: " + item);
}
}}
S R I Dept. of CSE
27
B.Tech Java
Input and Output
There are no standard statements in Java for doing input or output.
All input and output is done by using methods found in classes within the JDK.
Objects in memory communicate in different ways. Each way is a method, and using each method
results in a different reaction to the object being used
The java.io package is the package used for I/O.
A package is a collection of classes which may be used by other programs.
IO Streams
In Java, a source of input data is called an input stream and the output data is called an output stream
Output Stream
Input Stream
Input data is usually called reading data; and output data is usually called writing data.
Commonly used IO Streams
•System.in --- the input stream form the keyboard.
•System.out --- the output stream for normal results to the terminal.
•System.err --- the output stream for error messages to the terminal.
Characters In, Characters Out
System.in
The data a keyboard sends to a program is character data, even when the characters include the
digits '0' through '9'.
Java Program
System.out
S R I Dept. of CSE
28
B.Tech Java
If your program does arithmetic, the input characters will be converted into one of the primitive numeric
types. Then the result is calculated (using arithmetic), and then the result is converted to character data.
The information a program sends to the monitor is character data.
Import a Package
The line import java.io.*; says that the package java.io will be used. The * means that any class
inside the package might be used.
Main Method
The main method of class Echo starts with the line:
public static void main (String[] args) throws IOException
throws IOException is necessary for programs that perform Input / Output. There are better
ways of handling this that will be discussed later.
It informs the compiler that main performs an input operation that might fail.
When the program is running and an input operation fails, the computer system is informed of the
failure and the program halts
Buffered Reader
InputStreamReader in = new InputStreamReader( System.in) ;
BufferedReader br = new BufferedReader( inStream );
This code creates a buffered reader that is used to read input from the keyboard.
Note: For now, don’t worry about the details of how this creates a buffered reader.
1
2
3
1
2
3
System.out
S R I Dept. of CSE
29
B.Tech Java
Think of this as an assembly line: System.in gets characters from the keyboard.
The InputStreamReader reads the characters from System.in and hands them to the BufferedReader.
The BufferedReader objects hands the data to your program when requested.
readLine()
The program reads a line of character data from the buffered reader by using the method readLine()
It gets a line of characters, and assign them to the String inData
InputStreamReader in = new InputStreamReader( System.in) ;
BufferedReader br = new BufferedReader( in );
Numeric Input
Notice that the characters '1', '4', '9', and '2' were read in and written out just as were the other characters.
If you want the user to enter numeric data, your program must convert from character data to a numeric
type.
The characters are first read into a String object. Then the String object converts the characters into a
numeric type. This is done using a wrapper class.
Wrapper Class
A wrapper class can be used to convert a primitive data value into an object, and some types of objects
into primitive data.
For each primitive type, there is a corresponding wrapper class.
Primitive type
Wrapper
Type
byte
Byte
short
Short
int
Int
long
Long
float
Float
double
Double
char
Char
boolean
Boolean
Converting to Integers
This uses the method parseInt() of the Integer wrapper class. This method takes a String containing an
integer in character form.
It looks at those characters and calculates an int value. That value is assigned to num.
S R I Dept. of CSE
30
B.Tech Java
Example:import java.io.*;
class Sample
{
public static void main(String[] args) throws IOException
{
int a;
float b;
double d;
char ch;
String name;
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.println("Enter the integer value");
a=Integer.parseInt(br.readLine());
System.out.println("Enter the Float value");
b=Float.parseFloat(br.readLine());
System.out.println("Enter the Double value");
d=Double.parseDouble(br.readLine());
System.out.println("Enter the Name");
name=(br.readLine());
System.out.println("Enter the integer value");
ch=(char)br.read();
System.out.println("The integer value of a="+a);
System.out.println("The Float value of a="+b);
System.out.println("The Double value of a="+d);
System.out.println("The Name ="+name);
System.out.println("The Character ="+ch);
} }
S R I Dept. of CSE
31
B.Tech Java
Example Programs:-
3)Q. WAP to print Prime Numbers with in range
series.
1)Q. WAP to find factorial of a given number.
import java.io.*;
import java.io.*;
public class Fact
{
public static void main(String args[])throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.println("Enter the integer N value");
int n = Integer.parseInt(br.readLine());
int fact=1;
public class Fact
{
public static void main(String args[])throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.println("Enter the integer N value");
int n = Integer.parseInt(br.readLine());
for(int i=1;i<=n;i++)
{
int t=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
t++;
}
if(t==2)
System.out.println(i);
for(int i=1;i<=n;i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+n+" = "+fact);
}}
2)Q. WAP to print Fibonacci series.
import java.io.*;
public class Fact
{
public static void main(String args[])throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.println("Enter the integer N value");
int n = Integer.parseInt(br.readLine());
int a,b,c;
a=0;b=1;
System.out.println(a);
System.out.println(b);
for(int i=1;i<n;i++)
{
c=a+b;
System.out.println(c);
a=b;
b=c;
}
}}}
4)Q. WAP to check the given number is AMSTRONG
ot NOT.
import java.io.*;
import java.math.*;
public class Fact
{public static void main(String args[])throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.println("Enter the integer N value");
int n = Integer.parseInt(br.readLine());
int n1=n;
int res=0;
while(n>0)
{
int t=n%10;
res=res+(int)Math.pow(t,3);
n=n/10;
}
if(res==n1)
System.out.println("Amstrong");
else
System.out.println("Not Amstrong");
}
}
}}
S R I Dept. of CSE
32
B.Tech Java
ARRAYS
Def:- Array is a group of similar kind of data types that is reference by a common name. (or) Array is
collection of homogeneous elements with a common name.
Suppose if we want a group of integers from 1 to 100 to be reference by a common name, we create an
array of them.
Each variable in an array is called array element. It is important to note that the array numbering stars
from 0 and not 1.
Array is an object and not a primitive, even if it is made up of primitives. Like objects, array
required initialization and declaration only creates a reference to the array. To explain in depth, to create a
array is to 3 steps
Declaration
Creation
Initialization
Declaration
One is not obliged to create the array itself when you declare the array variable. The array
variable is distinct from the array itself. This is how one declares a array.
int a []
String s []
-
This is a array of integers with the variable a
This is a array of strings with the variable s
Creation
Once you declare an array of any data type, you should create the same with the help of the new
keyword and the same is done like this.
a = new int [10];
s = new String [5];
The above example shows that the array with the variable a will store integers up to 10 values and the
second example creates that the s (String variable) will store Strings up to 5 values.
Remember: The array length starts from 0
The creation of array only reserves the space in memory for 10 integers and 5 strings, but nothing is
inside it.
Initialization
Once we have the memory reserved, we can put values into each of the individual spaces like this:
a[0] = 10; This puts 10 as the first value of the array
a[1] = 20; This puts 20 as the second value of the array and so on. Similarly we can put strings into the 5
spaces as under;
s[0] = “Gurukul” and so on.
S R I Dept. of CSE
33
B.Tech Java
Accessing Array Values
You can refer to an element of an array by using the array variable followed by the element’s index
value enclosed between square brackets. For Example
Existing Array: int a [] = { 1,25,30,55}
If we have to access the 2nd element of the array, we will do it like this int a[1], here we use 1 because,
as said earlier, the array indexing begins with 1.
Important:
Any attempt to access array indexes beyond the length of the array causes runtime error. For example:
If we try to access the 5th element, it will give a runtime error, because there is no 5th element in the
array.The exception thrown would be called as ArrayIndexOutOfBoundsException.
Example :import java.io.*;
import java.util.*;
class Arrays
{
public static void main(String[] args) throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.println("Enter the how may elements u want....");
int n=Integer.parseInt(br.readLine());
int a[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter elements into the array");
a[i]=Integer.parseInt(br.readLine());
}
System.out.println("The elements in the array is......");
for(int i=0;i<n;i++)
System.out.println(a[i]);
}
}
S R I Dept. of CSE
34
B.Tech Java
Example for ArrayIndexOutOfBoundsException.
class Test22
{
public static void main(String[] args)
{
int a [] = new int[10];
System.out.println(a[10]);
}
}
Output:java.lang.ArrayIndexOutOfBoundsException
at Test22.main(Test22.java:6) Exception in thread "main"
Multi-Dimensional Arrays
In java, multidimensional arrays are actually array of arrays.
To declare a multidimensional array a variable, specify each additional index using another set of
square brackets. For example, the following declares a two-dimensional array variable called D.
int D [ ] [ ] = new int [2] [4]
The above array creates and allocated a 2 by 4 array. Internally this acts like a matrix in which the first
square bracket is for the number of rows and the second bracket is for the number of columns.
Remember: Note that you can have an array with 0 columns but not with 0 rows. For example
int D[] [] = new int [2] [0]
int D[] [] = new int [0] [2]
-
Ok
Not Ok.
Example:import java.io.*;
import java.util.*;
class Arrays
{
public static void main(String[] args) throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.println("Enter the how may elements u want....");
int n=Integer.parseInt(br.readLine());
int a[][]=new int[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
a[i][j]=Integer.parseInt(br.readLine());
System.out.println("The elements in the array is......");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
System.out.println(a[i][j]); }}
S R I Dept. of CSE
35
B.Tech Java
Understanding Classes and Functions
Introduction
In the first chapter, you studied about OOP, classes, functions and their use in Java language. As it was
just a start you were introduced with certain basic concepts. The most powerful features were left
untouched.
e.g. - You had only seen the use of main method but are yet to discover the concept of using multiple
methods in a class other then the “main”. Now you will explore them in depth. Before going to deep let
us revise the things and start from basics.
A general class declaration with methods--Class name1
{
//public variable declaration
void methodname()
{
//body of method…
//Anything
}
}
Let us apply this concept and take an example of real world class.
class learn
{
private int x,y,z;
public void input()
{ x=10; y=15;
}
public void sum()
{
z=x+y;
}
public void show()
{
System.out.println(“Answer is =” +z);
}}
public static void main(String args[])
{
learn obj1=new learn();
ob1.input ();
obj1.sum ();
obj1.print_it ();
}}
S R I Dept. of CSE
36
B.Tech Java
This is a class ‘learn’ with three methods, i.e., input, sum and print. The three functions are designed to
do a specific task. This you can easily figure out by seeing the code. The input () method initializes the
two values, sum () adds them and finally show() shows the answer.
In the first line we created an object. An object can be simply created by typing--learn obj1=new learn();
The object thus created will be null and so we need to instantiate it. The new operator allocates memory
for the object and instantiate it . Constructors are also called at this point (You will read about
constructors in the next chapter).
The three methods are called by using the dot operator. When we call a method the code inside its block
is executed.
Creating “main” in a separate class
You can even create the main method in a separate class, but during compilation you need to make sure
that you compile the class with the “main” method. The program will thus be like this….
class learn
{
private int x,y,z;
public void get()
{ x=10;
y=15;
}
public void sum()
{
z=x+y;
}
public void show()
{
System.out.println(“Answer is =” +z);
}
}
class apply
{
public static void main(String args[])
{
learn obj1=new learn();
obj1.get();
obj1.sum();
obj1.show();
}
}
S R I Dept. of CSE
37
B.Tech Java
Access Specifiers/Modifiers/Controls
Encapsulation links data with the code that manipulates it. However, encapsulation provides another
important attribute: access control.
Through encapsulation, you can control what parts of a program can access the members of a class. By
controlling access, you can prevent misuse. For example, allowing access to data only through a welldefined set of methods, you can prevent the misuse of that data.
Following is the list of access specifies used in java
1) private
Private members can be accessed only within the class in which it is defined. Private
members are declared using private keyword.
2) public
Public members can be accessed within the class in which it is declared as well as
anywhere outside the class through an instance of class. Here classes can be same
package or different package. Public members are declared by using public keyword.
3) Protected
Protected members can be accessed within the class in which it is declared as well as in
its child class but here base class and child class should be within the same package.
Protected members are declared by using protected keyword.
4) Friendly
When a member is declared in a class without any access specifier that is by default
considered is a friendly. Friendly access specifier behaves somewhat like public.
Friendly members are accessed within a class in which it is declared as well as another
classes within the same package. Friendly members cannot be accessed outside the
package in which it is declared.
6) public protected
When a member is declared with public protected access specifier that member can
be accessed within the class as well as in child class. Here child class may be in
different package.
S R I Dept. of CSE
38
B.Tech Java
The dot operator
The dot operator is used to call methods or access them. It has other use too Before you understand this
concept properly, a little theory is needed to be understood.
Instance Variable
All variables (Assume int num) are also known as instance variable. This is because of the fact that each
instance or object has its own copy of values for the variable.
Hence other use of the “dot” operator is to initialize the value of variable for that
instance.
Example :class dot1
{
int x,y,z;
public void sum()
{
z=x+y;
}
public void show()
{ System.out.print(“The Answer is “+z);
}
}
class apply1
{
public static void main(String args[])
{
dot1 object=new dot1();
dot1 object2=new dot1();
object.x=10;
object.y=15;
object2.x=5;
object2.y=10;
object.sum();
object.show();
object2.sum();
object2.show();
}}
S R I Dept. of CSE
39
B.Tech Java
Static keyword -- you read about the use of “static” keyword when it was used before the method’s name. This keyword can
even be used with variables. e.g. — static int num;
This will make the variable independent of any instance and it will have the same copy of value for
each and every object.
Methods with parameters
Take an example of a method named ‘sum()’. You can see ‘sum()’ with parenthesis. As they are empty,
it shows that the method has no parameters. You can even add some parameters of your own to
serve as an add-on to your method’s functionality. Observe the following example —
class learn2
{
int n1,n2,sum;
public void get(int x,int y)
{
n1=x;
n2=y;
}
public void sum()
{
sum=n+n2;
}
public void print()
{ System.out.println("The Sum is"+sum);
}
}
class my_main
{
public static void main(String args[])
{
learn2 obj=new learn2();
obj.get(10,15);
obj.sum();
obj.print();
}
}
In this “learn2” program, the method “get(int x,int y)” has two parameters. These parameters are
supplied with values from the main, when the method is called. The variables x, y are declared
as parameters and you have transferred their values to two other variables n1 & n2 respectively.
Remember: Values supplied should match with the data type of parameters.
S R I Dept. of CSE
40
B.Tech Java
Method Overloading
You were earlier introduced to the concept of “method overloading” under the caption “polymorphism”.
In same class, if name of the method remains common but the number and type of parameters are
different, then it is called method overloading in Java.
Example:class meth_over
{
int x=5,y=5,z=0;
public void sum()
{
z=x+y;
System.out.println("Sum is "+z);
}
public void sum(int a,int b)
{ x=a;
y=b;
z=x+y;
System.out.println("Sum is "+z);
}
public int sum(int a)
{
x=a; z=x+y; return z;
}
}
class Sample
{
public static void main(String args[])
{
meth_over obj=new meth_over();
obj.sum();
obj.sum(10,12); System.out.println(+obj.sum(15));
}}
You might be wondering how this program was able to compile successfully. Another important
question that might arise is “how did the compiler choose to execute a particular method?”.
Resolving all your mind conflicts…
The java run time system decides to execute any of the particular method on the basis of its
parameter(s). In the first call to the method “sum()” we had not specified any parameter and
hence the method “sum()” with no parameter would be executed.
In the second and the third call, the method “sum ()” with two parameters and a single parameter
would be executed respectively.
S R I Dept. of CSE
41
B.Tech Java
Recursion
When a method calls itself, it is known as recursion.
The power of recursion can be demonstrated by taking an example of a class that calculates
factorial of a number.
Example :1)Q. WAP to find factorial of a given number by using
recursion..
Import java.io.*;
class factorial
{
int ans;
public int fact(int n)
{
if(no==1)
return 1;
else
ans=fact(n-1)*n;
return ans;
}
public static void main(String args[]) throws IOException
{
InputStreamReader in = new InputStreamReader(System.in ) ;
BufferedReader br = new BufferedReader( in);
factorial obj=new factorial ();
System.out.println(“Enter n”);
n=Integer.parseInt(br.readLine());
System.out.println(+obj.fact(n));
}}
2)Q. WAP to find N th Fibonacci of a given number by
using recursion..
import java.io.*;
import java.math.*;
class NthFibonacci
{
public static void main(String[] args) throws Exception
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.print("Enter an integer to find nth Fibonacci it ");
int n=Integer.parseInt(br.readLine());
Fib obj=new Fib();
System.out.println(n+"th fibonacci number:"+obj.recFib(n));.
}}
S R I Dept. of CSE
class Fib
{
int recFib(int n)
{ if(n==0)
return 0;
if(n==1)
return 1;
if(n>=2)
return (recFib(n-1)+recFib(n-2)); //recursive call
return 0;
}}
2)Q. WAP to find Fibonacci of a given number by
using recursion..
import java.io.*;
class Fibo_Series
{
public static void main(String[] args)throws IOException
{
Fibo_Series obj = new Fibo_Series ();
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.print("Enter an integer to print Fibonacci it ");
int n=Integer.parseInt(br.readLine());
for (int i = 1; i <=n; i++)
System.out.print(obj.fibo(i) + ", ");
}
int fibo(int n)
{
if(n==1||n==2)
return 1;
else
return fibo(n-1)+fibo(n-2);
}}
42
B.Tech Java
Constructor
Constructor is a special type of function which have same name as class in which it is declared.
Once a constructor is defined it is automatically called immediately after the object is created.
Following are the rules for constructor declaration
Constructor should have same name as that of its class name.
Constructor should not return any value.
Constructor may take parameters
Constructor should not be abstract or static.
Need of Constructor
A class contains one of the process which requires some data and code. Data is stored in the form of
instance variables of class.
Means it will not execute a process defined in the class without initializing the variables of class.
It is difficult to initialize all the class variables by using like getdata() method as used in all programs.
So we can define a constructor which will call automatically when the object is created of that class and
initializes the variables of class.
Example:class Const_Example
{
int x;
Const_Example() //Defaulte Constructor
{
x=5;
}
void show()
{
System.out.println("x="+x);
}
public static void main(String[] args)
{
Const_Example obj1=new Const_Example();
obj1.show();
}
}
Parameterized constructor
If you want to assign different values to the instance variables when different objects are created. So we
make constructor which takes some argument whose value will be assigned to variable. In short
“Constructor which have arguments are known as parameterized constructor.”
S R I Dept. of CSE
43
B.Tech Java
Example:class Const_Example
{
int x,y;
Const_Example(int a,int b) //Parameterized Constructor
{
x=a;
y=b;
}
void show()
{
System.out.println("x="+x);
System.out.println("y="+y);
}
public static void main(String[] args)
{
Const_Example obj1=new Const_Example(25,59);
obj1.show();
}
}
‘this’ Keyword
Sometimes a method will need to refer to the object that invoked it.To allow this, Java defines the this
keyword.
this can be used inside any method to refer to the current object. That is, this is always a reference to
the object on which the method was invoked. You can use this anywhere a reference to an object of the
current class ’ type is permitted.
Example:class Const_Example
{
int x,y;
Const_Example(int x,int y)
{
this.x=x;
this.y=y;
}
void show()
{
System.out.println("x="+x);
System.out.println("y="+y);
}
public static void main(String[] args)
{
Const_Example obj1=new Const_Example(25,59);
obj1.show();
}
}
S R I Dept. of CSE
44
B.Tech Java
Static members of class
Normally a class member must be accessed only in conjunction with an object of its class. However, it is
possible to create a member that can be used by itself, without reference to a specific instance.
To create such a member, precede its declaration with the keyword static. When a member is declared
static, it can be accessed before any objects of its class are created, and without reference to any object.
The most common example of a static member is main (). The main()is declared as static because it
must be called before any objects exist.
Instance variables declared as static are, essentially, global variables. When objects of its class are
declared, no copy of a static variable is made. Instead, all instances of the class share the same static
variable.
Static Methods
A Static method is a method that does not act upon instance variables of a class. A Static method is
declared by using the keyword ‘static’.
Static method s are called using ClassName.MethodName().
The reason why static methods can not act on instance variables is that the JVM first executes the static
methods and then only it creates the Objects. Since the objects are not available at the time of calling
the static methods, the instance variables are also not available.
Methods declared as static have several restrictions:
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way.
Example:Class Static_Example
{
static int x=99;
static void show()
{
System.out.println(“static method”);
System.out.println(“X=”+x);
}
public static void main(String[] args)
{
Static_Example obj1=new Static_Example ();
obj1.show();
}
}
S R I Dept. of CSE
45
B.Tech Java
Static Block
A static block is a block of statements declared as ‘ static’ .
Static
{
Statements;
}
JVM executes a static block on a highest priority basis. This means JVM first goes to static block even
before it looks for the main() method in the program .
Example:Class Static_block
{
Static
{
System.out.println(“ Static block”);
}
public static void main(String[] args)
{
System.out.println(“ Main method block”);
}}
A java program without having the main method
Class Static_block
{
Static
{
System.out.println(“ Static block”);
System.out.exit(0);
}
}
Example :-
class Static_methods
{
int x=0;
static int y;
Static_methods()
{
x++;
y++;
System.out.println("x="+x+"y="+y); }
void show()
{
System.out.println("x="+x+"y="+y);
public static void main(String[] args)
{
Static_methods obj1=new Static_methods();
Static_methods obj2=new Static_methods();
obj1.show();
obj2.show(); } }
S R I Dept. of CSE
}
46
B.Tech Java
Handling Strings
A String is a series of characters treated as a single unit. A string may include letters, digits and other
various special characters like +,-,@, # etc.
A white space has no meaning in a java source code, but if included in a String, it is also taken as a
character.
String is the only object in Java which can be created with out the new keyword and incase it is
done so, it is treated as a primitive data type, however when we create String with the new keyword,
then it becomes a proper object.
Hence the different ways of creating a String are:
String s = “Hello”;
String s1 = new String (“Hello”);,
// in which case it is taken as a primitive and stored in the stack,
// in which case it is taken as a Object properly initialized with
The new keyword and stored in the Heap
The 4 Important Constructors of the String class are:-
String ( String s )
String ( )
String ( char c[] )
String (char c[], int startindex ,
int number of chars)
creates an object of the character item passed in the
parameters
creates an instance of String with no characters in it.
creates an object of the char array passed into it
This creates an object of the c array starting from the
position in the 2nd parameter till the number of
characters as specified in the 3rd parameter.
The String objects are immutable - their character contents cannot be changed after
they are created.
A String reference cannot be used to modify a String object to delete or modify a String object from
the memory as in other programming languages such as C or C++.
S R I Dept. of CSE
47
B.Tech Java
Example :class String_example
{
public static void main(String[] args)
{
String s = new String();
String s1 = new String("Hello friends");
char c [] = {'h','e','l','l','o'}; String s2 = new String (c);
String s3 = new String(c,0,4);
String name=" hai friends";
System.out.println(s);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s3);
System.out.println(name);
}}
Out put:-
Example 2:class String_example
{
public static void main(String[] args)
{
String name1=" hai friends ";
String name2=" welcome to MCA ";
String name3=name1+name2;
System.out.println(name1);
System.out.println(name2);
System.out.println(name3);
}}
S R I Dept. of CSE
48
B.Tech Java
String Methods
int length ()
Example
String s = new String("Hello");
int a = s.length();
This returns the number of
characters that it contains
char c = s.charAt(1);
To extract a single character at the
specified index.
char charAt (int index)
boolean equals( )
Description
String s = new String("Hello");
String s1 = new String("Hello");
boolean b = s.equals(s1);
Actual contents of the String,
which included the case
sensitiveness also.
boolean equalsIgnoreCase( )
boolean b = s.equalsIgnoreCase(s1);
Checks without the case
sensitiveness.
boolean startsWith (String s)
boolean c = s1.startsWith("H");
Determines if the String starts with
the String specified in the
parameter.
boolean startsWith (String s ,
int index)
boolean d = s.startsWith("s",2);
This allows you to specify a
starting point.
int indexOf (int c or String s)
String s = new String ("Hello lilly");
Checks for the first occurrence of
the character or the string.
int a = s.indexOf('l');
int lastIndexOf(int c or String s)
int b = s.lastIndexOf('l');
This enables u to start searching
from the specified position.
String substring(int startindex)
String s1 = s.substring(5);
Copies all the characters till the
end from the start position in this
string to another string.
String substring (int start, int end)
String s2 = s.substring(5,9);
Copies the characters form the
start till the end into another
string.
String s = new String ("Hello");
String s1 = s.replace('l','m');
Replaces the original character
with the replacement character in
the whole string and returns a
new String.
String toUpperCase ()
String s1 = new String ("Hello lilly");
String s2 = s1.toUpperCase();
Converts all the characters to
Upper Case.
String toLowerCase()
String s3 = s1.toUpperCase();
Converts all the characters to
Lower Case.
static String valueOf (any
datatype)
String s3 = String.valueOf(10);
Returns the String object of any
primitive data type.
The trim() method is used to
remove spaces in a String from
both of its ends.
String replace (char original,
char replacement)
String trim ()
S R I Dept. of CSE
String s1="
s1=s1.trim();
Welcome to India";
49
B.Tech Java
StringBuffer Class : StringBuffer is a class which is the mutable version for string concatenation. All the
methods of the String class return a new string object, as once a string object is created,
it cannot be changed.
However most of the methods of the StringBuffer class return the same object and changes are
made in the same memory location.
StringBuffer ()
Creates space for 16 characters.
StringBuffer (int size)
Creates a StringBuffer with the size specified in the
parameter.
StringBuffer (String s)
Creates a StringBuffer with the string specified and additional
16 Character spaces.
Example :import java.lang.String;
class StringBuffer_example
{
public static void main(String[] args)
{
String name1=" hai friends ";
StringBuffer sb1=new StringBuffer("hai Lilly");
StringBuffer sb2=new StringBuffer(name1);
System.out.println(sb1);
System.out.println(sb2);
}
}
Output:-
S R I Dept. of CSE
50
B.Tech Java
String Methods
Example
int length ( )
StringBuffer s1 = new StringBuffer("Hello");
s1.length( );
This returns the current length of
the StringBuffer.
s1.capacity( );
This returns the total capacity of
the StringBuffer.
StringBuffer s1 = new StringBuffer("Hello");
Adds new string at the end of the
String Buffer.
int capacity ( )
StringBuffer append (String s)
s1 = s1.append("Techno guys");
StringBuffer reverse ( )
StringBuffer insert (int position,
String s)
S1.reverse( );
StringBuffer s1 = new StringBuffer("Hello");
Description
Reverses the contents of the
String.
Inserts at the specified int position.
s1 = s1.insert(5," guys from");
StringBuffer delete ( int start ,
int end )
StringBuffer deleteCharAt
( int position)
StringBuffer replace( int start,
int end, String s)
Deletes a range of characters
s1.delete(1,3);
s1.deleteCharAt(1);
StringBuffer s2 = new StringBuffer("lilly");
s2.replace(1,4,"Hello");
String substring (int start)
StringBuffer s2 = new StringBuffer("lilly");
String s = s2.substring(5,9);
Deletes the character at the
specified position.
Replaces the set of characters
specified between start and end
with the String s.
This returns the substring from the
StringBuffer object.
Note: A StringBuffer class returns an StringBuffer object only. If we want to convert that object to as String,
we are using a method toString.
Example :StringBuffer sb=new StringBuffer(“life is Beutiful”);
String name= sb.toString( );
S R I Dept. of CSE
51
B.Tech Java
Q) a java program for String Palindrom.
import java.lang.String;
import java.io.*;
class String_palindrome
{
public static void main(String[] args) throws IOException
{
String name;
InputStreamReader inStream = new InputStreamReader( System.in ) ;
BufferedReader br = new BufferedReader( inStream);
System.out.println("Enter a name.....");
name=br.readLine();
String temp=name;
StringBuffer sb=new StringBuffer(name);
sb.reverse();
name=sb.toString();
// converting the SB obj to String
if(temp.equals(name))
System.out.println("Given String is Palindrome");
else
System.out.println("Given String is Not--Palindrome");
}
}
String Methods Examples
1)
class String2
{
public static void main(String[] args)
{
String s = new String("Hello"); String s1 = new String("Hello");
int a = s.length();
char c = s.charAt(1);
boolean b = s.equals(s1);
System.out.println("The number of characters in s is = "+a);
System.out.println("The character at position 1 in s is = "+c);
System.out.println("The contents of S and S1 are equal = "+b);
}
}
2)
class String5
{
public static void main(String[] args)
{
String s = new String ("Hello lilly");
int a = s.indexOf('l');
System.out.println("The first occurence of l is = "+a);
int b = s.lastIndexOf('l');
System.out.println("The last occurence of l is = "+b);
int c = s.indexOf('l',4);
System.out.println("The first occurence of l from position
4 is = "+c);
String s1 = s.substring(5);
System.out.println("The substring from position 5 is = "+s1);
String s2 = s.substring(5,9);
System.out.println("The substring from position 5 till 9 is =
"+s2);
}
}
S R I Dept. of CSE
52
B.Tech Java
Inheritance
Inheritance is one of the measure principles of object-oriented programming because it allows the creation
of hierarchical classifications. Using inheritance, you can create general class that defines traits common
to a set of related items.
Def: Deriving a new class form already existing class is called as inheritance. The derived class contains or
acquires all the features of existing class.
In the terminology of Java, a class that is inherited is called a super class. The class that does the
inheriting is called a subclass.
By using the key word extends we can derive new class from already existing class.
Example :class Base
{
void show()
{
System.out.println(“I am Base”);
}
}
class Child extends Base
{
void display()
{
System.out.println(“I am child”);
}
}
class BaseChild
{
public static void main(String args[])
{
Base b=new Base();
b.show();
b.display();
}}
Output:-
S R I Dept. of CSE
53
B.Tech Java
Access Modifiers
There are 4 types of access control modifiers which can be used to control the visibility of the
methods and class variables.
a) Public
b) Private
c) Default
(when we do not write any modifier also called as friendly)
d) Protected
Public Access Modifier
When a member of a class is having a public access modifier then that member can be accessed by any
other code in your program.
Remember our original program whether we had used public access modifier in our main (). This is
done so to enable the code outside the program – that is the Java run-time system to call it.
Private Access Modifier
There are many situations when we want some data members or methods which access those data
members to be accessed by that class and not to be accessed by any other class either by way of
inheritance or by way of creation of objects.
The variables / methods prefixed with the private access modifier can be used only within that
particular class. Other classes, which extend this class, also cannot access these variables. This
keyword provides the maximum security.
Example :class Test
{
public static void main (String arg[])
{
int i = 10
private int j = 10
}
}
class Test1 extends Test
{
public static void main (String arg [])
{
System.out.println (j); // it is not possible to access j since it is private.
}
}
Protected Access Modifier
If a variable or a method is prefixed with this modifier then it will be accessible to all classes in the same
package as well as in another class in another package provided the following two conditions are
met:S R I Dept. of CSE
54
B.Tech Java
a) The class in the other package extends the original class
b) An instance of sub class is created.
Method Overriding
In a class hierarchy, when a method in a subclass / child class has the same name and same signature as
a method in its super class / base class, then the method in the subclass is said to override the method in
the super class.
Consider the following code for Method Overriding situation.
class One
{
void show()
{
int i = 10;
int j = 20;
System.out.println(" The value of i and j are " + i+""+j);
}
}
class Two extends One
{
void show()
{
int a = 50;
int b = 60;
System.out.println(" The value of a and b are " + a+""+b);
}
}
class Test
{
public static void main(String arg[])
{
Two t = new Two();
t.show();
}
}
In the above example the sub class Two class method show() will be overrides the super class method
show().Just observe the out put we get sub class show() method code.
S R I Dept. of CSE
55
B.Tech Java
Super Keyword
In java there is a keyword named ‘super’ which is used in inheritance. super keyword is used for the following
purposes.
1. To access the private members of base class in child class by calling the constructor of base class in child
class. But the constructor calling statement should be the first statement in the child constructor
definition.
2. To access the members of base class in the child class having same name.
Super can be used to refer to super class variables as
Super. Variable
Super can be used to refer to super class method as
Super. Method ( )
Super can be used to refer to super class constructor as
Super (values)
Example :class One
{
void show()
{
int i = 10;
int j = 20;
System.out.println(" The value SUPER CLASSof i and j are " + i+""+j);
}
}
class Two extends One
{
void show()
{
int a = 50;
int b = 60;
System.out.println(" The value SUB CLASS of a and b are " + a+""+b);
Super. show( ); // calling the super class show( ) method.
}
}
class Test
{
public static void main(String arg[])
{
Two t = new Two();
t.show();
}}
S R I Dept. of CSE
56
B.Tech Java
Calling the super class constructor by using the super key word.
class A
{
int i, j;
A(int a, int b)
// class A constructor
{
i = a;
j = b;
}
// display i and j
void show()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
// class B constructor
// calling the Class A constructor by using super( )
// display k – this overrides show() in A
void show()
{
Super.show( );
// calling the Class A show( ) method
by using super
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B obj1 = new B(1, 2, 3);
Obj1.show();
// this calls show() in B
}}
Out put:-
S R I Dept. of CSE
57
B.Tech Java
final keyword
final is one of the keyword used in java program for following purposes
1. To declare the constant variables in java.
e.g. final float PI=3.14F;
2. To prevent a method from overriding, e .g if one of the methods is defined in the base class as a final then
that method can’t be override in the child class.
3. To prevent the class from inheritance. If one of the class is declared as final then any other classes can’t
inherit to the final classes.
Note: When we declared a class as a final class a sub class to that class cannot be created.
Example:final class Area
{
final float PI=3.14F;
final float calArea(float r)
{
return PI*r*r;
}
void display()
{
System.out.println("Area of circle="+calArea(5.6F));
}
}
class FinalDemo extends Area
{
public static void main(String str[])
{
Area obj=new Area();
obj.display();
}
}
In the above program PI variable declared as a final(constant) e.g the value of the PI variable cannot be
changed. Area class is also declared as a final so no any other classes can inherit the Area class. CalArea()
method is declared as a final means the calArea cannot be overridden in the child class.
Dynamic method dispatch
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run
time, rather than compile time. Dynamic method dispatch is important because this is how Java
implements run-time polymorphism.
The polymorphism exhibited at run time is called Dynamic Polymorphism. This means when a method is
called, the method call is bound to the method body at the time of running the program dynamically.
S R I Dept. of CSE
58
B.Tech Java
In this case java compiler does not know which method is called at the time of compilation. Only JVM
knows at run time which method is to be executed. So it is also called as ‘Run time polymorphism’ or
’Dynamic polymorphism’.
a super class reference variable can refer to a subclass object. Java uses this fact to resolve calls to
overridden methods at run time.
Here is how. When an overridden method is called through a super class reference, Java determines which
version of that method to execute based upon the type of the object being referred to at the time the call
occurs.
Example:Following program demonstrates the use of Dynamic method dispatch.
class Base
{
void display()
{
System.out.println(“Hello from base class”);
}
}
class Child extends Base
{
void display()
{
System.out.println(“Hello from child class”);
}
}
class DynamicDemo
{
public static void main(String args[])
{
Base b=new Base();
b.display();
b=new Child();
b.display();
}
}
Here in above program base class object b pints to the base class first time it will call the display method
of base class. When base class object points to the child class then it will calls the method of child class.
S R I Dept. of CSE
59
B.Tech Java
Abstract Method
An abstract method does not contain any body.
It contains only the method header. So we can say it is an incomplete method.
Abstract class
An abstract class is a class that generally contains some abstract methods.
Any class that contains one or more abstract methods must also be declared abstract. To declare a class
abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class
declaration.
Both the abstract class and the abstract methods should be declared by using the key word ‘abstract’.
To declare an abstract method, use this general form:
abstract type name(parameter-list);
Following program demonstrates the use of abstract classes
abstract class Animal
{
abstract void travel();
void show()
{
System.out.println(“I am abstract”);
}}
class Bird extends Animal
{
void travel()
{
System.out.println(“I am bird”);
}
}
class Fish extends Animal
{
void travel()
{
System.out.println(“I am Fish”);
}}
class AbstractDemo
{
public static void main(String args[])
{
Bird b=new Bird();
b.travel();
b.show();
Animal obj=new Fish();
obj.travel();
obj.show();
}}
S R I Dept. of CSE
60
B.Tech Java
In the above program Animal class is declared as abstract. In Animal class travel method is declared as a
abstract. Fish class and Bird class inheriting the Animal class so Fish and Bird class overrides the travel
method of Animal class.
For Example, we have a class called Figure which has a method called area () which does nothing,
but lets the subclasses like Circle, Triangle, Square to override it and give specific implementation
to the same. In this case you should call the area () as abstract.
The points to be remember here are:
a) Any class, which has one or more abstract method, should be declared as abstract. To declare a class as
abstract, simply use the abstract keyword in front of the class.
b) There can be no objects of the abstract class. That is an abstract class cannot be directly instantiated with
the new keyword. This is so because the class is not complete.
c) Any subclass of an abstract class must override all the abstract methods, or the subclass must also be
declared as abstract. That means any subclass must override all of the abstract methods.
d) An abstract class can have a non-abstract method also.
e) An abstract class can have member variables also, which can be used by the subclass after it overrides
the abstract methods.
f) An abstract class need not have any abstract methods, but incase a class has an abstract method, it
should mandatorily be declared as abstract class.
Abstract class A
{
abstract void area(int r);
abstract void show();
}
class B extends A
{
void area(int r)
{
System.out.println(3.147*r*r);
}
}
class Abstract_ex
{
public static void main(String[] args)
{
B obj1=new B();
obj1.area(5);
}
}
S R I Dept. of CSE
61
B.Tech Java
This program gives an error because in abstract class we declared two methods but in sub class of
B we write definition for only one method ,so its give an error.
To avoid this we must define or override each method in abstract class ( show() ) or super class.
Interface
We have discussed about the concept of inheritance and have understood that java has
simple inheritance only.
Java does not support Multiple Inheritance but java
multiple Inheritances by using a new notation called interface.
achieves
the
technique
of
By using interface we can define fully abstract class. That is, using interface, you can specify
what a class must do, but not how it does it.
Interfaces are syntactically similar to classes, but they lack instance variables, and their methods
are declared without any body.
Once it is defined, any number of classes can implement an interface .Also, one class can
implement any number of interfaces.
To implement an interface, a class must create the complete set of methods defined by the
interface.
By using the interface keyword and a class can implement the interface by using implements
keyword.
Def: In short “interface is a class like structure which contains only final variables and abstract
methods though which java achieves the concept of multiple inheritances”.
Following is the general form of interface.
access interface identifier
{
return-type method-name1 (parameter-list );
return-type method-name2 (parameter-list );
type final-varname1 =value;
type final-varname2 =value;
.
return-type method-nameN (parameter-list );
type final-varnameN =value;
}
S R I Dept. of CSE
62
B.Tech Java
Following program demonstrates the use of interface in java.
interface Area
{
float PI=3.14F;
float Area(float x, float y);
}
class Circle implements Area
{
public float Area(float x,float y)
{
return PI*x*x;
}
}
class Rectangle implements Area
{
public float Area(float x, float y)
{
return x*y;
}
}
class InterfaceDemo
{
public static void main(String args[])
{
Circle c=new Circle();
Rectangle r=new Rectangle ();
float a1,a2;
a1=c. Area(3.4F,0);
a2=r. Area(4.5F,6.7F);
System.out.println(“Area of circle=”+a1);
System.out.println(“Area of Rectangle=”+a2);
}}
Differences between Abstract class and Interfaces
(1)
(2)
(3)
(4)
(5)
(6)
Abstract Class
An abstract class is written when there are some
common features shred by all the objects.
When an abstract class is written, it is the duty of
the programmer to provide sub classes to it.
An abstract class contains some abstract methods
and also some ordinary (or) concrete methods.
An abstract class can contain instance variables
also.
All the abstract methods of the abstract class
should be implemented in its sub classes.
Abstract class is declared by using the keyword
abstract.
S R I Dept. of CSE
Interface
An interface is written when all the features are
implemented differently in different objects.
An interface is written when the programmer wants
to leave the implantation to the third part vendors.
An interface contains only abstract methods.
An interface can not contain instance variables It
contains only Constants.
All the (abstract) methods of the interface should be
implemented in its implementation classes.
Interface is declared using the keyword interface.
63
B.Tech Java
Multiple Inheritance using Interfaces : We know that in multiple inheritance , sub classes are derived from multiple super classes. If two super
classes have same names for their members (variables and methods ) then which member is inherited in to
sub class is the main confusion in multiple inheritance.
This is the reason , java does not support the concept of multiple inheritance.
This confusion is reduced by using multiple interfaces to achieve multiple inheritance .
Example :interface Father
{
float ht=6.2f;
void height( );
}
interface Mother
{
float ht=6.2f;
void height( );
}
Class Child implements Father, Mother
{
Public void height( )
{
Float ht=(Father.ht+Mother.ht);
System.out.println(“Child height=”+ht);
}
}
Class multi
{
Public static void main(String args[])
{
Child obj=new child( );
Obj.height( );
}
}
S R I Dept. of CSE
64
B.Tech Java
Concept of Packages
Def:- A package represents a directory that contain related group of classes and interfaces .In general a package is
a collection of classes.
One can define classes inside a package that is not accessible to others outside the package. Essentially a
package is a named collection of classes.
The syntax for the package statement is:
package <package_name>;
Example :
package abc ;
// abc is the name of the package
IMP: If you want the classes in a package to be accessible outside the package, you must declare the
class using the public keyword. The class definitions
that aren’t preceded by the public keyword are only
accessible from methods in classes that belong to the same package.
The package mechanism is for two main purposes:
a) Reduce the problems with name conflicts.
b) Control the visibility of classes, interfaces and the methods and data defined within them.
One can also have a hierarchy of packages. To do so, simply separate each package name from
the one above it by the use of the period. For Example:
package abc.xyz.nmq;
Java uses file systems directories to store packages. For example, a class file for the above class you declare
will be a part of the abc package and in a directory called as abc. Remember java is case-sensitive.
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 Java Soft people only once, and millions of programmers
all over the world daily by using them in various programs.
Different types of Packages :They are two different types of packages in Java. They are
Built – in packages .
User-Defined packages.
S R I Dept. of CSE
65
B.Tech Java
Built-in packages : These are the packages which are already available in java language.
These packages provide all most all necessary classes.
The Important java packages are:
a) java.applet
-
Classes for implementing Graphics.
b) java.awt
-
Classes for text, windows and GUIs.
c) java.io
-
Classes for all kinds of input and output
d) java.net
-
Classes for networking.
e) java.Math
-
Classes for calculations.
User Defined packages : just like the Built in packages shown earlier, the users of the java language can also create their own
packages . They are called as User Defined packages.
Example :-
package pack;
public class Addition
{
private int x,y;
public Addition(int a,int b)
{
x=a;
y=b;
}
public void show()
{
System.out.println("The class method from a package......");
System.out.println("Sum="+(x+y));
}
}
S R I Dept. of CSE
66
B.Tech Java
See the output to understand how to compile a java program that contains a pakage . The –d option
tells the java compiler to create a separate sub directory and place the .class file there. The dot (.)
after –d indicates that the package should be created in the current directory.
Setting the class path : The classpath is an environment variable that the java compiler where to look for class files to import.
To view the current setting classpath we use a DOS command c:\> echo %classpath%.
By using the set classpath command we can set the set class path.
Example :C:>set classpath=c:\java\pack;.;
Importing a package : By using the import key word we can importing user defined packages and as well as Built in packages.
By creating the object to a class which are in available in package.
Example :-
import pack.*;
// importing the pack package.
class Exam_package
{
public static void main(String[] args)
{
pack.Addition obj= new pack.Addition(5,6);
// creating the Addition class obj
obj.show();
}
}
S R I Dept. of CSE
67
B.Tech Java
Adding a new class to package :package pack;
public class Subtraction
{
private int x,y;
public Subtraction (int a,int b)
{
x=a;
y=b;
}
public void show()
{
System.out.println("The class method from a package......");
System.out.println("Sum="+(x+y));
}
}
Hiding a class : when we import a package using asterisk(*) all public classes .However we may prefer to not
import certain classes. That is , we may like to hide classes from accessing from outside of the
package. Such classes should be declared “ not public “.
Example :package pack1;
public class A
{
Void show()
{ System.out.println(“ A class “);
}
}
Class B
{
Void display()
{ System.out.println(“ A class “);
}
}
in the above example class B not declared as public so it is hidden from out side of the package.
S R I Dept. of CSE
68
B.Tech Java
Creating sub package : we can create a sub package wit in another package.
Example :package pack1.pack2;
class A
{
Void show()
{
System.out.println(“ sub package A class “);
}
}
In the above example we create a sub package pack2 in main package pack1.
S R I Dept. of CSE
69
B.Tech Java
“Friendly”
•
•
•
•
Default access, has no keyword
Public to other members of the same package, private to anyone outside the package.
Easy interaction for related classes (that you place in the same package)
Also referred to as “package access”
Class Access
• Classes as a whole can be public or “friendly”
• Only one public class per file, usable outside the library
• All other classes “friendly,” only usable within the library
S R I Dept. of CSE
70
B.Tech Java
Exception Handling
Exception
An exception is a condition that is caused by run time error in the program when the java interpreter
encounters an error such as dividing by zero; it creates an exception object and throws it. In short
“Exceptions are java’s predefined objects which are instantiated by java runtime System whenever
error occurs at runtime.”.
Need of Exception Handling.
Before you learn how to handle exceptions in your program, it is useful to see what happens when you
don ’t handle them. This small program includes an expression that intentionally causes a divide-by-zero
error.
class MyException
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object
and then throws this exception.
This causes the execution of MyException to stop, because once an exception has been thrown, it must
be caught by an exception handler and dealt with immediately.
In this example, we haven ’t supplied any exception handlers of our own , so the exception is caught by
the default handler provided by the Java run-time system.
Any exception that is not caught by your program will ultimately be processed by the default handler. The
default handler displays a string describing the exception, prints a stack trace from the point at which the
exception occurred, and terminates the program.
If the exception object is not caught and handled properly, the interpreter will display an error message
and will terminate the program. If we want to continue the program with the execution of the remaining
code then we should try to catch the exception object thrown by the error condition and display an
appropriate message for taking corrective actions. This task is known as “Exception Handling”.
S R I Dept. of CSE
71
B.Tech Java
The purpose of exception handling mechanism is to provide means to detect and report an ‘exceptional
circumstance or exceptional rising situations ’ so that appropriate action can be taken.
To handle the exceptions in java program perform the following task.
1.
2.
3.
4.
Find the problem (Hit the exception).
Inform that an error information (Throw the exception)
Receive the error information (Catch the exception)
Take corrective actions (Handle the exceptions)
try ---catch---finally construct
The try –catch—finally construct is a technique of handling exceptions in java program.
Following is the general structure of try-catch-finally construct
try
{
//block of java code which causes the exception
Exception rising statements
}
catch(ExceptionType1 obj)
{
//block of java code which is executed when
the exception is generated in try block
}
catch(ExceptionType2 obj2)
{
//block of java code which is executed when
the exception is generated in try block
}
---------------------------------------------------------------------------catch(ExceptionTypen objn)
{
//block of java code which is executed when
the exception is generated in try block
}
finally
{
//block of java code which assures for guarantee execution
}
S R I Dept. of CSE
72
B.Tech Java
try and catch blocks
All though the default exception handler provided by the Java runtime system is useful for
debugging, you will usually want to handle an exception yourself. Doing so will be advantageous in
two ways:1. It allows one to fix the error and allows program to continue.
2. It prevents the program from terminating automatically. Most users would be confused if the
program stopped running and printed a stack trace whenever an error occurred!. They
need to be told in a softer manner and in plain words what caused the above abnormal
condition.
Example :class Exception_1
{
public static void main(String[] args)
{
try
{
int a = 10 / 0;
}
catch (ArithmeticException e)
{
System.out.println("Exception caught");
System.out.println("----------------------------------------------");
e.printStackTrace();
System.out.println("---------------------------------");
System.out.println(e);
System.out.println("---------------------------------");
System.out.println(e);//.getMessage());
}
}
}
Output:-
If in the above user will try to find out 10 / 0 ,when program execution java runtime system throws an
Exception named ArithmeticException.
S R I Dept. of CSE
73
B.Tech Java
Built in Exceptions :Exception Name
ArithmeticException
ArrayIndexOutOfBoundsException
FileNotFoundException
IOException
NullPointerException
OutOfMemoryException
StringIndexOutOfBoundsException
NumberFormatException
SQLException
Description
Throws when user or programmer is trying to divide
the no by zero in java program.
Throws when we are exceeding the array indexes
Throws when a program tries to attempt to access a
non-existent file.
Caused by general I/O failures, such as inability to read
from file or writ e to file.
Caused when we are accessing methods or members
through a null object. (Non-initialized)
Causes when there is no enough memory to allocate a
new object.
Throws when we are accessing a non-existent character
from a string
Throws when we are trying to convert an invalid string
to the no in java program.
Throws while communicating with database
management systems
Important points when we writing the try and catch blocks
1. An exception can be handled using try, catch and finally blocks.
2. It is possible to handled multiple exceptions using multiple catch blocks.
3. Even though there is possibility for several exceptions in try block, at a time only one exception will be
raised or handilied.
4. A single try block can be followed by several catch blocks.
5. We can not write a catch without a try block, but we can write try with out ant catch block.
6. It is not possible to insert some or any statements between try and catch.
7. It is possible to write a try block within another try. They are called nested try block.
throws Clause
Even if the programmer is not handling runtime exceptions, the java compiler will not give any error
related to run time exceptions.
But the rule is that the programmer should handle checked exceptions.
checked exceptions
The exceptions that are checked at compilation-time by the java compiler are called
“Checked Exceptions”.
The exceptions that are checked by the JVM are called “Un Checked Exceptions “.
In case the programmer does not want to handle the checked exception, he should throw them out using
throws clause. other wise there will be an error flagged by java compiler.
S R I Dept. of CSE
74
B.Tech Java
Following program demonstrates the use of multiple catch statements in the java program.
import java.io.*;
class MultipleCatchDemo
{
public static void main(String arg[])throws IOException
{
int a,b,c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int array[]={10,20,30};
try
{
System.out.println("Enter the values for a , b");
b=Integer.parseInt(br.readLine());
c=Integer.parseInt(br.readLine());
a=b/c;
System.out.println( array[5]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception caught");
System.out.println("----------------------------------------------");
System.out.println(e);
System.out.println("---------------------------------");
System.out.println("In sufficient Elemnts in array ");
System.out.println("---------------------------------");
}
catch(ArithmeticException ae)
{
System.out.println("Exception caught");
System.out.println("----------------------------------------------");
System.out.println(ae);
System.out.println("---------------------------------");
System.out.println("Second value b should not be zero");
System.out.println("---------------------------------");
}
finally
{
System.out.println("-=-----End of the Exception Handling-------");
}}}
S R I Dept. of CSE
75
B.Tech Java
‘throw’ keyword
In all above programs exceptions are thrown automatically by java runtime system when a runtime error
occurs. Java also allows programmer to throw exceptions manually on user defined situations. This task
is done by the throw keyword.
Following is the syntax of throw diagram.
throw obj;
Here obj is object of any subclass of java.lang.Throwable class.
e.g.
throw new Exception(“Sal out of Range”);
import java.io.*;
class ThrowDemo
{
public static void main(String args[])throws IOException
{
int sal=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println(" Enter the amount of sal :");
sal=Integer.parseInt(br.readLine());
if(sal<5000)
{
Exception e=new Exception("Salary out of range or less than 5000");
throw e;
// throwing the a exception
}
}
catch(Exception se)
{
System.out.println(se);
}
finally
{
System.out.println("Salary="+sal);
}}}
S R I Dept. of CSE
76
B.Tech Java
User Defined Exceptions
Although Java ’s built-in exceptions handle most common errors,you will probably want to create your
own exception types to handle situations specific to your applications.
This is quite easy to do:just define a subclass of Exception (which is,of course,a subclass of
Throwable).Your subclasses don ’t need to actually implement anything —it is their existence in the type
system that allows you to use them as exceptions.
Example :import java.io.*;
class UserDefinedException extends Exception
{
UserDefinedException(String str)
{
super(str);
}
public static void main(String[] args) throws IOException
{
int accno;
String name;
double balance;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n Enter the accno : ");
accno=Integer.parseInt(br.readLine());
System.out.print("\n Enter the Name : ");
name=br.readLine();
System.out.print("\n Enter the Balance Amount : ");
balance=Double.parseDouble(br.readLine());
try
{
if(balance<1000)
throw new UserDefinedException("Balance Amount is less than 1000 ");
}
catch (UserDefinedException e)
{
System.out.println("\nException caught");
System.out.println("----------------------------------------------");
System.out.println(e);
System.out.println("\n Please enter amount greater than 1000");
System.out.println("----------------------------------------------");
}
finally
{
System.out.println("\nThe Account Details.....");
System.out.println("----------------------------------------------");
System.out.println("\n Accno :"+accno+"\t name : "+name+"\t balance ="+balance);
}}}
S R I Dept. of CSE
77
B.Tech Java
Re-throwing an Exception
When an exception occurs in try block, it is caught by a catch block. This means that the thrown
exception is available to the catch block.
Syntax :try
{
throw exception;
}
Catch(Exception obj)
{
throw exception;
}
Example :-
S R I Dept. of CSE
// re-throw the exception out
class A
{
void method()
{
try
{
int a=1/0;
System.out.println(" value of A = "+a);
}
catch (ArithmeticException e)
{
throw e;
// re- throw the exception
}}}
class re_throw_exam
{
public static void main(String[] args)
{
A obj=new A();
try
{ obj.method();
}
catch (ArithmeticException e)
{
System.out.println(e);
}
}}
78
B.Tech Java
Threads
The Java platform is designed from the ground up to support concurrent programming, with basic
concurrency support in the Java programming language and the Java class libraries. Since version 5.0, the
Java platform has also included high-level concurrency APIs.
In concurrent programming, there are two basic units of execution: processes and threads. In the Java
programming language, concurrent programming is mostly concerned with threads. However, processes
are also important.
A computer system normally has many active processes and threads. This is true even in systems that
only have a single execution core, and thus only have one thread actually executing at any given moment.
Processing time for a single core is shared among processes and threads through an OS feature called time
slicing.
It's becoming more and more common for computer systems to have multiple processors or processors
with multiple execution cores. This greatly enhances a system's capacity for concurrent execution of
processes and threads — but concurrency is possible even on simple systems, without multiple processors
or execution cores.
Processes
A process has a self-contained execution environment. A process generally has a complete, private set
of basic run-time resources; in particular, each process has its own memory space.
Processes are often seen as synonymous with programs or applications. However, what the user sees as a
single application may in fact be a set of cooperating processes. To facilitate communication between
processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes
and sockets.
Threads
Thread: can be defined as single sequential flow of control with in a program.
Threads are sometimes called lightweight processes. Both processes and threads provide an execution
environment, but creating a new thread requires fewer resources than creating a new process.
Threads exist within a process — every process has at least one.
Threads share the process's resources, including memory and open files. This makes for efficient, but
potentially problematic, communication.
S R I Dept. of CSE
79
B.Tech Java
Creating a Thread : We can create the threads by following the two ways ,they are
1. By implementing the Runnable Interface.
2. By extending the thread Class.
Creating the threads by implanting the Runnable interface
Runable Interface
The Runnable interface consist of a Single method run( ), which is executed when the thread is
activated.
When a program need to inherit from another class besides the thread Class, you need to implement
the Runnable interface.
Example :class MyThread1 implements Runnable
{
String name;
MyThread1(String str)
{
name=str;
}
public void run()
{
for(int i=0;i<=5;i++)
System.out.println(name+"
}
: "+i);
public static void main(String[] args)
{
MyThread1 obj1=new MyThread1("Thread");
Thread t1=new Thread(obj1,"ONE"); // Creating the Thread
t1.start();
}}
Out put:-
S R I Dept. of CSE
80
B.Tech Java
Creating Thread By Extends the Thread class :class MyThread1 extends Thread
{
String name;
MyThread1(String str)
{
name=str;
}
public void run()
{
for(int i=0;i<=5;i++)
System.out.println(name+"
}
: "+i);
public static void main(String[] args)
{
MyThread1 obj1=new MyThread1("Thread");
Thread t1=new Thread(obj1,"ONE");
t1.start();
}}
Single Thread : Application can perform only one task at a time.
Multithreaded :
A process having more than one thread is said to be multithreaded.
The multiple threads in the process run at the same time, perform different task and interact with each
other.
Thread Class :
Java.lang.Threadclass is used to construct and access the individual threads in
a multithreaded application.
The Thread class define several methods .
getName() –
getPriority() –
Start( )
Run( )
Sleep( )
isAlive( ) Join( )
-
S R I Dept. of CSE
obtain a thread name.
obtain thread priority.
start a thread by calling a Run( ).
Entry point for the thread.
suspend a thread for a period of time.
Determine if a thread is still running.
wait for a thread to terminate.
81
B.Tech Java
Creating the Multiple Threads :class MyThread implements Runnable
{
String name;
MyThread(String str)
{
name=str;
}
public void run()
{
for(int i=0;i<=3;i++)
{
System.out.println(name+" : "+i);
try
{ Thread.sleep(2000);
}
catch (Exception e)
{
System.out.println(e);
}
}}
public static void main(String[] args)
{
MyThread obj1=new MyThread("cut the ticket");
MyThread obj2=new MyThread("Show the seat ");
Thread t1=new Thread(obj1,"ONE");
Thread t2=new Thread(obj2,"TWO");
t1.start();
t2.start();
}
}
Out put:-
S R I Dept. of CSE
82
B.Tech Java
Thread Priorities :
Thread Priorities are used by the thread scheduler to decide when each thread should ne allowed to run.
To set a thread priority, use setPriority( ), which is a member of a thread.
final void setpriority(int level)
- here level specifies the new priority seting for the calling
thread.
The value level must be with in the range :MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
You can obtain the current priority setting by calling getpriority( ) of thread.
o final int getPriority( )
A program to find out the Current thread used by JVM .
class Current_Th
{
public static void main(String[] args)
{
System.out.println("\nLet us find Current Thread ");
System.out.println("-------------------------------");
Thread t=Thread.currentThread();
System.out.println("Current Thread= "+t);
System.out.println("Current Thread Name---= "+t.getName());
System.out.println("Current Thread PRIORITY= "+t.getPriority());
}
}
Out put:-
In a java program if we write a group of statements , then these statements are executed by JVM one by
one. This execution is called a THREAD.
The main( ) Thread will run always in a java program by Default.
S R I Dept. of CSE
83
B.Tech Java
class A extends Thread
{
public void run()
{
System.out.println("Thread A started");
for(int i=1;i<=4;i++)
System.out.println("\t From ThreadA: i= "+i);
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
System.out.println("Thread B started");
for(int j=1;j<=4;j++)
System.out.println("\t From ThreadB: j= "+j);
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
System.out.println("Thread C started");
for(int k=1;k<=4;k++)
System.out.println("\t From ThreadC: k= "+k);
System.out.println("Exit from C");
}
}
class ThreadPriority
{
public static void main(String args[])
{
A obj1=new A();
B obj2=new B();
C obj3=new C();
obj3.setPriority(Thread.MAX_PRIORITY);
obj2.setPriority(Thread.NORM_PRIORITY);
obj1.setPriority(Thread.MIN_PRIORITY);
System.out.println("Started Thread A");
obj1.start();
System.out.println("Started Thread B");
obj2.start();
System.out.println("Started Thread C");
obj3.start();
System.out.println("End of main thread");
}}
S R I Dept. of CSE
84
B.Tech Java
Synchronization:
Two or more threads trying to access the same method at the same point of time leads to
synchronization. If that method is declared as Synchronized , only one thread can access it at a
time. Another thread can access that method only if the first thread’s task is completed.
Synchronized statement :
Synchronized statements are similar to Synchronized method.
Synchronized statements can only be executed after a thread has acquired a lock for the object or
Class referred in the Synchronized statements.
The general form is Synchronized(object)
{
// statements to be Synchronized
}
Example program :class Reserve implements Runnable
{
int available=3;
int wanted;
Reserve(int i)
{
wanted=i;
}
public void run()
{
synchronized ( this )
{
System.out.println("Available Berths= "+available);
if(available >= wanted)
{
String name=Thread.currentThread().getName();
System.out.println(wanted+" Berths reserved for "+name);
try
{
Thread.sleep(1500);
available=available-wanted;
}
catch (InterruptedException ie){
}
}
else
System.out.println("Sorry, no Berths");
}}}
S R I Dept. of CSE
85
B.Tech Java
class synchronized_safe
{
public static void main(String[] args)
{
Reserve obj=new Reserve(1);
Thread t1=new Thread(obj);
Thread t2=new Thread(obj);
t1.setName("First person");
t2.setName("Second Person");
t1.start();
t2.start();
}
}
Inter Thread Communication:
To Avoid pooling, Java includes an elegant interposes communication mechanism.
Wait( ) - tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor & call notify( ).
notify( ) -
wake up the first thread that called wait( ) on the same Object.
notifyAll( ) – wake up all the threads that called wait( ) on the same Object.
The highest priority thread will run fast.
( Q ) What is the difference between the sleep( ) and wait( ) methods ?
Both the sleep( )and wait( ) methods are used to suspend a thread execution for a specified time.
When sleep( ) is executed inside a synchronized block, the object is still under lock.
When wait( ) method is executed , it breaks the synchronized block , so that the object lock is removed
and it is available.
Generally , sleep( ) is used for making a thread to wait for some time. But wait( ) is used in connection
with notify( ) or notifyAll( ) methods in thread communication.
T1
T2 wait till T1 comes end
Enter the Obj
( Thread Synchronization )
S R I Dept. of CSE
86
B.Tech Java
class Resource
{
synchronized public static void disp() // synchronized method
{
System.out.print("[ ");
System.out.print("HELLO-");
try
{
Thread.sleep(1000);
}
catch(Exception e){}
System.out.println("show ]");
}}
class MyThread extends Thread
{
public void run()
{
Resource.disp();
}
}
class Sync
{
public static void main(String args[])
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
MyThread t3=new MyThread();
t1.start();
t2.start();
t3.start();
}
}
Out Put:-
S R I Dept. of CSE
87
B.Tech Java
Program for producer and consumer problem. (out put will comes until we press Ctrl+ C )
class Item
{
int n;
boolean value=false;
class producer implements Runnable
{
Item q;
producer(Item obj)
{
q=obj;
synchronized int get()
{
if(!value)
try
{
System.out.println(" Got : "+n);
wait();
Thread.sleep(500);
}
catch (Exception e)
{
}
value=false;
notify();
return n;
}
synchronized void put(int n)
{
if(value)
try
{
wait();
}
catch (Exception e)
{
}
Thread t=new Thread(this,"producer");
t.start();
}
public void run()
{
int i=0;
while(true)
q.put(i++);
}
}
class consumer implements Runnable
{
Item q;
consumer(Item obj)
{
q=obj;
Thread t=new Thread(this,"Consumer");
t.start();
}
this.n=n;
value=true;
System.out.println(" Put : "+n);
public void run()
{
while(true)
q.get();
notify();
}
}
}
}
class cust_prod
{
public static void main(String as[])
{
Item q=new Item();
new producer(q);
new consumer(q);
}
}
S R I Dept. of CSE
88
B.Tech Java
Thread Group: A thread group represents several threads as a single group. The main advantage of taking several threads
as a group is that by using a single method, we will be able to control all the threads in the group.
To create a thread group, we should simply create an object to ThreadGroup.
ThreadGroup tg=new ThreadGroup( “ Group Name “ );
Example:class TGgroups
{
public static void main(String[] args)
{
Reservation res=new Reservation();
Cancellation can=new Cancellation();
ThreadGroup tg1=new ThreadGroup("First Group");
System.out.println(" \nNo of Threads active in tg
"+tg1.activeCount());
System.out.println("-------------------------------------------");
}
}
class Reservation extends Thread
{
public void run()
{
Thread t1=new Thread(tg1,res,"First Thread");
Thread t2=new Thread(tg1,res,"Second Thread");
try
{
Thread.sleep(1500);
System.out.println(" Iam in Reservation Thread");
}
catch (Exception e)
{
}
}
ThreadGroup tg2=new ThreadGroup(tg1,"Second Group");
Thread t3=new Thread(tg2,can,"First Thread");
Thread t4=new Thread(tg2,can,"Second Thread");
System.out.println("-------------------------------------");
System.out.println("\n parent of Tg1 thread--- "+tg1.getParent());
}
System.out.println(" \nparent of Tg2 thread--- "+tg2.getParent());
System.out.println("----------------------------------------");
class Cancellation extends Thread
{
public void run()
{
try
{
Thread.sleep(1000);
System.out.println(" Iam in Cancellation Thread");
}
catch (Exception e)
{
}
}
}
System.out.println(" \nThread of t1 --- "+t1.getThreadGroup());
System.out.println(" \nThread of t3 --- "+t3.getThreadGroup());
System.out.println("--------------------------------------");
t1.start();
t2.start();
t3.start();
t4.start();
S R I Dept. of CSE
89
B.Tech Java
Daemon Threads : Some times , a thread has to continuously execute without ant interruption to provide services to other
Threads . Such threads are called as Daemon Threads.
A Daemon Thread is a thread that executes continuously . Daemon threads are service providers for
other threads or Objects. It generally provides a Background processing.
To make a thread t as a Daemon Thread , we can use setDaemon( ) method.
t . setDaemon ( true );
Thread life Cycle : Starting from the birth of a thread , till its death , a thread exists in different states which are collectively
called “ Thread Life Cycle”.
A thread will born when it is created using Thread class.
From runnable state , a Thread may get into not-runnable state, When sleep( ) and wait( )
act on it.
The Thread would be in not-runnable state till the user provides the required input – output .
After coming out from not – runabble state, again the thread comes back to runnable state.
methods
Finally , a thread is terminated from memory only when it comes out of run ( ) method . When the thread
completely executes the run( ) method and naturally comes out , or when the user forces it to come out of
run( ) method.
All these state transitions of a thread , starting from its birth till its death are called “Thread Life Cycle”.
(Thread Life Cycle )
S R I Dept. of CSE
90
B.Tech Java
Thread Applications : Threads are useful where a process should run continuously, . For example , a continuously running
animation or continuously running server application needs a daemon thread which keeps it running for
ever.
Being light weight, threads use minimal system resources and hence they are highly preferred to actual
heavy weight processes.
S R I Dept. of CSE
91
B.Tech Java
AWT components : The Java programming language class library provides a user interface toolkit called the Abstract
Windowing Toolkit, or the AWT.
The AWT is both powerful and flexible. Effective graphical user interfaces are inherently challenging to
design and implement, and the sometimes complicated interactions between classes in the AWT only
make this task more complex.
Components and containers
A graphical user interface is built of graphical elements called components.
Typical components include such items as buttons, scrollbars, and text fields.
Components allow the user to interact with the program and provide the user with visual feedback about
the state of the program.
Components are found in within containers.
Containers contain and control the layout of components. Containers are themselves components, and
can thus be placed inside other containers.
Types of components
The AWT provides nine basic non-container component classes from which a user interface may be
constructed.
These nine classes are class Button, Canvas, Checkbox, Choice, Label, List, Scrollbar, TextArea, and
TextField. Figure depicts an instance of each class.
S R I Dept. of CSE
92
B.Tech Java
(AWT components )
AWT classes
Container : Which can hold other AWT components.
Window : Window is the top level container with no title and border.
Frame : Frame is the top level container with both title and border.
Panel: A panel is the simplest containers. It can add other panels and AWT components. But
must be placed on some other container.
Applet: An applet is a small java program that can be executed in an java compatible web
browser or the appletviewer.
o
Applet can be either remote or local. A remote applet is the applet that is downloaded from
remote server using the URL(Universal Resource Locator).
o
The local applet is the one which is created in the local pc.
Dialog: A Dialog is a top-level window with a title and a border that is typically used to take
some form of input from the user.
FileDilaog : The FileDialog class displays a dialog window from which the user can select a file.
ScrollPane : A container class which implements automatic horizontal and/or vertical scrolling
for a single child component.
Canvas: A Canvas component represents a blank rectangular area of the screen onto which the
application can draw or from which the application can trap input events from the user.
Source : The source is an object which generates an event.
Listener : A listener is an object that gets notified when an event occurs.
S R I Dept. of CSE
93
B.Tech Java
Event Delegation Model : When we create a component, generally the component is displayed on the screen but it is not capable of
performing any actions.
For example we created a push button , which can be displayed but cannot perform any actions, even
when someone clicks on it But user expectation will be different, A user wants the push button to perform
some action, clicking like this is called Event.
An event represents a specific action done on a component.
When an event is generated on the component , the component will not know about it because it cannot
listen to the event.
A listener is an interface which listens to an event coming from a component. A listener will have some
abstract methods which need to be implemented by the programmer.
Method1()
Component
listener
Method2()
Event
Component part
Method3()
Action part
( Event Delegation Model )
Example program Creating a frame without having event handling .
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
public static void main(String[] args)
{
MyFrame f=new MyFrame();
f.setTitle("s r i n a t h");
public void paint(Graphics g)
{
f.setSize(500,330);
f.setVisible(true);
setBackground(Color.white);
g.drawString(" Hello , How are U?",100,100);
}
}
}
S R I Dept. of CSE
94
B.Tech Java
Listeners and Listener Methods :Component
Listener
Listener Methods
Button
ActionListener
public void actionPerformed ( ActionEvent e )
CheckBox
ItemListener
public void itemStateChanged ( ItemEvent e )
CheckBoxGroup
ItemListener
public void itemStateChanged ( ItemEvent e )
TextField
ActionListener
FocusListener
public void actionPerformed ( ActionEvent e )
public void focusGained (FocusEvent e)
public void focusLost ( FocusEvent e)
TextArea
ActionListener
FocusListener
public void actionPerformed ( ActionEvent e )
public void focusGained (FocusEvent e)
public void focusLost ( FocusEvent e)
Choice
ActionListener
ItemListener
public void actionPerformed ( ActionEvent e )
public void itemStateChanged ( ItemEvent e )
List
ActionListener
ItemListener
public void actionPerformed ( ActionEvent e )
public void itemStateChanged ( ItemEvent e )
Frame
WindowListener
public void windowActivated ( WindowEvent e)
public void windowDeactivated ( WindowEvent e)
public void windowClosed ( WindowEvent e)
public void windowClosing ( WindowEvent e)
public void windowIconified ( WindowEvent e)
public void windowDeiconified ( WindowEvent e)
public void windowOpened ( WindowEvent e)
KeyBoard
KeyListener
public void keyPressed ( KeyEvent e)
public void keyReleased ( KeyEvent e)
public void keyTyped ( KeyEvent e)
S R I Dept. of CSE
95
B.Tech Java
MouseListener
MouseMotionListener
Mouse
public void mouseClicked ( MouseEvent e)
public void mouseEntered ( MouseEvent e)
public void mouseExited ( MouseEvent e)
public void mousePressed ( MouseEvent e)
public void mouseReleased ( MouseEvent e)
public void mouseDragged ( MouseEvent e)
public void mouseMoved ( MouseEvent e)
Example program Creating a frame with event handling .
class MyFrame_event extends Frame implements WindowListener
{
MyFrame_event()
{
addWindowListener(this); // adding the windowListener to current Object
}
public void paint(Graphics g)
{
setBackground(Color.white);
g.drawString(" Hello , How are U?",100,100);
}
public void windowActivated ( WindowEvent e) { }
public void windowDeactivated ( WindowEvent e){ }
public void windowClosed ( WindowEvent e){ }
public void windowClosing ( WindowEvent e)
{
System.exit(0);
}
// window closing event
public void windowIconified ( WindowEvent e){ }
public void windowDeiconified ( WindowEvent e){ }
public void windowOpened ( WindowEvent e){ }
public static void main(String[] args)
{
MyFrame_event f=new MyFrame_event( );
f.setTitle("s r i n a t h");
f.setSize(500,330);
f.setVisible(true);
}}
S R I Dept. of CSE
96
B.Tech Java
Adapter class:
Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in
certain situations.
An adapter class provides an empty implementation of all methods in an event listener interface.
Adapter classes are useful when you want to receive and process only some of the events that are handled
by a particular event listener interface.
You can define a new class to act as an event listener by extending one of the adapter classes and
implementing only those events in which you are interested.
Example :import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements WindowListener
{
public void paint(Graphics g)
{
setBackground(Color.white);
g.drawString(" Hello , How are U?",100,100);
}
public static void main(String[] args)
{
MyFrame f=new MyFrame();
f.setTitle("s r i n a t h");
f.setSize(500,330);
f.setVisible(true);
f.addWindowListener(new MyClass());
}
}
Class MyClass extends WindowAdapter// Adapter class for window Listener
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
S R I Dept. of CSE
97
B.Tech Java
Anonymous inner class :
Anonymous inner class is an inner class whose name is not mentioned, and for which only one object
is created.
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements WindowListener
{
public void paint(Graphics g)
{
setBackground(Color.white);
g.drawString(" Hello , How are U?",100,100);
}
public static void main(String[] args)
{
MyFrame f=new MyFrame();
f.setTitle("S R I ");
f.setSize(500,330);
f.setVisible(true);
// anonymous inner class
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}}
So far we discussed the following three ways to close the frame
.
I.
By implementing all the methods of WindowListener interface
II.
III.
By using WindowAdapter class and by implementing only the required method.
By directly copying the code of an anonymous inner class.
S R I Dept. of CSE
98
B.Tech Java
Push Button
The Button class is use full to create Push Buttons. A push button is use full to perform a particular
action.
To create a push Button with label, we can create an object to Button class.
Constructs a button with an empty string for its label.
Button()
Constructs a button with the specified label.
Button(String label)
Example :-
Button b1=new Button("Yellow");
Button b2=new Button("Red");
Button b3=new Button("Green");
When a button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling
processEvent on the button. The button's processEvent method receives all events for the button; it passes
an action event along by calling its own processActionEvent method.
If an application wants to perform some action based on a button being pressed and released, it should
implement ActionListener and register the new listener to receive events from this button, by calling the
button's addActionListener method.
Some important methods on Buttons
String getLabel()
Gets the label of this button.
String setLabel(String label)
Sets the button's label to be the specified string.
String
getActionCommand()
Returns the command name of the action event fired by
this button.
void addActionListener(ActionListener l) Adds the specified action listener to receive action
events from this button.
S R I Dept. of CSE
99
B.Tech Java
Example :import java.awt.*;
import java.awt.event.*;
class MyButton extends Frame implements ActionListener
{
Button b1,b2,b3;
MyButton()
{
setLayout(new FlowLayout());
b1=new Button("Yellow");
b2=new Button("Red");
b3=new Button("Green");
add(b1);
add(b2);
add(b3);
b1.setBackground(Color.red);
b1.setForeground(Color.yellow);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Yellow"))
this.setBackground(Color.yellow);
if(str.equals("Red"))
this.setBackground(Color.red);
if(str.equals("Green"))
this.setBackground(Color.green);
}
public static void main(String[] args)
{
MyButton mb=new MyButton();
mb.setSize(400,400);
mb.setTitle(" colors Demo");
mb.setVisible(true);
}}
S R I Dept. of CSE
100
B.Tech Java
Check Box
A Check Box is a square shaped box which displays an option to the user. The user can select one or more
options from a group of check boxes.
To create a push Button with label, we can create an object to CheckBox class.
Checkbox()
Creates a check box with an empty string for its label.
Checkbox(String label)
Creates a check box with the specified label.
Creates a check box with the specified label and sets the
specified state.
Checkbox(String label, boolean state)
Example :Checkbox c1=new Checkbox("yes");
Checkbox c2=new Checkbox("No",true);
Some important methods on CheckBox
void
setLabel(String label)
Sets this check box's label to be the string argument.
void
setState(boolean state)
boolean
getState()
Determines whether this check box is in the "on" or "off" state.
String
getLabel()
Gets the label of this check box.
Object
getSelectedObjects()
Returns an array (length 1) containing the checkbox label or null if
the checkbox is not selected.
Sets the state of this check box to the specified state.
Sample Output for below CheckBox program.
S R I Dept. of CSE
101
B.Tech Java
Example :import java.awt.event.*;
import java.awt.*;
class MyCheckBox extends Frame implements ItemListener
{
String msg=" ";
Checkbox c1,c2;
MyCheckBox()
{
c1=new Checkbox("yes");
c2=new Checkbox("No",true);
setLayout(new FlowLayout());
add(c1);
add(c2);
c1.addItemListener(this);
c2.addItemListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0); }
});
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
Font f=new Font("Monotype Corsiva",Font.BOLD+Font.ITALIC,30);
g.setFont(f);
g.setColor(Color.red);
g.drawString("Current State",10,100);
g.drawString("---------------",10,110);
Font f1=new Font("Monotype Corsiva",Font.BOLD+Font.ITALIC,20);
g.setFont(f1);
g.setColor(Color.green);
msg=c1.getLabel()+"--------- "+c1.getState();
g.drawString(msg,10,120);
msg=c2.getLabel()+"-------- "+c2.getState();
g.drawString(msg,10,140);
}
public static void main(String[] args)
{
MyCheckBox mch=new MyCheckBox();
mch.setTitle(" Check Box Demo ");
mch.setSize(500,500);
mch.setVisible(true);
}}
S R I Dept. of CSE
102
B.Tech Java
CheckboxGroup ( Radio Button )
It is possible to create a set of mutually exclusive check boxes in which one and only one check box in
the group can be checked at any one time.
These check boxes are often called radio buttons, because they act like the station selector on a car
radio—only one station can be selected at any one time.
To create a set of mutually exclusive check boxes, you must first define the group to which they will
belong and then specify that group when you construct the check boxes.
Check box groups are objects of type CheckboxGroup. Only the default constructor is defined, which
creates an empty group.
You can determine which check box in a group is currently selected by callinggetSelectedCheckbox( ).
You can set a check box by calling setSelectedCheckbox( ).
These methods are as follows:
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox obj)
import java.awt.event.*;
import java.awt.*;
class MyRadio extends Frame implements ItemListener
{
String msg=" ";
CheckboxGroup cbg;
Checkbox c1,c2;
MyRadio()
{
cbg=new CheckboxGroup();
c1=new Checkbox("Male",cbg,true);
c2=new Checkbox("Female",cbg,false);
setLayout(new FlowLayout());
add(c1);
add(c2);
c1.addItemListener(this);
c2.addItemListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}});
}
S R I Dept. of CSE
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
Font f=new Font("Monotype
Corsiva",Font.BOLD+Font.ITALIC,30);
g.setFont(f);
g.setColor(Color.red);
g.drawString("Current State",10,100);
g.drawString("---------------",10,115);
Font f1=new Font("Monotype
Corsiva",Font.BOLD+Font.ITALIC,20);
g.setFont(f1);
g.setColor(Color.green);
msg=cbg.getSelectedCheckbox().getLabel()+"---"+cbg.getSelectedCheckbox().getState();
g.drawString(msg,10,130);
}
public static void main(String[] args)
{
MyRadio mch=new MyRadio();
mch.setTitle(" RadioButton Box Demo ");
mch.setSize(500,500);
mch.setVisible(true);
}}
103
B.Tech Java
Choice Controls
The Choice class is used to create a pop-up list of items from which the user may choose.
Thus, a Choice control is a form of menu. When inactive, a Choice component has only enough
space to show the currently selected item.
When the user clicks on it, the whole list of choices pops up, and a new selection can be made.
Each item in the list is a string that appears as a left-justified label in the order it is added to the
Choice object. Choice only defines the default constructor, which creates an empty list.
Creating the Choice item :-
Creates a new choice menu.
Choice()
Ex :- Choice ch=new Choice( ); // creates an emty choice list
To add a selection to the list, call addItem( ) or add( ). They have these general forms:
void addItem(String name)
void add(String name)
Here, name is the name of the item being added. Items are added to the list in the order in which calls to
add( ) or addItem( ) occur.
Some important methods on ChoiceList
void
add(String item)
Adds an item to this Choice menu.
void
addItem(String item)
Obsolete as of Java 2 platform v1.1.
String
getItem(int index)
Gets the string at the specified index in this Choice menu.
int
getItemCount()
Returns the number of items in this Choice menu.
String
getSelectedItem()
Gets a representation of the current choice as a string.
void
remove(String item)
Removes the first occurrence of item from the Choice menu.
Void
removeAll()
Removes all items from the choice menu.
Void
select(int pos)
Sets the selected item in this Choice menu to be the item at the
specified position.
S R I Dept. of CSE
104
B.Tech Java
Using Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice object,
which shows only the single selected item in the menu, a List object can be constructed to show any
number of choices in the visible window. It can also be created to allow multiple selections.
List provides these constructors:
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
The first version creates a List control that allows only one
item to be selected at any onetime.
the value of numRows specifies the number of entries in
the listthat will always be visible (others can be scrolled
into view as needed).
IfmultipleSelect is true, then the user may select two or
more items at a time. If it is false,then only one item may
be selected.
For lists that allow multiple selection, you must use either getSelectedItems( ) or getSelectedIndexes( ),
shown here, to determine the current selections:
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
S R I Dept. of CSE
105
B.Tech Java
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
Example program on Choice :import java.awt.*;
import java.awt.event.*;
// Display current selections.
public void paint(Graphics g)
{
public class ChoiceDemo extends Frame implements
ItemListener
{
Choice os, browser;
String msg = null;
msg = "Current OS: ";
msg += os.getSelectedItem();
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
ChoiceDemo()
{
setLayout(new FlowLayout());
}
public static void main(String[] args)
{
os = new Choice();
browser = new Choice();
ChoiceDemo mb=new ChoiceDemo();
// add items to os list
mb.setSize(300,180);
mb.setTitle(" Choice Demo");
mb.setVisible(true);
os.add("Windows 98");
os.add("Windows NT");
os.add("Solaris");
os.add("MacOS");
// add items to browser list
browser.add("Netscape 1.1");
browser.add("Netscape 2.x");
browser.add("Netscape 3.x");
browser.add("Netscape 4.x");
browser.add("Internet Explorer 2.0");
browser.add("Internet Explorer 3.0");
browser.add("Internet Explorer 4.0");
browser.add("Lynx 2.4");
browser.select("Netscape 4.x");
}
}
Out put :-
// add choice lists to window
add(os);
add(browser);
os.addItemListener(this);
browser.addItemListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}});
}
S R I Dept. of CSE
106
B.Tech Java
Example program on List :import java.awt.*;
import java.awt.event.*;
public class ListDemo extends Frame implements
ActionListener
{
List os, browser;
String msg = "";
ListDemo()
{
setLayout(new FlowLayout());
public void actionPerformed(ActionEvent ae)
{
repaint();
}
// Display current selections.
public void paint(Graphics g)
{
int idx[];
msg = "Current OS: ";
idx=os.getSelectedIndexes();
for(int i=0; i<idx.length; i++)
msg += os.getItem(idx[i]) + " ";
os = new List(4, true);
browser = new List(4, false);
// add items to os list
os.add("Windows 98");
os.add("Windows NT");
os.add("Solaris");
os.add("MacOS");
// add items to browser list
browser.add("Netscape 1.1");
browser.add("Netscape 2.x");
browser.add("Netscape 3.x");
browser.add("Netscape 4.x");
browser.add("Internet Explorer 2.0");
browser.add("Internet Explorer 3.0");
browser.add("Internet Explorer 4.0");
browser.add("Lynx 2.4");
browser.select(1);
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
public static void main(String[] args)
{
ListDemo mb=new ListDemo();
mb.setSize(300,180);
mb.setTitle(" Choice Demo");
mb.setVisible(true);
}
}
Out put :-
// add lists to window
add(os);
add(browser);
os.addActionListener(this);
browser.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});}
S R I Dept. of CSE
107
B.Tech Java
Using a TextField
The TextField class implements a single-line text-entry area, usually called an edit control.
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys, and
mouse selections. TextField is a subclass of TextComponent.
TextField defines the following constructors:
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
creates a default text field
creates a text field that is numChars characters wide
initializes the text field with the string contained in str
initializes a text field and sets its width.
Some important methods on TextField
int
getColumns()
Gets the number of columns in this text field.
char
getEchoChar()
Gets the character that is to be used for echoing.
void
setEchoChar(char c)
Sets the echo character for this text field.
Void
setText(String t)
Sets the text that is presented by this text component to be the specified text.
String
getText(String t)
Gets the text that is presented by this text component to be the specified text.
Using a TextArea
Sometimes a single line of text input is not enough for a given task. To handle these situations, the
AWT includes a simple multiline editor called TextArea.
Following are the constructors for TextArea:
TextArea( )
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int
numChars)
S R I Dept. of CSE
creates a default text Area
creates a text Area that is num of lines &numChars
characters wide
initializes the text Area with the string contained in str
initializes a text Area and sets its width.
108
B.Tech Java
TextArea is a subclass of TextComponent. Therefore, it supports the getText( ),setText( ),
getSelectedText( ), select( ) methods.
void
append(String str)
Appends the given text to the text area's current text.
void
insert(String str, int pos)
Inserts the specified text at the specified position in this text
area.
void
replaceRange(String str,
int start, int end)
Replaces text between the indicated start and end positions
with the specified replacement text.
Example :import java.awt.event.*;
import java.awt.*;
class MyText extends Frame implements ActionListener
{
TextField name,password;
TextArea ta;
String msg,msg1;
Button b1;
MyText()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
Label n=new Label(" Name :",Label.LEFT);
Label p=new Label(" Pass word :",Label.LEFT);
b1=new Button("SHOW");
ta=new TextArea(4,50);
name=new TextField(40);
password=new TextField(20);
password.setEchoChar('*'); //set the password Char
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
msg=" Name===="+name.getText();
msg1=" \n Password===="+password.getText();
ta.append(msg+msg1);
}
Public c static void main(String[] args)
{
MyText mb=new MyText();
mb.setSize(400,400);
mb.setTitle(" colors Demo");
mb.setVisible(true);
}}
ta.setBackground(Color.cyan);
add(n); add(name);
add(p); add(password);
add(b1);
add(ta);
name.addActionListener(this);
password.addActionListener(this);
b1.addActionListener(this);
S R I Dept. of CSE
109
B.Tech Java
Layout Manager
A layout manger is a class that is useful to arrange components in a particular manner in a frame or
container.
Layout Managers in JAVA
1)
2)
3)
4)
5)
Flow Layout
Border Layout
Grid Layout
GridBagLayout
CardLayout
6) BoxLayout
Flow Layout
Flow Layout is useful to arrange the components in a line one after the other.
When a line is filled with components , they are automatically placed in next line.
To create Flow Layout we can use following ways
1) FlowLayout obj= new FlowLayout();
2) FlowLayout obj= new FlowLayout(int alignement);
3) FlowLayout obj= new FlowLayout(int alignement, int HGAP, int VGAP);
Here HGAP & VGAP specify space between components.
HGAP---- Horizontal Gap VGAP----- Vertical Gap
Field Summary
static int
CENTER
This value indicates that each row of components should be centered.
static int
LEADING
This value indicates that each row of components should be justified to the leading edge of
the container's orientation, for example, to the left in left-to-right orientations.
static int
LEFT
This value indicates that each row of components should be left-justified.
static int
RIGHT
This value indicates that each row of components should be right-justified.
static int
TRAILING
This value indicates that each row of components should be justified to the trailing edge of
the container's orientation, for example, to the right in left-to-right orientations.
S R I Dept. of CSE
110
B.Tech Java
Border Layout
A border layout lays out a container, arranging and resizing its components to fit in five regions: north,
south, east, west, and center.
Each region may contain no more than one component, and is identified by a corresponding constant:
NORTH, SOUTH, EAST, WEST, and CENTER.
When adding a component to a container with a border layout
1) BorderLayout obj= new BorderLayout();
2) BorderLayout obj= new BorderLayout(int HGAP, int VGAP);
Here HGAP & VGAP specify space between components.
HGAP---- Horizontal Gap VGAP----- Vertical Gap
Adding Components to the Border Layout
Syntax:
add(“Direction”,<component>)
add(“North”,b1);
add(“South”,b2);
add(“East”,b3);
add(“West”,b3);
add(“Center”,b4);
Grid Layout
The GridLayout class is a layout manager that lays out a container's components in a rectangular grid.
The container is divided into equal-sized rectangles, and one component is placed in each rectangle.
For example, the following is an applet that lays out four buttons into two and two columns:
S R I Dept. of CSE
111
B.Tech Java
Creating the Grid Layout
1) GridLayout obj= new GridLayout();
2) GridLayout obj= new GridLayout(int Rows, int Cols);
3) GridLayout obj =new GridLayout(int rows, int cols, int hgap, int vgap)
Here HGAP & VGAP specify space between components.
HGAP---- Horizontal Gap VGAP----- Vertical Gap
Note :- Card Layout and Box Layout will applied only on Swing Components .
Example on BorderLayout
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{System.exit(0);
}});}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyButton extends Frame implements ActionListener
{
Button b1,b2,b3,b4;
MyButton()
{
setLayout(new BorderLayout());
if(str.equals("Yellow"))
this.setBackground(Color.yellow);
if(str.equals("Red"))
this.setBackground(Color.red);
if(str.equals("Green"))
this.setBackground(Color.green);
if(str.equals("pink"))
this.setBackground(Color.pink);
b1=new Button("Yellow");
b2=new Button("Red");
b3=new Button("Green");
b4=new Button("pink");
add("North",b1);
add("South",b2);
add("East",b3);
add("West",b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
S R I Dept. of CSE
}
public static void main(String[] args)
{
MyButton mb=new MyButton();
mb.setSize(300,180);
mb.setTitle(" colors Demo");
mb.setVisible(true);
}}
112
B.Tech Java
Example on Grid Layout :-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public static void main(String[] args)
{
class MyButton extends Frame implements ActionListener
{
Button b1,b2,b3,b4;
MyButton()
{
setLayout(new GridLayout(2,2,10,10));
MyButton mb=new MyButton();
mb.setSize(200,180);
mb.setTitle(" colors Demo");
mb.setVisible(true);
}
}
b1=new Button("Yellow");
b2=new Button("Red");
b3=new Button("Green");
b4=new Button("pink");
add(b1);
add(b2);
add(b3);
add(b4);
Out put for Grid Layout:-
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}});
}
Out put for Border Layout :-
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Yellow"))
this.setBackground(Color.yellow);
if(str.equals("Red"))
this.setBackground(Color.red);
if(str.equals("Green"))
this.setBackground(Color.green);
if(str.equals("pink"))
this.setBackground(Color.pink);
}
S R I Dept. of CSE
113
B.Tech Java
Applets
An applet represents JAVA Byte Code embedded in a web page.
Applet = Java byte code + HTML page
Creating Applet
To create an applet we have Applet class of java.appletpackage and javax.swing package.
These classes use the following methods , which are automatically run by any applet program.
Applet Initialization and Termination
When an applet begins, the AWT calls the following methods, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
4. stop( )
5. destroy( )
init ( ) method
The init( ) method is the first method to be called.
So, the programmer can use this method to initialize any variables creating components and creating
threads.
The init( ) method is called only once during the run time of our applet..
Start ( ) method
The start( ) method is called after init( ).
It is also called to restart an applet after it has been stopped. Whereas init( ) is called only once—the first
time an applet is loaded—start( )
It is called each time an applet's HTML document is displayed onscreen. So, if a user leaves a web
page and comes back, then the applet calls the start( ) and executes.
S R I Dept. of CSE
114
B.Tech Java
Paint( ) method
The paint( ) method is called each time your applet's output must be redrawn the applet window may be
minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must
redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics.
This parameter will contain the graphics context, which describes the graphics environment in which the
applet is running.
Stop( ) method
This method is called by the browser when the applet is to be stopped.
If the user minimizes the web page , then this method is called and when the user again comes back to this
page, then start() method is called.
In this way start() and stop() methods can be called repeatedly.
destroy( ) method
This method is called by the browser when the applet is being terminated from memory.
The stop() method will always be called before destroy( ).
The code related to releasing the memory allocated to the applet and stopping any running threads should
be written in this method.
(Applet Life Cycle)
S R I Dept. of CSE
115
B.Tech Java
( Q ). Where are the applets executed ?
Applets are executed by a program called applet engine which is similar to virtual machine that exists
inside the web browser at client side.
More about applets..
Applets can show images and animations, play sounds take user input and send it to the server.
Applets cannot interact and cannot spoil the resources of the client system and hence they are
harmless.
The applets are executing area is called as “ sandbox”.
The sandbox provides an applet with some amount of memory to get executed and does not allow
the applet to do any illegal operations on the client system.
An Applet cannot run any executable program in the client system.
An applet cannot communicate with any server other than the server from which it was
downloaded.
An applet cannot read from a file or write into a file that belongs to the client computer.
An applet cannot find sensitive data like users login name, email address like..
Uses of applets
Applets are used on Internet for creating Dynamic web page. There are two types of web page:
1. Static
2. Dynamic
Static web pages provide some information to the user but the user cannot interact with the web page
other than viewing the information.
Dynamic web pages interact with the user at the run time.
For example , a student can type his hall ticket number in a text field and click the show button to get
back his results from University server. Applets are useful to provide such interaction with the user at
runtime.
o
A LOCAL applet is the one which is stored on our computer system. When browser
try to access the applet, it is not necessary for our computer to be connected to
The Internet.
o
A REMOTE applet
is the one which is not stored on our computer system and we are
required to be connected to the Internet
S R I Dept. of CSE
116
B.Tech Java
Example program:import java.applet.Applet;
import java.awt.*;
/*
<applet code="Simple" width=300 height=100>
</applet>
*/
public class Simple extends Applet
{
String msg="applet...";
public void init()
{
setBackground(Color.yellow);
setForeground(Color.red);
msg+="initializing... ";
repaint();
}
public void start()
{
msg+="starting... ";
repaint();
}
public void stop()
{
msg+="stopping... ";
repaint();
}
public void destroy()
{
msg+="preparing for unloading...";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,50,50);
}
}
Compile the applet :Run the applet :-
S R I Dept. of CSE
c:\> javac <prog_name.java >;
c:\> appletviewer <prog_name.java>
ex:- c:\>javc Simple.java
ex:- c:\>appletviewer Simple.java
117
B.Tech Java
The KeyEvent Class
A KeyEvent is generated when keyboard input occurs.
There
are
three
types
of
keyevents,
which
are
identified
by
these
integer
constants:
KEY_PRESSED,KEY_RELEASED, and KEY_TYPED.
The first two events are generated when any keyis pressed or released.
The last event occurs only when a character is generated.Remember, not all key presses result in
characters. For example, pressing the SHIFTkey does not generate a character.
There are many other integer constants that are defined by KeyEvent. For example,VK_0 through VK_9
and VK_A through VK_Z define the ASCII equivalents of the numbers and letters. Here are some others:
VK_ENTER
V K_ESCAPE
V K_CANCEL
VK_UP
VK_DOWN
V K_LEFT
V K_RIGHT
VK_PAGE_DOWN
VK_PAGE_UP
V K_SHIFT
VK_ALT
VK_CONTROL
The MouseEvent Class
There are seven types of mouse events. The MouseEvent class defines the following integer constants that
can be used to identify them:
MOUSE_CLICKED
MOUSE_DRAGGED
MOUSE_ENTERED
MOUSE_EXITED
MOUSE_MOVED
MOUSE_PRESSED
MOUSE_RELEASED
T he user clicked the mouse.
T he user dragged the mouse.
The mouse entered a component
The mouse exited from a component
The mouse moved.
T he mouse was pressed
T he mouse was released.
The most commonly used methods in this class are getX( ) and getY( ). These return the X and Y
coordinates of the mouse when the event occurred. Their forms are shown here:
int getX( )
int getY( )
The getClickCount( ) method obtains the number of mouse clicks for this event. Its signature is shown
here:
int getClickCount( )
S R I Dept. of CSE
118
B.Tech Java
Example program on Handling KeyBoard Events
// Demonstrate some virtual key codes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=500 height=500>
</applet>
*/
public class KeyEvents extends Applet implements
KeyListener
{
String msg = " ";
int X = 20, Y = 20; // output coordinates
public void init()
{
addKeyListener(this);
// request input focus
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
int key = ke.getKeyCode();
switch(key)
{
case KeyEvent.VK_F1:
msg += "<F1>";
break;
case KeyEvent.VK_F2:
msg += "<F2>";
break;
case KeyEvent.VK_F3:
msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
break;
default:
msg = "character typed
break;
:";
}
repaint();
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{
Font f=new Font("Bookman Old Style",Font.BOLD,20);
g.setColor(Color.red);
g.setFont(f);
g.drawString(msg, X, Y);
}
}
Out put :-
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
S R I Dept. of CSE
119
B.Tech Java
Example program on Handling Mouse Events
// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet implements
MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0;
// coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
public void mouseReleased(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "M C A";
showStatus("Dragging at " + mouseX + ", " + mouseY);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving at " + me.getX() + ", " +me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g)
{
Font f=new Font("Bookman Old Style",Font.BOLD,10);
g.setColor(Color.red);
g.setFont(f);
g.drawString(msg, mouseX, mouseY);
}
}
public void mousePressed(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
S R I Dept. of CSE
120
B.Tech Java
Drawing Shapes
The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled.
Objects are drawn and filled in the currently selected graphics color, which is black by default. When a graphics
object is drawn that exceeds the dimensions of the window, output is automatically clipped.
Let’s take a look at several of the drawing methods.
Lines are drawn by means of the drawLine( ) method, shown here:
void drawLine(int startX, int startY, int endX, int endY)
drawLine( ) displays a line in the current drawing color that begins at startX, startY and ends at endX, endY.
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, respectively.
They are shown here:
void drawRect ( int top, int left, int width, int height )
void fillRect ( int top, int left, int width, int height )
Ex:- drawRect(40,40,50,50);
fillRect(40,40,50,50);
The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle are specified by width and height.
To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ).
void drawRoundRect (I nt top, int left, int width, int height, int xDiam, int yDiam)
Example:- drawRoundRect(190, 10, 60, 50, 15, 15);
Drawing Oval
To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methods are shown here:
void drawOval (int top, int left, int width, int height)
void fillOval (int top, int left, int width, int height)
Exa:drawOval(10, 10, 50, 50);
fillOval(100, 10, 75, 50);
Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ), shown here:
void drawArc ( int top, int left, int width, int height, int startAngle,int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by top,left and whose width and
height are specified by width and height.
The arc is drawn from startAngle through the angular distance specified by sweepAngle.
Angles are specified in degrees. Zero degrees is on the horizontal, at the three o’clock position. The arc is
drawn counterclockwise if sweepAngle is positive, and clockwise if sweepAngle is negative. Therefore, to
draw an arc from twelve o’clock to six o’clock, the start angle would be 90 and the sweep angle 180.
S R I Dept. of CSE
121
B.Tech Java
Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( ),shown here:
void drawPolygon (int x[ ], int y[ ], int numPoints)
void fillPolygon (int x[ ], int y[ ], int numPoints)
Example :import java.awt.*;
import java.applet.*;
int y[]={125,200,200};
int n=3;
g.setColor(Color.darkGray);
g.fillPolygon(x,y,n);
/*
<applet code="DrawShapes", width=500 height=400>
</applet>
*/
g.setColor(Color.green);
g.fillOval(100,100,60,60);
g.setColor(Color.green);
g.fillArc(50,250,150,100,0,180);
g.fillArc(150,250,150,100,0,180);
g.fillArc(450,250,150,100,0,180);
public class DrawShapes extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.gray);
g.drawLine(50,300,600,300);
g.setColor(Color.yellow);
g.fillRect(300,200,150,100);
g.drawString("MY Happy Home",275,350);
}
g.setColor(Color.blue);
g.fillRect(350,210,50,60);
}
g.drawLine(350,280,400,280);
int x[]={375,275,475};
Output :-
S R I Dept. of CSE
122
B.Tech Java
Java Foundation Classes (JFC)
JFC is an extension of the original AWT. It contains classes that are completely portable. Since the entire JFC
is developed in pure Java.
JFC components are light- weight . This means , they utilize minimum system resources .Their speed is
completely good hence JFC programs execute much faster.
JFC components have same look - and – feel on all platforms. Once A component is created it looks same on
any Operating System. So the programmer can be sure of the look of his screen.
MVC Architecture
All the components in swing follow a model-view – controller(MVC) architecture.
Model represents the data that represents the state of a component.
Working MVC
MVC can be defined as an architectural pattern that is used while developing interactive application on the
web. As the name suggests there are three major components of MVC:
Model:
Encapsulates core data and logic. Model is often related with the business logic of the application. It knows
all the data that needs to be displayed. It is always isolated from the User Interface (UI) and the way data
needs to be displayed.
View:
It is the UI part of the application. It uses read-only methods of the model and queries data to display them to
the end users. It may be a window GUI or a HTML page. View encapsulates the presentation of the data,
there can be many views of the common data
Controller:
It acts as a interacting glue between models and views. It accepts input from the user and makes request from
the model for the data to produce a new view.
S R I Dept. of CSE
123
B.Tech Java
Window Panes
A window pane represents a free area of a window where some text or components can be displayed.
We have four types of window panes available in javax.swing package.
Panes
1.
2.
3.
4.
Glass pane
Root Pane
Layered Pane
Content Pane
Glass pane
This is the first pane and very close to monitors screen. Any components to be displayed in the foreground are
attached to this glass pane.
To reach this glass pane we use getGlassPane() methodof Jframe class.
Root pane
This is the pane below the glass pane. any components to be displayed in the background are displayed in this
pane .
The Root pane and Glass Pane are used in animation also.
Layered pane
This is the pane below the Root pane. When we want to take several components as a group, we attach them
in to in the layered pane.
To reach this Layered pane we use getLayeredPane() methodof Jframe class.
Content pane
This is the bottom of most pane all. Individual comopnents are attached to this pane.
To reach this Content pane we use getContentPane() methodof Jframe class.
S R I Dept. of CSE
124
B.Tech Java
Swing Components Hierarchy
All Swing components are available under javax.swing package.
JApplet
Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must be subclasses
of JApplet. JApplet is rich with functionality that is not found in Applet.
For example, JApplet supports various "panes," such as the content pane, the glass pane, and the root pane.
Icons and Labels
In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image. Two of its
constructors are shown here:
ImageIcon(String filename)
ImageIcon(URL url)
The first form uses the image in the file named filename. The second form uses the image in the resource
identified by url.
S R I Dept. of CSE
125
B.Tech Java
Labels
Swing labels are instances of the JLabel class, which extends JComponent. It can display text and/or an icon.
Some of its constructors are shown here:
JLabel(Icon i)
Label(String s)
JLabel(String s, Icon i, int align)
Here, s and i are the text and icon used for the label. The align argument is either LEFT, RIGHT, or
CENTER. These constants are defined in the SwingConstants interface, along with several others used by the
Swing classes.
Example:import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=150>
</applet>
*/
public class JLabelDemo extends JApplet
{
public void init()
{
// Get content pane
Container con = getContentPane();
// Create an icon
ImageIcon ii = new ImageIcon("france.gif");
// Create a label
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
// Add label to the content pane
con.add ( jl );
}}
The above example illustrates how to create and display a label containing both an icon and a string. The applet
begins by getting its content pane.
Next, an ImageIcon object is created for the file france.gif. This is used as the second argument to the JLabel
constructor. The first and last arguments for the JLabel constructor are the label text and the alignment. Finally,
the label is added to the content pane.
S R I Dept. of CSE
126
B.Tech Java
Text Fields
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent. It
provides functionality that is common to Swing text components.
One of its subclasses is JTextField, which allows you to edit one line of text. Some of its constructors
are shown here.
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)
Here, s is the string to be presented, and cols is the number of columns in the text field.
Text Area
A JTextArea is a multi-line area that displays plain text. It is intended to be a lightweight component
that provides source compatibility with the java.awt.TextArea class where it can reasonably do so.
JTextArea( )
JTextArea(int rows,int columns)
-- Constructs a new TextArea.
--Constructs a new empty TextArea with the specified
number of rows and columns.
JTextArea(String text,int rows,int columns) --- Constructs a new TextArea with the specified
text and number of rows and columns.
Buttons
Swing buttons provide features that are not found in the Button class defined by the AWT. For
example, you can associate an icon with a Swing button.
Swing buttons are subclasses of the AbstractButton class, which extends JComponent. AbstractButton
contains many methods that allow you to control the behavior of buttons, check boxes, and radio
buttons.
For example, you can define different icons that are displayed for the component when it is disabled,
pressed, or selected. Another icon can be used as a rollover icon, which is displayed when the mouse is
positioned over that component. The following are the methods that control this behavior:
void setDisabledIcon ( Icon di )
void setPressedIcon ( Icon pi )
void setSelectedIcon ( Icon si )
void setRolloverIcon ( Icon ri )
Here, di, pi, si, and ri are the icons to be used for these different conditions.
S R I Dept. of CSE
127
B.Tech Java
The JButton Class
The JButton class provides the functionality of a push button. JButton allows an icon, a string, or both to be
associated with the push button. Some of its constructors are shown here:
JButton (Icon i)
JButton (String s)
JButton (String s, Icon i)
Here, s and i are the string and icon used for the button.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="JButton_ex",width=500 eight=500>
</applet>
*/
public class JButton_ex extends JApplet implements
ActionListener
{
JButton b1,b2,b3;
JTextField jtf;
Container con=getContentPane();
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
jtf.setText(str); // Display Selected Button
name on Text Filed.
}}
public void init()
{
ImageIcon i1=new ImageIcon("Image_1.gif");
ImageIcon i2=new ImageIcon("Image_2.gif");
ImageIcon i3=new ImageIcon("Image_3.gif");
b1=new JButton("India",i1);
b2=new JButton("China",i2);
b3=new JButton("America",i3);
jtf=new JTextField(40);
con.setLayout(new FlowLayout(FlowLayout.LEFT));
con.add(b1);
con.add(b2);
con.add(b3);
con.add(jtf);
b1.setRolloverIcon(i2);
S R I Dept. of CSE
128
B.Tech Java
Check Boxes
The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of
AbstractButton. Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the check box is initially
selected. Otherwise, it is not.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JCheckBoxDemo" width=400
height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener
{
cb = new JCheckBox("Java");
cb.addItemListener(this);
con.add(cb);
cb = new JCheckBox("Perl");
cb.addItemListener(this);
con.add(cb);
// Add text field to the content pane
JTextField jtf;
public void init()
{
// Get content pane
Container con = getContentPane();
con.setLayout(new FlowLayout());
// Add check boxes to the content pane
JCheckBox cb = new JCheckBox("C");
cb.addItemListener(this);
con.add(cb);
jtf = new JTextField(15);
jtf.setEditable(false);
con.add(jtf);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb = (JCheckBox) ie.getItem();
jtf.setText(cb.getText());
}
}
cb.addItemListener(this);
con.add(cb);
S R I Dept. of CSE
129
B.Tech Java
Radio Buttons
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
AbstractButton. Some of its constructors are shown here:
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the button is initially selected.
Otherwise, it is not.
Radio buttons must be configured into a group. Only one of the buttons in that group can be selected at
any time.
For example, if a user presses a radio button that is in a group, any previously selected button in that
group is automatically deselected.
The ButtonGroup class is instantiated to create a button group. Its default constructor is invoked for this
purpose. Elements are then added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300
height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet
implements ActionListener
{
JTextField tf;
public void init()
{
// Get content pane
Container con = getContentPane();
con.setLayout(new FlowLayout());
// Add radio buttons to content pane
JRadioButton b1 = new JRadioButton("male");
b1.addActionListener(this);
S R I Dept. of CSE
con.add(b1);
JRadioButton b2 = new RadioButton("Female");
b2.addActionListener(this);
con.add(b2);
// Define a button group
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
tf = new JTextField(5);
jtf.setEditable(false);
con.add(tf);
}
public void actionPerformed(ActionEvent ae)
{
tf.setText(ae.getActionCommand());
}}
130
B.Tech Java
Combo Boxes
the JComboBox class, which extends JComponent. A combo box normally displays one entry. However,
it can also display a drop-down list that allows a user to select a different entry. You can also type your
selection into the text field.
Two of JComboBox's constructors are shown here:
JComboBox( )
JComboBox(Vector v)
Here, v is a vector that initializes the combo box.
Items are added to the list of choices via the addItem( ) method, whose signature is shown here:
void addItem (Object obj )
Here, obj is the object to be added to the combo box.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300
height=100>
</applet>
*/
public class JComboBoxDemo extends JApplet
implements ItemListener
{
JLabel jl;
Container con = getContentPane();
jc.addItem("Green");
jc.addItem("Pink");
jc.addItemListener(this);
con.add(jc);
}
public void itemStateChanged(ItemEvent ie)
{
String str = (String)ie.getItem();
if(str.equals("Yellow"))
con.setBackground(Color.yellow);
if(str.equals("Red"))
con.setBackground(Color.red);
if(str.equals("Green"))
con.setBackground(Color.green);
if(str.equals("Pink"))
con.setBackground(Color.pink);
public void init()
{
// Get content pane
con.setLayout(new FlowLayout());
// Create a combo box and add it to the panel
JComboBox jc = new JComboBox();
jc.addItem("Red");
jc.addItem("Yellow");
S R I Dept. of CSE
}
}
131
B.Tech Java
Tabbed Panes
A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title.
When a user selects a folder, its contents become visible. Only one of the folders may be selected at a time.
Tabbed panes are commonly used for setting configuration options.
Tabbed panes are encapsulated by the JTabbedPane class, which extends JComponent. We will use its
default constructor. Tabs are defined via the following method:
void addTab(String str, Component comp)
Here, str is the title for the tab, and comp is the component that should be added to the tab. Typically, a
JPanel or a subclass of it is added.
The general procedure to use a tabbed pane in an applet is outlined here:
1. Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane.
(The arguments to this method define the title of the tab and the component it contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the content pane of the applet.
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400
height=100>
</applet>
*/
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
JButton b1 = new JButton("India");
JButton b2 = new JButton("China");
JButton b3 = new JButton("Hong Kong");
JButton b4 = new JButton("Tokyo");
add(b1);
add(b2);
add(b3);
add(b4);
}
}
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}}
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
class ColorsPanel extends JPanel
{
public ColorsPanel()
{
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
S R I Dept. of CSE
public class JTabbedPaneDemo extends JApplet
{
public void init()
{
JTabbedPane jtp = new JTabbedPane();
getContentPane().add(jtp);
}
}
132
B.Tech Java
Out put :-
Scroll Panes
A scroll pane is a component that presents a rectangular area in which a component may be viewed.
Horizontal and/or vertical scroll bars may be provided if necessary. Scroll panes are implemented in Swing
by the JScrollPane class, which extends JComponent. Some of its constructors are shown here:
JScrollPane(Component comp)
JScrollPane(int vsb, int hsb)
JScrollPane(Component comp, int vsb, int hsb)
Here, comp is the component to be added to the scroll pane. vsb and hsb are int
constants that define when vertical and horizontal scroll bars for this scroll pane are shown. These
constants are defined by the ScrollPaneConstants interface. Some examples of these constants are
described as follows:
Constant
Description
HORIZONTAL_SCROLLBAR_ALWAYS
Always provide horizontal scroll bar
HORIZONTAL_SCROLLBAR_AS_NEEDED
Provide horizontal scroll bar, if needed
VERTICAL_SCROLLBAR_ALWAYS
Always provide vertical scroll bar
VERTICAL_SCROLLBAR_AS_NEEDED
Provide vertical scroll bar, if needed
Here are the steps that you should follow to use a scroll pane in an applet:
1. Create a JComponent object.
2. Create a JScrollPane object. (The arguments to the constructor specify the component and the
policies for vertical and horizontal scroll bars.)
3. Add the scroll pane to the content pane of the applet
S R I Dept. of CSE
133
B.Tech Java
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet
{
public void init()
{
// Get content pane
Container con = getContentPane();
con.setLayout(new BorderLayout());
// Add 400 buttons to a panel
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(10, 10));
int b = 0;
for(int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++)
{
jp.add(new JButton("Button " + b));
++b;
}
// Add panel to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);
// Add scroll pane to the content pane
con.add(jsp, BorderLayout.CENTER);
}
}
Out put :-
S R I Dept. of CSE
134