OOPC Course Plan 3 May 4PM
OOPC Course Plan 3 May 4PM
OOPC Course Plan 3 May 4PM
Learning Resources
Chalk & Talk, Course notes PDF’s, PPTs, Tutorial Sites and Videos.
Required Resources
TEXT BOOKS:
1. Java 7 Programming - Black Book, By Kogent Learning Solutions Inc., Freamtech
Publications
2. Head First Java 2nd Edition by Kathy Sierra, Oreilly Publication
3. T.Budd “Understanding OOP with Java” updated Edition, pearson
eduction,ISBN:10:0201612739
4. Herbert schildt “Java the complete reference”, 7th Edition, TMH,ISBN:0072263857
REFERENCE BOOKS:
1. Y. Daniel Liang “Introduction to Java programming” 6th Edition, pearson
ducation,ISBN:10:0132221586
2. R.A. Johnson-An introduction to Java programming and object oriented application
development, Thomson, ISBN:-10:0619217464
WEB LINKS:
1. www.tatamcgrawhill.com/html/9780070636774.html
2. http://nptel.iitm.ac.in
3. https://www.cl.cam.ac.uk/teaching/0910/OOProg/OOP.pdf
4. www.java2s.com
Assessment
The course will be evaluated for a total of 100 marks, with 30 marks for Continuous
Internal Assessment (CIA) and 70 marks for Semester End Examination (SEE). Out of
30 marks allotted for CIA during the semester, marks are awarded by taking average of
two CIA examinations or the marks scored in the make-up examination.
Continuous Internal Assessment (CIA):
CIA is conducted for a total of 30 marks (Table 1), with 20 marks for Continuous
Internal Examination (CIE), 05 marks for Assignment and 05 marks for Attendance.
Table 1: Assessment pattern for CIA
Component Theory Total
CIE Mark
Type of Assessment Exam Assignment/Quiz Attendance s
CIA Marks 25 5 5 30
Semester End Examination (SEE): The SEE is conducted for 70 marks of 3 hours
duration. The syllabus for the theory courses is divided into five units and each unit
carries equal weightage in terms of marks distribution.
Quizzes /Assignments Schedule
Course Activity
Topic 1:
Introduction to Object Oriented Programming,Classes,Objects,Methods, Constructors
and Encapsulation
Think Pair Share
Topic 2:
Inheritance,Polymorphism,Abstraction Concepts
Think Pair Share and Group Writing Assignments
Topic 3:
Exception Handling and Multi Threading Concepts
Group Writing Assignments and Case Study
Topic 4:
Introduction to GUI Programming,Applets,Event Handling and AWT Controls
Case Study and Team Based Learning
Topic 5:
MVC Architecture and Swings
Group Writing Assignments and Team Based Learning
Note: The knowledge and abilities tested (Blooms Level) along with tentative date/week and
time of exam shall be mentioned
Overview of Course:
What is the course about:
This course explains the fundamental ideas behind the object oriented approach to
programming. Knowledge of java helps to create the latest innovations in
programming. Like the successful computer languages that came before, java is the
blend of the best elements of its rich heritage combined with the innovative concepts
required by its unique environment. This course involves OOP concepts, java basics,
inheritance, polymorphism, interfaces, packages, Exception handling, multithreading,
files, and GUI components.
What are the general topics or focus?
Object Oriented Principles and their Implementation
How does it fit with other courses in the department or on campus?
It can be a pre requisite course for various Computer Science Programming Subjects
in the forth coming semesters as well as for other advanced technologies like android
and web programming. It helps the students of other branches to perform well in
Placement Drives where most of the placements are being held for Software
Companies.
Why would students want to take this course and learn this material?
Students want to take this course to gain knowledge of Object Oriented Programming
and it is the only language which provides and has more no of jobs in the industry.
Methods of instruction
Lecture
Discussion
Workload
Estimated amount of time to spend on course readings:4 Theory Hours and 3
Laboratory Hours per Week
Estimate amount of time to spend on course assignments and projects: 3 Hours
per week
Key concepts
Class, objects, methods, constructors, various object oriented principles, their
implementation, Exception handling, multi threading concepts and gui programming
Difficult Topics
multi threading
Optional: Pre Assessment Test -Review of the student’s standard: C Basics Test
Lesson Plan
Course Outcomes (COs):
At the end of the course the student should be able to:
1. Identify classes, objects, members of a class and relationships among them needed for
a specific problem
2. Demonstrate the concepts of polymorphism and inheritance and reusability
3. Illustarte Java programs to implement error handling techniques using exception
handling
4. Compare Multithreaded programming with ordinary programming models
5. Build GUI based applications.
Demonstrate the 3 3 1 1 3 1
concepts of
polymorphism and
inheritance and
reusability
Illustarte Java 3 3 2 2 3 2
programs to
implement error
handling techniques
using exception
handling
Compare 3 3 2 2
Multithreaded
programming with
ordinary
programming
models
Create GUI based 3 3 2 3 1 3 3
applications.
UNIT I
UNIT WISE PLAN
UNIT-I: Object Oriented Thinking Planned Hours: 09
Blooms
S. No. Topic Learning Outcomes Cos
Levels
1 Explain the concept of class and objects with access control CO1 L2
to represent real world entities
2 Demonstrate the behavior of programs involving the basic CO1 L2
programming constructs like control structures,
constructors, string handling and garbage collection
3 Use object oriented programming concepts to solve real CO2 L3
world problems
4 Use overloading methodology on methods and constructors CO2,CO3 L3
to develop application programs.
As you know, all computer programs consist of two elements: code and data. Furthermore,a
program can be conceptually organized around its code or around its data. That is, some
programs are written around ―what is happening‖ and others are written around ―who is
being affected.‖ These are the two paradigms that govern how a program is constructed.
The first way is called the process-oriented model. This approach characterizes a program as
a series of linear steps (that is, code). The process-oriented model can be thought of as code
acting on data. Procedural languages such as C employ this model to considerable success.
Problems with this approach appear as programs grow larger and more complex. To manage
increasing complexity, the second approach, called object-oriented programming, was
conceived.
Object-oriented programming organizes a program around its data (that is, objects) and a set
of well-defined interfaces to that data. An object-oriented program can be characterized as
data controlling access to code. As you will see, by switching the controlling entity to data,
you can achieve several organizational benefits.
There are many high level languages like COBOL, FORTRAN, PASCAL, C used for
conventional programming commonly known as POP.
POP basically consists of writing a list of instructions for the computer to follow, and
organizing these instructions into groups known as functions.
A typical POP structure is shown in below: Normally a flowchart is used to organize these
actions and represent the flow of control logically sequential flow from one to another. In a
multi-function program, many important data items are placed as global so that they may be
accessed by all the functions. Each function may have its own local data. Global data are
more vulnerable to an in advent change by a function. In a large program it is very difficult to
identify what data is used by which function. In case we need to revise an external data
structure, we should also revise all the functions that access the data. This provides an
opportunity for bugs to creep in.
Drawback: It does not model real world problems very well, because functions are action
oriented and do not really corresponding to the elements of the problem.
OOP allows us to decompose a problem into a number of entities called objects and then
builds data and methods around these entities.
That is ,an object a considered to be a partitioned area of computer memory that stores data
and set of operations that can access that data. Since the memory partitions are independent,
the objects can be used in a variety of different programs without modifications.
Characteristics of Object Oriented Programming:
Emphasis on data .
Programs are divided into what are known as methods.
Data structures are designed such that they characterize the objects.
Methods that operate on the data of an object are tied together .
Data is hidden.
Objects can communicate with each other through methods.
Reusability.
Follows bottom-up approach in program design.
Features(Buzzwords) of Java
Features of a language are nothing but the set of services or facilities provided by the
language vendors to the industry programmers. Some important features of java are;
1. Simple
It is simple because of the following factors:
It is free from pointer due to this execution time of application is improve.
[Whenever we write a Java program without pointers then internally it is converted
into the equivalent pointer program].
It has Rich set of API (application protocol interface).
It has Garbage Collector which is always used to collect un-Referenced (unused)
Memory location for improving performance of a Java program.
It contains user friendly syntax for developing any applications.
2. Platform Independent
A program or technology is said to be platform independent if and only if which can run on
all available operating systems with respect to its development and compilation. (Platform
represents O.S).
3. Architectural Neutral
Architecture represents processor. A Language or Technology is said to be Architectural
neutral which can run on any available processors in the real world without considering there
architecture and vendor (providers) irrespective to its development and compilation.
5. Multithreaded
A flow of control is known as thread. When any Language executes multiple threads at a time
that language is known as multithreaded Language. It is multithreaded Language.
6. Distributed
Using this language we can create distributed application. RMI and EJB are used for creating
distributed applications. In distributed application multiple client system are depends on
multiple server systems so that even problem occurred in one server will never be reflected
on any client system.
7. Networked
It is mainly design for web based applications; J2EE is used for developing network based
applications.
8. Robust
Simply means of Robust is strong. It is robust or strong Programming Language because of
its capability to handle Run-time Error, automatic garbage collection, lack of pointer concept,
Exception Handling. All these points make it robust Language.
9. Dynamic
It supports Dynamic memory allocation, due to this memory wastage is reduced and
performance of application is improved. The process of allocating the memory space to the
input of the program at a run-time is known as dynamic memory allocation. To allocate
memory space dynamically we use an operator called 'new'. 'new' operator is known as
dynamic memory allocation operator.
10. Secure
It is more secured language compare to other language; in this language all code is converted
into byte code after compilation which is not readable by human.
12. Interpreted
It is one of the highly interpreted programming languages.
JVM
JVM (Java Virtual Machine) is a software. It is a specification that provides runtime
environment in which java byte code can be executed. It not physically exists.
JVMs are not same for all hardware and software, for example for window os JVM is
different and for Linux VJM is different. JVM, JRE and JDK are platform dependent because
configuration of each OS differs. But, Java is platform independent.
JRE
The Java Runtime Environment (JRE) is part of the Java Development Kit (JDK). It contains
set of libraries and tools for developing java application. The Java Runtime Environment
provides the minimum requirements for executing a Java application. It physically exists. It
contains set of libraries + other files that JVM uses at runtime.
JDK
The Java Development Kit (JDK) is primary component. It physically exists. It is collection
of programming tools and JRE, JVM.
The path is required to be set for using tools such as javac, java etc.
If you are saving the java source file inside the jdk/bin directory, path is not required to be set
because all the tools will be available in the current directory.
But If you are having your java file outside the jdk/bin folder, it is necessary to set
path of JDK.
There are 2 ways to set java path:
1. temporary
2. permanent
1) How to set Temporary Path of JDK in Windows
To set the temporary path of JDK, you need to follow following steps:
Open command prompt
copy the path of jdk/bin directory
write in command prompt: set path=copied_path
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
Let's see it in the figure given below:
2) How to set Permanent Path of JDK in Windows
For setting the permanent path of JDK, you need to follow these steps:
Go to MyComputer properties -> advanced tab -> environment variables -> new tab
of user variable -> write path in variable name -> write path of bin folder in variable
value -> ok -> ok -> ok
For Example:
1)Go to MyComputer
properties
2)click on advanced tab
8)click on ok button
9)click on ok button
Now your permanent path is set. You can now execute any program of java from any drive.
All the tools are present in bin folder so we set path upto bin folder.
Classpath variable is used to set the path for all classes which is used in our program so we
set classpath upto rj.jar. in rt.jar file all the .class files are present. When we decompressed
rt.jar file we get all .class files.
Example
"C:\Program Files\Java\jre1.6.0\jre\lib\rt.jar"
In above rt.jar is a jar file where all the .class files are present so we set the classpath upto
rt.jar.
First Java Program
Requirements for java Program
For executing any java program we need given things.
Install the JDK any version if you don't have installed it.
Set path of the jdk/bin directory.
Create the java program
Compile and run the java program
Steps For compiling and executing the java program
Java is very simple programming language first we write a java program and save it with
program class name.
In below program we create a java program with "First" name so we save this program with
"First.java" file name. We can save our java program anywhere in our system or computer.
Create First program
Example
Class First
{
public static void main(String[] args)
{
System.out.println("Hello Java");
System.out.println("My First Java Program");
}
}
Compile and Execute Java Code
To compile: javac First.java
To execute: java First
Output
Hello Java
My First Java Program
Save Java Program
Syntax:
Filename.java
Example:
First.java
Compile Java Program
Syntax:
Javac Filename.java
Example:
Javac First.java
Note: Here Javac and Java are called tools or application programs or exe files developed by
sun micro system and supply as a part of jdk 1.5/1.6/1.7 in bin folder. Javac is used for
compile the java program and java is used for run the java program.
During the program execution internally following steps will be occurs.
Class loader subsystem loads or transfer the specified class into main memory(RAM)
from secondary memory(hard disk)
JVM takes the loaded class
JVM looks for main method because each and every java program start executing
from main() method.
Since main() method of java is static in nature, JVM call the main() method with
respect to loaded class (Example: First as First.main(--))
Note: A java program can contain any number of main method but JVM start execution from
that main() method which is taking array of object of String class.
Compile and Run Java Program
In the Java programming language, all source code is first written in plain text files and save
with the .java extension. After compilation, .class files are generated by javac compiler. A
.class file does not contain code that is native to your processor; it instead contains bytecode
(it is machine language of the Java Virtual Machine (JVM)).
The java launcher tool then runs your application with an instance of the Java Virtual
Machine (JVM).
In the above diagram javac and java are called tools or application programs or exe files
developed by sun micro system and supply as a part of jdk 1.5/1.6/1.7 in bin folder (starting
directory of java is called java home directory).
Data Types in Java
Datatype is a special keyword used to allocate sufficient memory space for the data, in other
words Data type is used for representing the data in main memory (RAM) of the computer.
In general every programming language is containing three categories of data types. They are
Fundamental or primitive data types
Derived data types
User defined data types.
Syntax
Variable_name = value;
Rules to declare a Variable
Every variable name should start with either alphabets or underscore (_) or dollar ($)
symbol.
No space is allowed in the variable declarations.
Except underscore ( _ ) no special symbol are allowed in the middle of variable
declaration
Variable name always should exist in the left hand side of assignment operators.
Maximum length of variable is 64 characters.
No keywords should access variable name.
Note: Actually a variable also can start with ¥, ¢, or any other currency sign.
Example of Variable Declaration
class Sum
{
public static void main(String[] args)
{
int _a, ¢b, ¥c, $d, result;
_a=10;
¢b=20;
¥c=30;
$d=40;
result=_a+¢b+¥c+$d;
System.out.println("Sum is :" +result);
}
}
Output
Sum is : 100
Variable declarations
In which sufficient memory will be allocated and holds default values.
Syntax
Datatype variable_name;
byte b1;
Variable initialization
It is the process of storing user defined values at the time of allocation of memory space.
Variable assignment
Value is assigned to a variable if that is already declared or initialized.
Syntax
Variable_Name = value
int a = 100;
Syntax
int a= 100;
int b;
b = 25; // ------> direct assigned variable
b = a; // ------> assigned value in term of variable
b = a+15; // ------> assigned value as term of expression
Operators in Java
Operator is a special symbol that tells the compiler to perform specific mathematical or
logical Operation. Java supports following lists of operators.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Ternary or Conditional Operators
Arithmetic Operators
Given table shows the entire Arithmetic operator supported by Java Language. Let’s suppose
variable A hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
Relational Operators
Which can be used to check the Condition, it always returns true or false. Let’s suppose
variable A hold 8 and B hold 3.
Operators Example (int A=8, B=3) Result
< A<B False
<= A<=10 True
> A>B True
>= A<=B False
== A== B False
!= A!=(-4) True
Logical Operators
Which can be used to combine more than one Condition? Suppose you want to combined two
conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C).
Here && is Logical Operator.
Operator Example (int A=8, B=3, C=-10) Result
&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True
Truth table of Logical Operator
C1 C2 C1 && C2 C1 || C2 !C1 !C2
T T T T F F
T F F T F T
F T F T T F
F F F F T T
Assignment operators
Which can be used to assign a value to a variable? Let’s suppose variable A hold 8 and B hold
3.
Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
=a=b Value of b will be assigned to a
Ternary operator
If any operator is used on three operands or variable is known as ternary operator. It can be
represented with “?:”
Decision making statement statements is also called selection statement. That is depending on
the condition block need to be executed or not which is decided by condition. If the condition
is "true" statement block will be executed, if condition is "false" then statement block will not
be executed. In java there are three types of decision making statement.
if
if-else
switch
if-then Statement
if-then is most basic statement of Decision making statement. It tells to program to execute a
certain part of code only if particular condition is true.
Syntax
if(condition)
{
Statement(s)
}
Example if statement
class Hello
{
int a=10;
public static void main(String[] args)
{
if(a<15)
{
System.out.println("Hello good morning!");
}
}
}
Output
Hello good morning
if-else statement
In general it can be used to execute one block of statement among two blocks, in java
language if and else are the keyword in java.
Syntax
if(condition)
{
Statement(s)
}
else
{
Statement(s)
}
........
In the above syntax whenever condition is true all the if block statement are executed,
remaining statement of the program by neglecting. If the condition is false else block
statement executed and neglecting if block statements.
Example if else
import java.util.Scanner;
class Oddeven
{
public static void main(String[] args)
{
int no;
Scanner s=new Scanner(System.in);
System.out.println("Enter any number :");
no=s.nextInt();
if(no%2==0)
{
System.out.println("Even number");
}
else
{
System.out.println("Odd number");
}
}
}
Output
Enter any number :
10
Even number
Switch Statement
The switch statement in java language is used to execute the code from multiple conditions or
case. It is same like if else-if ladder statement.
A switch statement work with byte, short, char and int primitive data type, it also works with
enumerated types and string.
Syntax
switch(expression/variable)
{
case value:
//statements
// any number of case statements
break; //optional
default: //optional
//statements
}
Rules for apply switch statement
With switch statement use only byte, short, int, char data type (float data type is not allowed).
You can use any number of case statements within a switch. Value for a case must be same as
the variable in switch.
Limitations of switch statement
Logical operators cannot be used with switch statement. For instance
Example
case k>=20: // not allowed
Example of switch case
import java.util.*;
class switchCase
{
public static void main(String arg[])
{
int ch;
System.out.println("Enter any number (1 to 7) :");
Scanner s=new Scanner(System.in);
ch=s.nextInt();
switch(ch)
{
case 1:
System.out.println("Today is Monday");
break;
case 2:
System.out.println("Today is Tuesday");
break;
case 3:
System.out.println("Today is Wednesday");
break;
case 4:
System.out.println("Today is Thursday");
break;
case 5:
System.out.println("Today is Friday");
break;
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
default:
System.out.println("Only enter value 1 to 7");
}
}
}
Output
Enter any number (1 to 7) :
5
Today is Friday
Looping/Iteration statement
Looping statements are the statements execute one or more statement repeatedly several
number of times. In java programming language there are three types of loops:while, for and
do-while.
Why use loop?
When you need to execute a block of code several number of times then you need to use
looping concept in Java language.
Advantage with looping statement
Reduce length of Code
Take less memory space.
Burden on the developer is reducing.
Time consuming process to execute the program is reduced.
Difference between conditional and looping statement
Conditional statement executes only once in the program where as looping statements
executes repeatedly several number of time.
While loop
In while loop first check the condition if condition is true then control goes inside the loop
body otherwise goes outside of the body. while loop will be repeats in clock wise direction.
Syntax
while(condition)
{
Statement(s)
Increment / decrements (++ or --);
}
Example while loop
class whileDemo
{
public static void main(String args[])
{
int i=0;
while(i<5)
{
System.out.println(+i);
i++;
}
Output
1
2
3
4
5
for loop
for loop is a statement which allows code to be repeatedly executed. For loop contains 3 parts
Initialization, Condition and Increment or Decrements
Syntax
for ( initialization; condition; increment )
{
statement(s);
}
Initialization: This step is executed first and this is executed only once when we are
entering into the loop first time. This step is allowed to declare and initialize any loop
control variables.
Condition: This is next step after initialization step, if it is true, the body of the loop
is executed, if it is false then the body of the loop does not execute and flow of control
goes outside of the for loop.
Increment or Decrements: After completion of Initialization and Condition steps
loop body code is executed and then Increment or Decrements steps is execute. This
statement allows updating any loop control variables.
Flow Diagram
Example:
class Test
{
public static void main(String[] args)
{
int i = 100;
Output:
Int value 100
Long value 100
Float value 100.0
Narrowing or Explicit Conversion
If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.
This is useful for incompatible data types where automatic conversion cannot be
done.
Here, target-type specifies the desired type to convert the specified value to.
Char and number are not compatible with each other. Let’s see when we try to convert one
into other.
//Java program to illustrate incompatible data
// type for explicit type conversion
public class Test
{
public static void main(String[] argv)
{
char ch = 'c';
int num = 88;
ch = num;
}
}
Error:
7: error: incompatible types: possible lossy conversion from int to char
ch = num;
^
1 error
How to do Explicit Conversion?
Example:
//Java program to illustrate explicit type conversion
class Test
{
public static void main(String[] args)
{
double d = 100.04;
Output:
Double value 100.04
Long value 100
Int value 100
While assigning value to byte type the fractional part is lost and is reduced to modulo
256(range of byte).
Example:
//Java program to illustrate Conversion of int and double to byte
class Test
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
System.out.println("Conversion of int to byte.");
//i%256
b = (byte) i;
System.out.println("i = b " + i + " b = " + b);
System.out.println("\nConversion of double to byte.");
//d%256
b = (byte) d;
System.out.println("d = " + d + " b= " + b);
}
}
Output:
Conversion of int to byte.
i = 257 b = 1
// The Expression
double result = (f * b) + (i / c) - (d * s);
Output:
Result = 626.7784146484375
Explicit type casting in Expressions
While evaluating expressions, the result is automatically updated to larger data type of the
operand. But if we store that result in any smaller data type it generates compile time error,
due to which we need to type cast the result.
Example:
//Java program to illustrate type casting int to byte
class Test
{
public static void main(String args[])
{
byte b = 50;
Output
100
NOTE- In case of single operands the result gets converted to int and then it is type casted
accordingly.
Example:
//Java program to illustrate type casting int to byte
class Test
{
public static void main(String args[])
{
byte b = 50;
Arrays
An array is a container that holds data (values) of one single type. For example, you can
create an array that can hold 100 values of int type.
Array is a fundamental construct in Java that allows you to store and access large number of
values conveniently.
How to declare an array?
Here's how you can declare an array in Java:
dataType[] arrayName;
dataType can be a primitive data type like: int, char, Double, byte etc. or an
object (will be discussed in later chapters).
arrayName is an identifier.
Let's take the above example again.
Double[] data;
Here, data is an array that can hold values of type Double.
But, how many elements can array this hold?
Good question! We haven't defined it yet. The next step is to allocate memory for array
elements.
data = new Double[10];
The length of data array is 10. Meaning, it can hold 10 elements (10 Double values in this
case).
Note, once the length of the array is defined, it cannot be changed in the program.
System.out.println(age[0]);
System.out.println(age[1]);
System.out.println(age[2]);
System.out.println(age[3]);
System.out.println(age[4]);
}
}
When you run the program, the output will be:
0
0
0
0
0
There is a better way to access elements of an array by using looping construct (generally for
loop is used).
class ArrayExample {
public static void main(String[] args) {
Multidimensional Arrays
It's also possible to create an array of arrays known as multidimensional array. For example,
int[][] a = new int[3][4];
Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of type
int.
Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts with 0 and
not 1.
// test is a 3d array
int[][][] test = { { {1, -2, 3}, {2, 3, 4} }, {
{-4, -5, 6, 9}, {1}, {2, 3} } };
Class: Class is a blue print which is containing only list of variables and method and no
memory is allocated for them. A class is a group of objects that has common properties.
A class in java contains:
Data Members
Methods
Constructor
Blocks
Class and Interface
Object: Object is an instance of class, object has state and behavior.
An Object in java has three characteristics:
State
Behavior
Identity
State: Represents data (value) of an object.
Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify each object
uniquely.
Class is also can be used to achieve user defined data types.
Object is the physical as well as logical entity where as class is the only logical entity.
Vehicle class
Car, bike, truck these all are belongs to vehicle class. These Objects have also different
different states and behaviors. For Example car has state - color, name, model, speed,
Mileage. as we;; as behaviors - distance travel
Access modifiers are those which are applied before data members or methods of a class.
These are used to suggest “where to access and where not to access the data members or
methods”.
In java programming these are classified into four types:
Private
Default (not a keyword)
Protected
Public
Note: Default is not a keyword (where as public, private, protected are keywords)
If we are not using private,protected and public keywords then JVM is by default takes
default access mode.
Access modifiers are always used for how to reuse the features within the package and access
the package between class to class, interface to interface and interface to class. Access
modifiers provide features accessing and controlling mechanism among the classes and
interfaces.
Note: A protected member of class is accessible within the same class and other class of same
package and also accessible in inherited class of other package.
Private: private members of a class are only accessible within the class, but not accessible
anywhere in the program. Private is also called class level access modifier.
Example
class Hello
{
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}
class B extends A
{
public static void main(String args[]){
B obj = new B();
obj.show();
}
}
Output
Hello Java
default: default members of a class are accessible only within the same class and the other
class of the same package. default is also called package level access modifier.
Example
//save by A.java
package pack;
class A
{
void show()
{
System.out.println("Hello Java");
}
}
//save by B.java
package pack2;
import pack1.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error, can't access outside the package
obj.show(); //Compile Time Error, can't access outside the package
}
}
Output
Hello Java
Note: private access modifiers is also known as native access modifiers, default access
modifiers is also known as package access modifiers, protected access modifiers is also
known as inherited access modifiers, public access modifiers is also known as universal
access modifiers.
Here data type is one of Java's datatypes and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java −
Example
Local Variables
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or block.
Local variables are implemented at stack level internally.
There is no default value for local variables, so local variables should be declared and
an initial value should be assigned before the first use.
Example
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited
to only this method.
Example
Following example uses age without initializing it, so it would give an error at the time of
compilation.
Instance Variables
Instance variables are declared in a class, but outside a method, constructor or any
block.
When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present
throughout the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access
modifiers.
Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null. Values can be assigned during
the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the
class. However, within static methods (when instance variables are given
accessibility), they should be called using the fully qualified name.
ObjectReference.VariableName.
Example
name : Ransika
salary :1000.0
Class/Static Variables
Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program
stops.
Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during
the declaration or within the constructor. Additionally, values can be assigned in
special static initializer blocks.
Static variables can be accessed by calling with the class name
ClassName.VariableName.
When declaring class variables as public static final, then variable names (constants)
are all in upper case. If the static variables are not public and final, the naming syntax
is the same as instance and local variables.
Example
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
Note − If the variables are accessed from an outside class, the constant should be accessed as
Employee.DEPARTMENT
// Student class
class Student
{
String name;
int rollNo;
// static variable
static String cllgName;
this.rollNo = setRollNo();
}
// static method
static void setCllg(String name){
cllgName = name ;
}
// instance method
void getStudentInfo(){
System.out.println("name : " + this.name);
System.out.println("rollNo : " + this.rollNo);
s1.getStudentInfo();
s2.getStudentInfo();
}
}
Syntax
static
{
........
//Set of Statements
........
}
Note: In real time applications, static block can be used whenever we want to execute any
instructions or statements before execution of main method.
Example of Static Block
class StaticDemo
{
static
{
System.out.println("Hello how are u ?");
}
public static void main(String args[])
{
System.out.println("This is main()");
}
}
Output
Hello how are u ?
This is main()
Run java program without main method
class StaticDemo
{
static
{
System.out.println("Hello how are u ?");
}
}
Output
Output:
Hello how are u ?
Exception is thread "main" java.lang.no-suchmethodError:Main
Note: "Exception is thread "main" java.lang.no-suchmethodError:Main" warning is given in
java 1.7 and its above versions
More than one static block in a program
class StaticDemo
{
static
{
System.out.println("First static block");
}
static
{
System.out.println("Second Static block");
}
public static void main(String args[])
{
System.out.println("This is main()");
}
}
Output
Output:
First static block
Second static block
This is main()
Note: "Here static block run according to their order (sequence by) from top to bottom.
Why a static block executes before the main method?
A class has to be loaded in main memory before we start using it. Static block is executed
during class loading. This is the reason why a static block executes before the main method.
Constructor
Constructor in Java is a special member method which will be called implicitly
(automatically) by the JVM whenever an object is created.
Constructors are mainly created for initializing the object. Initialization is a process of
assigning user defined values at the time of allocation of memory space.
Syntax
className()
{
.......
.......
}
Advantages of constructors in Java
A constructor eliminates placing the default values.
A constructor eliminates calling the normal or ordinary method implicitly.
How Constructor eliminate default values?
Constructor are mainly used for eliminate default values by user defined values, whenever we
create an object of any class then its allocate memory for all the data members and initialize
there default values. To eliminate these default values by user defined values we use
constructor.
Example
class Sum
{
int a,b;
Sum()
{
a=10;
b=20;
c=a+b;
System.out.println("Sum: "+c);
}
public static void main(String s[])
{
Sum s=new Sum();
}
}
Output
Sum: 30
In above example when we create an object of "Sum" class then constructor of this class call
and initialize user defined value in a=10 and b=20. If we cannot create constructor of Sum
class then it print " Sum: 0 " because default values of integer is zero.
Methods
What is a method?
In mathematics, you might have studied about functions. For example, f(x) = x2 is a function
that returns squared value of x.
If x = 2, then f(2) = 4
If x = 3, f(3) = 9
and so on.
Similarly, in programming, a function is a block of code that performs a specific task.
In object-oriented programming, method is a jargon used for function. Methods are bound to
a class and they define the behavior of a class.
Types of Java methods
Depending on whether a method is defined by the user, or available in standard library, there
are two types of methods:
Standard Library Methods
User-defined Methods
Standard Library Methods
The standard library methods are built-in methods in Java that are readily available for use.
These standard libraries come along with the Java Class Library (JCL) in a Java archive
(*.jar) file with JVM and JRE.
For example,
print() is a method of java.io.PrintSteam. The print("...") prints the string inside
quotation marks.
sqrt() is a method of Math class. It returns square root of a number.
Here's an working example:
public class Numbers {
public static void main(String[] args) {
System.out.print("Square root of 4 is: " + Math.sqrt(4));
}
}
When you run the program, the output will be:
Square root of 4 is: 2.0
User-defined Method
You can also define methods inside a class as per your wish. Such methods are called user-
defined methods.
How to create a user-defined method?
Before you can use (call a method), you need to define it.
Here is how you define methods in Java.
public static void myMethod() {
System.out.println(“My Function called”);
}
Here, a method named myMethod() is defined.
The complete syntax for defining a Java method is:
modifier static returnType nameOfMethod (Parameter List) {
// method body
}
Here,
modifier - defines access type whether the method is public, private and so on.
static - If you use static keyword in a method then it becomes a static method. Static
methods can be called without creating an instance of a class.
For example, the sqrt() method of standard Math class is static. Hence, we can
directly call Math.sqrt() without creating an instance of Math class.
It can return native data types (int, float, double etc.), native objects (String, Map, List
etc.), or any other built-in and user defined objects.
If the method does not return a value, its return type is void.
You can give any name to a method. However, it is more conventional to name it after
the tasks it performs. For example, calculateInterest, calculateArea, and so on.
Parameters (arguments) - Parameters are the values passed to a method. You can
pass any number of arguments to a method.
Method body - It defines what the method actually does, how the parameters are
manipulated with programming statements and what values are returned. The codes
inside curly braces { } is the body of the method.
1. While Java is executing the program code, it encounters myMethod(); in the code.
2. The execution then branches to the myFunction() method, and executes code inside
the body of the method.
3. After the codes execution inside the method body is completed, the program returns to
the original state and executes the next statement.
// method call
myMethod();
class Output {
}
When you run the program, the output will be:
Squared value of 10 is: 100
In the above code snippet, the method square() does not accept any arguments and always
returns the value of 10 squared.
Notice, the return type of square() method is int. Meaning, the method returns an integer
value.
As you can see, the scope of this method is limited as it always returns the same value.
Now, let's modify the above code snippet so that instead of always returning the squared
value of 10, it returns the squared value of any integer passed to the method.
n=3
result = square(n);
System.out.println("Square of 3 is: " + result);
n=4
result = square(n);
System.out.println("Square of 4 is: " + result);
}
Java is a strongly-typed language. If you pass any other data type except int (in the above
example), compiler will throw an error.
The argument passed n to the getSquare() method during the method call is called actual
argument.
result = getSquare(n);
The parameter i accepts the passed arguments in the method definition getSquare(int i). This
is called formal argument (parameter). The type of the formal argument must be explicitly
typed.
You can pass more than one argument to the Java method by using commas. For example,
public class ArithematicMain {
// method defined
private static int getSquare(int x){
return x * x;
}
// method call
result = getSquare(i)
System.out.println("Square of " + i + " is : " + result); }
}
}
When you run the program, the output will be:
Square of 1 is : 1
Square of 2 is : 4
Square of 3 is : 9
Square of 4 is : 16
Square of 5 is : 25
In above code snippet, the method getSquare() takes int as a parameter. Based on the
argument passed, the method returns the squared value of it.
Here, argument i of type int is passed to the getSquare() method during method call.
result = getSquare(i);
The parameter x accepts the passed argument [in the function definition getSquare(int x)].
return i * i; is the return statement. The code returns a value to the calling method and
terminates the function.
Did you notice, we reused the getSquare method 5 times?
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by
taking the number of parameters, and their type.
In other words whenever same constructor is existing multiple times in the same class
with different number of parameters or order of parameters or type of parameters is known as
Constructor overloading.
In general constructor overloading can be used to initialize same or different objects with
different values.
Syntax
class ClassName
{
ClassName()
{
..........
..........
}
ClassName(datatype1 value1)
{.......}
ClassName(datatype1 value1, datatype2 value2)
{.......}
ClassName(datatype2 variable2)
{.......}
ClassName(datatype2 value2, datatype1 value1)
{.......}
........
}
Why overriding is not possible at constructor level.
The scope of constructor is within the class so that it is not possible to achieved overriding at
constructor level.
Method Overloading
In Java, two or more methods can have same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called
overloaded methods and this feature is called method overloading. For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
Here, func() method is overloaded. These methods have same name but accept different
arguments.
Notice that, the return type of these methods is not same. Overloaded methods may or may
not have different return type, but they must differ in parameters they accept.
class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}
class MethodOverloading {
this is a reference variable that refers to the current object. It is a keyword in java language
represents current class object
Usage of this keyword
It can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
It can be used to invoke current class method (implicitly)
It can be passed as an argument in the method call.
It can be passed as argument in the constructor call.
It can also be used to return the current class instance.
Why use this keyword in java ?
The main purpose of using this keyword is to differentiate the formal parameter and data
members of class, whenever the formal parameter and data members of the class are similar
then jvm get ambiguity (no clarity between formal parameter and member of the class)
To differentiate between formal parameter and data member of the class, the data member of
the class must be preceded by "this".
"this" keyword can be use in two ways.
this . (this dot)
this() (this off)
this . (this dot)
which can be used to differentiate variable of class and formal parameters of method or
constructor.
"this" keyword are used for two purpose, they are
It always points to current class object.
Whenever the formal parameter and data member of the class are similar and JVM
gets an ambiguity (no clarity between formal parameter and data members of the
class).
To differentiate between formal parameter and data member of the class, the data members of
the class must be preceded by "this".
Syntax
this.data member of current class.
Note: If any variable is preceded by "this" JVM treated that variable as class variable.
Example without using this keyword
class Employee
{
int id;
String name;
this ()
which can be used to call one constructor within the another constructor without creation of
objects multiple time for the same class.
Syntax
this(); // call no parametrized or default constructor
this(value1,value2,.....) //call parametrize constructor
this keyword used to invoke current class method (implicitly)
By using this keyword you can invoke the method of the current class. If you do not use the
this keyword, compiler automatically adds this keyword at time of invoking of the method.
finalize () method
The finalize () method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This method is
defined in Object class as:
protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by
new keyword. So if you have created any object without new, you can use finalize
method to perform cleanup processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.
public static void gc(){}
String Class
Generally, string is a sequence of characters. But in java, string is an object that represents a
sequence of characters.
The java.lang.String class is used to create string object.
How to create String object?
1) String Literal
Java String literal is created by using double quotes.
For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the
string already exists in the pool, a reference to the pooled instance is returned.
If string doesn't exist in the pool, a new string instance is created and placed in the pool.
For example:
String s1="Welcome";
String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any
string object with the value "Welcome" in string constant pool, so it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create new
object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool.
String class is immutable that means whose content cannot be changed at the time of
execution of program.
String class object is immutable that means when we create an object of String class it never
changes in the existing object.
Example:
class StringHandling
{
public static void main(String arg[])
{
String s=new String("java");
s.concat("software");
System.out.println(s);
}
}
Output
java
Explanation: Here we cannot change the object of String class so output is only java not java
software.
length()
length(): This method is used to get the number of characters of any string.
Example
class StringHandling
{
public static void main(String arg[])
{
int l;
String s=new String("Java");
l=s.length();
System.out.println("Length: "+l);
}
}
Output
Length: 4
charAt(index)
charAt(): This method is used to get the character at a given index value.
Example
class StringHandling
{
public static void main(String arg[])
{
char c;
String s=new String("Java");
c=s.charAt(2);
System.out.println("Character: "+c);
}
}
Output
Character: v
toUpperCase()
toUpperCase(): This method is use to convert lower case string into upper case.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java";
System.out.println("String: "+s.toUpperCase());
}
}
Output
String: JAVA
toLowerCase()
toLowerCase(): This method is used to convert upper case string into lower case.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="JAVA";
System.out.println("String: "+s.toLowerCase());
}
}
Output
String: java
concat()
concat(): This method is used to combine two strings.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Reddy";
System.out.println("Combined String: "+s1.concat(s2));
}
}
Output
Combined String: HiteshReddy
startsWith()
startsWith(): This method returns true if string starts with given another string, otherwise it
returns false.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.startsWith("Java"));
}
}
Output
true
endsWith()
endsWith(): This method returns true if string ends with given another string, otherwise it
returns false.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.endsWith("language"));
}
}
Output
true
substring()
substring(): This method is used to get the part of given string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8)); // 8 is starting index
}
}
Output
programming language
Example2
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8, 12));
}
}
Output
prog
indexOf()
indexOf(): This method is used find the index value of given string. It always gives starting
index value of first occurrence of string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.indexOf("programming"));
}
}
Output
8
lastIndexOf()
lastIndexOf(): This method used to return the starting index value of last occurence of the
given string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Java is programming language";
String s2="Java is programming language programming language";
System.out.println(s1.indexOf("programming"));
System.out.println(s2.lastIndexOf("programming"));
}
}
Output
8
29
trim()
trim(): This method remove space which are available before starting of string and after
ending of string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s=" Java is programming language ";
System.out.println(s.trim());
}
}
Output
Java is programming language
split()
split(): This method is used to divide the given string into number of parts based on delimiter
(special symbols like @ space , ).
Example
class StringHandling
{
public static void main(String arg[])
{
String s="contact@srecwarangal.ac.in";
String[] s1=s.split("@"); // divide string based on @
for(String c:s1) // foreach loop
{
System.out.println(c);
}
}
}
Output
contact
@srecwarangal.ac.in
replace()
replace(): This method is used to return a duplicate string by replacing old character with new
character.
Note: In this method data of original string will never be modify.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="java";
String s2=s1.replace('j', 'k');
System.out.println(s2);
}
}
Output
kava
String Comparison
String comparison can be done in 3 ways.
1. Using equals() method
2. Using == operator
3. By CompareTo() method
It compares the content of the strings. It will return true if string matches, else returns false.
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
s1.equals(s2); //true
s.equals(s1) ; //false
Using == operator
== operator compares two object references to check whether they refer to same instance.
This also, will return true on successful match.
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(s1 == s2) //true
test(s1 == s3) //false
Reason:
Its because we are creating a new object using new operator, and thus it gets created in a non-
pool memory area of the heap. s1 is pointing to the String in string pool while s3 is pointing
to the String in heap and hence, when we compare s1 and s3, the answer is false.
The following image will explain it more clearly.
By compareTo() method
compareTo() method compares values and returns an int which tells if the string compared is
less than, equal to or greater than the other string. It compares the String based on natural
ordering i.e alphabetically. Its general syntax is,
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
s1.compareTo(S2); //return -1 because s1 < s2
s1.compareTo(S3); //return 0 because s1 == s3
s2.compareTo(s1); //return 1 because s2 > s1
equalsIgnoreCase()
equalsIgnoreCase(): This method is case insensitive method, It return true if the contents of
both strings are same otherwise false.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="HITESH";
String s3="Raddy";
System.out.println("Compare String: "+s1.equalsIgnoreCase(s2));
System.out.println("Compare String: "+s1.equalsIgnoreCase(s3));
}
}
Output
Compare String: true
Compare String: false
compareToIgnoreCase()
compareToIgnoreCase(): This method is case insensitive method, which is used to compare
two strings similar to compareTo().
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="HITESH";
int i;
i=s1.compareToIgnoreCase(s2);
if(i==0)
{
System.out.println("Strings are same");
}
else
{
System.out.println("Strings are not same");
}
}
}
Output
Strings are same
StringBuffer class
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class
in java is same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since
JDK 1.5.
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given
position.
class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex to
endIndex.
class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
class StringBuilderExample6{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
class StringBuilderExample7{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
UNIT II
UNIT WISE PLAN
UNIT-II: Inheritance, Pakages and Inerfaces Planned Hours: 09
Blooms
S. No. Topic Learning Outcomes Cos
Levels
1 Demonstrate the implementation of inheritance (multilevel, CO3 L2
hierarchical and multiple) by using extend and implement
keywords.
2 Describe the concept of interface and abstract classes to CO2,CO3 L2
define generic classes.
3 Use dynamic and static polymorphism to process objects CO3 L3
depending on their class.
4 Illustrate different techniques on creating and accessing CO3 L3
packages (fully qualified name and import statements).
Inheritance in Java
The process of obtaining the data members and methods from one class to another class is
known as inheritance. It is one of the fundamental features of object-oriented programming.
Important points
In the inheritance the class which gives the data members and the methods is known
as base or super or parent class.
The class which is taking the data members and the methods is known as sub or
derived or child class.
The data members and methods of a class are known as features.
The concept of inheritance is also known as re-usability or extendable classes or sub
classing or derivation.
Syntax of Inheritance
class Subclass-Name extends Superclass-Name
{
//methods and fields
}
Real life example of inheritance
The real life example of inheritance is child and parents, all the properties of father are
inherited by his son.
Types of Inheritance
Based on number of ways inheriting the feature of base class into derived class we have five
types of inheritance; they are:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance
Single inheritance
In single inheritance there exists single base class and single derived class.
Example of Single Inheritance
class Faculty
{
float salary=30000;
}
class Science extends Faculty
{
float bonus=2000;
public static void main(String args[])
{
Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonus is:"+obj.bonus);
}
}
Output
Salary is: 30000.0
Bonus is: 2000.0
Hence all the above three inheritance types are supported by both classes and interfaces.
Example of Multilevel Inheritance
class Faculty
{
float total_sal=0, salary=30000;
}
The concept of multiple inheritance is not supported in java through concept of classes but it
can be supported through the concept of interface.
Hybrid inheritance
Combination of any inheritance type
In the combination if one of the combination is multiple inheritance then the inherited
combination is not supported by java through the classes concept but it can be supported
through the concept of interface.
Inheriting the feature from base class to derived class
In order to inherit the feature of base class into derived class we use the following syntax
Syntax
class ClassName-2 extends ClasssName-1
{
variable declaration;
Method declaration;
}
Explanation
1. ClassName-1 and ClassName-2 represents name of the base and derived classes
respectively.
2. extends is one of the keyword used for inheriting the features of base class into
derived class it improves the functionality of derived class.
Important Points for Inheritance:
In java programming one derived class can extends only one base class because java
programming does not support multiple inheritance through the concept of classes,
but it can be supported through the concept of Interface.
Whenever we develop any inheritance applications first create an object of bottom
most derived class but not for top most base class.
When we create an object of bottom most derived class, first we get the memory
space for the data members of top most base class, and then we get the memory space
for data member of other bottom most derived class.
Bottom most derived class contains logical appearance for the data members of all top
most base classes.
If we do not want to give the features of base class to the derived class then the
definition of the base class must be preceded by final hence final base classes are not
reusable or not inheritable.
If we are do not want to give some of the features of base class to derived class than
such features of base class must be as private hence private features of base class are
not inheritable or accessible in derived class.
Data members and methods of a base class can be inherited into the derived class but
constructors of base class cannot be inherited because every constructor of a class is
made for initializing its own data members but not made for initializing the data
members of other classes.
An object of base class can contain details about features of same class but an object
of base class never contains the details about special features of its derived class (this
concept is known as scope of base class object).
For each and every class in java there exists an implicit predefined super class called
java.lang.Object. Because it provides garbage collection facility to its sub classes for
collecting un-used memory space and improves the performance of java application.
Example of Inheritance
class Faculty
{
float salary=30000;
}
class Science extends Faculty
{
float bonus=2000;
public static void main(String args[])
{
Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonus is:"+obj.bonus);
}
}
Output
Salary is: 30000.0
Bonus is: 2000.0
Why multiple inheritance is not supported in java?
Due to ambiguity problem java does not support multiple inheritance at class level.
Example
class A
{
void disp()
{
System.out.println("Hello");
}
}
class B
{
void disp()
System.out.println("How are you ?");
}
}
class C extends A,B //suppose if it were
{
Public Static void main(String args[])
{
C obj=new C();
obj.disp();//Now which disp() method would be invoked?
}
}
In above code we call both class A and class B disp() method then it confusion which class
method is call. So due to this ambiguity problem in java do not use multiple inheritance at
class level, but it support at interface level.
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
Method overriding is used to provide the specific implementation of a method which
is already provided by its superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Example of method overriding
In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method are the same,
and there is IS-A relationship between the classes, so there is method overriding.
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike is running safely");
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Dynamic Method Dispatch or Runtime Polymorphism
Method overriding is one of the ways in which Java supports Runtime Polymorphism.
class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
3. Now we are assigning a reference to each type of object (either A’s or B’s or C’s) to
ref, one-by-one, and uses that reference to invoke m1( ). As the output shows, the
version of m1( ) executed is determined by the type of object being referred to at the
time of the call.
ref = a; // r refers to an A object
ref.m1(); // calling A's version of m1()
Super keyword
Super keyword in java is a reference variable that is used to refer parent class object. Super is
an implicit keyword created by JVM and supply each and every java program for performing
important role in three places
At variable level
At method level
At constructor level
Need of super keyword:
Whenever the derived class is inherits the base class features, there is a possibility that base
class features are similar to derived class features and JVM gets an ambiguity. In order to
differentiate between base class features and derived class features must be preceded by super
keyword.
Syntax
super.baseclass features.
Super at variable level:
Whenever the derived class inherits base class data members there is a possibility that base
class data member are similar to derived class data member and JVM gets an ambiguity.
In order to differentiate between the data member of base class and derived class, in the
context of derived class the base class data members must be preceded by super keyword.
Syntax
void display()
{
message();//will invoke or call current class message() method
super.message();//will invoke or call parent class message() method
}
void display()
{
message();//will invoke or call parent class message() method
}
super()
super() It is used for calling super class default constructor from the context of derived class
constructor.
Super keyword used to call base class constructor
class Employee
{
Employee()
{
System.out.println("Employee class Constructor");
}
}
class HR extends Employee
{
HR()
{
super(); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}
Output
super(….) (with parameters) it is used for calling super class parameterized constructor from
the context of derived class constructor explicitly.
class Person
{
int id;
String name;
Person(int id,String name)
{
this.id=id;
this.name=name;
}
}
class Emp extends Person
{
float salary;
Emp(int id,String name,float salary)
{
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display()
{
System.out.println(id+" "+name+" "+salary);
}
}
class TestSuper5
{
public static void main(String[] args)
{
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}
}
Note: When the super class has a parameterized constructor and if you want to use that
constructor in a sub class constructor, you have to call the super class constructor explicitly
otherwise the compiler reports an error.
Final keyword
It is used to make a variable as a constant, restrict a method from overriding, and can restrict
inheritance. In java language final keyword can be used in following way.
Final at variable level
Final at method level
Final at class level
}
class B extends A
{
public void fun1()
{
.......
}
public void fun2()
{
// it gives an error because we cannot override final method
}
}
Example of final keyword at method level
Example
class Employee
{
final void disp()
{
System.out.println("Hello Good Morning");
}
}
class Developer extends Employee
{
void disp()
{
System.out.println("How are you ?");
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
obj.disp();
}
}
Output
It gives an error
Final at class level
It makes a class final, meaning that the class cannot be inheriting by other classes. When we
want to restrict inheritance then make class as a final.
Example
public final class A
{
......
......
}
public class B extends A
{
// it gives an error, because we cannot inherit final class
}
Example of final keyword at class level
Example
final class Employee
{
int salary=10000;
}
class Developer extends Employee
{
void show()
{
System.out.println("Hello Good Morning");
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
Developer obj=new Developer();
obj.show();
}
}
Output
It gives an error
Abstraction
Abstraction is the concept of exposing only the required essential characteristics and behavior
with respect to a context.
Hiding of data is known as data abstraction. In object oriented programming language this is
implemented automatically while writing the code in the form of class and object.
Real Life Example of Abstraction in Java
Abstraction shows only important things to the user and hides the internal details, for
example, when we ride a bike, we only know about how to ride bikes but cannot know how it
work? And also we do not know the internal functionality of a bike.
Another real life example of Abstraction is ATM Machine; All are performing operations on
the ATM machine like cash withdrawal, money transfer, retrieve mini-statement…etc. but we
can't know internal details about ATM.
Note: Data abstraction can be used to provide security for the data from the unauthorized
methods.
Note: In Java language data abstraction can achieve using class.
Example of Abstraction
class Customer
{
int account_no;
float balance_Amt;
String name;
int age;
String address;
void balance_inquiry()
{
/* to perform balance inquiry only account number
is required that means remaining properties
are hidden for balance inquiry method */
}
void fund_Transfer()
{
/* To transfer the fund account number and
balance is required and remaining properties
are hidden for fund transfer method */
}
How to achieve Abstraction?
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (Achieve 100% abstraction)
Abstract class
We know that every Java program must start with a concept of class that is without the class
concept there is no Java program perfect.
In Java programming we have two types of classes they are
Concrete class
Abstract class
Concrete class in Java
A concrete class is one which is containing fully defined methods or implemented methods.
Example
class Helloworld
{
void display()
{
System.out.println("Good Morning........");
}
}
Here Helloworld class is containing a defined method and object can be created directly.
Create an object
Helloworld obj=new Helloworld();
obj.display();
Every concrete class has specific features and these classes are used for specific requirement,
but not for common requirement.
If we use concrete classes for fulfill common requirements than such application will get the
following limitations.
Application will take more amount of memory space (main memory).
Application execution time is more.
Application performance is decreased.
To overcome above limitation you can use abstract class.
Abstract class in Java
A class that is declared with abstract keyword is known as abstract class. An abstract class is
one which is containing some defined methods and some undefined methods. In java
programming undefined methods are known as un-implemented or abstract methods.
Syntax
abstract class className
{
......
}
Example
abstract class A
{
.....
}
If any class has any abstract method then that class becomes an abstract class.
Example
class Vahicle
{
abstract void Bike();
}
Class Vehicle is become an abstract class because it has abstract Bike() method.
Make class as abstract class
To make the class as abstract class, whose definition must be preceded by an abstract
keyword.
Example
abstract class Vehicle
{
......
}
Abstract method
An abstract method is one which contains only declaration or prototype but it never contains
body or definition. In order to make any undefined method as abstract whose declaration
must be predefined by abstract keyword.
Syntax
abstract ReturnType methodName(List of formal parameter)
Example
abstract void sum();
abstract void diff(int, int);
Example of abstract class
abstract class Vehicle
{
abstract void speed(); // abstract method
}
class Bike extends Vehicle
{
void speed()
{
System.out.println("Speed limit is 40 km/hr..");
}
public static void main(String args[])
{
Vachile obj = new Bike(); //indirect object creation
obj.speed();
}
}
Output
Speed limit is 40 km/hr..
Create an Object of abstract class
An object of abstract class cannot be created directly, but it can be created indirectly. It means
you can create an object of abstract derived class. You can see in above example
Example
Vachile obj = new Bike(); //indirect object creation
Important Points about abstract class
Abstract class of Java always contains common features.
Every abstract class participates in inheritance.
Abstract class definitions should not be made as final because abstract classes always
participate in inheritance classes.
An object of abstract class cannot be created directly, but it can be created indirectly.
All the abstract classes of Java makes use of polymorphism along with method
overriding for business logic development and makes use of dynamic binding for
execution logic.
Advantage of abstract class
Less memory space for the application
Less execution time
More performance
Why abstract classes have no abstract static method?
In abstract classes we have the only abstract instance method, but not containing abstract
static methods because every instance method is created for performing repeated operation
where as static method is created for performing a onetime operations in other word every
abstract method is instance but not static.
Abstract base class
An abstract base class is one which is containing physical representation of abstract methods
which are inherited by various sub classes.
Abstract derived class
An abstract derived class is one which is containing logic representation of abstract methods
which are inherited from abstract base class with respect to both abstract base class and
abstract derived class one cannot create objects directly, but we can create their objects
indirectly both abstract base class and abstract derived class are always reusable by various
sub classes.
When the derived class inherits multiple abstract methods from abstract base class and if the
derived class is not defined at least one abstract method then the derived class is known as
abstract derived class and whose definition must be made as abstract by using abstract
keyword
If the derived class defined all the abstract methods which are inherited from abstract Base
class, then the derived class is known as concrete derived class.
Example of abstract class having method body
abstract class Vehicle
{
abstract void speed();
void mileage()
{
System.out.println("Mileage is 60 km/ltr..");
}
}
class Bike extends Vehicle
{
void speed()
{
System.out.println("Speed limit is 40 km/hr..");
}
public static void main(String args[])
{
Vehicle obj = new Bike();
obj.speed();
obj.mileage();
}
}
Output
Mileage is 60 km/ltr..
Speed limit is 40 km/hr..
Example of abstract class having constructor, data member, methods
abstract class Vehicle
{
int limit=40;
Vehicle()
{
System.out.println("constructor is invoked");
}
void getDetails()
{
System.out.println("it has two wheels");
}
abstract void run();
}
Interface
Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract
methods in the interface. It is used to achieve fully abstraction and multiple inheritance in
Java.
Why we use Interface?
It is used to achieve fully abstraction.
By using Interface, you can achieve multiple inheritance in java.
It can be used to achieve loose coupling.
Properties of Interface
It is implicitly abstract. So we no need to use the abstract keyword when declaring an
interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
Methods in an interface are implicitly public.
All the data members of interface are implicitly public static final.
How interface is similar to class?
Whenever we compile any Interface program it generate .class file. That means the byte code
of an interface appears in a .class file.
How interface is different from class?
You cannot instantiate an interface.
It does not contain any constructors.
All methods in an interface are abstract.
Interface cannot contain instance fields. Interface only contains public static final
variables.
Interface is cannot extended by a class; it is implemented by a class.
Interface can extend multiple interfaces. It means interface support multiple
inheritance
Behavior of compiler with Interface program
In the above image when we compile any interface program, by default compiler added
public static final before any variable and public abstract before any method. Because
Interface is design for fulfill universal requirements and to achieve fully abstraction.
Declaring Interfaces:
The interface keyword is used to declare an interface.
Example
interface Person
{
datatype variablename=value;
//Any number of final, static fields
returntype methodname(list of parameters or no parameters)
//Any number of abstract method declarations
}
Explanations
In the above syntax Interface is a keyword interface name can be user defined name the
default signature of variable is public static final and for method is public abstract. JVM will
add implicitly public static final before data members and public abstract before methods.
Example
public static final datatype variable name=value; ----> for data member
public abstract returntype methodname(parameters)---> for method
Implementing Interfaces:
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
Example
interface Person
{
void run();
}
class Employee implements Person
{
public void run()
{
System.out.println("Run fast");
}
}
When we use abstract and when Interface
If we do not know about any things about implementation just we have requirement
specification then we should be go for Interface
If we are talking about implementation but not completely (partially implemented) then we
should be go for abstract
Rules for implementation interface
A class can implement more than one interface at a time.
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, similarly to the way that a class can extend
another class.
Relationship between class and Interface
Any class can extends another class
Packages
Purpose of package
The purpose of package concept is to provide common classes and interfaces for any
program separately. In other words if we want to develop any class or interface which is
common for most of the java programs than such common classes and interfaces must be
placed in a package.
Packages in Java are the way to organize files when a project has many modules.
Same like we organized our files in Computer. For example we store all movies in one folder
and songs in other folder, here also we store same type of files in a particular package for
example in awt package have all classes and interfaces for design GUI components.
Advantage of package
Package is used to categorize the classes and interfaces so that they can be easily
maintained
Application development time is less, because reuse the code
Application memory space is less (main memory)
Application execution time is less
Application performance is enhance (improve)
Redundancy (repetition) of code is minimized
Package provides access protection.
Package removes naming collision.
Types of package
Packages are classified into two types which are given below.
1. Predefined or built-in package
2. User defined package
Predefined or built-in package
These are the packages which are already designed by the Sun Microsystem and supply as a
part of java API, every predefined package is collection of predefined classes, interfaces and
sub-package.
User defined package
If any package is designed by the user that is known as a user defined package. User defined
package are those which are developed by java programmer and supply as a part of their
project to deal with common requirement.
Rules to create user defined package
package statement should be the first statement of any package program.
Choose an appropriate class name or interface name and whose modifier must be
public.
Any package program can contain only one public class or only one public interface
but it can contain any number of normal classes.
Package program should not contain any main class (that means it should not contain
any main())
modifier of constructor of the class which is present in the package must be public.
(This is not applicable in case of interface because interface has no constructor.)
The modifier of method of class or interface which is present in the package must be
public (This rule is optional in case of interface because interface methods by default
public)
Every package program should be save either with public class name or public
Interface name
UNIT III
UNIT WISE PLAN
UNIT-III: Exception Handling and Multi Threading Planned Hours: 09
Blooms
S. No. Topic Learning Outcomes Cos
Levels
1 Understand the impact of exception handling to avoid CO4 L2
abnormal termination of program using checked and
unchecked exceptions.
2 Demonstrate the user defined exceptions by exception CO4 L3
handling keywords ( try, catch, throw, throws and finally).
3 Use multithreading concepts to develop inter process CO4 L3
communication.
4 Understand and implement concepts on file streams and CO4 L2
operations in java programming for a given application
programs
1. try block
inside try block we write the block of statements which causes executions at run time in other
words try block always contains problematic statements.
Important points about try block
If any exception occurs in try block then CPU controls comes out to the try block and
executes appropriate catch block.
After executing appropriate catch block, even though we use run time statement, CPU
control never goes to try block to execute the rest of the statements.
Each and every try block must be immediately followed by catch block that is no
intermediate statements are allowed between try and catch block.
Syntax
try
{
.....
}
/* Here no other statements are allowed
between try and catch block */
catch()
{
....
}
Each and every try block must contains at least one catch block. But it is highly
recommended to write multiple catch blocks for generating multiple user friendly
error messages.
One try block can contains another try block that is nested or inner try block can be
possible.
Syntax
try
{
.......
try
{
.......
}
}
2. catch block
Inside catch block we write the block of statements which will generates user friendly error
messages.
catch block important points
Catch block will execute exception occurs in try block.
You can write multiple catch blocks for generating multiple user friendly error
messages to make your application strong. You can see below example.
At a time only one catch block will execute out of multiple catch blocks.
in catch block you declare an object of sub class and it will be internally referenced by
JVM.
Example without Exception Handling
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
ans=a/0;
System.out.println("Denominator not be zero");
}
}
Abnormally terminate program and give a message like below, this error message is not
understandable by user so we convert this error message into user friendly error message, like
"denominator not be zero".
3. finally block
Inside finally block we write the block of statements which will relinquish (released or close
or terminate) the resource (file or database) where data store permanently.
finally block important points
Finally block will execute compulsory
Writing finally block is optional.
You can write finally block for the entire java program
In some of the circumstances one can also write try and catch block in finally block.
Example
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.out.println("Denominator not be zero");
}
finally
{
System.out.println("I am from finally block");
}
}
}
Output
Denominator not be zero
I am from finally block
4. throw
throw is a keyword in java language which is used to throw any user defined exception to the
same signature of method in which the exception is raised.
Note: throw keyword always should exist within method body.
whenever method body contain throw keyword than the call method should be followed by
throws keyword.
Syntax
class className
{
returntype method(...) throws Exception_class
{
throw(Exception obj)
}
}
5. throws
throws is a keyword in java language which is used to throw the exception which is raised in
the called method to it's calling method throws keyword always followed by method
signature.
Example
returnType methodName(parameter)throws Exception_class....
{
.....
}
Difference between throw and throws
throw throws
throws is a keyword which gives an indication to
throw is a keyword used for hitting and
the specific method to place the common
1 generating the exception which are
exception methods as a part of try and catch block
occurring as a part of method body
for generating user friendly error messages
The place of using throw keyword is The place of using throws is a keyword is always
2
always as a part of method body. as a part of method heading
When we use throw keyword as a part of When we write throws keyword as a part of
method body, it is mandatory to the java method heading, it is optional to the java
3
programmer to write throws keyword as a programmer to write throw keyword as a part of
part of method heading method body.
Example of throw and throws
// save by DivZero.java
package pack;
// save by ArthException.java
import pack.DivZero;
import java.util.*;
class ArthException
{
public static void main(String args[])
{
System.out.println("Enter any two number: ");
Scanner s=new Scanner(System.in);
try
{
int a=s.nextInt();
int b=s.nextInt();
DivZero dz=new DivZero();
dz.division(a, b);
}
catch(Exception e)
{
System.err.println(e);
}
}
}
Compile: javac ArthException.java
Un-Checked Exception
Un-Checked Exception are the exception both identifies or raised at run time. These
exception are directly sub-class of java.lang.RuntimeException class.
Note: In real time application mostly we can handle un-checked exception.
Only for remember: Un-checked means not checked by compiler so un-checked exception are
checked at run-time not compile time.
If any exception is design by the user known as user defined or Custom Exception. Custom
Exception is created by user.
Rules to design user defined Exception
1. Create a package with valid user defined name.
2. Create any user defined class.
3. Make that user defined class as derived class of Exception or RuntimeException class.
4. Declare parametrized constructor with string variable.
5. call super class constructor by passing string variable within the derived class
constructor.
6. Save the program with public class name.java
Example
// save by AgeException.java
package nage;
import nage.AgeException;
import nage.CheckAge;
import java.util.*;
Multithreading in Java
Thread
Thread is a lightweight components and it is a flow of control. In other words a flow of
control is known as thread.
1. New : A
thread begins
its life cycle
in the new
state. It
remains in
this state until
the start()
method is
called on it.
2. Runnable : After invocation of start() method on new thread, the thread becomes
runnable.
3. Running : A thread is in running state if the thread scheduler has selected it.
4. Waiting : A thread is in waiting state if it waits for another thread to perform a task. In
this stage the thread is still alive.
5. Terminated : A thread enter the terminated state when it complete its task.
Thread Priorities
Every thread has a priority that helps the operating system determine the order in which
threads are scheduled for execution. In java thread priority ranges between 1 to 10,
MIN-PRIORITY (a constant of 1)
MAX-PRIORITY (a constant of 10)
By default every thread is given a NORM-PRIORITY(5). The main thread always have
NORM-PRIORITY.
Note: Thread priorities cannot guarantee that a higher priority thread will always be executed
first than the lower priority thread. The selection of the threads for execution depends upon
the thread scheduler which is platform dependent.
Thread Class
Thread class is the main class on which Java's Multithreading system is based. Thread class,
along with its companion interface Runnable will be used to create and run threads for
utilizing Multithreading feature of Java.
Result:
Initial Name of Thread:Thread-0
Initial Priority of Thread:5
Initial Daemon State of Thread:false
Initial Aliveness of Thread:false
Post Name of Thread:SREC
Post Priority of Thread:10
Post Daemon State of Thread:true
Post Aliveness of Thread:false
Creating a thread
Java defines two ways by which a thread can be created.
1. By implementing the Runnable interface.
2. By extending the Thread class.
class MyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
classMyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
}
}
Joining threads
Sometimes one thread needs to know when other thread is terminating.
In java, isAlive() and join()are two different methods that are used to check whether a thread
has finished its execution or not.
The isAlive() method returns true if the thread upon which it is called is still running
otherwise it returns false.
But, join() method is used more commonly than isAlive(). This method waits until the thread
on which it is called terminates.
Using join() method, we tell our thread to wait until the specified thread completes its
execution. There are overloaded versions of join() method, which allows us to specify time
for which you want to wait for the specified thread to terminate.
As we know, the main thread must always be the last thread to finish its execution, we can
use Thread join() method to ensure that all the threads created by the program has been
terminated before the execution of the main thread.
Example of thread without join() method
r1
r1
r2
r2
In this above program two thread t1 and t2 are created. t1 starts first and after printing "r1" on
console thread t1 goes to sleep for 500 ms. At the same time Thread t2 will start its process
and print "r1" on console and then go into sleep for 500 ms. Thread t1 will wake up from
sleep and print "r2" on console similarly thread t2 will wake up from sleep and print "r2" on
console. So you will get output like r1 r1 r2 r2
Example of thread with join() method
try{
t1.join(); //Waiting for t1 to finish
}catch(InterruptedException ie){}
t2.start();
}
}
r1
r2
r1
r2
In this above program join() method on thread t1 ensures that t1 finishes it process before
thread t2 starts.
t1.join(1500);
Doing so, initially t1 will execute for 1.5 seconds, after which t2 will join it.
Synchronization
At times when more than one thread try to access a shared resource, we need to ensure that
resource will be used by only one thread at a time. The process by which this is achieved is
called synchronization. The synchronization keyword in java creates a block of code referred
to as critical section.
General Syntax:
synchronized (object)
{
//statement to be synchronized
}
Every Java object with a critical section of code gets a lock associated with the object. To
enter critical section a thread need to obtain the corresponding object's lock.
class First
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}
Synchronized Keyword
To synchronize above program, we must synchronize access to the shared display() method,
making it available to only one thread at a time. This is done by using
keyword synchronized with display() method.
class First
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}
[welcome]
[new]
[programmer]
wait() is generaly used on condition sleep() method is simply used to put your thread
on sleep.
Thread Pooling
Pooling is usually implemented by loop i.e. to check some condition repeatedly. Once
condition is true appropriate action is taken. This wastes CPU time.
Deadlock
Deadlock is a situation of complete Lock, when no thread can complete its execution because
lack of resources. In the above picture, Thread 1 is holding a resource R1, and need another
resource R2 to finish execution, but R2 is locked by Thread 2, which needs R3, which in turn
is locked by Thread 3. Hence none of them can finish and are stuck in a deadlock.
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we
can suspend, resume or interrupt group of threads by a single method call.
Note: Now suspend(), resume() and stop() methods are deprecated.
Java thread group is implemented by java.lang.ThreadGroup class.
Constructors of ThreadGroup class
There are only two constructors of ThreadGroup class.
No. Constructor Description
1) ThreadGroup(String name) creates a thread group with given name.
ThreadGroup(ThreadGroup parent, String creates a thread group with given parent
2)
name) group and name.
Important methods of ThreadGroup class
There are many methods in ThreadGroup class. A list of important methods are given below.
No. Method Description
1) int activeCount() returns no. of threads running in current group.
2) int activeGroupCount() returns a no. of active group in this thread group.
3) void destroy() destroys this thread group and all its sub groups.
4) String getName() returns the name of this group.
5) ThreadGroup getParent() returns the parent of this group.
6) void interrupt() interrupts all threads of this group.
7) void list() prints information of this group to standard console.
Let's see a code to group multiple threads.
1. ThreadGroup tg1 = new ThreadGroup("Group A");
2. Thread t1 = new Thread(tg1,new MyRunnable(),"one");
3. Thread t2 = new Thread(tg1,new MyRunnable(),"two");
4. Thread t3 = new Thread(tg1,new MyRunnable(),"three");
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is
the class that implements Runnable interface and "one", "two" and "three" are the thread
names.
Now we can interrupt all threads by a single line of code only.
1. Thread.currentThread().getThreadGroup().interrupt();
ThreadGroup Example
File: ThreadGroupDemo.java
public class ThreadGroupDemo implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
}
}
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
System.out.print("finished");
}
}
3 Identify the output of the following Understand
program? class s1 implements Runnable
{
int x = 0, y = 0; int
addX()
{
x++;
return x;
}
int addY()
{
y++;
return y;
}
public void run()
{
for(int i = 0; i < 10; i++)
System.out.println(addX() + " " + addY());
}
public static void main(String args[])
{
s1 run2 = new s1();
Threadt1 = new Thread(run1);
Thread t2 =new Thread(run2);
t1.start();
t2.start();
}
4 Interpret the output of following program? Understand
class Exceptions
{
public static void main(String[] args)
{
String languages[] = { "C", "C++", "Java", "Perl",
"Python" }; try {
for (int c = 1; c <= 5; c++)
{
System.out.println(languages[c]);
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
5 Analyze the output of the below Understand
program? class Allocate
{
public static void main(String[] args)
{
try
{
long data[] = new long[1000000000];
}
catch (Exception e)
{
System.out.println(e);
}
Finally
{
System.out.println("finally block will execute always.");
}
}
}
6 Identify the output of the program? Understand
class MyThread extends Thread
{
public static void main(String [] args)
{
MyThread t = new MyThread();
Thread x = new Thread(t); x.start();
}
public void run()
{
for(int i = 0; i < 3; ++i)
{
System.out.print(i + "..");
}
}
}
7 Interpret the output of the program? Understand
public class RTExcept
{
public static void throwit ()
{
System.out.print("throwit ");
throw new RuntimeException();
}
public static void main(String [] args)
{
try
{
System.out.print("hello ");
throwit();
}
catch (Exception re )
{
System.out.print("caught ");
} finally
{
System.out.print("finally ");
}
System.out.println("after ");
}
}
8 Analyze the program and find the Remember
output public class NFE
{
public static void main(String [] args)
{
String s = "42"; try
{
s = s.concat(".5");
double d = Double.parseDouble(s);
s = Double.toString(d);
int x = (int) Math.ceil(Double.valueOf(s).doubleValue());
System.out.println(x);
}
catch (NumberFormatException e)
{
System.out.println("bad number");
}
}
}
9 Identify the output of the program? Understand
class MyThread extends Thread
{
MyThread()
{
System.out.print(" MyThread");
}
public void run()
{
System.out.print(" bar");
}
public void run(String s)
{
System.out.println(" baz");
}
}
public class TestThreads
{
public static void main (String [] args)
{
Thread t = new MyThread()
{
public void run()
{
System.out.println(" foo");
}
}
t.start();
}
}
10 Analyze the output of the program? Remember
class implements Runnable
{
int x, y;
public void run()
{
for(int i = 0; i < 1000; i++)
synchronized(this)
{
x = 12;
y = 12;
}
System.out.print(x + " " + y + " ");
}
public static void main(String args[])
{
s run = new s(); Thread
t1=new
Thread(run); Thread
t2=new Thread(run);
t1.start();
t2.start();
}
}
UNIT IV
UNIT WISE PLAN
UNIT-IV: Applets, Event Handling and AWT Planned Hours: 09
Blooms
S. No. Topic Learning Outcomes Cos
Levels
1 Understand the difference between Applications and CO5 L2
Applets
2 Develop applications with some event handling CO5 L6
3 Use AWT controls in GUI Programming CO5 L6
4 Use different layouts (Flow Layout, Boarder Layout, Grid CO5 L6
Layout, Card Layout) to position the controls for
developing graphical user interface applications.
Applet in Java
Applets are small Java applications that can be accessed on an Internet server,
transported over Internet, and can be automatically installed and run as a part of
a web document.
After a user receives an applet, the applet can produce a graphical user interface.
It has limited access to resources so that it can run complex computations without
introducing the risk of viruses or breaching data integrity.
Any applet in Java is a class that extends the java.applet.Applet class.
An Applet class does not have any main() method. It is viewed using JVM. The
JVM can use either a plug-in of the Web browser or a separate runtime
environment to run an applet application.
JVM creates an instance of the applet class and invokes init() method to initialize
an Applet.
A Simple Applet
import java.awt.*;
import java.applet.*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}
Every Applet application must import two packages - java.awt and java.applet.
java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the
user (either directly or indirectly) through the AWT. The AWT contains support for a
window-based, graphical user interface. java.applet.* imports the applet package, which
contains the class Applet. Every applet that you create must be a subclass of Applet
class.
The class in the program must be declared as public, because it will be accessed by code
that is outside the program. Every Applet application must declare a paint() method.
This method is defined by AWT class and must be overridden by the applet. The paint()
method is called each time when an applet needs to redisplay its output. Another
important thing to notice about applet application is that, execution of an applet does
not begin at main() method. In fact an applet application does not have any main()
method.
Advantages of Applets
1. It takes very less response time as it works on the client side.
2. It can be run on any browser which has JVM running in it.
Differences between Applets and Applications
An applet runs under the control of a browser, whereas an application runs stand-alone,
with the support of a virtual machine. As such, an applet is subjected to more stringent
security restrictions in terms of file and network access, whereas an application can
have free reign over these resources.
Applets are great for creating dynamic and interactive web applications, but the true
power of Java lies in writing full blown applications. With the limitation of disk and
network access, it would be difficult to write commercial applications (though through
the user of server based file systems, not impossible). However, a Java application has
full network and local file system access, and its potential is limited only by the
creativity of its developers.
Types of Applets: Web pages can contain two types of applets which are named after
the location at which they are stored.
1. Local Applet
2. Remote Applet
Local Applets: A local applet is the one that is stored on our own computer system.
When the Web-page has to find a local applet, it doesn't need to retrieve information
from the Internet. A local applet is specified by a path name and a file name as shown
below in which the codebase attribute specifies a path name, whereas the code attribute
specifies the name of the byte-code file that contains the applet's code.
<applet codebase="MyAppPath" code="MyApp.class" width=200 height=200> </applet>
Remote Applets: A remote applet is the one that is located on a remote computer
system. This computer system may be located in the building next door or it may be on
the other side of the world. No matter where the remote applet is located, it's downloaded
onto our computer via the Internet. The browser must be connected to the Internet at
the time it needs to display the remote applet. To reference a remote applet in Web page,
we must know the applet's URL (where it's located on the Web) and any attributes and
parameters that we need to supply. A local applet is specified by a url and a file name as
shown below.
<applet codebase="http://www.srecwarangal.ac.in" code="MyApp.class" width=200
height=200> </applet>
Applet class
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provides methods that load and display images and methods
that load and play audio clips.
Applet Class Hierarchy
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
Life cycle of applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1
life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser
is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
Note: The stop() method is always called before destroy() method.
Running of applet programs
Applet program can run in two ways.
Using html (in the web browser)
Using appletviewer tool (in applet window)
Running of applet using html
In general no java program can directly execute on the web browser except markup language
like
html, xml etc.
Html supports a predefined tag called <applet> to load the applet program on the browser
window.
Example of applet program to run applet using html
Java code, JavaApp.java
import java.applet.*;
import java.awt.*;
public class JavaApp extends Applet
{
public void paint(Graphics g)
{
Font f=new Font("Arial",Font.BOLD,30);
g.setFont(f);
setForeground(Color.red);
setBackground(Color.white);
g.drawString("Student",200,200);
}
}
Html code, myapplet.html
<html>
<title> AppletEx</Title>
<body>
<applet code="JavaApp.class"
height="70%"
width="80%">
</applet>
</body>
</html>
Running of applet using appletviewer
Some browser does not support <applet> tag so that Sun MicroSystem was introduced a
special
tool called appletviewer to run the applet program.
In this Scenario java program should contains <applet> tag in the commented lines so that
appletviewer tools can run the current applet program.
Example of Applet
import java.applet.*;
import java.awt.*;
/*<applet code="LifeApp.class" height="500",width="800">
</applet>*/
public class LifeApp extends Applet
{
String s= " ";
public void init()
{
s=s+ " int ";
}
public void start()
{
s=s+ "start ";
}
public void stop()
{
s=s+ "stop ";
}
public void destroy()
{
s=s+ " destory ";
}
public void paint(Graphics g)
{
Font f=new Font("Arial",Font.BOLD,30);
setBackgroundColor(Color."red");
g.setFont(f);
g.drawString(s,200,250);
}
}
Execution of applet program
javac LifeApp.java
appletviewer LifeApp.java
Note: init() always execute only once at the time of loading applet window and also it will be
executed if applet is restarted.
Passing Parameter in Java Applet
Java applet has the feature of retrieving the parameter values passed from the html page. So,
you can pass the parameters from your html page to the applet embedded in your page. The
param tag(<param name="" value=""></param>) is used to pass the parameters to an applet.
For
the illustration about the concept of applet and passing parameter in applet, a example is
given
below.
In this example, we will see what has to be done in the applet code to retrieve the value from
parameters. Value of a parameter passed to an applet can be retrieved using getParameter()
function. E.g. code:
String strParameter = this.getParameter("Message");
Printing the value:
Then in the function paint (Graphics g), we prints the parameter value to test the value passed
from html page. Applet will display "Hello! Java Applet”. if no parameter is passed to the
applet
else it will display the value passed as parameter. In our case applet should display "Welcome
in
Passing parameter in java applet example." message.
Here is the code for the Java Program :
import java.applet.*;
import java.awt.*;
public class appletParameter extends Applet
{
private String strDefault = "Hello! Java Applet.";
public void paint(Graphics g)
{
String strParameter = this.getParameter("Message");
if (strParameter == null)
strParameter = strDefault;
g.drawString(strParameter, 50, 25);
}
}
Here is the code for the html program:
<html>
<head>
<title>passing parameter in java applet</title>
</head>
<body>
this is the applet:<p>
<applet code="appletParameter.class" width="800" height="100">
<param name="message" value="welcome in passing parameter in java applet example.">
</applet>
</body>
</html>
There is the advantage that if need to change the output then you will have to change only the
value of the param tag in html file not in java code.
Compile the program:
javac appletParameter.java
Output after running the program:
To run the program using appletviewer, go to command prompt and type appletviewer
appletParameter.html Appletviewer will run the applet for you and and it should show output
like
Welcome in Passing parameter in java applet example. Alternatively you can also run this
example
from your favorite java enabled browser.
Event Handling
Any program that uses GUI (graphical user interface) such as Java application written
for windows, is event driven.
Event describes the change in state of any object.
For Example: Pressing a button, entering a character in Textbox, Clicking or dragging a
mouse, etc.
Java uses the Delegation Event model technique to handle events in GUI (Graphical
User Interface), which has the following components and process of event
handling.
Components of Event Handling
Event handling has three main components,
● Event: An event is a change in state of an object.
● Events Source: Event source is an object that generates an event.
● Event Listener: A listener is an object that listens to the event. A listener gets
notified when an event occurs.
How Events are handled?
A source generates an Event and sends it to one or more listeners registered with the
source. Once event is received by the listener, they process the event and then return.
Events are supported by a number of Java packages, like java.util, java.awt and
java.awt.event.
Important Event Classes and Interface
Event Classes Description Listener Interface
ActionEvent generated when button is pressed, menuitem
is selected, list-item is double clicked ActionListener
MouseEvent
generated when mouse is dragged,
moved,clicked,pressed or released and also
when it enters or exit a component
MouseListener
KeyEvent generated when input is received from
keyboard KeyListener
ItemEvent generated when check-box or list item is
clicked ItemListener
TextEvent generated when value of textarea or
textfield is changed TextListener
MouseWheelEvent generated when mouse wheel is moved MouseWheelListener
WindowEvent
generated when window is activated,
deactivated, deiconified, iconified, opened
or closed
WindowListener
ComponentEvent generated when component is hidden,
moved, resized or set visible ComponentEventListener
ContainerEvent generated when component is added or
removed from container ContainerListener
AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener
FocusEvent generated when component gains or loses
keyboard focus FocusListener
Example of Key Event Handling
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Test extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
HTML code :
< applet code="Test" width=300, height=100 ></applet>
Example of Mouse Event Handling
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse" width=500 height=500>
</applet>
*/
public class Mouse extends Applet
implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="S R";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="Engineering";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="College";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse Moved"+m.getX()+" "+m.getY());
repaint();
}
public void mouseClicked(MouseEvent m)
{
msg="Students";
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Adapter classes
Java adapter classes provide the default implementation of listener interfaces. If you
inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event
packages. The Adapter classes with their corresponding listener interfaces are given
below
java.awt.event Adapter classes
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
Adapter Class Example
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="AdapterDemo" width=300 height=300>
</applet>*/
public class AdapterDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo ad;
public MyMouseAdapter(AdapterDemo ad)
{
this.ad=ad;
}
public void mouseClicked(MouseEvent me)
{
ad.showStatus("Mouse Clicked");
}
}
What if you don't want your event-handling class to inherit from an adapter class? For
example, suppose you write an applet, and you want your Applet subclass to contain
some code to handle mouse events. Since the Java language doesn't permit multiple
inheritance, your class can't extend both the Applet and MouseAdapter classes. The
solution is to define an inner class -- a class inside of your Applet subclass -- that
extends the MouseAdapter class,
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="InnerClassDemo" width=300 height=300>
</applet>*/
public class InnerClassDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
}
}
}
Inner classes work well even if your event handler needs access to private instance
variables from the enclosing class. As long as you don't declare an inner class to be
static, an inner class can refer to instance variables and methods just as if its code is in
the containing class.
Anonymous classes enable you to make your code more concise. They enable you to
declare and instantiate a class at the same time. They are like local classes except that
they do not have a name.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="AnonymousInnerClassDemo" width=300 height=300>
</applet>*/
public class AnonymousInnerClassDemo extends Applet
{
public void init()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
}
});
}
}
AWT
Controls are components that allow a user to interact with your application in various ways—
for example; a commonly used control is the push button.
Control Fundamentals
The AWT supports the following types of controls:
• Labels
• Push buttons
• Check boxes
• Choice lists
• Lists
Scroll bars
• Text editing
These controls are subclasses of Component.
Adding and Removing Controls
To include a control in a window, you must add it to the window. To do this, you must first
create an instance of the desired control and then add it to a window by calling add( ), which
is defined by Container. The add( ) method has several forms. It has this general form:
Component add(Component compObj)
Here, compObj is an instance of the control that you want to add. A reference to
compObj is returned. Once a control has been added, it will automatically be visible
whenever its parent window is displayed.
Sometimes you will want to remove a control from a window when the control is no longer
needed. To do this, call remove( ). This method is also defined by Container. It has this
general form:
void remove(Component obj)
Here, obj is a reference to the control you want to remove. You can remove all controls by
calling removeAll( ).
Responding to Controls
Except for labels, which are passive, all controls generate events when they are
accessed by the user. For example, when the user clicks on a push button, an event is sent that
identifies the push button. In general, your program simply implements the appropriate
interface and then registers an event listener for each control that you need to monitor. Once a
listener has been installed, events are automatically sent to it.
Labels
The easiest control to use is a label. A label is an object of type Label, and it contains a string,
which it displays. Labels are passive controls that do not support any interaction with the
user. Label defines the following constructors:
Label( ) throws HeadlessException
Label(String str) throws HeadlessException
Label(String str, int how) throws HeadlessException
The first version creates a blank label. The second version creates a label that contains the
string specified by str. This string is left-justified. The third version creates a label that
contains the string specified by str using the alignment specified by how. The value of how
must be one of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.
You can set or change the text in a label by using the setText( ) method. You can obtain the
current label by calling getText( ). These methods are shown here:
void setText(String str)
String getText( )
For setText( ), str specifies the new label. For getText( ), the current label is returned.You can
set the alignment of the string within the label by calling setAlignment( ).To obtain the
current alignment, call getAlignment( ). The methods are as follows:
void setAlignment(int how)
int getAlignment( )
Here, how must be one of the alignment constants shown earlier.
The following example creates three labels and adds them to an applet window:
// Demonstrate Labels
import java.awt.*;
import java.applet.*;
/*
<applet code="LabelDemo" width=300 height=200>
</applet>
*/
public class LabelDemo extends Applet {
public void init() {
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
// add labels to applet window
add(one);
add(two);
add(three);
}
}
Here is the window created by the LabelDemo applet.
Buttons
A push button is a component that contains a label and that generates an event when it is
pressed. Push buttons are objects of type Button. Button defines these two constructors:
Button( ) throws HeadlessException
Button(String str) throws HeadlessException
The first version creates an empty button. The second creates a button that contains str as a
label.
After a button has been created, you can set its label by calling setLabel( ). You can retrieve
its label by calling getLabel( ). These methods are as follows:
void setLabel(String str)
String getLabel( )
Here, str becomes the new label for the button.
Handling Buttons
Each time a button is pressed, an action event is generated. This is sent to any
listeners that previously registered an interest in receiving action event notifications from that
component. Each listener implements the ActionListener interface. That interface defines the
actionPerformed( ) method, which is called when an event occurs. An ActionEvent object is
supplied as the argument to this method. It contains both a reference to the button that
generated the event and a reference to the action command string associated with the button.
By default, the action command string is the label of the button. Usually, either the
button reference or the action command string can be used to identify the button. (You will
soon see examples of each approach.)
Here is an example that creates three buttons labeled “Yes”, “No”, and “Undecided”.
Each time one is pressed, a message is displayed that reports which button has been pressed.
In this version, the action command of the button (which, by default, is its label) is used to
determine which button has been pressed. The label is obtained by calling the
getActionCommand( ) method on the ActionEvent object passed to actionPerformed( ).
// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/
public class ButtonDemo extends Applet implements ActionListener {
String msg = "";
Button yes, no, maybe;
public void init() {
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
}
}
Sample output from the ButtonDemo program is shown in Figure below
.
As mentioned, in addition to comparing button action command strings, you can also
determine which button has been pressed, by comparing the object obtained from the
getSource( ) method to the button objects that you added to the window. To do this, you must
keep a list of the objects when they are added. The following applet shows this approach:
// Recognize Button objects.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonList" width=250 height=150>
</applet>
*/
public class ButtonList extends Applet implements ActionListener {
String msg = "";
Button bList[] = new Button[3];
public void init() {
Button yes = new Button("Yes");
Button no = new Button("No");
Button maybe = new Button("Undecided");
// store references to buttons as added
bList[0] = (Button) add(yes);
bList[1] = (Button) add(no);
bList[2] = (Button) add(maybe);
// register to receive action events
for(int i = 0; i < 3; i++) {
bList[i].addActionListener(this);
}
}
public void actionPerformed(ActionEvent ae) {
for(int i = 0; i < 3; i++) {
if(ae.getSource() == bList[i]) {
msg = "You pressed " + bList[i].getLabel();
}
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
}
}
In this version, the program stores each button reference in an array when the buttons
are added to the applet window. (Recall that the add( ) method returns a reference to the
button when it is added.) Inside actionPerformed( ), this array is then used to determine
which button has been pressed.
For simple programs, it is usually easier to recognize buttons by their labels.
However,in situations in which you will be changing the label inside a button during the
execution of your program, or using buttons that have the same label, it may be easier to
determine which button has been pushed by using its object reference. It is also possible to
set the action command string associated with a button to something other than its label by
calling setActionCommand( ). This method changes the action command string, but does not
affect the string used to label the button. Thus, setting the action command enables the action
command and the label of a button to differ.
Check Boxes
A check box is a control that is used to turn an option on or off. It consists of a small box that
can either contain a check mark or not. There is a label associated with each check box that
describes what option the box represents. You change the state of a check box by clicking on
it. Check boxes can be used individually or as part of a group. Check boxes are objects of the
Checkbox class.
Checkbox supports these constructors:
Checkbox( ) throws HeadlessException
Checkbox(String str) throws HeadlessException
Checkbox(String str, boolean on) throws HeadlessException
Checkbox(String str, boolean on, CheckboxGroup cbGroup) throws HeadlessException
Checkbox(String str, CheckboxGroup cbGroup, boolean on) throws HeadlessException
The first form creates a check box whose label is initially blank. The state of the check box is
unchecked. The second form creates a check box whose label is specified by str. The state of
the check box is unchecked. The third form allows you to set the initial state of the check
box. If on is true, the check box is initially checked; otherwise, it is cleared. The fourth and
fifth forms create a check box whose label is specified by str and whose group is specified by
cbGroup. If this check box is not part of a group, then cbGroup must be null. (Check box
groups are described in the next section.) The value of on determines the initial state of the
check box.
To retrieve the current state of a check box, call getState( ). To set its state, call
setState( ). You can obtain the current label associated with a check box by calling
getLabel( ). To set the label, call setLabel( ). These methods are as follows:
boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
Here, if on is true, the box is checked. If it is false, the box is cleared. The string passed in str
becomes the new label associated with the invoking check box.
CheckboxGroup
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 calling
getSelectedCheckbox( ). You can set a check box by calling setSelectedCheckbox( ).
These methods are as follows:
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)
Here, which is the check box that you want to be selected. The previously selected check box
will be turned off.
Here is a program that uses check boxes that are part of a group:
// Demonstrate check box group.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CBGroup" width=250 height=200>
</applet>
*/
public class CBGroup extends Applet implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
CheckboxGroup cbg;
public void init() {
cbg = new CheckboxGroup();
winXP = new Checkbox("Windows XP", cbg, true);
winVista = new Checkbox("Windows Vista", cbg, false);
solaris = new Checkbox("Solaris", cbg, false);
mac = new Checkbox("Mac OS", cbg, false);
add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the checkboxes.
public void paint(Graphics g) {
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}
}
Output generated by the CBGroup applet is shown in Figure. Notice that the checkboxes are
now circular in shape.
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( ) throws HeadlessException
TextField(int numChars) throws HeadlessException
TextField(String str) throws HeadlessException
TextField(String str, int numChars) throws HeadlessException
The first version creates a default text field. The second form creates a text field that is
numChars characters wide. The third form initializes the text field with the string contained
in str. The fourth form initializes a text field and sets its width.
TextField (and its superclass TextComponent) provides several methods that allow you
to utilize a text field. To obtain the string currently contained in the text field, call getText( ).
To set the text, call setText( ). These methods are as follows:
String getText( )
void setText(String str)
Here, str is the new string.
The user can select a portion of the text in a text field. Also, you can select a portion of text
under program control by using select( ). Your program can obtain the currently selected text
by calling getSelectedText( ). These methods are shown here:
String getSelectedText( )
void select(int startIndex, int endIndex)
getSelectedText( ) returns the selected text. The select( ) method selects the characters
beginning at startIndex and ending at endIndex–1. You can control whether the contents of a
text field may be modified by the user by calling setEditable( ). You can determine editability
by calling isEditable( ). These methods are shown here:
boolean isEditable( )
void setEditable(boolean canEdit)
isEditable( ) returns true if the text may be changed and false if not. In setEditable( ), if
canEdit is true, the text may be changed. If it is false, the text cannot be altered. There may be
times when you will want the user to enter text that is not displayed, such as a password. You
can disable the echoing of the characters as they are typed by calling setEchoChar( ). This
method specifies a single character that the TextField will display when characters are entered
(thus, the actual characters typed will not be shown). You can check a text field to see if it is
in this mode with the echoCharIsSet( ) method. You can retrieve the echo character by calling
the getEchoChar( ) method. These methods are as follows:
void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( )
Here, ch specifies the character to be echoed.
Handling a TextField
Since text fields perform their own editing functions, your program generally will not
respond to individual key events that occur within a text field. However, you may want to
respond when the user presses ENTER. When this occurs, an action event is generated.
Here is an example that creates the classic user name and password screen:
// Demonstrate text field.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="TextFieldDemo" width=380 height=150>
</applet>
*/
public class TextFieldDemo extends Applet
implements ActionListener {
TextField name, pass;
public void init() {
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep);
add(name);
add(passp);
add(pass);
// register to receive action events
name.addActionListener(this);
pass.addActionListener(this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae) {
repaint();
}
public void paint(Graphics g) {
g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: "
+ name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6, 100);
}
}
Sample output from the TextFieldDemo applet is shown in Figure
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( ) throws HeadlessException
TextArea(int numLines, int numChars) throws HeadlessException
TextArea(String str) throws HeadlessException
TextArea(String str, int numLines, int numChars) throws HeadlessException
TextArea(String str, int numLines, int numChars, int sBars) throws HeadlessException
Here, numLines specifies the height, in lines, of the text area, and numChars specifies
its width,in characters. Initial text can be specified by str. In the fifth form, you can specify
the scroll
bars that you want the control to have. sBars must be one of these values:
SCROLLBARS_BOTH SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_VERTICAL_ONLY
TextArea is a subclass of TextComponent. Therefore, it supports the getText( ), setText( ),
getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described in the
preceding section.
TextArea adds the following methods:
void append(String str)
void insert(String str, int index)
void replaceRange(String str, int startIndex, int endIndex)
The append( ) method appends the string specified by str to the end of the current text. insert(
)
inserts the string passed in str at the specified index. To replace text, call replaceRange( ). It
replaces the characters from startIndex to endIndex–1, with the replacement text passed in
str.
Text areas are almost self-contained controls. Your program incurs virtually no management
overhead. Text areas only generate got-focus and lost-focus events.Normally, your program
simply obtains the current text when it is needed.
The following program creates a TextArea control:
// Demonstrate TextArea.
import java.awt.*;
import java.applet.*;
/*
<applet code="TextAreaDemo" width=300 height=250>
</applet>
*/
public class TextAreaDemo extends Applet {
public void init() {
String val =
"Java SE 6 is the latest version of the most\n" +
"widely-used computer language for Internet programming.\n" +
"Building on a rich heritage, Java has advanced both\n" +
"the art and science of computer language design.\n\n" +
"One of the reasons for Java's ongoing success is its\n" +
"constant, steady rate of evolution. Java has never stood\n" +
"still. Instead, Java has consistently adapted to the\n" +
"rapidly changing landscape of the networked world.\n" +
"Moreover, Java has often led the way, charting the\n" +
"course for others to follow.";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}
public void init() {
String val =
"Java SE 6 is the latest version of the most\n" +"widely-used computer language for Internet
programming.\n" + "Building on a rich heritage, Java has advanced both\n" + "the art and
science of computer language design.\n\n" +"One of the reasons for Java's ongoing success
is its\n" +"constant, steady rate of evolution. Java has never stood\n" +"still. Instead, Java
has consistently adapted to the\n" +
"rapidly changing landscape of the networked world.\n" +"Moreover, Java has often led the
way, charting the\n" +"course for others to follow.";
TextArea text = new TextArea(val, 10, 30);
add(text);
}}
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 takes
up 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.
To add a selection to the list, call add( ). It has this general form:
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( ) occur. To determine which item is currently selected, you may call either
getSelectedItem( ) or getSelectedIndex( ). These methods are shown here:
String getSelectedItem( )
int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the item.
getSelectedIndex( ) returns the index of the item. The first item is at index 0. By default,the
first item added to the list is selected.To obtain the number of items in the list, call
getItemCount( ). You can set the currently selected item using the select( ) method with either
a zero-based integer index or a string that will match a name in the list. These methods are
shown here:
int getItemCount( )
void select(int index)
void select(String name)
Given an index, you can obtain the name associated with the item at that index by
calling getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
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( ) throws HeadlessException
List(int numRows) throws HeadlessException
List(int numRows, boolean multipleSelect) throws HeadlessException
The first version creates a List control that allows only one item to be selected at any one
time. In the second form, the value of numRows specifies the number of entries in the list that
will always be visible (others can be scrolled into view as needed). In the third form, if
multipleSelect 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.To add a selection to the list, call add( ). It has the following
two forms:
void add(String name)
void add(String name, int index)
Here, name is the name of the item added to the list. The first form adds items to the end of
the list. The second form adds the item at the index specified by index. Indexing begins at
zero. You can specify –1 to add the item to the end of the list. For lists that allow only single
selection, you can determine which item is currently selected by calling either
getSelectedItem( ) or getSelectedIndex( ). These methods are shown here:
String getSelectedItem( )
int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the item. If more than
one item is selected, or if no selection has yet been made, null is returned. getSelectedIndex( )
returns the index of the item. The first item is at index 0. If more than one item is selected, or
if no selection has yet been made, –1 is returned. For lists that allow multiple selection, you
must use either getSelectedItems( ) or
getSelectedIndexes( ), shown here, to determine the current selections:
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
getSelectedItems( ) returns an array containing the names of the currently selected
items.getSelectedIndexes( ) returns an array containing the indexes of the currently selected
items. To obtain the number of items in the list, call getItemCount( ). You can set the
currently selected item by using the select( ) method with a zero-based integer index. These
methods are shown here:
int getItemCount( )
void select(int index)
Given an index, you can obtain the name associated with the item at that index by
calling getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
Handling Lists
To process list events, you will need to implement the ActionListener interface. Each time a
List item is double-clicked, an ActionEvent object is generated. Its getActionCommand( )
method can be used to retrieve the name of the newly selected item. Also, each time an item
is selected or deselected with a single click, an ItemEvent object is generated. Its
getStateChange( ) method can be used to determine whether a selection or deselection
triggered this event. getItemSelectable( ) returns a reference to the object that triggered this
event.Here is an example that converts the Choice controls in the preceding section into List
components, one multiple choice and the other single choice:
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ListDemo" width=300 height=180>
</applet>
*/
public class ListDemo extends Applet implements ActionListener {
List os, browser;
String msg = "";
public void init() {
os = new List(4, true);
browser = new List(4, false);
// add items to os list
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
browser.select(1);
// add lists to window
add(os);
add(browser);
// register to receive action events
os.addActionListener(this);
browser.addActionListener(this);
}
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]) + " ";
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
Sample output generated by the ListDemo applet is shown in Figure
FlowLayout
FlowLayout is the default layout manager. FlowLayout implements a simple layout
style, which is similar to how words flow in a text editor. The direction of the layout is
governed by the container’s component orientation property, which, by default, is left to right,
top to bottom. Therefore, by default, components are laid out line-by-line beginning at the
upper-left corner. In all cases, when a line is filled, layout advances to the next line. A small
space is left between each component, above and below, as well as left and right. Here are the
constructors for FlowLayout:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centers components and leaves five
pixels of space between each component. The second form lets you specify how each line is
aligned.Valid values for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING
These values specify left, center, right, leading edge, and trailing edge alignment,
respectively.
The third constructor allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.
// Use left-aligned flow layout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="FlowLayoutDemo" width=250 height=200>
</applet>
*/
public class FlowLayoutDemo extends Applet
implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
public void init() {
// set left-aligned flow layout
setLayout(new FlowLayout(FlowLayout.LEFT));
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
add(solaris);
add(mac);
// register to receive item events
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
// Repaint when status of a check box changes.
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();
g.drawString(msg, 6, 160);
}
}
Here is sample output generated by the FlowLayoutDemo applet.
BorderLayout
The BorderLayout class implements a common layout style for top-level windows. It
has four narrow, fixed-width components at the edges and one large area in the center. The
four sides are referred to as north, south, east, and west. The middle area is called the center.
Here are the constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)
The first form creates a default border layout. The second allows you to specify the horizontal
and vertical space left between components in horz and vert, respectively.BorderLayout
defines the following constants that specify the regions:
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
When adding components, you will use these constants with the following form of add( ),
which is defined by Container:
void add(Component compObj, Object region)
Here, compObj is the component to be added, and region specifies where the component will
be added.
Here is an example of a BorderLayout with a component in each layout area:
// Demonstrate BorderLayout.
import java.awt.*;
import java.applet.*;
import java.util.*;
/*
<applet code="BorderLayoutDemo" width=400 height=200>
</applet>
*/
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("This is across the top."),
BorderLayout.NORTH);
add(new Label("The footer message might go here."),
BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg = "The reasonable man adapts " +
"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLayout.CENTER);
}
}
Sample output from the BorderLayoutDemo applet is shown here:
GridLayout
GridLayout lays out components in a two-dimensional grid. When you instantiate a
GridLayout, you define the number of rows and columns. The constructors supported by
GridLayout are shown here:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
The first form creates a single-column grid layout. The second form creates a grid layout with
the specified number of rows and columns. The third form allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively. Either
numRows or numColumns can be zero. Specifying numRows as zero allows for unlimited-
length columns.Specifying numColumns as zero allows for unlimited-length rows.
Here is a sample program that creates a 4×4 grid and fills it in with 15 buttons, each
labeled with its index:
// Demonstrate GridLayout
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=300 height=200>
</applet>
*/
public class GridLayoutDemo extends Applet {
static final int n = 4;
public void init() {
setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
}
}
}
}
Following is the output generated by the GridLayoutDemo applet:
CardLayout
The CardLayout class is unique among the other layout managers in that it stores
several different layouts. Each layout can be thought of as being on a separate index card in a
deck that can be shuffled so that any card is on top at a given time. This can be useful for user
interfaces with optional components that can be dynamically enabled and disabled upon user
input. You can prepare the other layouts and have them hidden, ready to be activated when
needed.CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
The first form creates a default card layout. The second form allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.Use of a
card layout requires a bit more work than the other layouts. The cards are typically held in an
object of type Panel. This panel must have CardLayout selected as its layout manager. The
cards that form the deck are also typically objects of type Panel. Thus, you must create a
panel that contains the deck and a panel for each card in the deck. Next, you add to the
appropriate panel the components that form each card. You then add these panels to the panel
for which CardLayout is the layout manager. Finally, you add this panel to the window. Once
these steps are complete, you must provide some way for the user to select between cards.
One common approach is to include one push button for each card in the deck.When card
panels are added to a panel, they are usually given a name. Thus, most ofthe time, you will
use this form of add( ) when adding cards to a panel:
void add(Component panelObj, Object name)
Here, name is a string that specifies the name of the card whose panel is specified by
anelObj.After you have created a deck, your program activates a card by calling one of the
following methods defined by CardLayout:
void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)
Here, deck is a reference to the container (usually a panel) that holds the cards, and
cardName is the name of a card. Calling first( ) causes the first card in the deck to be shown.
To show the last card, call last( ). To show the next card, call next( ). To show the previous
card, call previous( ). Both next( ) and previous( ) automatically cycle back to the top or
bottom of the deck, respectively. The show( ) method displays the card whose name is passed
in cardName. The following example creates a two-level card deck that allows the user to
select an operating system. Windows-based operating systems are displayed in one card.
Macintosh and Solaris are displayed in the other card.
// Demonstrate CardLayout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CardLayoutDemo" width=300 height=100>
</applet>
*/
public class CardLayoutDemo extends Applet
implements ActionListener, MouseListener {
Checkbox winXP, winVista, solaris, mac;
Panel osCards;
CardLayout cardLO;
Button Win, Other;
public void init() {
Win = new Button("Windows");
Other = new Button("Other");
add(Win);
add(Other);
cardLO = new CardLayout();
osCards = new Panel();
osCards.setLayout(cardLO); // set panel layout to card layout
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
// add Windows check boxes to a panel
Panel winPan = new Panel();
winPan.add(winXP);
winPan.add(winVista);
// add other OS check boxes to a panel
Panel otherPan = new Panel();
otherPan.add(solaris);
otherPan.add(mac);
// add panels to card deck panel
osCards.add(winPan, "Windows");
osCards.add(otherPan, "Other");
// add cards to main applet panel
add(osCards);
// register to receive action events
Win.addActionListener(this);
Other.addActionListener(this);
// register mouse events
addMouseListener(this);
}
// Cycle through panels.
public void mousePressed(MouseEvent me) {
cardLO.next(osCards);
}
// Provide empty implementations for the other MouseListener methods.
public void mouseClicked(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == Win) {
cardLO.show(osCards, "Windows");
}
else {
cardLO.show(osCards, "Other");
}
}
}
Here is the output generated by the CardLayoutDemo applet. Each card is activated by
pushing its button. You can also cycle through the cards by clicking the mouse.
GridBagLayout
Although the preceding layouts are perfectly acceptable for many uses, some
situations will require that you take a bit more control over how the components are arranged.
A good way to do this is to use a grid bag layout, which is specified by the GridBagLayout
class. What makes the grid bag useful is that you can specify the relative placement of
components by specifying their positions within cells inside a grid. The key to the grid bag is
that each component can be a different size, and each row in the grid can have a different
number of columns. This is why the layout is called a grid bag. It’s a collection of small grids
joined together._
</APPLET>
</div>
</BODY>
</HTML>
4 Predict output in following code? Understand
}
5 Analyze the program output. Understand
import java.awt.*;
class Frame1 extends Frame
{
Frame1()
{
setTitle(“demo”);
setSize(200,200);
setVisible(true);
setLayout(newFlowLayout());
Label l1= new Label(“java”);
Label l2= new Label(“j2ee”);
add(l1);
add(l2);
}
}
Class Labeldemo
{
Public static void main(String args();
{
Frame1 f= new Frame();
}
}
6 Identify the program output Understand
import java.awt.*;
import java.applet.*;
public class satusdemo extends Applet
{
Public void init()
{
setBackground(Color.red);
}
Public void paint(Graphics g)
{
g.drawString(“this is in the applet window”
10,20)‟ showStatus(“this is the status window
message”);
}
}
7 Identify the program output Understand
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();
}
8 Identify the program output Understand
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();
}
UNIT V
UNIT WISE PLAN
UNIT-V: Swings Planned Hours: 09
Blooms
S. No. Topic Learning Outcomes Cos
Levels
1 Distinguish applets and swings CO5 L4
2 Explain MVC Architecture CO5 L2
3 Use swing controls in GUI Programming CO5 L6
4 Use graphical IDE for design and implementation of real CO5 L6
time applications in java.
Java Swings is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Controller
The controller is the portion of the user interface that dictates how the component
interacts with events. Events come in many forms — a mouse click, gaining or losing
focus, a keyboard event that triggers a specific menu command, or even a directive to
repaint part of the screen. The controller decides how each component will react to the
event—if it reacts at all.
Figure shows how the model, view, and controller work together to create a scrollbar
component. The scrollbar uses the information in the model to determine how far into the
scrollbar to render the thumb and how wide the thumb should be. Note that the model
specifies this information relative to the minimum and the maximum. It does not give the
position or width of the thumb in screen pixels—the view calculates that. The view
determines exactly where and how to draw the scrollbar, given the proportions offered by the
model. The view knows whether it is a horizontal or vertical scrollbar, and it knows exactly
how to shadow the end buttons and the thumb. Finally, the controller is responsible for
handling mouse events on the component. The controller knows, for example, that dragging
the thumb is a legitimate action for a scroll bar, and pushing on the end buttons is acceptable
as well. The result is a fully functional MVC scrollbar.
MVC in Swing
Swing actually makes use of a simplified variant of the MVC design called the model-
delegate . This design combines the view and the controller object into a single element that
draws the component to the screen and handles GUI events known as the UI delegate .
Bundling graphics capabilities and event handling is somewhat easy in Java, since much of
the event handling is taken care of in AWT. As you might expect, the communication between
the model and the UI delegate then becomes a two-way street, as shown in fig
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.
1. public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot
edit it directly. It inherits JComponent class.
JLabel class declaration
Let's see the declaration for javax.swing.JLabel class.
1. public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:
Constructor Description
Creates a JLabel instance with no image and with an
JLabel()
empty string for the title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,
horizontalAlignment) image, and horizontal alignment.
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.
JTextField class declaration
Let's see the declaration for javax.swing.JTextField class.
1. public class JTextField extends JTextComponent implements SwingConstants
Commonly used Constructors:
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text
columns) and columns.
Creates a new empty TextField with the specified number of
JTextField(int columns)
columns.
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing
of multiple line text. It inherits JTextComponent class
JTextArea class declaration
Let's see the declaration for javax.swing.JTextArea class.
1. public class JTextArea extends JTextComponent
Commonly used Constructors:
Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text initially.
JTextArea(int row, int Creates a text area with the specified number of rows and
column) columns that displays no text initially.
JTextArea(String s, int row, Creates a text area with the specified number of rows and
int column) columns that displays specified text.
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
Output:
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
JCheckBox class declaration
Let's see the declaration for javax.swing.JCheckBox class.
1. public class JCheckBox extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description
Creates an initially unselected check box button with no
JJCheckBox()
text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not
selected) it is initially selected.
Creates a check box where properties are taken from the
JCheckBox(Action a)
Action supplied.
Commonly used Methods:
Methods Description
AccessibleContext It is used to get the AccessibleContext associated with
getAccessibleContext() this JCheckBox.
protected String paramString() It returns a string representation of this JCheckBox.
Java JCheckBox Example
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
JComboBox class declaration
Let's see the declaration for javax.swing.JComboBox class.
1. public class JComboBox extends JComponent implements ItemSelectable, ListData
Listener, ActionListener, Accessible
Commonly used Constructors:
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] Creates a JComboBox that contains the elements in the specified
items) array.
JComboBox(Vector<?> Creates a JComboBox that contains the elements in the specified
items) Vector.
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb); f.add(label); f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:
Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.
JTable class declaration
Let's see the declaration for javax.swing.JTable class.
Commonly used Constructors:
Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
If you select an element in column NAME, name of the element will be displayed on the
console:
Table element selected is: Sachin
Java JList
The object of JList class represents a list of text items. The list of text items can be set up so
that the user can choose either one item or multiple items. It inherits JComponent class.
JList class declaration
Let's see the declaration for javax.swing.JList class.
1. public class JList extends JComponent implements Scrollable, Accessible
Java JTree
The JTree class is used to display the tree structured data or hierarchical data. JTree is a
complex component. It has a 'root node' at the top most which is a parent for all nodes in the
tree. It inherits JComponent class.
JTree class declaration
Let's see the declaration for javax.swing.JTree class.
1. public class JTree extends JComponent implements Scrollable, Accessible
Commonly used Constructors:
Constructor Description
JTree() Creates a JTree with a sample model.
JTree(Object[] Creates a JTree with every element of the specified array as the child of
value) a new root node.
JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays
root) the root node.
Java JTree Example
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
Output:
Java JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a given title or icon. It inherits JComponent class.
JTabbedPane class declaration
Let's see the declaration for javax.swing.JTabbedPane class.
public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingC
onstants
Commonly used Constructors:
Constructor Description
JScrollPane(Component,
int, int)
Useful Methods
Modifier Method Description
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_S
CROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROL
LBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
Output:
Fill in the Blanks
1.The ______package provides classes for java swing API such as JButton,JTextField etc.
2. Java swing components are platform______
3. _____ method creates a button with no text and icon.
4. _____ method creates an unselected radio button with specified text.
5. The ______class is used to create a text area.
6. ______ method is used to remove all the items from the list.
7. ______ method creates a table with empty cells.
8. ________ method is used to set the graphics current font to the specified font.
9. The ______are used to arrange components in a particular manner.
10. The BorderLayout is used to arrange the components in ___ number of regions.
11. MVC Stands for____,_____ &______
12. A ________provides a space where a component can be located.
13. Component represents an object with _____representation.
14. A ______is the abstract base class for the non menu user-interface controls of SWING.
15. A _______ is a base class for all swing UI components.
16. ____are generated as result of user interaction with the graphical user interface
components.
17. The ____is an object on which event occurs.
18. ______is responsible for generating response to an event.
19. ________is the root class from which all event state objects shall be derived.
20. __________interface is responsible to handle events.
1. Develop a Java Applet Program which has the following GUI, converts the value
of a currency entered in Rupees to Dollar.
2. Develop a Java Applet Program which has the following GUI, accepts First
Name, Middle Name and Last Names into three different Text Fields and Prints
the full name in a Text Area.
3. Develop a Java Applet Program which has the following GUI.
Write the code for
a) To display the series of odd or even number(depending on Starting Number
and Last Number entered in TextField 1 and TextField 2 respectively)in the
Text Area on click of “Display the Series” Button.
For Example:
If the starting number is 5 and last number is 11 then text area should
contain 5,7,9,11.
If the starting number is 2 and last number is 10 then text area should
contain 2,4,6,8,10.
b) To clear both the text fields and text area by click on “Reset” button.
c) To terminate the application by click on “Clear” button
6. Develop a Java Applet Program which has the following GUI, adds the selected
item from the Choice (contains Mr,Miss,Ms) to the Name entered in text field
and prints in the text area provided.
7. Develop a Java Program which has the following GUI, adds the selected
information from all the controls and prints in the text area provided.
8. Develop a Java Applet Program which has the following GUI, calculates and
displays Interest Amount taking values of Principal amount, ROI, Time.
9. Develop a Java Program which has the following GUI, checks whether a number
entered in a text field is positive or not and display on a Label provided
10. Develop a Java program with the below GUI, verify the criteria for admission in
army.
If the person is male with greater than or equal to 175cm of height then he is
eligible for admission in army. For ladies height criteria is 160cm. or more.
11. Develop a Java program with the below GUI, calculates discount amount.
This Program accepts size, type and price of a TV set and calculates discount
based on the policy given in table below.
Type Size Discount
B/W 21’’ 10%
B/W 27’’ 15%
Color 21’’ 20%
Color 27’’ 25%
12. Write a Java Program to create the following GUI,which accepts a number and
prints the name of the digit in word.
13. Develop a java program to create the following GUI, which accepts a start
number and end number and a digit and counts the numbers of between start
and end number divisible by entered digit using for loop.
14. Develop a java application which converts the entered a number in a text field
into binary or octal or hexadecimal number by using radio button as illustrated
in the following GUI.
Previous Mid and External Theory Exams Question Papers
PART – B
Answer any FIVE questions
All questions carry equal marks
5 x 10
1. Explain the important features of Java.
2. Explain different types of inheritances with examples.
3. Give a detail note on interfaces and packages in java with examples.
4. What is thread synchronization? Discuss with an example.
5. Differentiate method overloading with method overriding with examples
6. Write a Java program to create a combo box which includes list of subjects. Copy the
subjects in text field on click using applet.
7. Write a java program using listeners for handling keyboard events.
8. Construct an application to explain the use of JTabbedPane.
*
*
*
PART – B
Note: Answer Any THREE Questions.
3x5
1. a) What is an event? Explain the event delegation model.
b) Write a java program to handle keyboard events.
2. a) What is exception? Explain the exception handling mechanism.
b) Explain File Input and FileOutputStream with suitable example.
3. a) Explain border and grid layout mangers briefly.
b) Explain about applet life cycle with a suitable example.
4. a) Define a thread? Give syntax for creating a thread using a class and an interface.
b) Explain multithreaded environment with suitable example.
5. Design a swing application that creates registration form of a student.
*