Programming in Java - Notes
Programming in Java - Notes
SYLLABUS
COURSE OBJECTIVES:
To acquire the programming skills with java.
To implement the object-oriented concepts with java language
To learn the art of GUI programming with Applet.
UNIT - I:
Foundation, Essentials, Control Statement and Classes & Objects. Stage of Java – origin of Java –
challenges - features - Object-Oriented Programming; Java Essentials: Elements - API - variables -
primitive data types – String Class - operators –combined assignment operators - conversion –scope
– comments - keyboard input; Control Statements: if, if-else, nested if & if-else-if statements –
logical operators – comparison – conditional operator – switch – increment and decrement – while,
do-while &f or loops – nested loops – break and continue; Classes and Objects: classes and objects
-modifiers - passing arguments– constructors - package & import - static class members –method
overloading– constructor overloading –returning objects – this variable – recursion – nested & inner
classes – abstract classes & methods.
UNIT - II:
Arrays, String Handling, Inheritance, Interface and Packages. Introduction –processing array –
passing arrays – returning arrays – String arrays – two Dimensional Arrays - Arrays with Three or
More Dimensions; String Handling : String class – concatenation – comparison – substring –
methods – other methods–String Buffer, String Builder &String Tokenizer classes; Inheritance:
basics –inheriting and overriding superclass methods – calling superclass constructor –
polymorphism – inherit from different classes – abstract classes – final Class; Interfaces: Basics –
multiple Interfaces – multiple inheritance using interface – multilevel interface – Packages – Create
and access packages in NetBeans IDE – static Import and package class – access specifiers.
UNIT - III:
Exception Handling, I/O and File Handling and Multithreading. Introduction - try and catch block -
multiple catch block - nested try - finally Block – throw Statement – exception propagation – throw
Clause - custom exception – built-in exception; Multithreading: Introduction – threads – thread
creation – life cycle – joining a thread – scheduler &priority – synchronization – inter-thread
communication – thread control – thread Pool – thread group – daemon thread; Files and I\O
Streams: file Class – streams – byte streams – filtered byte streams – Random Access File class –
character streams.
UNIT - IV:
Applet and GUI Part I. Fundamentals – applet class – life cycle – steps for applet program – passing
values through parameters – graphics – event handling; GUI I:GUI – creating windows – dialog
boxes – layout managers – AWT component classes – Swing component classes – applications of
AWT controls.
UNIT - V:
GUI Part II and Java Database Connectivity Event handling – AWT components – AWT graphics
classes – Swing controls – application using Swing and AWT; Java Database Connectivity: types of
drivers – JDBC architecture – JDBC classes &interfaces – steps in JDBC applications – creating a
new Database and table with JDBC.
Page 1
Unit - VI: Current Contours (for Continuous Internal Assessment Only):
Contemporary Developments Related to the Course during the Semester Concerned.
TEXT BOOK:
1. [Link], [Link], [Link] & [Link], ―Constructive Java Programming―,
Universities Press, 2021.
2. E. Balagurusamy, ―Programming with JAVA‖, Tata McGraw Hill, New Delhi, 2019.
3. C. Muthu, ―Programming with JAVA‖, Vijay Nicole Imprints Private Limited,
Chennai, Second Edition, 2011.
4. Bruce Eckel, Chuck Allison, ―Thinking in Java‖, Prentice Hall Publications, 2006
5. Malina Pronto, "Java: How To Learn Java Programming: How To Improve Your Java
Coding In 2020/2021: 5 Programming Languages To Learn For Beginners In Tech",
Independently Published, 2020.
6. Nick Samoylov, ―Learn Java 12 Programming: A Step-by-step Guide to Learning
Essential Concepts in Java‖, Packt Publishing, 2019.
7. [Link]
COURSE OUTCOMES:
Upon successful completion of this course the students would be able to:
Understand the concept of OOP as well as the purpose and usage principles of
inheritance, polymorphism, encapsulation and method overloading.
Identify members of a class and to implement them
Create Java application programs using sound OOP practices (e.g., interfaces and
APIs) and proper program structuring (e.g., by using access control identifies, and
create user define package for specific task,(reusability concepts) error exception
handling)
Develop programs using the Java standard class library.
Develop software using Java programming language, (using applet, AWT controls,
and JDBC)
*****
Page 2
CONTENTS
Topic Page
Topic
No No.
I UNIT-I
1.1 Introduction to Java 7
1.2 Basic Concept of Object-Oriented Programming (OOPs) 9
1.3 Features of Java 12
1.4 Java API and JVM 14
1.5 Comment Line And Java Program Structure 16
1.6 Java Tokens 18
1.7 Variables and Scope of Variable 22
1.8 Data Types 23
1.9 Operators and Its Precedence 25
1.10 Type conversion 29
1.11 Condition Statements (if, switch) 30
1.12 Loop Statement ( for. While, do..while) 35
1.13 Other Control Statements (break, continue, goto) 38
1.14 Class and Objects, Access Specifiers 39
1.15 Constructors and Its types 41
1.16 Method Overloading and Constructor Overloading 44
1.17 Static Class Members 46
1.18 this Keyword and Recursion 47
1.19 Abstract Class and Methods 48
1.20 Inner Class and Nested Class 49
Sample Questions 50
II UNIT- II
2.1 Arrays (One & Multi-Dimensional Array) 51
2.2 String Class And String Handling Method 54
2.3 String Buffer Class 57
2.4 Inheritance and Its types 58
2.5 Method Overriding and Polymorphism 62
2.6 Interface , its Implementation and Multiple Inheritance 64
2.7 Package Creation and Importing packages 66
2.8 Super Keyword 70
2.9 Final Keyword 71
Simple Questions 73
Page 3
III
UNIT-III
3.1 Exception Handling 74
3.1.1 Exception Handling Techniques (try .. catch, finally, throw, throws) 75
3.1.2 Types of Exception 79
3.1.3 User-Defined Exceptions 80
3.2 Multithread Programming (Main Thread & Thread Method) 82
3.2.1 Thread Creation using Thread Class and Runnable Interface 84
3.2.2 Life Cycle of Thread 88
3.2.3 Thread Priority 89
3.2.4 Synchronization and Join Thread 90
3.3 I/O Stream and File Classes 93
3.3.1 Byte Stream Classes 94
3.3.2 Character Stream Classes: 95
3.3.3 File Handling Classes 98
3.3.4 Random Access Files And Sequential File 101
Simple Questions 104
IV UNIT-IV
4.1 Applet Fundamentals 105
4.2 Life Cycle Of Applet 106
4.3 APPLET Tag in HTML 108
4.4 Steps to Create Applet program 109
4.5 Passing Parameters in APPLET 110
4.6 Applet Class and Methods 112
4.7 Applet Graphics using AWT Methods 113
4.8 Displaying Image in Applet 114
4.9 Playing Audio in applet: 115
4.10 Event Handling in applet 117
4.11 AWT and GUI 118
4.12 AWT Component Classes 119
4.13. AWT Layout Manager 122
4.14 AWT Controls 128
Programs and Questions 137
UNIT V
V
SWING AND DATABASE CONNECTIVITY
5.1 Introduction to Java Swing 142
5.2 Layout Managers: 144
5.3 Swing control 146
5.4 JDBC-Java Database Connectivity 154
Page 4
5.5 Architecture of JDBC 155
Page 5
5.6 JDBC Driver 156
5.7 JDBC Classes 158
5.8 Steps of Java Database Connectivity 159
5.9 JDBC Program using MySQL and MS-Access Database 160
Sample Questions 164
Page 6
Unit I:
Foundation, Essentials, Control Statement and Classes & Objects. Stage of Java – origin of Java –
challenges - features - Object-Oriented Programming; Java Essentials: Elements - API - variables -
primitive data types – String Class - operators –combined assignment operators - conversion –scope
– comments - keyboard input; Control Statements: if, if-else, nested if & if-else-if statements –
logical operators – comparison – conditional operator – switch – increment and decrement – while,
do-while &f or loops – nested loops – break and continue; Classes and Objects: classes and objects
-modifiers - passing arguments– constructors - package & import - static class members –method
overloading– constructor overloading –returning objects – this variable – recursion – nested & inner
classes – abstract classes & methods.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since
Oak was already a registered company, so James Gosling and his team changed the name from
Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.
History of Java:
In 1990, Sun Micro Systems Inc (US) was conceived a project to develop software for
consumer electronic devices that could be controlled by a remote This project was called Stealth
Project but later its name was changed to Green Project
In January 1991, Project Manager James Gosling and his team members Patrick Naughton,
Mike Sheridan, Chris Wrath, and Ed Frank met to discuss about this project
Gosling thought C and C++ would be used to develop the project But the problem he faced
with them is that they were system dependent languages The trouble with C and C++ (and most
other languages) is that they are designed to be compiled for a specific target and could not be
used on various processors, which the electronic devices might use
Page 7
James Gosling with his team started developing a new language, which was completely
system independent This language was initially called OAK Since this name was registered by
some other company, later it was changed to Java
James Gosling and his team members were consuming a lot of coffee while developing this
language Good quality of coffee was supplied from a place called ―Java Island‟ Hence they
fixed the name of the language as Java The symbol for Java language is cup and saucer Sun
formally announced Java.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Java Version History
JDK Alpha and Beta (1995)
The Java Alpha and Beta was the first releases but they have highly unstable APIs and ABIs.
The supplied Java web browser was named Web Runner.
JDK 1.0 (January 23, 1996)
It was the first stable released version of Java. Its codename was Oak. The first stable version
of JDK was JDK 1.0.2 and it was called Java 1.
Up to JDK 1.0.1, private and protected keywords could be used together to create yet another
form of protection which used to act as a restriction to methods or variables mainly to subclasses
of a given class. In JDK 1.0.2, this capability has been removed.
J2SE 1.2 (December 8, 1998)
Its codename was Playground. First time, it was called J2SE (Java 2 Platform, Standard
Edition) .It replaced JDK to recognize the base platform from J2EE (Java 2 Platform, Enterprise
Edition) and J2ME(Java 2 Platform, Micro Edition) .It was a very important java release as it
tripled the size of the Java platform to 1520 classes in 59 packages.
These include:
Objects
Classes
Data abstraction
Encapsulation
Inheritance
Polymorphism
Dynamic binding
Message passing
i) Objects:
Objects are the basic run-time entities in an object oriented programming.
It is an instance of class.
Each instance of an object can hold its own relevant data.
They may represent a person, a place, a bank account or any item that the program has
to handle.
Each object contains data (data members) and code (member functions) to manipulate
the data.
Object: STUDENT
DATA:
Name
Roll No
Mark 1, Mark 2
FUNCTIONS (Method)
Total
Average
Display
Page 9
ii) Classes:
It is a representation (or) blueprint of an object.
The entire set of data and code of an object can made a user defined data type with the help
of a class.
Classes are user-defined data types and behave like built-in data types of Programming language
and they are known as Abstract Data Type.
For Example: If Student has been declared as a class, then the statement
Class Student
{
char name[10];
int RollNo, m1.m2;
void Getdata();
void Putdata():
}
iii) Encapsulation:
The wrapping up of data and functions into a single unit is known as encapsulation.
The data is not accessible to the outside world and only those functions which are wrapped in
the class can access it.
These functions provide interface b/n the object‘s data and the program. This insulation of the
data from direct access by the program is called data hiding or information hiding.
iv) Data Abstraction:
It represents the act of representing the essential features without including the background details or
explanations.
Classes use the concept of abstraction and are defined as a list of abstract attributes
such as size, weight and cost and functions to operate on these attributes.
The attributes are called data members and functions are called member functions or methods.
Since the classes use the concept of data abstraction, they are known as Abstract Data Types
(ADT).
v). Inheritance:
It is the process by which objects of one class acquire the properties of objects of another class.
It supports the concept of hierarchical classification. For example, the ‗student‘
and the ‗employee‘ is a part of the class ‗person‘.
This concept provides the idea of reusability. This means that we can add additional features to
an existing class without modifying it.
Page 10
Person
Attributes
Name
Age
Student Employees
Attributes Attributes
Types of Inheritance
Single inheritance
Multiple inheritance
Multilevel inheritance
Hierarchical inheritance
Hybrid inheritance
Advantage:
It offers code reusability.
It is a technique of design and code sharing.
vi). Polymorphism:
It means the ability to take more than one form. An operation may exhibit different behaviors in
different instances. The behavior depends upon the types of data used in the operation.
For example the operation addition will generate sum if the operands are numbers whereas if
the operands are strings then the operation would produce a third string by concatenation. The
process of making an operator to exhibit different behaviors in different instances is known as
operator overloading.
A single function name can be used to handle different types of tasks based on the
number and types of arguments. This is known as function overloading.
Shape
Draw()
Page 11
vii). Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic Binding (late binding) means the code associated with the given procedure call is not
known until the time of the call at run-time.
Page 12
There is no need to remove unreferenced objects because there is an automatic garbage
collection in java.
Object-oriented
Java is an object-oriented programming language. Everything in java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporates both data and behaviour.
Basic concepts of oops are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is
a platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
No explicit pointer
Robust:
Robust simply means strong. Java is robust because:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
There is automatic garbage collection in java which runs on the Java Virtual Machine to get
rid of objects which are not being used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points
make Java robust.
Page 13
Architecture-neutral:
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
Portable:
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
High-performance:
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++).
Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed:
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet.
Multi-threaded:
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic:
Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage Collections)
Java APIs are important software components bundled with the JDK. APIs in java include
classes, interfaces, and user interfaces. They enable developers to integrate various applications
and websites and offer real-time information. That is it used to develop any application programs.
The Class and Interface of java are grouped in to several Packages. It is also known as JSL-
Java Standard Library. The main java Packages are
Page 14
This package contains important classes like String, StringBuilder, Math, Integer, System, etc.
What is JVM?
Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the
Java Code or applications. It converts Java bytecode into Native machines code language. JVM is
a part of Java Runtime Environment (JRE). In other programming languages, the compiler produces
machine code for a particular system. However, Java compiler produces code for a Virtual Machine
known as Java Virtual Machine.
Page 15
Java Compiler (javac)
Java Compiler convert the java source code(program) into Byte code (Class file ,object
code).
JVM (java)
Page 16
Structure of the Java Program:
As all other programming languages, Java also has a structure, in Java first we need to
import the required packages By default javalang* is imported Java has several such packages in its
library A package is a kind of directory that contains a group of related classes and interfaces A
class or interface contains methods
Since Java is purely an Object Oriented Programming language, we cannot write a Java program
without having at least one class or object So, it is mandatory to write a class in Java program We
should use class keyword for this purpose and then write class name
In Java, program starts executing from main method The return type of main method is void
because program starts executing from main method and it returns nothing.
Sample Program:
//A Simple Java Program
import [Link];
import [Link];
class Sample
{
public static void main(String args[])
{
Systemoutprint ("Hello world");
}
}
Since Java is purely an Object Oriented Programming language, without creating an object to a
class it is not possible to access methods and members of a class But main method is also a method
inside a class, since program execution starts from main method we need to call main method
without creating an object.
Static methods are the methods, which can be called and executed without creating objects Since
we want to call main () method without using an object, we should declare main () method as static
JVM calls main () method using its Class name main () at the time of running the program. JVM is
a program written by Java Soft people (Java development team) and main () is the method written
by us Since, main () method should be available to the JVM, it should be declared as public If we
don‟t declare main () method as public, then it doesn‟t make itself available to JVM and JVM
cannot execute it
JVM always looks for main () method with String type array as parameter otherwise JVM
cannot recognize the main () method, so we must provide String type array as parameter to main ()
method.
A class code starts with a {and ends with a} A class or an object contains variables and
methods (functions) We can create any number of variables and methods inside the class This is our
first program, so we had written only one method called main () .
Page 17
1.6. JAVA TOKENS:
The smallest individual units of a Java program are known as tokens. That is each word
and symbol in Java program are called tokens.
a) Keywords b) Identifiers
c) Constants d) Strings
e) Special symbols f) Operators
a) Key words:
Keywords are pre-defined words (reserved word)s; this words are built in with Java
compiler.
All keywords have fixed meaning and these meaning can‘t be change.
All keywords must be written in lower case.
There are SOME keywords in Java they are as follows
Page 18
b) IDENTIFIERS:
Identifier is a user-defined name , Identifier refer to the variable name, functions name,
array name. It consists of a sequence of letter and number, The first character must be
alphabet. The underscore ( _ )character is only allowed other special character not allowed.
Example: Reg_no, name , amout.
The identifier must begin with a letter and must be followed by letters or digits
Both upper and lower case are permitted
Upper and lowercase letters are not same, it is different.
The underscore (_) can also be included.
It can‘t became an keyword
C) Constant:
Constant is a fixed values that do not change during the execution of a program. It can
be placed on the right side of the assignment operator (=).
TYPES OF CONSTANT
a. i ) Integer constant:
Page 19
Integer constant is a whole number. It consist of sequence of numbers( eg. 23, 478)
Integer constant can be classified in to 3 types they are as follows
1. Decimal integer
2. Octal integer
3. Hexadecimal integer
Decimal integer consist of a set of digits 0 to 9 preceded by either + or – sign
eg: +123, -114
Octal integer consist of any combination of digits from 0 to 7 with leading ‗0
eg: 045, 0768
Hexadecimal integer consist of hexa decimal integer values preceded by ‖0X‖.They also
includes number( 0…9) and alphabets of both upper and lower case letters (A…..F),
represents the number 0 to 15. Eg: 0X4, 0X8E
Ii) Real constant:
A number with decimal point is called as a real and floating point constant.
Eg: 25.75
A real number can also be expressed in exponential or scientific notation
Eg: 2.1565e2 in exponential notation where e2 means 210
the generalized form as [ MANTISSA e Exponent]
where Mantissa is either a real number expressed in decimal notation or an integer
Exponent is an integer number.
b) Character constant :
i) Single character constant:
A single character contain one character with in single quotes ( ‗ )
eg: ‟X‟, ‟a‟ „7.
ii) String constant:
It is an sequence of character enclosed in double quotes ( ― )
eg: ”WELCOME”, ”hello 1st bsc cs”
iii) Backslash character Constant:
Constant Meaning
‗\n‘ new line
‗\0‘ null
‗\t‘ horizontal tab
‗\v‘ vertical tab
‗\f‘ form feed
‗\b‘ back space
‗\‖ ‗ double quote
Page 20
d). String
String is a sequence of characters within double quote(“ “) That contain any alphanumeric
characters. It use control string “%s” in input and output statemens.
F) OPERATORS:
An OPERATOR is an symbol that tells the computer to perform certain
mathematical ( or ) logical manipulation.
Eg: c=a+b where + is operator doing addition operation
An OPERAND Is an entity on which OPERATION is to be performed.
Eg:c=a+b where a and b are operand
They are of 7 types
1. Arithimetic operator 2. Logical operator 3. Relational operator 4. Assignment
operator [Link] and decrement operator [Link] operator 7. Bitwise
operator [Link] operator
Page 21
1.7 VARIABLES and Scope of Variable:
A variable is a data name ( identifier) It refer a memory location that may be used to
store a value. A variable may take different values during execution.
Eg: int a=3; float B;
Rulers for naming a variable:
They must begin with a letter
It should not be a keyword
White space is not allowed
Underscore( _ ) symbol is only used b/w two words
Eg: Invalid one : Reg&No, 34reg;
Valid one : Reg_No, reg34;
Declaring Variables:
Declaring the variables must be done before they are used in program.
A declaration consist of a date type followed by one or more variable names ending
with semicolon (;)
The value are assigned to variable when the variable is declared . This is called variable initializing
using an assignment operator’=’. The declaring and initialization can also be done in the same line
Page 23
a). INTEGER TYPES (int):
The integer data type is whole number without decimal point.
Int is keyword.
Memory size is required 4 byte .
Value ranges is from -2,147,483,648 to +2,147,483,647
Its sub data types : short, byte, long,.
Eg.) int a, b, c;
a=65;
b). CHARACTER (char):
The Character data type is a single character within single quote(‗a‘)
The Character data type Values are used the UNICODE Character sets.
The Unicode include Enclish, Tamil, Hindi, etc language
char is keyword.
Memory size is required 2 byte
Value ranges from 0 to + 65 536
Eg.) char a=‟X‟;
C) FLOAT TYPE:
The float data type is Real number with decimal point (42.21). It is single precision (6 digits)
float is keyword.
Memory size is required 4 byte.
Value ranges from 3.4e-38 to 3.4e+38
Control string is %f.
. Eg.) float a, b, c;
a=42.21;
d) DOUBLE TYPE:
The double data type is Real number with decimal point (42.21). It is double precision
(14digits)
double is keyword.
Memory size is required 8 byte.
Value ranges from 1.7e-308 to 1.7e+308.
Control strings is %lf
Long double having 10 byte and ranges from 3.4e-4932 to 3.4e+4932.
. Eg.) double a, b, c;
a=42.21
Page 24
1.9 OPERATOR AND ITS PRECEDENCE:
1.9.1. Operators in Java
Types of operators in C
1. Arithmetic operator 2. Logical operator
3. Relational operator 4. Assignment operator
5. Increment and Decrement operator [Link] operator
7. Bitwise operator [Link] operator
1) ARITHMETIC OPERATOR:
JAVA provides all the basic arithmetic operator. It perform the arithmetic operations. They
are listed below
It can operate any built in data type allowed in ―c‖.
The modulo(%) division operator produces remainder of an integer division.
Eg: a=10, b=3 1) a+b=13 2) a-b=7 3) a*b = 30
4) a/b=3 5) a%b=1 Remainder.
2. RELATIONAL OPERATOR:
It is used to compare two quantities
There should be no whitespaces character between two symbols of relational operator
The result of relational operator is s Boolean constant
The relation operator forms an condition
Relation expression is used in Decision statement such as if and while to decide the
course of action of a running program.
Page 25
3. LOGICAL OPERTORS:
This operator are used to logically relate the sub-expression
This operates works according to the truth tables
The logical operator && and||are used when we want to test more than one condition
and make decision eg: (a>b) && (x==10).
Logical Operators
This are used to assign the result of an expression to a variable or assign an value to the
variable .
The common assignment operator is (=). In addition ―java‖ has a set of ‗shorthand‘
assignment operators of the form
var=exp;
Page 26
5. INCREMENT & DECREMENT OPERATOR:
( ++ ) Increment operator
( -- ) Decrement operator
Increment Operator:
If the increment operator appears towards the left side of its operand it is known as pre
increment operator. Eg:a= ++m The pre increment (++m) increments m value by 1 and
then assigns the value to a.
If the increment operator appears towards the right side of its operand it is known as post
increment operator. Eg.a= m++ ,The post increment (a++) assigns the value to a and then
m increments the value by 1
Eg: PRE Increment Operator
m=5; Result
Y=m++; m=6 y=5
EG: POST Increment Operator
m=5; Result
Y=++m; m=6 y=5
Decrement Operator:
Similarly, The decrement operator can appear towards the left side (pre) or towards the right
side (post) of the operand
m=5;
Y= - - m; Result y=4
? : conditional operator
It is called ternary operator. It is used to construct conditional expression
The general form of conditional operator is
E1 ? E2 : E3
where E1,E2,E3 are sub expressions.
Page 27
The sub expression E1 must be a condition it is evaluated 1st.
If E1 evaluates to true, then E2 is evaluated and E3 is ignored
If E1 evaluates to false then E3 is evaluated and E2 is ignored
Eg: (a<b)? a : b;
Java supports special operator as known as bitwise operation for manipulation of data at bit
level.
These outputs are used to testing the bits or shifting them right to left.
These operator do not consider the operand as one entity.
a) New operator
new is a special operator. It allocate the memory to object and also allocate memory to
array variables.
Example : int a[] = new int[5]; // allocate memory to array variable
Student obj = new Student() // allocate memory to object
1.9.2 Expression:
It is consist of operands and operators that specifies computations of a value. The
expression is evaluated the mathematic calculation.
eg: c=a+b;
Where a,b, c are operand (Variable).
+, = are operator
Page 28
1.9.3. PRECEDENCE OF ARITHMETIC OPERATOR
An arithmetic expression without parameter will be evaluated from left to right using the
rules of precedence of operator
PRECENDENCE ORDERS
EVALUATION OF EXPRESSION
Step1 : X=a-b/3+c*2-1
Step 2 : X=9-12/3+3*2-1
Step 3 : 9-4+6-1
Step 4 : 5+6-1 Step 5 : 11-1 Step 6 : 10
Rules for evaluation of expression:
Page 29
A) IMPLICIT CONVERSION :
Implicit conversions are automatically performed when a value is copied to a compatible type
C permits mixing of constant and variable of different data types an expression
If the operands are different types the “lower” type is automatically converted to the
“higher” type before the operation preceded
In a mixed-type expression, data of one or more subtypes can be converted to a super type as
needed at runtime so that the program will run correctly.
RULES :
All short and byte are automatically into int
If one of the operand is float the other will be converted and result in double
Eg: int a=234;
float b =a; Result of b =234.00
Where a value is converted automatically to float in b.
Important point
1. float to int causes truncation, i.e., removal of the fractional part.
2. double to float causes rounding of digit.
3. long to int causes dropping of excess higher order bits.
Page 30
Conditional statements
The Conditional statement is first check the condition, if the condition is true, then
execute a set of statements, if it false then execute a set of statements.
Two types:
I). if Statements
II). switch Statement
I) . if Statements
If statements have four structures , they are
a) Simple if.. statement
b) if ..else ..statement
c) nested if….else statement
d) if….else ladder.
a) Simple if .. statement:
This if statement is first check the condition, if the condition is true, then execute one or set
of statements, if it false then exit from if statements.
Syntax : Example:
if(condition ) if (a>b)
{ (
statements; big=a;
} }
Syntax : Example:
if(condition ) if (a>b)
{ (
Statements-1; big=a;
} }
else else
{ (
Statements-2; big=b;
} }
Page 31
c). Nested if…else statement:
Example:
If (a>b)
{
Big=a;
}
else if (b>c)
big=b;
else
big=c;
Page 32
/*program to determine the given number is even or odd using if else statement*/
import [Link];
class odd
{ Output :
public static void main(String ag[])
{ Enter your number :59
int Num,rem;
The entered number is odd.
Scanner ob=new Scanner()
[Link](―enter your number:‖);
Num=[Link]();
rem==Num%2;
if(rem==0)
[Link] (―the entered number is even.‖);
else
[Link] (―the entered number is odd.‖);
}
}
II) Switch Statements
The switch statement is selection statements. It check a variable from the list of variable, mach
its then It selects a block of statements to execute from the several block of statements base on
the condition.
Syntax:
switch(var)
{
case 1:
statements-I;
break;
case 2:
statements-II;
break;
default:
statements-III;
break;
}
Rules to a switch statement:
Page 33
Example
main()
{ int a=1;
switch(a )
{
case 1:
printf("Case 1 \n");
break;
case 2:
printf("Case 2 Selected\n");
break;
default:
printf("Default Case Selected\n");
break;
}
Simple program:
1. To find largest number from the given Three numbers.
import [Link];
class Large
{
public static void main(String ag[])
{
float n1, n2, n3;
Scanner ob=new Scanner()
[Link](―enter your Three number:‖);
n1=[Link]();
n2=[Link]();
n3=[Link]();
if (n1>=n2)
{
if(n1>=n3)
[Link] (" the largest number is "+ n1);
else
[Link] (" the largest number is "+n3);
}
else
{
if(n2>=n3)
[Link] (" the largest number is", +n2);
else
[Link] (― the largest number is ."+n3);
}}
Output
Enter Three number: 6,7,20
20 is the largest number.
Page 34
1.12 LOOPING STRUCTURE(for, while do..while):
The loop statements are repeatedly executed a set of statements for certain number of times.
Any loop statement would contain the following steps:
Initialization of a condition variable.
Test the control statement
Executing the body of the loop depending on the condition
Updating the condition variable.
a) While…
b) do … while…
c) for ……
The while statement is a loop statement. It is repeatedly execute the set of statements within
the body of loop until the condition becomes false.
It is an entry controlled loop statements i.e., the condition is check first ,if it is true, then the
body of the loop is executed.
After executing the body of the loop then the condition is once again checked and if it is true
the body is executed once again, the process of repeated execution of the body of the loop continues
until the condition becomes false and the execution control is exited from the loop.
Syntax: Flow Chart
Example:
while(i<=10)
{
sum=sum+i;
i++;
}
Simple Program-1
/* Sum of natural numbers up to 10 using while loop*/
class natural
{
public static void main(String arg[])
{
int i=1,sum=0;
while(i<=10)
Page 35
{
sum=sum+i;
i++;
}
[Link](―the sum of numbers upto 10 is ―+sum);
}
Output :
the sum of numbers upto 10 is 55
Simple program-2:
/* sum of even numbers upto 10 using do..while loop*/
class Evenl
{
public static void main(String arg[])
{ int i=2,sum=0;
do{
sum=sum+i;
i=i+2;
}
while(i<=10)
[Link](―the sum of even numbers upto 10 is= ‖+sum);
}
Output: the sum of even numbers upto 10 is =30
Page 36
In this statement, the initialize , increment or decrement and condition checking is done
within for structure only.
Syntax: for (initialize ; Condition; increment/ decrement)
{
// body of loop statements;
}
Condition: First check the condition in for loop statement, then execute the body of loop
statements.
Increment/decrement: After executing the body of the loop then increment/decrement the
initial value and then check the condition if it is true, then it executes the body, this process
is continue until the condition becomes false.
Example:
for( int i=0; i<=10; ++i)
{
sum=sum+i;
printf(― %d ,‖,i);
}
Simple program-3:
/* print and sum of odd numbers upto 10 using for loop*/
class Odd1
{
public static void main(String arg[])
{
int sum=0;
[Link](― odd numbers is\n‖);
for( int i=0; i<=10; i=i+2)
{
sum=sum+i;
printf(― %d ,‖,i);
}
[Link] (―\n the sum of odd numbers upto 10 is= %d‖+sum);
}
Output:
Odd number is
1,3,5,7,9
the sum of odd numbers upto 10 is =27
Page 37
1.11.2. OTHER CONTROL STATEMENTS
(break, continue, goto)
a) Break Statement
b) Continue Statement
c) Go to Statement
a) Break statement
It is used to terminate the loop and control structure. When the keyword break is used
inside any control structure, the execution control automatically transferred to the 1st
statement after control structure.
A break usually associated with an if , switch loop statement.
The break used in if, switch & loop structure. The break is immediately exited from the
control structure.
Syntax: break;
Example; if(a>b)
{ ….
break;
…. }
b). Continue statement
When the statement continue is encountered inside any c loop control automatically passes
to the beginning of the loop.
A goto statement can cause the program control almost anywhere in the program
unconditionally.
The goto statement require a label to identify the place to move the execution. A label is a
valid variable name and must be ended with colon(:)
………..
label:
label-1:
……….
goto label-1;
Page 38
1.14. CLASS AND OBJECTS, ACCESS MODIFIER
a) Class
A class is a Blueprint or Template of object It is also called User defined data type.t. In Java
A class contain Data member and Method( code) member that is its operation. In java the factions
is called methods.
When you define a class with declare the data and function. the data and function of a class are
called members of the class. The general form of class :
Syntax:
[modifier] class class-name
{
[access-modifier]:
Data member;
Method members();
// ...
}
The data members are a variable. It is also called attributes.
Example:
Class Student
{
private:
int a,b;
public:
void getdata()
{
a=5;
b=10;
}
}
b) Method definition :
In Java. The function is called method. The method is operation (behaviours)
of class. It contain set of statements (code) that it perform specific task. We can define more than on
methods with a class. The methods can be accessed all properties (member) of class.
Page 39
c) Object
An object is a runtime entity in oops. An object is said to be an instance of a class. Declare an
object is similar to declare a variable of any data type. So, the object is called class variable. This is
also called instantiating them.
Once a Class has been declared, we can create objects of that Class by using the class Name
like any other built-in type variable as shown:
Declaration of object:
Syntax:
Class-Name object-Name = new Class_name();
Example:
Student obj1 = new Student(); //these are object of class
d) Access-Specifier
The access Specifier is control the access of class properties (members); It allow
the member of class to use inside and outside of class in program.
Example Program: Java program to find sum of two numbers using classes
class Add
{
int a,b,c;
public:
void sum(int i, int j)
{
Page 40
a=i; b=j;
c=a+b;
[Link]("sum="+c);
}}
class Sample
{
Public static void main(String arg[])
{
Int x=5, x=10;
Add obj =new Add();
[Link](x,y);
}
} output: sum=15
Page 41
Characteristics of Constructor:
A constructor has the same name as the class itself.
It is invoked automatically when the objects are created.
It should be defined public.
They can have default argument.
It can be overload.
It has no return type even void.
We cannot refer to their address.
They cannot be inherited.
Types of Constructor
i) Default Constructor
ii) Parameterized Constructor (Arguments Constructor)
iii) Copy Constructor
Constructor-name()
{
Statement;
}
Example: class Sample
{
int a,b:
public:
Sample() //constructor
{
a=5;
b=10;
} }
class mainclass
{
Public static void main(String arg[])
{
Sample obj =new Sample();
}
}
Page 42
ii) Parameterized Constructor
The constructor that can take argument is called Parameterized Constructor. Initial
values must be passed at the time of object creation. It can be done by two ways.
Syntax:
Constructor-name(parameter-list)
{
// statements;
}
Example: class Sample
{
int a,b:
public:
Sample(int x. int y) // parameterized constructor
{
a=x;
b=y;
} }
class mainclass
{
Public static void main(String arg[])
{
Sample obj =new Sample(5,10); // pass values to constructor
}
}
iv) Copy Constructor?
A copy constructor is a special type of constructor which initializes all the data
members of the newly created object by copying the contents of an existing object.
The syntax of calling a Copy Constructor is
Syntax:
Class-Name New-Object(Existing Object);
Example:
Assume that we have a class called Student and object S1 of this class has been
already defined. Then we can create new object S2 belonging to same class as
class Sample
{
int a,b:
public:
Sample(Sample x) // parameterized constructor
{
a=x.a;
b=x.b;
} }
Page 43
1.16. METHOD OVERLOADING and CONSTRUCTOR
OVERLOADING
1.16.1. Method Overloading:
A class has multiple methods having same name but different in parameters, it is known as
method overloading.
Method overloading in java is a feature that allows a class to have more than one method
with the same name, but with different parameters. Java supports method overloading through two
mechanisms: by changing the number of parameters and different data type of parameters.
A signature is a combination of a function name and its parameters.
Parameter is differentiated by
1. Number of arguments
Sum(int, int);
Sum(int, int, int);
2. Type of arguments
Square(int);
Square(float);
Example Program
class adder
{
static int Sum (int a, int b)
{
return (a+b;) // Sum ( ) Method Overloading with different Parameters & data type
}
static int Sum (int a, int b, float c)
{
return a+b+c;
} }
class Mettload
{
public static void main(String[] args)
{
[Link](adder. Sum (5,10));
[Link](adder. Sum (3,5,8.2)); // pass different Values to Sum () Methods
}
}
Page 44
1.16.2. CONSTRUCTOR OVERLOADING:
Constructor overloading in Java refers to the use of more than one constructor in an
instance class. However, each overloaded constructor must have different signatures. For the
compilation to be successful, each constructor must contain a different list of arguments.
Parameter is differentiated by
[Link] of arguments
Class Sum()
{
Sum(int, int);
Sum(int, int, int);
}
3. Type of arguments
Class Square
{
Square(int);
Square(float);
}
Example Program
class Sum
{
int X,Y;
float Z;
Sum (int a, int b)
{
X=a;
Y=b; // Sum ( ) Constructor Overloading with different Parameters & data type
}
Sum (int a, int b, float c)
{
X=a;
Y=b;
Z= c;
} }
class Mettload
{
public static void main(String[] args)
{
Sum obj1=new Sum (5,10);
Sum obj1=new Sum (3,5,8.2); // pass different Values to Sum () constructor
}}
Page 45
1.17. Static Class Members
Static class members can be defined using static keyword. When we declare a
member of a class as static it means no matter how many objects of the class are created, there
is only one copy of the static member which is shared by all objects of the class.
A) Static data member B) Static member Methods
Example:
Class Sample
{
static int a,b;
}
Characteristics:
At once the object for the class are declared, the static member variables are initialized to
zero.
For each static variable separate memory locations are allocated and it is common for
all objects in the class.
Page 46
} }
Class Sample
{
Public static void main(String arg[])
{
[Link](); // Static Data & Method call using class name without object.
[Link](‗b= ‗+Sdemo.b);
}}
A abstract class is a class that contains more than one abstract method. We cannot create
objects to abstract class because it is having incomplete code Whenever an abstract class is created,
subclass should be created to it and the abstract methods should be implemented in the subclasses,
then we can create objects to the subclasses. the common members of the abstract class are also
shared by the sub classes.
Abstract Method
A method with method body is called concrete method In general any class will have all concrete
methods A method without method body is called abstract method. A class that contains abstract
method is called abstract class It is possible to implement the abstract methods differently in the
subclasses of an abstract class.
Page 48
Syntax:
abstract class class-name
{
abstract type Method-name();
}
Example:
abstract class Sample
{
abstract void Meth();
}
Class Demo extend Sample
{
void Meth()
{
[Link](― Simple demo of abstract class and method‖);
}}
The Inner class can be accessed all the member of outer class without objects including
private members. The inner class can be defined as static class.
Class Outer {
int a;
class Inter {
a=5;
}}
Page 49
Sample Questions:
Two marks:
Page 50
UNIT-II
Arrays, String Handling, Inheritance, Interface and Packages. Introduction –processing array –
passing arrays – returning arrays – String arrays – two Dimensional Arrays - Arrays with Three or
More Dimensions; String Handling : String class – concatenation – comparison – substring –
methods – other methods–String Buffer, String Builder &String Tokenizer classes; Inheritance:
basics –inheriting and overriding superclass methods – calling superclass constructor –
polymorphism – inherit from different classes – abstract classes – final Class; Interfaces: Basics –
multiple Interfaces – multiple inheritance using interface – multilevel interface – Packages – Create
and access packages in NetBeans IDE – static Import and package class – access specifiers.
a[0]
a[1]
a[2]
a[3]
a[4]
Page 51
Assign a value to arrays:
a[0] = 10;
a[1] = 15;
a[2] = 20;
a[3] = 12;
a[4] = 25;
Where, a[0] ,a[1].. is array element. 0,1,2.. are index value
Initialization of array:
Syntax: type array-name[size]={value1, val2,….};
Example: int a[4]={5,43,6,21};
.Where a[0]=5, a[1]=43, a[2]=6, a[3]=21.
Simple Program:
1. Write a program to add 10 array elements (Sum of 10 numbers)
Import [Link];
Class DemoArray
{
Public static void main(String args[])
{
int i ;
int a[10]; int sum=0;
Scanner obj = new Scanner([Link]);
[Link] (―enter the 10 element \n‖);
for (i=0; i<=9; i++)
{
a[i])= [Link]();
}
for (i=0; i<=9; i++)
{
sum = sum + a[i];
}
[Link] (―the sum of 10 array elements is = ‖+ sum);
}
OUTPUT:
Enter the 10 elements
5 10,12,3,4,7, 13,8,4,5
the sum of 10 array elements is = 70
Page 52
Example:-
int a[][] = new int [2][3];
Total no of elements=row*column is 2*3 =6
It means the matrix consist of 2 rows and 3 columns
For example:-
4 2 7 it is Matrix
8 3 5
00 ,01 ,02
10 ,11, 12
Reading 2-D Array
int a[2][3];
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
a[i][j]) =; [Link]();
}
}
Initialization of 2-d array:
2-D array can be initialized in a way similar to that of 1-D array. for example:-
int a[2][3]={4,2,7,8,3,5};
(or)
int a[2][3]={{4,2,7},{8,3,5}};
These values are assigned to the elements row wise, so the values of
elements after this initialization are
a[0][0]=4, a[0][1]=4, a[0][2]=7
a[1][0]=,8 a[1][1]=3, a[1][2]=5
int a[3][3][3];
Page 53
for(i=0;i<2;i++)
{ for(j=0;j<3;j++)
{ for(k=0;k<2;k++)
{
a[i][j][k] =; [Link]();
}
}}
What is string?
A String is a group of characters, digits and symbols enclose within double quotes.
In otherwise, strings is an array of characters.
Example: ― Kannan‖
Declare Strings Variable or String array
A string variable declare as character arrays:
Syntax: char str-nmae[size];
Example: char str[10];
Initialize Strings Variable or String array
static char str[5] = {‗B‘,‘C‘,‘S‘,‘M‘‘\0‘};
static char st1[6]=‖ INDIA‖
• String()
• String(String value)
• String(char value[])
• String(char value[], int offset, int count)
• String(byte ascii[], int hibyte, int offset, int count)
• String(byte ascii[], int hibyte)
It is readily apparent from the number of creation methods for String that there are many
ways to create String objects. The first creation method simply creates a new string that is empty.
All of the other creation methods create strings that are initialized in different ways from various
Page 54
types of text data. Following are examples of using some of the String creation methods to create
String objects:
In the first example, an empty String object (s1) is created. In the second example, a String
object (s2) is created from a literal String value, ―Hello‖. The third example shows aString object
(s3) being created from an array of characters.
a) Length()) Method
b) Substring()
The substring() method used to extract a new string as substring from give string from
specific length. There are Two methods
String substring(int beginIndex)
String substring(int beginIndex, int endIndex)
Example: String s1 = new String(―Hello Annai college‖);
1. [Link](s1. substring(7));
Output: Annai college
2 [Link](s1. substring(7,12));
Output: Annai
c) String Compare methods
There are Two methods
1. compareTo()
Page 55
This method Compare the Two string then show the following result:
Less than zero
Greater than zero
Zero
Example:
String s1 = new String(―abcfj‖);
String s2 = new String(―abcdz‖);
[Link]([Link](s2));
2. equals()
This method Compare the Two string then show the following result
String s1 = new String(―abcfj‖);
String s2 = new String(―abcdz‖);
[Link]([Link](s2));
Output: false
d) Concat() method
This method concatenate two strings
String s1 = new String(―Hello‖);
String s2 = new String(―I-BCA‖);
[Link]([Link](s2));
Output: Hello I-BCA
e) replace() & replaceAll()
The replace() method is used to replace characters in a string. All occurrences of
oldChar are replaced with new Char
Syntax: String replace(char original, char replace)
Example: String s1=‖‖Annai‖
[Link]([Link](‗n‘,‘l‘));
Output: Allai
The replaceAll() method is replaced a string by another strings.
String s1=‖‖Annai School‖
[Link]([Link](‗School‘,‘College‘));
Output: Allai College
Page 56
2.3. The StringBuffer Class
The StringBuffer class is used to represent variable, or non-constant, strings. The
StringBuffer class is useful when you know that a string will change in value or in length. The
creation methods for the StringBuffer class follow:
• StringBuffer()
• StringBuffer(int length)
• StringBuffer(String str)
The first creation method simply creates a new string buffer that is empty. The second
creation method creates a string buffer that is length characters long, initialized with spaces. The
third creation method creates a string buffer from a String object. This last creation method is useful
when you need to modify a constant String object. Following are examples of using the
StringBuffer creation methods to create StringBuffer objects:
• int length()
• int capacity()
• synchronized char charAt(int index)
• synchronized void setCharAt(int index, char ch)
• synchronized StringBuffer append(Object obj)
• String toString()
Example: StringBuffer s1 = new StringBuffer(14);
[Link](―capacity = ― + [Link]());
[Link](―length = ― + [Link]());
Output : capacity = 14
length = 0
Page 57
2.4. INHERITANCE and Its Types
DEFINITION:
Inheritance is the process of creating new class or classes from an already existing class or
classes. The existing class is known as base class. The new class is known as sub class or derived
class. The derived class inherits all the properties of the base class.
When a base class is privately inherited then the public members of the base class become
private members of the derived class. Therefore they are not accessible by using the objects
of the derived class.
When a base class is publicly inherited then the public members of the base class become
public members of the derived class. Therefore they are accessible by using the objects of
the derived class.
In both case the private members are not inherited and therefore the private members of a
base class will not become the members of its derived class.
(OR)
The ability to write a class that inherits the member variable or member function of
another class. (Or)
The ability to write a class that extends the definition of a superclass. The new class
inherits the member function of this superclass .The new class may override the behavior it is
inheriting .
Advantage:
Code Reusability.
Reduce the debugging time.
Reduce the testing time.
Reduce the maintenance charge.
Derive Class :
A Class is created from existing class. The new class is derived class or subclass.
The Old class is called base class or super class.
Syntax: Class Derived-class-name extends Base-class-name
{
// body of derived class
}
Example: Class A
{
int a;
}
Class B extends A
{
A=10;
}
The derived class can access all the properties of base class without objects.
Page 58
Superclass
A class from which a given inherits . This can be its immediate parent class or can
be more levels away. Superclasses become more than more generic as you travel up the inheritance
hierarchy and, for this reason , can often be abstract.
SubClass
A class that descends or inherits (extends in Java terminology) from a
given class. Subclasses are more specialized than the classes they inherit from.
Types of Inheritance:
1. Single Inheritance: A class derived form a single base class is known as single inheritance.
Example: Class A
{
int a;
}
Class B extends A
{
A=10;
}
Where , A is base class, B is a derived(subclass) class
Example: Class A
{
int a;
}
Class B extends A
Page 59
{
Int b;
A=10;
}
Class C extends B
{
c=a+10;
}
3. Hierarchical Inheritance: More than one Class is derived from a single base class.
Example: Class A
{
int a;
}
Class B extends A
{
A=10;
}
Class C extends A
{
int c=a+10;
}
4. Multiple Inheritance: One class derived from more than one base class. (OR)
The ability to write a class that inherits the member variable and member functions of more
than one class. see also inheritance.
In Java, the Multiple Inheritance do not implemented directly using class. We can implemented
using interface only.
Base interface Base interface Student Mark
Page 60
[Link] Inheritance: (Combination of above two inheritances)
In some situations we need to apply two or more inheritance to design a program. Such type
of inheritance is known as hybrid inheritance.
Derived 2 Result
Import [Link];
class base
{
public:
int a,b,c;
Scanner obj = new Scanner([Link]);
void getdata()
{
[Link](”Enter 2 values : ”);
a= [Link]();
b= [Link]();
} };
class derived1 extends base
{
public: void add()
{
c=a+b;
} };
class derived2 extends derived1
{
public:
void display()
{
[Link](“ Sum = ”+c);
} };
Class DemoInh
{
Page 61
Public static void main(String arg[])
{
derived2 d;
[Link]();
[Link]();
[Link](); ;
}}
class SuperC
{
public:
void display()
{
[Link](― Super class method‖);
}
}
class SubClass extends SuperC
{
public:
void display() // Same name method in subclass.
{
[Link](― Subclass class method‖);
}
}
Class DemoOver
{
Public static void main(String arg[])
{
Subclass obj = new Subclass();
[Link]();
}
}
Output: Subclass method // super class method is not access, that is hidden.
Page 62
2.5.2. Polymorphism
The Polymorphism is a process that one interface perform different task. That is , the
one method perform different task. There are Two type polymorphism
a) Compile Time Polymorphism
b) Run Time Polymorphism
Page 63
Subclass sb = new Subclass();
SuperC R;
R=sp;
[Link](); // super Class reference object R call super class method
R=sb;
[Link](); // call subclass method, the two call is polymorphism.
}
}
Output: Superclass method
Subclass method
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
Syntax:
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}
Implement 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.
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviours‘ of the interface.
Page 64
Example:
Interface Sample
{
public:
void display();
}
class SubInter implements Sample
{
void display() // Same name method in subclass.
{
[Link](― Interface method is implemented in class‖);
}
}
Class DemoInter
{
Public static void main(String arg[])
{
SubInter obj = new SubInter();
[Link]():
}}
Output: Interface method is implemented in class
[Link] Inheritance
The more than one interface can be implemented in one class, this is a multiple Inheritance
interface A
{
Disp1();
}
interface B
{
Page 65
Disp2();
}
Class SubInter implements A, B
{
void Disp1() .
{
[Link](― Interface A method is implemented in class‖);
}
void Disp2()
{
[Link](― Interface B method is implemented in class‖);
} }
Class DemoInter
{
Public static void main(String arg[])
{
SubInter obj = new SubInter();
Obj.disp1():
Obj.disp2():
}}
Output: Interface method is implemented in class
Page 66
2.7.1. JAVA API PACKAGES:
Java API provides a large number of classes grouped into different packages according
to functionality. Most of the time we use the packages available with the java API. Java has a
six packages.
[Link] :
Language support classes. These are classes that java compiler itself uses and therefore
they are automatically imported. They include classes for primitive types, strings, math function,
threads and exception.
[Link] :
Language utility classes such as vectors, hash tables, random numbers, date, etc.
[Link] :
Input/output support classes. They provide facilities for the input and output of data.
[Link] :
Set of classes for implementing graphical user interface. They include classes for windows,
buttons, lists, menus and so on.
[Link] :
Classes for networking. They include classes for communicating with local computers as well as
with internet servers.
[Link] :
Classes for creating and implementing applets.
User create a packages and process is called user defined packages. Let us see how to create
our own packages. We must first declare the name of the package using the package keyword
followed by a package name. This must be the first statement in a java source file (except for
comment and white spaces). Then we define a class, just as we normally define a class.
Steps
Creating our own package involves the following steps:
1. First Create a Directory(Folder) in D drive
2. Create a Java program file with package statement as first statement
using the form package packagename;
3. Define the class that is to be put in the package and declare it public.
4. Under the directory where the main source files are stored.
5 Store the listing as the [Link] file in the Directory
6. Compile the your all package java program, now created .class file by compiler.
Now ready your own packages, You will use the package in other program using import
statements.
Page 67
Here is an example
package firstpackage;
public class firstclass
{
Int a,b,c;
Int Add()
{
a=5; b=10;
c=a+c;
}
Here the package name is firstpackage. The class firstclass is now considered a part of this
package. This listing would be saved as a file called [Link] , and located in a directory
named firstpackage. When the source file is compiled, java will create a .class file and store it in
the same directory.
Remember that the .class files must be located in a directory that has the same name as the
package, and this directory should be a subdirectory of the directory where classes that will import
the package are located.
Remember that case is significant and therefore the subdirectory name must match the
package name exactly. As pointed out earlier, java also supports the concept of package hierarchy.
This is done by specifying multiple names in a package statement, separated by dots.
Example:
package [Link];
Here package1 is the name of the top level package, package2 is the name of the package
that is inside the package1, and so on. We can have any number of packages in a package
hierarchy. Finally, the explicit classname is specified. Note that the statement must end with a
semicolon(;). The import statement should appear before any class definitions in a source file.
USING A PACKAGE :
Let us now consider some simple programs that will use classes from other packages.
The listing below shows a package named Annai containing a single class BCA.
Page 68
package Annai; // Annai package name, BCA class name
public class BCA
{
public void show()
{
[Link]("welcome to all by Annai college");
[Link]("welcome to package program");
}
}
This source file should be named [Link] and stored in the subdirectory Annai as started
earlier. Now compile this java file. The resultant [Link] will be stored in the same
subdirectory.
OUTPUT
This program compiled and run to obtain the results. The output will be as under
Welcome all by Annai college
Welcome to package program
Page 69
[Link] Keyword
Whenever a subclass need to refer to its immediate superclass it can do so by use of super
Keyword. Super has two general forms.
super() must always be the first statement executed inside a subclass constructor. The
Parameter list passes the values to constructor of super class that it initialize the data members
of super class. The parameter of super() match with the parameter of super class constructor.
Example:
class Add
{
int a,b;
Add( int x, int y)
{
a=x;
b=y;
}}
Class Mul extends Add // Mul is subclass of Add class
{
int c;
Mul( int n1, int n2 , int n3)
{
super(n1,n2); // call Add() constructor by super();
c=n3;
}
}
2. Super access the member of super class
The super keyword can used to access the data member and method member of the superclass
in subclass that has been hidden by a member of a subclass. That is , the super act as this keyword.
Syntax: [Link];
Example:
Page 70
class Add
{
int a;
void Disp()
{
[Link](― super class method‖);
}}
Class Mul extends Add // Mul is subclass of Add class
{
int a=5; // a is local variable
super.a=10; // here, super.a is super class variable
[Link](); // super call super class method Disp()
}}
Page 71
b) final class
A Class can be declared as final. The final class cannot be inherited. That is it cannot be
used to create subclass.
final class sample
{
// body of class
}
Class sub extends sample // error.
{
}
c) final methods
A method can be declared as final. The final method can not be overridden by subclass.
l class sample
{
final void meth()
{
int a=5;
}}
Class sub extends sample
{
void meth() // error, final method not overridden
{
}
}
Page 72
Sample Questions
1. Define Array.
2. What is interface?
3. Short note on Inheritance
4. Define polymorphism
5. Write the use of import statement.
6. Tell about final variable.
7. What is method overriding?
8. Write the use of super keyword
9. Write the use of equal() method.
10. Define package.
Page 73
Unit-III
Exception Handling, I/O and File Handling and Multithreading. Introduction - try and catch block -
multiple catch block - nested try - finally Block – throw Statement – exception propagation – throw
Clause - custom exception – built-in exception; Multithreading: Introduction – threads – thread
creation – life cycle – joining a thread – scheduler &priority – synchronization – inter-thread
communication – thread control – thread Pool – thread group – daemon thread; Files and I\O
Streams: file Class – streams – byte streams – filtered byte streams – Random Access File class –
character streams.
The advantage of exception handling is to maintain the normal flow of the application.
Types of errors:
Errors may broadly be classified into two categories:
a) Compile-time errors ,
b) Run-time errors.
a) Compile-time errors:
All syntax errors will be detected and displayed by the java compiler and therefore these errors are
known as compile-time errors. Whenever the compiler displays an error, it will not create the .class
file. It is therefore necessary that we fix all the errors before we can successfully compile and run
the program.
b) Run – time errors:
Sometimes, a program may compile successfully creating the .class file but may not run properly.
Such programs may produce wrong results due to wrong logic or may terminate due to errors such
as stack overflow. Most common run-time errors are
Dividing an integer by zero
Accessing an element that is out of the bounds of an array
Page 74
3.1.1. Exception Handling Techniques
Java exception handling is managed via five keywords
1. try
2. catch
3. finally
4. throw
5. throws
Page 75
}
}}
This program to run then the output as follows
Divide by zero
Note that the program did not stop at the point of exceptional condition. It catches the error
condition, prints the error message, and then continues the execution.
Syntax : try
{
statement;
}
catch (Exception-type e)
{
statement;
}
catch (Exception-type e1)
{
statement;
}
finally
{
statement;
}
Example :
class exe2
{
public static void main(String args[])
{
try
{
int a=10;
int c,b;
b=[Link](args[0]);
c=a/b; [Link](―c=
―+c);
}
catch(NumberFormatException e)
Page 76
{
[Link]("give only integer value");
}
catch(ArithmeticException e)
{
[Link]("divide by zero ");
}
finally
{
[Link]("Finally block ");
}
}}
3. throw Statements
So far you have only been catching exceptions that are thrown by the java runtime system.
However, it is possible for your program to throw an exception explicitly, using the throw
statement.
The general form of throw is shown here
throw throwable-instance;
here, throwable-instance must be an object of type throwable or a subclass of throwable.
Simple types , such as int or char, as well as non-throwable classes, such as string and object,
cannot be used as exceptions. There are two ways you can obtain a thrwoable object: using a
parameter into a catch clause, or creating one with the new operator .
The flow of execution stops immediately after the throw statement: any subsequent
statements are not executed. The nearest enclosing try block is inspected to see if it has a catch
statement that matches the type of the exception. If it does find a match, control is transferred to
that statement. If not, then the next enclosing try statements is inspected, and so on. If no matching
catch is found, then the default exception handler halts the program and prints the stack trace
Example:
class exe112
{
public static void main(String args[])
{
try
{
int N=9;
if(N%2==1)
{
throw new ArithmeticException(); // throw a exception to catch block
else
[Link]("N is even number‖);
}
catch(ArithmeticException e)
Page 77
{
[Link]("main block the error is " + e);
}
}
[Link]("main block is end ");
}}
4. throws Statements
If a method is capable of causing an exception that it does not handle, it must specify this
behaviour so that callers of the method can guard themselves against that exception. You do this by
including a throws clause in the method‘s declaration. A throws clause lists the types of exceptions
that a method might throw.
If some code within a method throws a checked exception, then the method must either
handle the exception or it must specify the exception using throws keyword.
It means if a method is throwing a checked exception then it should handle the exception
using try-catch block or it should declare the exception using throws keyword, otherwise the
program will give a compilation error.
Syntax
Type method-name(parameter-list) throws exception-list
{
body of method;
}
Example:
Class ThrDemo
{
Static void Thrmethod() throws IllegalAccessException
{
[Link]("inside throws ");
throw new IllegalAccessException;
}
public static void main(String args[])
{
try
{
Thrmethod();
} catch(IllegalAccessException e)
{
[Link]("Caught "+ e);
}}
Page 78
3.1.2. Types of Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as
the unchecked exception.:
Checked Exception
Unchecked Exception
1) Checked Exception
A checked exception is an exception that occurs at the compile time, these are also called as
compile time exceptions.
These exceptions cannot simply be ignored at the time of compilation, the programmer
should take care of these exceptions.
If some code within a method throws a checked exception, then the method must either
handle the exception or it must specify the exception using throws keyword.
It means if a method is throwing a checked exception then it should handle the exception
using try-catch block or it should declare the exception using throws keyword, otherwise the
program will give a compilation error.
The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions
2) Unchecked Exception
An unchecked exception is an exception that occurs at the time of execution. These are also
called as Runtime Exceptions. These include programming bugs, such as logic errors or
improper use of an API.
Runtime exceptions are ignored at the time of compilation.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions
The classes which inherit RuntimeException are known as unchecked exceptions
Example: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
Page 79
A hierarchy of Java Exception classes are given below
Page 81
[Link] Programming
Introduction to Thread and Main thread
Multithreading enable you to write very efficient program that make maximum use of the
CPU, because idle time of CPU can be kept to a minimum.
Multiprogramming:
The more than one programs are executed (run) concurrently at a time that it is called
multiprogramming. The almost all latest operating system is performed the multiprogramming. The
multiprogramming is also called Multitasking.
► Multithreading in java is a process of executing multiple threads simultaneously.
► A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
► Every thread in Java is created and controlled by the [Link] class.
Signature Description
String getName() Retrieves the name of running thread.
void setName(String name) It is used to set name for thread
void start() This method will start a new thread of execution by calling
run() method of Thread/runnable object.
void run() This method is the entry point of the thread. Execution of
thread starts from this method.
void sleep (int sleeptime) This method stops the thread for mentioned time duration in
argument (sleeptime in ms)
void yield() By invoking this method the current thread pause its execution
temporarily and allow other threads to execute.
void join() This method used to queue up a thread in execution. Once
called on thread, current thread will wait till calling thread
completes its execution
boolean isAlive() This method will check if thread is alive or dead
int getPriority() To retrieve priority of Thread
void It is used to set the priority value. There are 3 priorities.
setPriority(priorityConstant) MIN_PRIORITY , MAX_PRIORITY , NORM_PRORITY
Page 83
3.2.1. Thread Creation using Thread Class and Runnable Interface
► Every thread in Java is created and controlled by the [Link] class and manage
the thread its objects.
In java, we can create the Thread in Two way
a) Runnable interface implementing
b) Thread class extending
Inside run( ) , you will define the code that constitutes the new thread. It is important to
understand the run( ) can call other methods, use other classes, and declare variables, just like the
main thread .
Syntax
Class x implements Runnable
{
………….
}
After the new thread is created, it will not start running until you call its start( ) method, which is
declared within Thread. In essence, start( ) executes a call to run( ). The start( ) method is shown
here:
void start( )
Simple Example:
class exthread implements Runnable
{
exthread()
{
Thread t=new Thread(this,"demo thread");
[Link]("Child thread"+t);
[Link]();
}
public void run()
{
// child thread coding
}
Example : Program
class exthread implements Runnable
{
exthread()
{
Thread t=new Thread(this,"demo thread");
[Link]("Child thread"+t);
[Link]();
}
public void run()
{
try
{
for(int i=1;i<5;i++)
{
[Link]("child thread value is "+i);
[Link](500);
}}
catch(InterruptedException e)
{
[Link]("child interrupted");
}
[Link]("exiting the child thread");
}}
class Demothr
{
public static void main(String args[])
{
new exthread();
try
{
for(int i=10;i<15;i++)
{
[Link]("main thread "+i);
[Link](1000);
}}
catch(InterruptedException e)
{
[Link]("Main thread interrupted");
}
[Link]("exiting the main thread");
}}
Output
Page 85
Child thread: Tread[demo thread,5, main]
Main Thread: 5
Child thread: 5
……..
Child thread: 1
Exiting child thread
Main Thread: 1
Main thread exiting
Page 86
Simple Example:
class Ath extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link]("\t from thread a :i = "+i);
}
[Link]("exit form a");
}}
Page 87
Bth T2=new Bth(); [Link]();
Cth T3=new Cth() ; T3..start();
}}
Running State:--
If the thread is in execution then it is said to be in running state.
The thread can finish its work and end normally.
The thread can also be forced to give up the control when one of the following conditions
arise
A thread can be suspended by suspend( ) method. A suspended thread can be revived by
using the resume() method.
A thread can be made to sleep for a particular time by using the sleep(milliseconds) method.
Page 88
Blocked State:--
A thread is said to be in blocked state if it prevented from entering into the runnable state
and so the running state.
The thread enters the blocked state when it is suspended, made to sleep() or wait().
Dead State:--
The running thread ends its life when it has completed executing the run( ) method which is
called natural dead.
The thread can also be killed at any stage by using the stop( ) method.
MIN_PRIORITY = 1
NORM_PRIORITY= 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value between 1 and 10. Note that the
default setting is NORM_PRIORITY.
Simple Example
Class SPriority extends Thread
{
}
Class demo{
public static void main(String args[])
{
SPriority m1=new SPriority();
SPriority m2=new SPriority();
[Link](Thread.MIN_PRIORITY);
[Link](6);
[Link]("Thread priorityis:"+[Link]());
}}
Method: setPriority() - used to set priority value to thread
getPriority() - used to get priority value from running thread
Page 89
Program: Write a JAVA Program on Thread Priorities.
import [Link].*;
classTestPriority extends Thread
{
public void run()
{
[Link]("Thread name is:"+[Link]().getName());
[Link]("Thread priorityis:"+[Link]().getPriority());
}
}
class Demo2
{
public static void main(String args[])
{
TestPriority m1=new TestPriority();
Page 90
for(int x=200;x<203;x++)
{
[Link]("a thread x value is"+x);
}}}
b) Using synchronized Statements
Syntax:
synchronized (object)
{ }
Page 91
}}
class th12
{
public static void main(String args[])
{
new a().start();
new b().start();
}}
In this program first class a process completed then the class b process will be started.
Join method in Java allows one thread to wait until another thread completes its
execution. In simpler words, it means it waits for the other thread to die. It has a void type and
throws InterruptedException.
This process is like a relay race where the second runner waits until the first runner comes and hand
over the flag to him.
It provides services to user threads for background supporting tasks. It has no role in life
than to serve user threads.
Its life depends on user threads.
It is a low priority thread.
Methods for Java Daemon thread
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
1) [Link]: standard output stream
2) [Link]: standard input stream
3) [Link]: standard error stream
Java programs perform I/O through streams. A stream is an abstraction that either produces
or consumes information. A stream is linked to a physical device by the java I/O system. All
streams behave in the same manner, even if the actual physical devices to which they are linked
differ.
Page 93
Thus, the same I/O classes and methods can be applied to any type of device. This means that
an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a
network socket.
Likewise, an output stream may refer to the console, a disk file, or a network connection.
Types of Stream:
Java defines two types of Streams:
1. Byte Streams
2. Character Streams.
The abstract classes InputStream and OutputStream define several key methods that the
other stream classes implement. Two of the most implement are read( ) and write( ), which
respectively, read and write bytes of data. Both methods are declared as abstract inside InputStream &
OutputStream.
InputStream Method:
Method Description
1) int read() reads the next byte of data from the input stream. It returns -1 at the end of the file.
2) int read(byte[] buf) reads data up to buffer length of byte from the input stream. It returns -1 at the
end of the file.
Page 94
3) int available() returns an estimate of the number of bytes that can be read from the current input
stream.
4) void close() is used to close the current input stream.
OutputStream. Method
Method Description
1) void write(byte) is used to write a byte to the current output stream.
2) void write(byte[]) is used to write an array of byte to the current output stream.
3) void flush() flushes the current output stream.
4) void close() is used to close the current output stream.
Example
BufferedInputStream br=new BufferedInputStream([Link]);
byte name[];
try{
name=[Link]();
}catcha( IOException e){}
Simple program
import [Link].*;
public class Example {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("[Link]");
BufferedWriter buffer = new BufferedWriter(writer);
[Link]("Welcome to javaTpoint.");
[Link]();
[Link]("Success");
}
}
Page 95
StringWriter Output stream that writes to a string
Method:
String readLine() - read a line of text
int read() - read a single character.
void reset() -This method resets the stream.
Example
InputStreamReader br=new InputStreamReader([Link]);
BufferedReader r=new BufferedReader(br);
String name;
int a;
float b;
try{
name=[Link](); //read a string
a= [Link]([Link]()}; // read a string & convert to integer
b= [Link]([Link]()); // read a string & convert to float
} catch(IOException e){}
You can be used the method (nextInt()) of Scanner class to read the data. The scanner class
are available in [Link] package.
[Link];
Scanner in=new Scanner([Link]);
int a;
float b;
a=[Link]();
b=[Link]();
Page 96
through [Link].
Page 97
3.3.3. FILE Handling Classes:
We have used variables and arrays for storing data inside the programs. This approach poses
the following problems.
The data is lost either when a variable goes out of scope or when the program is terminated.
That is , the storage is temporary.
It is difficult to handle large volumes of data using variables and arrays.
We can overcome these problems by storing data on secondary storage devices such as
floppy disks or hard disks. The data is stored in these devices using the concept of files.
What is file?
A file is a collection of related records placed in particular area on the disk. Storing and
managing data using files is known as file processing which includes tasks such as creating files,
updating files and manipulation of data.
CREATION OF FILES:
If we want to create and use a disk file, we need to decide the following about the Intended
purpose.
Suitable name of the file
Data type to be stored
Purpose ( reading, writing, or updating)
Method of creating the file.
Example: Program
In this program , two file stream classes to copy the contents of a file amed [Link]‖
into a file called ―[Link]‖.
//coping characters from one file into another
import [Link].*;
class Demofile1
{
public static void main(String args[])
{
File infile=new File("[Link]");
File outfile=new File("[Link]");
FileReader ins=null;
FileWriter outs=null;
try
{
ins=new FileReader(infile);
outs=new FileWriter(outfile);
int ch;
while((ch=[Link]()) !=-1)
{
[Link](ch);
}
}
catch(IOException e)
{
[Link](e);
}
finally
{
try
{
[Link]();
[Link]();
}
Page 99
catch(IOException e)
{
[Link]("interupted");
}}}}
this program is very simple. It creates two file objects inFile & outFile and initializes them
with ―[Link]‖, and ―[Link]‖ respectively using the following code.
File infile= new File(―[Link]‖);
File outfile=new File(―[Link]‖);
The program then creates two file stream objects ins & outs and initializes them with ―null‖
as follows.
FileReader ins=null;
FileWriter outs=null;
These Streams are then connected to the named files using the following codes
ins=new FileReader(infile);
outs=new FileWriter(outfile);
This connects infile to the FileReader stream ins and outfile to the FileWriter stream outs.
This essentially means that the files ―[Link]‖ and ―[Link]‖ are opened. The statements
ch=[Link]( )
Reads a character from the infile through the input stream ins and assigns it to the variable ch
similarly, the statement
[Link](ch);
writes the character stored in the variable ch to the outfile through the output stream outs. The
character-1 indicates the end of the file and therefore the code
while((ch=[Link]( )) != -1)
causes the termination of the while loop when the end of the file is reached. The statements
[Link]( ); [Link]( );
enclosed in the finally( ) clause close the files created for reading and writing. When the
program catches an I/O exception, it prints a message and then exits from execution.
Example:
FileInputStream, FileOutputStream:
import [Link].*;
class Demofile2
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]);
String str;
try
{
FileOutputStream fos=new FileOutputStream("[Link]");
for(int i=1;i<5;i++)
{
Str=[Link]();
[Link](Str);
}
[Link]();
Page 100
}
catch(IOException e)
{
[Link](e);
}}}
In this program create a new file that is ―[Link]‖ and write the numbers between 1 and 10
and close that file.
import [Link].*;
class Demofile3
{
public static void main(String args[])
{
try
{
FileInputStream fis=new FileInputStream("[Link]");
int i;
while((i=[Link]())!=-1)
{
[Link](i);
}
[Link]();
}
catch(IOException e)
{
[Link](e);
}}}
In this program to open a new file that is ―[Link]‖ and read the message and print the
message to your console normal screen.
Page 101
Here , newpos specifies the new position, in bytes, of the file pointer from the beginning of the file.
After call to seek( ), the next read or write operation will occur at the new file position.
Example:
import [Link].*;
class RanFile
{
public static void main(String args[])
{
RandomAccessFile file=null;
try
{
file=new RandomAccessFile("[Link]","rw");
[Link]('A');
[Link](102);
[Link](42.45);
[Link](0); //go to the begining
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link](2);//go to the second item
[Link]([Link]());
[Link]([Link]());//go to the end and append false to the file
[Link](false);
[Link](3);
[Link]([Link]());
[Link]();
}
catch(IOException e)
{
[Link](e);
}
}}
In this program first to create a new file that is ―[Link]‖ that file is read and write file. Then
to write three message on that file. Then read on that file and print the message on the screen one by
one.
Then use of the seek( ) method and print the second message. Then use of length class to add
another message on that file.
Then use of the seek method to print the new (that is fourth) message on the screen.
This process is only available on RandomAccessFile method only.
The output as follows:
A
102
42.45
102
True
Page 102
b) Sequential File
SequenceInputStream:
The SequenceInputStream class allows you to concatenate multiple InputStream. The
construction of SequenceInputStream is different from any other InputStream. A
SequenceInputStream constructor use either a pair of InputStream or an Enumeration of
InputStream as its argument.
SequenceInputStream(InputStream first, InputStream second)
SequenceInputStream(Enumeration stream Enum)
Example
import [Link].*;
class Demofile5
{
public static void main(String args[])throws IOException
{
FileInputStream file1=null;
FileInputStream file2=null;
SequenceInputStream file3=null;
file1=new FileInputStream("[Link]");
file2=new FileInputStream("[Link]");
file3=new SequenceInputStream(file1,file2);
BufferedInputStream inb=new BufferedInputStream(file3);
BufferedOutputStream ob=new BufferedOutputStream([Link]);
int ch;
while((ch=[Link]())!=-1)
{
[Link]((char)ch);
}
[Link]();
[Link]();
[Link]();
[Link]();
}}
In this program to create two file that is ―[Link]‖ and ―[Link]‖ and write some message.
Then to store file3 that is SequenceInputStream it includes [Link] , [Link] (that is file1,file2).
Then file3 to be stored on BufferedInputStream. Then use of BufferedOutputStream to read the
character from file3 and print the message on to the screen.
Page 103
Sample Questions
Two Mark Questions
1. Define Exception
2. What is meant by compile time and run time error?
3. What is Uncheck Exception?
4. Write the use of Throws keyword?
5. List out built-in Exception.
6. Define Thread and Multithread.
7. What is meant by Multiprogramming?
8. Write run() & start() method.
9. Tell about Thread Priority.
10. What is meant by Daemon thread?
11. Define file.
12. What is stream?
13. List out Byte Stream Classes
14. What is Random Access file?
15. How to create file stream object?
Descriptive Questions
Page 104
UNIT-IV
Applet and GUI Part I. Fundamentals – applet class – life cycle – steps for applet program – passing
values through parameters – graphics – event handling; GUI I:GUI – creating windows – dialog
boxes – layout managers – AWT component classes – Swing component classes – applications of
AWT controls.
An applet developed locally and stored in a local system in known as local applet.
An remote applet is that which is developed by someone else and stored on a remote computer
connected to the internet. If our system is connected to the internet, we can download the remote
applet onto our system via the Internet and run it.
In order to locate and load a remote applet, we must know the applet‘s address on the web.
This address is known as Uniform Resource Locator(URL) and must be specified in the applet‘s
HTML document as the value of CODEBASE attribute.
All Applets program are subclasses of Applet. Thus all applets must import [Link]
package. Applets must also import [Link] package. Recall the AWT Abstract Window
Toolkit. Since all applets run in a window, it is necessary to include support for the window.
Applets are not executed by the console-based java run-time interpreter. Rather, they are executed
by either a web browser or an applet viewer.
Output to your applet‘s window is not performed by [Link]( ). Rather, it is
handled with various AWT methods, such as drawstring( ), which outputs a string to a specified
x,y location. Once an applet program has been compiled, it is included in an HTML file using the
APPLET TAG.
The applet will be executed by a java-enabled web browser when it encounters the APPLET
TAG within the HTML file. To view and test an applet more conveniently, simply include a
comment at the head of your java source code file that contains the APPLET tag. This
way, your code is documented with the necessary HTML statements needed by your applet, and
you can test the compiled applet by starting the applet viewer with your java source code file
specified as the target.
Page 105
Applets do not use the main( ) method for initiating the execution of the code. Applets,
when loaded, automatically call certain methods of Applet class to start and execute the applet
code.
Unlike stand-alone applications, applets cannot be run independently. They are run from
inside a web page using a special feature known as HTML tag.
Applets cannot read from or write to the files in the local computer.
Applets cannot communicate with other servers on the network.
Applets cannot run any program form the local computer.
Applets are restricted from using libraries from other languages such as c or c++.
An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.
import [Link].*;
import [Link].*;
public class AppletTest extends Applet
Page 106
{
public void init()
{
//initialization
}
public void start ()
{
//start or resume execution
}
public void stop()
{
//suspend execution
{
public void destroy()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}
APPLET ARCHITECTURE:
An applet is a window-based program. As such, its architecture is different from the so-
called normal, console-based programs. If you are familiar with windows programming, you will
be right at home writing applets.
Applets are event driven. It is important to understand in a general way how the event-driven
architecture impacts the design of an applet. An applet resembles a set of interrupt service routines.
Here is how the process works. An applet waits until an event occurs. The AWT notifies the applet
about an event by calling an event handler that has been provided by the applet.
The user initiates interaction with an applet – not the other way around. As you know, in a
non windowed program, when the program needs input, it will prompt the user and then call some
input method, such as readLine( ). This is not the way it works in an applet. Instead, the user
interacts with the applet as he or she wants, when he or she wants.
These interactions are sent to the applet as events to which the applet a mouse-clicked event
is generated. If the user presses a key while the applet‘s window has input focus, a key press event
is generated. Applets can contain various controls, such as push buttons and check boxes. When
the user interacts with one of these controls, an event is generated.
While the architecture of an applet is not as easy to understand as that of a console-based program,
java‘s AWT makes it as simple as possible.
Page 107
4.3. APPLET Tag in HTML:
The APPLET tag is used to start an applet from both an HTML(Hyper Text Markup
Language) document and from an applet viewer. (The newer OBJECT tag also works, but it will
use APPLET).
An applet viewer will execute each APPLET tag that if finds in a separate window, while
web browsers like Netscape Navigator, Internet Explorer, and HotJava will allow many applets on
a single page. So far, we have been using only a simplified form of the APPLET tag.
The syntax for the standard APPLET tag is shown here. Bracketed items are optional.
<APPLET
[CODEBASE = codebase URL]
CODE = applet file
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment] >
[<PARAM NAME = Attribute Name VALUE = Attribute value> ]
[<PARAM NAME = Attribute Name2 VALUE = attribute value> ]
</APPLET>
[Link]:
It is a required attribute that gives the name of the file containing your applet‘s compiled
.class file. This file is relative to the code base URL of the applet, which is the directory that the
HTML file was in or the directory indicated by CODEBASE if set.
[Link]:
It is an optional attribute that specifies the alignment of the applet. This attributes is treated
the same as the HTML IMG tag with these possible values: LEFT, RIGHT, TOP, BOTTOM,
MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.
Page 108
4.4. Steps to Create Applet program
1. Import [Link].* and [Link].* package in applet program.
2. Create a class that it is subclass of Applet class
3. If you need, define the init() & start() method.
4. Define the paint() method.
5. To display a text information use drawString() method and also audio , video and image
use suitable methods.
6. If you need, define the staop() & destroay() method.
7. To add Applet tag in the program as comment line (/* -- */)
8. Compile the Applet program.
9. Run the program on appletviewer or Any web browser.
Run By appletViewer
Example of Applet program:
import [Link].*;
import [Link].*;
/*
<applet code="[Link]" height = 400 width = 200 >
</applet>
*/
public class app1 extends Applet
{
public void paint(Graphics g)
{
[Link]("Hello World",30,30); Output
}}
Compile :
D:\RM>javac [Link].
Run :
D:\RM>: appletviewer [Link].
Output:
Page 109
Run By HTML File in Web Browser
1. Create a Java program: Save as [Link]
Simple example:
import [Link].*;
import [Link].*;
/*
<applet code="app3" width =400 height = 500>
<param name=name value="Kannan">
</applet>
*/
public class app3 extends Applet
{
String Name1;
Page 110
public void init()
{
Name1=getParameter("name");
}
public void paint(Graphics g)
{
[Link](―Name=‖+Name1,50,50);
}}}
Page 111
4.6. Applet Class and Methods
Every applet is an extension of the [Link] class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the browser
context.
These include methods that do the following −
Get applet parameters
Fetch an image
Fetch an audio clip
Play an audio clip
Print a status message in the browser
Resize the applet
Get the network location of the HTML file that contains the applet
Get the network location of the applet class directory
Request information about the author, version, and copyright of the applet
Request a description of the parameters the applet recognizes
Initialize the applet
Destroy the applet
Start the applet's execution
Stop the applet's execution
The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the
paint method.
[Link] in applet
Method Description
1. URL getCodeBase( ) - Returns the URL associated with the invoking applet.
2. URL getDocumentBase( ) - Returns the URL of the HTML document that invokes the
applet.
3. Image getImage(URL url) -Returns an Image object that encapsulates the image found at
the location specified by url.
4. Image getImage(URL url,String imageName) - Returns an Image object that encapsulates
the imagefound at the location specified by url and having the
name specified by imageName.
5. Locale getLocale( )- Returns a Locale object that is used by various localesensitive
classes and methods.
6. String getParameter(String paramName) - Returns the parameter associated with
paramName.
.
7. String[ ] [ ] getParameterInfo( ) - Returns a String table that describes the parameters
recognized by the applet. Each entry in the table must consist of three strings that contain
the name of the parameter, a description of its type and/or range, and an explanation of its
purpose.
Page 112
8. boolean isActive( ) Returns true if the applet has been started. It returns false if the applet
has been stopped.
9. static final AudioClipnewAudioClip(URL url) - Returns an AudioClip object that
encapsulates the audio clip found at the location specified by url. This method is similar to
getAudioClip( ) except that it is static and can be executed without the need for an Applet
object.
10. void play(URL url) - If an audio clip is found at the location specified by url, the clip is
played.
11. void resize(Dimension dim) - Resizes the applet according to the dimensions specified by
dim. Dimension is a class stored inside [Link]. It contains two integer fields: width and
height.
12.
1. void drawString(String str, int x, int y): is used to draw the specified string.
2. void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.
3. void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default
color and specified width and height.
4. void drawOval(int x, int y, int width, int height): is used to draw oval with the specified
width and height.
5. void fillOval(int x, int y, int width, int height): is used to fill oval with the default color
and specified width and height.
6. void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1,
y1) and (x2, y2).
7. boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the
specified image.
8. void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used
draw a circular or elliptical arc.
9. void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill
a circular or elliptical arc.
10. void setColor(Color c): is used to set the graphics current color to the specified color.
11. void setFont(Font font): is used to set the graphics current font to the specified font.
import [Link];
import [Link].*;
Page 113
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
[Link]([Link]);
[Link]("Welcome",50, 50);
[Link](20,30,20,300);
[Link](70,100,30,30);
[Link](170,100,30,30);
[Link](70,200,30,30);
[Link]([Link]);
[Link](170,200,30,30);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
}
}
/*<applet code="[Link]" width="300" height="300">
</applet> */
In the above example, drawImage() method of Graphics class is used to display the image. The 4th
argument of drawImage() method of is ImageObserver object. The Component class implements
ImageObserver interface. So current class object would also be treated as ImageObserver because
Applet class indirectly extends the Component class.
• public void play(): Plays the audio clip one time, from the beginning.
• public void loop(): Causes the audio clip to replay continually.
• public void stop(): Stops playing the audio clip.
To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class.
The getAudioClip() method returns immediately, whether or not the URL resolves to an actual
audio file. The audio file is not downloaded until an attempt is made to play the audio clip.
Page 115
}
try
{
URL url =new URL([Link](), audioURL);
clip = [Link](url);
}catch(MalformedURLException e)
{
[Link]();
[Link]("Could not load audio file!");
}}
public void start()
{
if(clip !=null)
{
[Link]();
}}
publicvoid stop()
{
if(clip !=null)
{
[Link]();
}}}
Page 116
4.10. Event Handling in applet:
Applets inherit a group of event-handling methods from the Container class. The
Container class defines several methods, such as process KeyEvent and process MouseEvent, for
handling particular types of events, and then one catch-all method called processEvent. In order to
react an event, an applet must override the appropriate event-specific method.
import [Link];
import [Link];
import [Link];
import [Link];
public class ExampleEventHandling extends Applet implements MouseListener{
StringBuffer strBuffer;
public void init(){
addMouseListener(this);
strBuffer =new StringBuffer();
addItem("initializing the apple ");
}
public void start(){
addItem("starting the applet ");
}
public void stop(){
addItem("stopping the applet ");
}
public void destroy(){
addItem("unloading the applet");
}
void addItem(String word){
[Link](word);
[Link](word);
repaint();
}
public void paint(Graphics g){
//Draw a Rectangle around the applet's display area.
[Link](0,0,
getWidth()-1,
getHeight()-1);
//display the string inside the rectangle.
[Link]([Link](),10,20);
}
public void mouseEntered(MouseEvent event){
Page 117
}
public void mouseExited(MouseEvent event){
}
public void mousePressed(MouseEvent event){
}
public void mouseReleased(MouseEvent event){
}
publicvoid mouseClicked(MouseEventevent){
addItem("mouse clicked! ");
}
}
Now, let us call this applet as follows
<html>
<title>Event Handling</title>
<hr>
<applet code="[Link]" width="300" height="300">
</applet>
<hr>
</html>
Initially, the applet will display "initializing the applet. Starting the applet. ." Then once you
click inside the rectangle "mouse clicked" will be displayed as well.
Graphical User Interface (GUI) offers user interaction via some graphical components. For
example our underlying Operating System also offers GUI via window, frame, Panel, Button,
Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are known as
components.
Using these components we can create an interactive user interface for an application.
GUI provides result to end user in response to raised events. GUI is entirely based events. For
example clicking over a button, closing a window, opening a window, typing something in a
Page 118
textarea etc. These activities are known as events. GUI makes it easier for the end user to use an
application. It also makes them interesting.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components uses the resources of system.
The [Link] package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
1. Component
At the top of the AWT is the Component class. Component is a abstract class that
encapsulates all of the attributes of a visual components. All user interface elements that ae
display on screen and interact with user are subclass of component.
2. Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extend Container class are known as container such as
Frame, Dialog and Panel.
3. Window
Page 119
The Window class creates a top-level window. A top-level window is not contained within
any other object; it sits directly on the desktop. Generally , you won‘t create Window objects
directly. Instead, you will use a subclass of Window called Frame, described next.
The window is the container that has no borders and menu bars. You must use frame, dialog
or another window for creating a window.
4. Panel
The Panel class is concrete subclass of Container . The Panel is the container that doesn't
contain title bar and menu bars. It can have other components like button, textfield etc.
5. Frame
The Frame is the container that contain title bar and can have menu bars border resizing
corner. It can have other components like button, textfield etc.
6. Canvas
Although it is not part of hierarchy for applet or frame window, there is another type of
window that you will find valuable. Canvas encapsulates a blank window upon which you can
draw.
The AWT classes are contained in the [Link] package. It is one of Java‘s largest
packages. Fortunately, because it is logically organized in a top-down, hierarchical fashion, it is
easier to understand and use than you might at first believe. Lists some of the many AWT classes.
Class Description
AWTEvent - Encapsulates AWT events.
AWTEventMulticaster -Dispatches events to multiple listeners.
BorderLayout -The border layout manager. Border layouts use five components:
North, South, East, West, and Center.
Button - Creates a push button control.
Canvas - A blank, semantics-free window.
CardLayout - The card layout manager. Card layouts emulate index cards.
Checkbox - Creates a check box control.
Page 120
CheckboxGroup - Creates a group of check box controls.
CheckboxMenuItem- Creates an on/off menu item.
Choice - Creates a pop-up list.
Color - Manages colors in a portable, platform-independent fashion.
Component - An abstract superclass for various AWT components.
Container - A subclass of Component that can hold other components.
Event - Encapsulates events.
FlowLayout - The flow layout manager. Flow layout positions components left
to right, top to bottom.
Font - Encapsulates a type font.
Frame - Creates a standard window that has a title bar, resize
corners, and a menu bar.
Image - Encapsulates graphical images.
Label - Creates a label that displays a string.
List -Creates a list from which the user can choose. Similar to the
standard Windows list box.
Menu - Creates a pull-down menu.
MenuBar - Creates a menu bar.
AWT Methods of Component class, All method as public.
Method Description
Page 121
void setTitle(String newTitle)
here, newTitle is the new title for the window.
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
Page 122
Each Container object has a layout manager associated with it. A layout manager is an instance
of any class that implements the LayoutManager interface. The layout manager is set by the
setLayout( ) method. If no call to setLayout( ) is made, then the default layout manager is used.
The setLayout( ) method has the following general form
1. BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west
and center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
import [Link].*;
import [Link].*;
public class Border {
JFrame f;
Border(){
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
[Link](b1,[Link]);
Page 123
[Link](b2,[Link]);
[Link](b3,[Link]);
[Link](b4,[Link]);
[Link](b5,[Link]);
[Link](300,300);
[Link](true);
}
public static void main(String[] args) {
new Border();
} }
2. FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is
the default layout of applet or panel.
Fields of FlowLayout class:
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class:
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal
and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.
Example of FlowLayout class:
import [Link].*;
import [Link].*;
public class MyFlowLayout {
JFrame f;
MyFlowLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
Page 124
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
[Link](b1); [Link](b2); [Link](b3); [Link](b4); [Link](b5);
[Link](new FlowLayout([Link]));
//setting flow layout of right alignment
[Link](300,300); [Link](true);
}
public static void main(String[] args) {
new MyFlowLayout();
} }
3. GridLayout
GridLayout lays out components in a two-dimensional grid. When you instantiate a GidLayout,
you define the number of rows and columns. The constructors supported by gridlayout ar shown
here
GridLayout() - Creates a new Gridlaout layout
GridLayout(int numRows, int numColumns) –
Creates a Gridlayout with the specified rows, columns
GridLayout(int numRows, int numColumns , int horz, int vert) –
Creates a Gridlayout with the specified rows with horizontal & vertical gaps
Here, this form creates a grid layout with the specified number of rows and columns.
Example:
import [Link].*;
import [Link].*;
//example of gridlayout
/*
<applet code = "app15" width = 300 height = 200>
</applet>
*/
public class app15 extends Applet
{
public void init()
{
setLayout(new GridLayout(3,4,10,10));
for(int i=1;i<=9;++i)
add(new Button(" "+i));
}}
Page 125
4. CardLayout
The class CardLayout arranges each component in the container as a card. Only one card is
visible at a time, and the container acts as a stack of cards.
CardLayout provides the two Constructors to create the card layout container. They are:
CardLayoutExample1()
{
cPane = getContentPane();
crd = new CardLayout();
[Link](crd);
// adding listeners to it
[Link](this);
[Link](this);
[Link](this);
[Link]("a", btn1); // first card is the button btn1
[Link]("b", btn2); // first card is the button btn2
[Link]("c", btn3); // first card is the button btn3
}
Page 126
5. GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.
The components may not be of the same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as its display
area. Each component associates an instance of GridBagConstraints. With the help of the
constraints object, we arrange the component's display area on the grid. The GridBagLayout
manages each component's minimum and preferred sizes in order to determine the component's
size. GridBagLayout components are also arranged in the rectangular grid but can have many
different sizes and can occupy multiple rows or columns.
Constructor
GridBagLayout(): The parameterless constructor is used to create a grid bag layout manager.
Example:
import [Link];
import [Link];
import [Link];
import [Link].*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
[Link](layout);
[Link] = [Link];
[Link] = 0;
[Link] = 0;
[Link](new Button("Button One"), gbc);
[Link] = 1;
[Link] = 0;
Page 127
[Link](new Button("Button two"), gbc);
[Link] = [Link];
[Link] = 20;
[Link] = 0;
[Link] = 1;
[Link](new Button("Button Three"), gbc);
[Link] = 1;
[Link] = 1;
[Link](new Button("Button Four"), gbc);
[Link] = 0; [Link] = 2;
[Link] = [Link];
[Link] = 2;
[Link](new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
0 Component
A Component is an abstract super class for GUI controls and it represents an
object with graphical representation.
Page 128
1 Label A Label object is a component for placing text in a container.
4 Check Box Group -The CheckboxGroup class is used to group the set of
checkbox.
5 List -The List component presents the user with a scrolling list of text items.
6 Text Field - A TextField object is a text component that allows for the editing
of a single line of text.
7 Text Area -A TextArea object is a text component that allows for the editing
of a multiple lines of text.
13 File Dialog - A FileDialog control represents a dialog window from which the
user can select a file.
1. 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( ) ,
Label (String str) ,
Label(String str, int how)
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.
Page 129
The value of how must be one of these three constants: [Link], [Link],
[Link].
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)
void getText( )
For setText( ), str specifies the new label. For getText( ), the current label is returned.
Example: public void init()
{
Label Label("a value");
add(one);
}
2. 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. TextFields is a subclass of TextComponent. TextField defines the
following constructors:
TextField( )
TextField(int numchars)
TextField(String str)
TextField(String str, int numchars)
The first version creates a default text field. The second form creates a text field that is
numchars characters eide. The third form initializes the text field with the string contained in str.
The fourth form initializes text field and sets it width.
TextField (and its superclass TextComponint) 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.
Example
public void init()
{
TextField T1=new TextField(8);
add(T1);
[Link]("0");
}
3. Buttons
The most widely used control is the push button. A push button is a component that contains a
label and the generates an event when it is pressed. Push buttons are objects of type Button. Button
defines these two constructors:
Button( )
Button(String str)
The first version creates an empty button. The second creates a button that contains str as a label.
Handling Buttons:
Page 130
Each time a button is pressed, an action event is generated. Each listener implements the
ActionListener interface. That interface defines the actionPerformed( ) method, which is called
when an event occurs. An ActionEvent objects is supplied as the argument to this method.
Example:
public class app10 extends Applet implements ActionListener
{
public void init()
{
Button b1=new Button("apple");
[Link](this);
add(b1);
}
public void actionPerformed(ActionEvent ae)
{
[Link]([Link]());
}}
4. 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 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( )
Checkbox(String str)
Checkbox(String str, Boolean on)
Checkbox(String str, Boolean on, CheckboxGroup cbgroup)
Checkbox(String str,CheckboxGroup cbgroup, Boolean on)
The first form creates a checkbox whose label is initially blank. The state of the check box in
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 in
initially checked; otherwise it si 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.
Handling Check Boxes:
Each time a check box is selected or deselected, an item event is generated. This is sent to any
listeners that previously registered an interest in receiving item event notifications from that
component. Each listener implements the ItemListener interface. The interface defines the
itemStateChanged( ) [Link] ItemEvent objects is supplied as the argument to this method.
Page 131
5. 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. Checkbox groups are objects of type CheckboxGroup. Only the default constructor
is defined, which creates an empty group.
CheckboxGroup c= new CheckboxGroup();
Checkbox c1=new Checkbox("black and white",c,true);
Checkbox c2=new Checkbox("Color",c,false);
6. Choice Controls:
The Choice class is used to create a pop-up lists 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.
Choice only defines the default constructor, which creates an empty list. To add a selection to the
list, call addItem( ) or add( ). They have these general forms:
void addItem(String name)
void add(String name)
Here, name is the name of the item being added. Items are added to the list in the order in which
calls to add( ) or addItem( ) occur.
Handling choice list:
Each time a choice is selected, an item event is generated. This is set to any listeners that
previously registered an interest in receiving item event notifications from that component. Each
listener implements the ItemListener interface. That interface defines the itemStateChanged(
)bmethod. An ItemEvent object is supplied as the argument to this method.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
//example of checkbox and choice
/* <applet code="app11" width=300 height =200>
</applet> */
public class app11 extends Applet
{
Label o1=new Label(" ");
Label o2=new Label(" ");
public void init()
{
CheckboxGroup c= new CheckboxGroup();
Checkbox c1=new Checkbox("black and white",c,true);
Checkbox c2=new Checkbox("Color",c,false);
[Link](new check1());
[Link](new check2());
add(c1);
Page 132
add(c2);
Choice abc=new Choice();
[Link]("onida");
[Link]("bpl");
[Link]("sumsung");
[Link]("philps");
[Link](new ch());
add(abc);
add(o1);
add(o2);
}
class check1 extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
[Link]("you have selected : black and whit tv");
}}
class check2 extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
[Link]("you have selected : color tv");
}}
class ch implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
String s= (String)[Link]();
[Link]("you have selected " + s + " brand");
}}}
7. 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 created allow multiple
selections.
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 he item to the end of the list.
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)
Example: List ob=new List();
Page 133
Example:
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="app12" height = 200 width = 300>
</applet>
*/
public class app12 extends Applet
{
List ob=new List();
TextField tx=new TextField(10);
Button b1=new Button("add");
String count[]={"one","two","three"};
public void start()
{
Label Label("text");
add(one);
add(tx);
for(int i=0;i<[Link];++i)
[Link](count[i]);
add(ob);
[Link](new Add());
add(b1);
}
class Add implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
[Link]([Link]());
}}}
8. Scroll Bars:
Scroll bars are used to select continuous values between a specified minimum and
maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is actually a
composite of several individual parts. Each end has an arrow that you can click to move the current
value of the scroll bar one unit in the direction of the arrow. The current value of the scroll bar
relative to its minimum and maximum values is indicated by the slider box for the scroll bar.
Scrollbar defines the following constructors:
Scrollbar( )
Scrollbar( int style)
Scrollbar(int style,int initial value, int thumbsize, int min, int max)
The first form creates a vertical scroll bar.
The second and third forms allow you to specify the orientation of the scrollbar. If style is
[Link], a vertical scroll bar is created. If style is [Link], the
scroll bar is horizontal.
Page 134
In the third form of the constructor, the initial value of the scroll bar is passed in initial
value. The number of units represented by the height of the thumb is passed int thumb size. The
minimum and maximum values for the scroll bar are specified by min and max.
Handling Scroll Bars:
To process scroll bar events, you need to implement the AdjustmentListerner interface.
Each time a user interacts with a scroll bar, an Adjustmentevent object is generated. Its
getAdjustmentType() method can be used to determinet the type of the adjustment.
[Link]:
Sometimes a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multilane editor called TextArea.
TextArea is a subclass of TextComponent. Therefore , it supports the getText( ), setText(
) methods described in the preceding section. TextArea adds the following methods:
void append(String str)
void insert(String str, int index)
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.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code = "app13" width = 300 height = 200>
</applet>
*/
public class app13 extends Applet implements AdjustmentListener
{
TextArea ta;
public void init()
{
Scrollbar sb=new Scrollbar([Link],0,0,0,100);
[Link](this);
add(sb);
ta=new TextArea(10,20);
add(ta);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
Scrollbar sb=(Scrollbar)[Link]();
[Link]("AdjustmentEvent :"+[Link]()+"\n");
}}
Page 135
Mycheckbox is an inner class that extends checkbox.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="app19" width = 300 height = 200>
</applet>
*/
public class app19 extends Applet
{
MyCheckbox cb1,cb2,cb3;
public void init()
{
cb1=new MyCheckbox("apple ");
add(cb1);
cb2=new MyCheckbox("orange");
add(cb2);
cb3=new MyCheckbox("mango");
add(cb3);
}
class MyCheckbox extends Checkbox
{
MyCheckbox(String label)
{
super(label);
enableEvents(AWTEvent.ITEM_EVENT_MASK);
}
public void processItemEvent(ItemEvent e)
{
showStatus("Checkbox name/state: "+getLabel()+"/"+getState());
}}}
Page 136
Programs and Questions:
1. Simple calculator
import [Link];
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
Maths Maths = new Maths();
double answer = 0;
double inputA, inputB;
char operator;
boolean done = false;
while (done == false) {
[Link]("Please enter your sum: ");
inputA = [Link]();
operator = [Link]().charAt(0);
inputB = [Link]();
switch (operator) {
case '+': answer = [Link](inputA, inputB);
break;
case '-': answer = [Link](inputA, inputB);
break;
case '*': answer = [Link](inputA, inputB);
break;
case '/': answer = [Link](inputA, inputB);
break;
case '^': answer = [Link](inputA, inputB);
break;
}
[Link](answer);
}
[Link]();
}}
And my second class...
public class Maths
{
double add(double a, double b) {
double answer = a+b;
return answer;
}
double subtract(double a, double b) {
double answer = a-b;
return answer;
}
double multiply(double a, double b)
{
Page 137
double answer = a*b;
return answer;
}
double divide(double a, double b)
{
double answer = a/b;
return answer;
}
double power(double a, double b){
double answer =a;
for (int x=2; x<=b; x++){
answer *= a;
} return answer;
}}
Page 138
EQ=new Button("EQ");
[Link](this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str=[Link]();
char ch=[Link](0);
if ( [Link](ch))
[Link]([Link]()+str);
else
if([Link]("add"))
{
v1=[Link]([Link]());
OP='+';
[Link]("");
}
else if([Link]("sub"))
{
v1=[Link]([Link]());
OP='-';
[Link]("");
}
else if([Link]("mul"))
{
Page 139
v1=[Link]([Link]());
OP='*';
[Link]("");
}
else if([Link]("div"))
{
v1=[Link]([Link]());
OP='/';
[Link]("");
}
else if([Link]("mod"))
{
v1=[Link]([Link]());
OP='%';
[Link]("");
}
if([Link]("EQ"))
{
v2=[Link]([Link]());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
[Link](""+result);
}
if([Link]("clear"))
{
[Link]("");
}}}
OUTPUT
Page 140
Sample Questions
Two Mark Question:
1. What is applet?
2. Write the use of start() & paint() methods.
3. Tell about the drawstring() method.
4. What are the use of Applet tag?
5. Write the use for PARAM tag.
6. What is use of CODEBASE attributes of Applet tag?
7. Tell about the getParametter() methods.
8. Define AWT and GUI.
9. List out the graphics methods of AWT.
10. Write the use of play() and loop() methods.
11. Define component in java.
12. Define Frame Class.
13. Write the use of add() method.
14. Tell about Label control.
15. Write about the checkbox control.
Descriptive Questions
1. Explain the Life cycle of Applet.
2. Illustrate the Applet Tag with example.
3. How to create a Applet program ? write steps and program.
4. Explain the Parameters passing to applet program.
5. Describe the Applet class and methods.
6. Write about the Graphic method of AWT.
7. Explain the AWT Component Class.
8. How to create a Frame windows in java?
9. Explain the AWT Layout Manager.
10. Explain the AWT Controls.
11. Explain the Label and TextField controls of AWT.
Page 141
UNIT-V
SWING AND DATABASE CONNECTIVITY
Swing API is set of extensible GUI Components to ease developer's life to create JAVA based
Front End/ GUI Applications. It is build upon top of AWT API and acts as replacement of AWT
API as it has almost every control corresponding to AWT controls. Swing component follows a
Model-View-Controller architecture to fulfill the following criterias.
A single API is to be sufficient to support multiple look and feel.
API is to model driven so that highest level API is not required to have the data.
API is to use the Java Bean model so that Builder Tools and IDE can provide better services
to the developers to use it.
MVC Architecture
Swing API architecture follows loosely based MVC architecture in the following manner.
A Model represents component's data.
View represents visual representation of the component's data.
Controller takes the input from the user on the view and reflects the changes in Component's
data.
Swing component have Model as a seperate element and View and Controller part are
clubbed in User Interface elements. Using this way, Swing has pluggable look-and-feel
architecture.
Swing features
Light Weight - Swing component are independent of native Operating System's API as
Swing API controls are rendered mostly using pure JAVA code instead of underlying
operating system calls.
Rich controls - Swing provides a rich set of advanced controls like Tree, TabbedPane,
slider, colorpicker, table controls
Highly Customizable - Swing controls can be customized in very easy way as visual
apperance is independent of internal representation.
Pluggable look-and-feel- SWING based GUI Application look and feel can be changed at
run time based on available values.
Java Swing 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.
Page 142
5.1.1. Difference between AWT and Swing
There are many differences between java awt and swing that are given below.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development
of desktop applications.
In the above example, we have created all the controls in init() method because it is invoked only
once.
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
5.2. LayoutManagers:
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout managers.
The layout manager automatically positions all the components within the container. If we do
not use layout manager then also the components are positioned by the default layout manager. It is
possible to layout the controls by hand but it becomes very difficult because of the following two
reasons.
It is very tedious to handle a large number of controls within the container.
Oftenly the width and height information of a component is not given when we need to
arrange them.
Page 144
1. GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
Constructors of GridLayout class:
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns
but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.
Example of GridLayout class:
import [Link].*;
import [Link].*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
[Link](b1);[Link](b2);[Link](b3);[Link](b4);[Link](b5);
[Link](b6);[Link](b7);[Link](b8);[Link](b9);
[Link](new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
[Link](300,300);
[Link](true);
}
public static void main(String[] args) {
new MyGridLayout();
}}
Page 145
5.3. Swing control
Following is the list of commonly used controls while designed GUI using SWING.
S. Control & Description
No
6 JList -A JList component presents the user with a scrolling list of text items.
8 JTextField A JTextField object is a text component that allows for the editing of a
single line of text.
10 JTextArea -A JTextArea object is a text component that allows for the editing of a
multiple lines of text.
13 JOptionPane -JOptionPane provides set of standard dialog boxes that prompt users
for a value or informs them of something.
15 JProgressBar -As the task progresses towards completion, the progress bar displays
the task's percentage of completion.
Page 146
16 JSlider -A JSlider lets the user graphically select a value by sliding a knob within a
bounded interval.
JSpinner A JSpinner is a single line input field that lets the user select a number or an
object value from an ordered sequence.
1. Jbutton control
The class JButton is an implementation of a push button. This component has a label and
generates an event when pressed. It can have Image also.
Class declaration
Following is the declaration for [Link] class −
public class Jbutton extends AbstractButton implements Accessible
Class constructors
S.N. Constructor & Description
2 JButton(Action a) -Creates a button where properties are taken from the Action
supplied.
5 JButton(String text, Icon icon) -Creates a button with initial text and an icon.
Class methods
S.N. Method & Description
1 AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JButton.
2 String getUIClassID() -Returns a string that specifies the name of the L&F class
that renders this component.
Page 147
is currently set as the default button on the RootPane, and if so, sets the RootPane's
default button to null to ensure the RootPane doesn't hold onto an invalid button
reference.
8 void updateUI() -Resets the UI property to a value from the current look and feel.
2. JtextField
The class JTextField is a component which allows the editing of a single line of text.
Class declaration
Following is the declaration for [Link] class −
public class JTextField extends JTextComponent implements SwingConstants
Field
Following are the fields for [Link] class −
static String notifyAction − Name of the action to send notification that the contents of the
field have been accepted.
Class constructors
S.N. Constructor & Description
2 void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this textfield.
Page 148
Sets the properties on this textfield to match those in the specified Action.
4 protected PropertyChangeListener
createActionPropertyChangeListener(Action a)
Creates and returns a PropertyChangeListener that is responsible for listening for
changes from the specified Action and updating the appropriate properties.
7 AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JTextField.
8 Action getAction() -Returns the currently set Action for this ActionEvent source,
or null if no Action is set.
4. JTextarea
JTextArea class
The JTextArea class is used to create a text area. It is a multiline area that displays the plain text
only.
Commonly used Constructors:
o JTextArea(): creates a text area that displays no text initially.
o JTextArea(String s): creates a text area that displays specified text initially.
o JTextArea(int row, int column): creates a text area with the specified number of rows and
columns that displays no text initially..
o JTextArea(String s, int row, int column): creates a text area with the specified number of
rows and columns that displays specified text.
Commonly used methods of JTextArea class:
1) public void setRows(int rows): is used to set specified number of rows.
2) public void setColumns(int cols):: is used to set specified number of columns.
Page 149
3) public void setFont(Font f): is used to set the specified font.
4) public void insert(String s, int position): is used to insert the specified text on the specified
position.
5) public void append(String s): is used to append the given text to the end of the document.
5. Jcombobox
JComboBox class:
The JComboBox class is used to create the combobox (drop-down list). At a time only one
item can be selected from the item list.
Commonly used Constructors of JComboBox class:
JComboBox()
JComboBox(Object[] items)
JComboBox(Vector<?> items)
Commonly used methods of JComboBox class:
1) public void addItem(Object anObject): is used to add an item to the item list.
2) public void removeItem(Object anObject): is used to delete an item to the item list.
3) public void removeAllItems(): is used to remove all the items from the list.
4) public void setEditable(boolean b): is used to determine whether the JComboBox is editable.
5) public void addActionListener(ActionListener a): is used to add the ActionListener.
6) public void addItemListener(ItemListener i): is used to add the ItemListener.
Page 150
Example of JComboBox class:
import [Link].*;
public class Combo {
JFrame f;
Combo(){
f=new JFrame("Combo ex");
String country[]={"India","Aus","U.S.A","England","Newzeland"};
JComboBox cb=new JComboBox(country);
[Link](50, 50,90,20);
[Link](cb);
[Link](null);
[Link](400,500);
[Link](true);
}
public static void main(String[] args) {
new Combo();
}}
6. Jtable
JTable class:
The JTable class is used to display the data on two dimensional tables of cells.
Commonly used Constructors of JTable class:
o JTable(): creates a table with empty cells.
o JTable(Object[][] rows, Object[] columns): creates a table with the specified data.
Page 151
7..Jprogressbar
JProgressBar class:
The JProgressBar class is used to display the progress of the task.
Commonly used Constructors of JProgressBar class:
o JProgressBar(): is used to create a horizontal progress bar but no string text.
o JProgressBar(int min, int max): is used to create a horizontal progress bar with the
specified minimum and maximum value.
o JProgressBar(int orient): is used to create a progress bar with the specified orientation, it
can be either Vertical or Horizontal by using [Link] and
[Link] constants.
o JProgressBar(int orient, int min, int max): is used to create a progress bar with the
specified orientation, minimum and maximum value.
Commonly used methods of JProgressBar class:
1) public void setStringPainted(boolean b): is used to determine whether string should be
displayed.
2) public void setString(String s): is used to set value to the progress string.
3) public void setOrientation(int orientation): is used to set the orientation, it may be either
vertical or horizontal by using [Link] and [Link]
constants..
4) public void setValue(int value): is used to set the current value on the progress bar.
Example of JProgressBar class:
import [Link].*;
public class MyProgress extends JFrame{
JProgressBar jb;
int i=0,num=0;
MyProgress(){
jb=new JProgressBar(0,2000);
[Link](40,40,200,30);
[Link](0);
[Link](true);
add(jb);
setSize(400,400);
setLayout(null);
}
public void iterate(){
while(i<=2000){
[Link](i);
i=i+20;
try{[Link](150);}catch(Exception e){}
} }
public static void main(String[] args) {
MyProgress m=new MyProgress();
[Link](true);
[Link]();
} }
Page 152
8. Jslider
Slider class:
The JSlider is used to create the slider. By using JSlider a user can select a value from a specific
range.
import [Link].*;
public class SliderExample1 extends JFrame{
public SliderExample1() {
JSlider slider = new JSlider([Link], 0, 50, 25);
JPanel panel=new JPanel();
[Link](slider);
add(panel);
}
public static void main(String s[]) {
SliderExample1 frame=new SliderExample1();
[Link]();
[Link](true);
}}
Page 153
5.4. JDBC-Java Database Connectivity
Introduction to JDBC
Java Database Connectivity(JDBC) is an Application Programming Interface(API)
used to connect Java application with Database. JDBC is used to interact with various type of
Database such as Oracle, MS Access, My SQL and SQL Server. JDBC can also be defined as the
platform-independent interface between a relational database and Java programming. It allows java
program to execute SQL statement and retrieve result from database.
The JDBC API consists of a set of interfaces and classes written in the Java programming language.
We can use JDBC API to handle database using Java program and can perform the following
activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open Database
Connectivity (ODBC) provided by Microsoft.
The [Link] package contains classes and interfaces for JDBC API. A list of
popular interfaces of JDBC API are given below:
Driver interface
Connection interface
Statement interface
PreparedStatement interface
CallableStatement interface
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface
A list of popular classes of JDBC API are given below:
DriverManager class
Blob class
Clob class
Types class
.
Page 154
5.5. Architecture of JDBC
Architecture of JDBC
Components of JDBC
There are generally four main components of JDBC through which it can interact with a
database. They are as mentioned below:
2. JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve
results. Some of the important classes and interfaces defined in JDBC API.
It provides various methods and interfaces for easy communication with the database. It provides
two packages as follows, which contain the java SE and Java EE platforms to exhibit WORA(write
once run anywhere) capabilities.
[Link].*;
3. DriverManager: It plays an important role in the JDBC architecture. It uses some database-
specific drivers to effectively connect enterprise applications to databases.
It loads a database-specific driver in an application to establish a connection with a database. It is
used to make a database-specific call to the database to process the user request.
4. JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver
that intelligently communicates with the respective data source.
5. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation) being
performed by JDBC Drivers.
6. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge
translates the JDBC method call to the ODBC function call. It makes use of
the [Link] package which includes a native library to access ODBC characteristics.
Page 155
5.6. JDBC Driver
JDBC Driver is required to process SQL requests and generate result. The following are the
different types of driver available in JDBC.
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
convert requests from Java programs to a protocol that the DBMS can understand.
There are 4 types of JDBC drivers:
Type-1 Driver or JDBC-ODBC bridge
Type-2 Driver or Native API Partly Java Driver
Type-3 Driver or Network Protocol Driver
Type-4 Driver or Thin Driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.
In Java 8, the JDBC-ODBC Bridge has been removed.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
Easy to use.
Can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC function
calls.
The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.
Advantage:
Performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
The Native driver needs to be installed on the each client machine.
The Vendor client library needs to be installed on client machine.
Page 156
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
No client side library is required because of application server that can perform many tasks
like auditing, load balancing, logging etc.
Disadvantages:
Network support is required on client machine.
Requires database-specific coding to be done in the middle tier.
Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That
is why it is known as thin driver. It is fully written in Java language.
Advantage:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.
Page 157
5.7. JDBC Classes
JDBC API is available in two packages [Link], core API and [Link] JDBC optional packages.
Following are the important classes and interfaces of JDBC.
Class/interface Description
DriverManager -This class manages the JDBC drivers. You need to register your drivers to this.
It provides methods such as registerDriver() and getConnection().
Driver - his interface is the Base interface for every driver class i.e. If you want to create a
JDBC Driver of your own you need to implement this interface. If you load a Driver
class (implementation of this interface), it will create an instance of itself and register
with the driver manager.
Statement - This interface represents a static SQL statement. Using the Statement object and its
methods, you can execute an SQL statement and get the results of it. It provides methods such as
execute(), executeBatch(), executeUpdate() etc. To execute the statements.
Connection -This interface represents the connection with a specific database. SQL statements are
executed in the context of a connection. This interface provides methods such as close(), commit(),
rollback(), createStatement(), prepareCall(), prepareStatement(), setAutoCommit() setSavepoint()
etc.
ResultSet -This interface represents the database result set, a table which is generated by
executing statements. This interface provides getter and update methods to retrieve and update its
contents respectively.
ResultSetMetaData -This interface is used to get the information about the result set such as,
number of columns, name of the column, data type of the column, schema of the result set, table
name, etc It provides methods such as getColumnCount(), getColumnName(), getColumnType(),
getTableName(), getSchemaName() etc.
Page 158
CallableStatement -Using an object of this interface you can execute the stored procedures. This
returns single or multiple results. It will accept input parameters too. You can create a
CallableStatement using the prepareCall() method of the Connection interface. Just like Prepared
statement, this will also provide setXXX() and getXXX() methods to pass the input parameters and
to get the output parameters of the procedures.
[Link]("[Link] ");
where jdbc is the API, mysql is the database, localhost is the server name on which mysql
is running, 3306 is the port number and Employ is the database name, root is user name
and password.
Page 159
3)Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.
Syntax : public Statement createStatement() throws SQLException
Example : Statement stmt=[Link]();
import [Link].*;
class Test{
public static void main(String ar[]){
try{
String url="jdbc:odbc:mydsn";
[Link]("[Link]");
Connection c=[Link](url);
Statement st=[Link]();
ResultSet rs=[Link]("select * from Student1");
while([Link]()){
[Link]([Link](1));
}
}catch(Exception ee)
{[Link](ee);}
}}
1. Create a database using MS-ACCESS.
Database name as ―stud1‖
Table name as ―student1‖
Save database in D:\RM>
Student1
ID Stname rgno m1 m2
2 Murugan 101 56 76
3 senthil 102 67 76
4 kannan 103 58 56
Page 162
c) Example program using MS-Access jdbc:ucanaccess Drever
The database file is located at d:\RM\[Link]. - This path will be used in database
URL. We will write a Java program that uses the UCanAccess JDBC driver to connect to this
database, insert a row and select all rows from the table Contacts.
You can use JDBC API as normal (see Connect to a database with JDBC). The differences
lie in the database URL and Access-specific SQL syntax you can use. For example, you need to
construct the database URL to include path of the Access database file like this:
import [Link].*;
/** This program demonstrates how to use UCanAccess JDBC driver to read/write
* a Microsoft Access database.
* @author [Link] */
public class JdbcAccessTest
{
public static void main(String[] args)
{
String databaseURL ="jdbc:ucanaccess://d://RM//[Link]";
try {
(Connection connection = [Link](databaseURL))
String sql = "INSERT INTO Contacts (Full_Name, Email, Phone) VALUES (?, ?, ?)";
Page 163
Sample Questions
Descriptive Questions
1. Difference between AWT and Swing
2. Explain the Swing controls
3. Describe the Architecture of JDBC.
4. Explain the four types of JDBC Driver.
5. Write the use of JDBC Classis.
6. Write the Steps to connect the JDBC.
7. Write a program to connect the JDBC database.
8. Explain the JTable and JProgressBar.
Page 164