[Go to site: main page, start]

0% found this document useful (0 votes)
3 views164 pages

Programming in Java - Notes

The document outlines the syllabus for a Java programming course, detailing course objectives, units covering foundational concepts, object-oriented programming, exception handling, GUI programming, and database connectivity. It includes a list of textbooks and expected course outcomes for students. The syllabus emphasizes practical skills in Java, including GUI development and JDBC for database interactions.

Uploaded by

kingasraf800
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views164 pages

Programming in Java - Notes

The document outlines the syllabus for a Java programming course, detailing course objectives, units covering foundational concepts, object-oriented programming, exception handling, GUI programming, and database connectivity. It includes a list of textbooks and expected course outcomes for students. The syllabus emphasizes practical skills in Java, including GUI development and JDBC for database interactions.

Uploaded by

kingasraf800
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROGRAMMING IN JAVA

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.

1.1. INTRODUCTION TO JAVA


.What is Java?

Java is an object-oriented programming language and a platform. Java is a high level,


robust, object-oriented, secure and general-purpose language programming language. Java is
also developing the Window based and Internet program.

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.

1. J2SE 1.3 (8th May 2000)


2. J2SE 1.4 (6th Feb 2002)
3. J2SE 5.0 (30th Sep 2004)
4. Java SE 6 (11th Dec 2006)
5. Java SE 7 (28th July 2011)
6. Java SE 8 (18th Mar 2014)
7. Java SE 9 (21st Sep 2017)
8. Java SE 10 (20th Mar 2018)
9. Java SE 11 (September 2018)
10. Java SE 12 (March 2019)
11. Java SE 13 (September 2019)
12. Java SE 14 (Mar 2020)
13. Java SE 15 (September 2020)
14. Java SE 16 (Mar 2021) & Java SE 17 (September 2021)
15. Java SE 18 (to be released by March 2022)
Page 8
1.2. BASIC CONCEPTS OF OBJECT-ORIENTED
PROGRAMMING (OOP)
Define object oriented programming.

Object oriented Programming is defined as an approach that provides a way of modularizing


programs by creating partitioned memory area for both data and functions that can be used as templates
for creating copies of such modules on demand. Writing object-oriented programs involves creating
classes, creating objects from those classes, and creating applications, which are stand-alone executable
programs that use those objects.

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():
}

Student S1, S2;


Student class create the object S1, S2.

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()

Circle object Triangle object


Draw(circle) Draw(triangle)

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.

viii). Message Passing:


The process of programming in OOP involves the following basic steps:
 Creating classes that define objects and their behavior
 Creating objects from class definitions
 Establishing communication among objects
A message for an object is request for execution of a procedure and therefore will invoke a function
(procedure) in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the function (message) and
the information to be sent.
E.g.: employee. salary(name);
Object : employee
Message: salary
Information: name

1.3. FEATURES OF JAVA


A list of most important features of java language is given below.
1. Simple
2. Object-oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According
to sun, java language is a simple programming language because:
Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.

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

 Java Programs run inside a virtual machine sandbox


Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

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)

1.4. JAVA API ( Application Programming Interface) & JVM


Java application programming interfaces (APIs) are predefined software tools that easily enable
interactivity between multiple applications.

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

1. Java Lang Package ([Link].*)


[Link] package is imported automatically, i.e. we can use the classes of this package
directly in our program. You do not need to import this package because it contains the classes that
are fundamental to the design of the Java programming language.

Page 14
This package contains important classes like String, StringBuilder, Math, Integer, System, etc.

2. Java Util Package ([Link].*)


[Link] package contains the collections framework, legacy collection classes like Vector,
internationalization and utility classes like a random-number generator or a string tokenizer.
This package contains important classes like ArrayList, HashMap, HashSet, etc.

3. Java IO Package ([Link].*)


[Link] package provides serialization, system input/output through data streams, and the file
system. This package contains important classes like BufferedReader, BufferedWriter, File,
InputStream, OutputStream, etc.

4. Java SQL Package ([Link].*)


[Link] package provides the API for accessing and processing the data stored in a data
source. This package contains important interfaces like Connection, PreparedStatement, ResultSet,
and classes like DriverManager, etc.
.
5. Java Net Package ([Link].*)
[Link] package provides classes and interfaces for implementing networking applications.
This package contains important classes like Socket, Proxy, Authenticator, URI, URL, etc.

6. Java Applet Package (java. Applet.*)


[Link] package provides classes and interfaces for implementing internet program.

7. Java AWT Package ([Link].*)


[Link] package provides classes and interfaces for implementing GUI programs. It contain
Abstract Windows Toolkits classes Label, Button, TextBox and etc.

8. Javax Swing Package ([Link].*)


[Link] package provides a set of "lightweight" components that almost work the same on
all the platforms. This package contains important classes like BoxLayout, ImageIcon, JButton,
JCheckBox, JComponent, JFrame, JLabel, JList, JPanel, 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).

Java Source code Java Byte code


Compiler

JVM (java)

It converts Java byte code into Native machines code

Byte code Java JVM Native Machine


code

1.5. COMMENT LINE and JAVA PROGRAM STRUCTURE:


 It consists of a set of comment lines Contains name, author, revision number etc.
 It describe about the code (Program) to user.
Comment line:
The comments line describe about the code to understand the user . it is not executable
statement in programs by JAVA compiler.

THREE type of comment lines:

(A) Single Line Comment:


It starts with two forward slashes(//).This commend is terminated with the end of line.
Eg: // Sum of two numbers

(B) Multi Line Comment


It starts with /* and terminates with*/. It is used when multiple line comments are
included.
Eg: /*sum of two numbers*/

(c) Java Documentation comments:


These comments start with /** and end with */
These comments are useful to create a HTML file called API (application programming
Interface) document This file contains description of all the features of software.

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.

Java has six types of tokens, they are as follows:

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.

Rules For Identifiers:

 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 (=).

conts int a=5

TYPES OF CONSTANT

a) Numeric constant b) Character constant


i) Integer constants I) single character constant
ii) Real constants ii) String constant III) Backslash 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.

Eg.) “ suriya Moorthy”, “CB1259810”

e) Special characters / special symbols:


There are different types of special characters and symbols used in c they are as follows:

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 (;)

Syntax: Data_type var1,var2………………….varn;

Eg: int tamil, English, maths;


float avg;
Assign a value to variable:
A value can be assign to variable using assignment operator.
Eg: tamil=65; maths=75;
Initializing Variables:

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

Syntax: Data- type variable _name= VALUE; eg:


int y=3;
int x,y,3;
Scope of Variables
Scope of a variable means the availability of variable within the program. Variable have two type
of scopes.
a) Local variable: The variable which are declared inside a function block or block of
program. This variable can be accessed only within the block or function. This variable is
called local variable.
Example: Fun()
{
int a,b; // a,b are local variable.
}
Page 22
b) Global variable: The variable which are declared outside main() function block or
block of program. This variable can be accessed anywhere in program and all function in
program. This variable is called global variable.

Example: int a; // a is global variable


FunOut()
{
int b; // b is local variable
int fun()
{ a=10 ;
} .
}

1.8 DATA TYPES


 The Data Type is a classification of data which tell how to use the data in the program.
 The data types provide the possible values and its operations that can be applied on it.
 It is used to declare the variables
 C language supports different types of data. Each data may be represented differently in
computer‘s memory.
 The data type can be broadly classified as

BASIC / PRIMITIVE / PRIMARY / BUILD-IN DATA TYPE:


The basic data types can be classified in to 8 types they are as follows
a) Integer
i.) Byte ii) Short iii) Long
b) Character
c) Float
d) Double
Type Size (bits) Size(bytes) Range
byte 8 bits 1 byte -127 to 127
short 16 bits 2 bytes -32,768 to 32,767
int 32 bits 4 bytes -2,147,483,648 to +2,147,483,647
long 64 bits 8 bytes -9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
float 32 bits 4 bytes 3.4e-038 to 3.4 e+0.38
double 64 bits 8 bytes 1.7e-308 to 1.7e+308
char 16 bits 2 bytes 0 to 65,536

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

E) VOID DATA TYPE:


 The void data type is empty data type, that does not have any value. That is, The void
data type is nothing of value .

Page 24
1.9 OPERATOR AND ITS PRECEDENCE:
1.9.1. Operators in Java

 An OPERATOR is an symbol that tells the computer to perform certain mathematical ( or


) logical operation.
Eg: c=a+b where + is operator doing addition operation
a,b, c are operand.
An OPERAND Is an entity(variable) on which OPERATION is to be performed.
 They are 8 types operator

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

Truth Table Of Logical Operators


4 ASSIGNMENT OPERTOR:

 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

6.. CONDITIONAL (OR) TERNARY OPERATOR:

? : 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;

If a is less than b then result is otherwise result is b.

7..) BIT WISE OPERATOR:

 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.

8.) SPECIAL OPERATOR:

Java supports various special operators they are as follows

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

Eg: x=9 b=12 c=3

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:

 The parenthesis ( ) sub expression from left to right are evaluated


 If parenthesis are nested evaluation begins with innermost sub expression
 The precedence rule is applied in determining the order of application of operators in
evaluating sub expression
 The associatively rule is applied when two or more operators of the same precedence level
appearing in a sub expression
 Arithmetic expression are evaluate from left to right using the rules of precedence

1.10. TYPE CONVERSION:


 Type conversion (often a result of type casting) refers to changing an entity of one data
type, expression, function argument, or return value into another. This is done to take
advantage of certain features of type hierarchies.
 Types of type conversion is as follows:
a) Implicitly conversion
b) Explicitly conversion

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.

A) EXPLICIT TYPE CONVERSION:


Type Costing
 There are some instances when we want to force a type conversion in a way that is different
from the automatic conversion is known as explicit type conversation (or) type casting.
Type costing operator
Var = (type)exp;
Eg: ) float a=42.12;
int b=(int)a;
Result of b =42
Where a float value is converted to int in b.

1.11. CONDITIONAL STATEMENTS (if, switch)

Control Statement (Structures)


Java provide the Control Statement that have structure. It control (change) the
execution of program sequence. They are
a) Conditional Statements
b) Loop Statements

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;
} }

b). if else statement:


This statements check the condition , if the condition is true , then execute the one block
statements. If false, another block of statement.

Syntax : Example:
if(condition ) if (a>b)
{ (
Statements-1; big=a;
} }
else else
{ (
Statements-2; big=b;
} }

Page 31
c). Nested if…else statement:

In Which, one if statement contain another if satatement.

If condition1 is true, then condition2 is executed. If condition2 is true then statement1 is


executed. Otherwise statement2 is executed. If conditio1 is false, then statement3 is executed.
Syntax: Example
if (conditon1) if(a>b)
{ {
if (condition 2) if(b>c)
statement1; big=b;
else else
statement2; big=c;
} }
else else
Statement 3;

d). The if…else ladder

In which , a if statement occurred in else part of if statement. First check condition, if


condition is true, then execute statements-1, if it false then check condition. This process is
continually up to our needed.

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.

The following are the loop structure available in ―c‖

a) While…
b) do … while…
c) for ……

a) While Loop Statement:

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

b) do..while loop Statements:


 The do..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 Exit controlled loop statements and First executes the body of the loop once
irrespective of the condition, then it checks the condition and continues the execution until
the condition becomes false.
 Here, the statement within the body of the loop is executed once, then it check the
condition, if it is true, then it executes the body until the condition becomes false.

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

c) for loop Statements


 The for statement is a loop statement. It is repeatedly execute the set of statements within
the body of loop until the condition becomes false.

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;
}

Where, initialize is used to assign a initial value ,

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.

Syntax: continue; Eg.) while( a>b)


{ ….
continue;
……
}
c). Goto statement

 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(:)

Syntax: goto label;

………..
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.

Return-type method-name(Arguments List)


{
Method body;
//codings
}

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

Where obj1 is object, Student is class name.


Accessing Class Members
Class members can be accessed only by an object of that class in main() method and outside
of class. To access class members, use the dot (.) operator. The dot operator links the name of an
object with the member name of class. The general form of the dot operator is shown here:
Syntax
[Link];
Example: obj.a=5;
obj.b=10;
The private members of a class cannot be accessed directly using the dot operator, but
through the member method of that class providing data hiding. A member method can call another
members (data, method) directly, without using the dot operator.

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.

Here, access-Specifier is one of these three java keywords:


1. public ,
2. private,
3. protected
Private member of class can not be accessed outside of class and only accessed
within a class.
The public access modifier allows the member of class can be accessed to outside
of class that is other parts of your program.
The protected access modifier is similarly private but, it allowed to access the
member of class in sub class of inheritance only when inheritance is involved.

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

1.15. CONSTRUCTORS and ITS TYPES


a) Constructors
Constructor is a special member function(methods), its name is the same name as its
class name. The Constructor are called automatically when an object is created.
Uses:
 It is used to initialize the object.
 It usually provides initial value for the data member of the object.
Syntax:
class class-name
{
public:
class-name( arguments) //constructor
{
Statements;
}
}
Example: class Sample
{
int a,b:
public:
Sample() //constructor
{
a=5;
b=10;
}
}

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

i) Default Constructor (or) Constructor with no argument


A Constructor that accepts no parameter is called Default Constructor . It is used to initialize
default values to data member of class. It call automatically when the object is created.
Syntax:

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;
} }

Sample S1=new Sample(); S1 object copy to S2 object


Sample S2=new Sample(S1);

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

a) Static Data member


The member variables in a class can be declared as static. It can be accessed outside of class
using class name without object The general form is,
Syntax:
static data-type member-variable;

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.

b) Static Methods member


It can be declared using static. It can only access the static members declared in the same
class. Static method can be called outside of class using class name without object.
Ii must only access static data and static methods.
Syntax:
Static data-type method-Name();
Example:
Class Sample
{
static int a,b;
static void Add()
{}
}
Example Program:
Class Sdemo
{
static int a =15;
static in b=50; // Static Data & Method declared.
static void Disp()
{
[Link](‗a= ‗+a);

Page 46
} }
Class Sample
{
Public static void main(String arg[])
{
[Link](); // Static Data & Method call using class name without object.
[Link](‗b= ‗+Sdemo.b);
}}

1.18. this Keyword and Recursion


a) this Keyword
In Java, The this Keyword refers to the current object of class inside any method. You can
use this anywhere a reference to an object of the current class type is permitted.
Syntax: [Link]-Variable ; // (Instant Variable is data member.
Example:
class Sample
{
int x,;
Sample( int a,)
{
this.x=a;
}}
When we used this keyword in the Demo class, it will refer to the Demo class. The this keyword
is often used in the Constructor Method.
Example:
class Sample
{
int x,y,z;
Sample( int a,int b)
{
this.x=a;
this.y=b;
}
void disp()
{
z=x+y;
[Link](z);
}}
class Dem0
{
public static void main(String args[])
{
Sample obj=new Sample(4,5);
[Link]();
}}
Page 47
b) Recursion:
A method that calls itself is said to be recursion. That is, A method call inside of same
method repeatedly to do some process. This process is call recursive process ( Recursion).
Simply. Recursion is the process of defining some thing in terms of itself.
Simple example:
int fact( int n)
{
fact(n-1)
}
Example Program:
class fact
{
int fact(int n)
{
int result;
if(n==1)
{
return 1;
}
else
{
result = fact(n-1)*n;
return result;
}
}
}

1.19. Abstract Class and Methods


Abstract Class
The abstract class and abstract methods should be declared using the keyword abstract

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‖);
}}

Characteristic of Abstract Class

 An abstract class is a class with zero or more abstract methods


 An abstract class contains instance variables & concrete methods in addition to abstract
methods
 It is not possible to create objects to abstract class
 But we can create a reference of abstract class type
 All the abstract methods of the abstract class should be implemented in its sub classes
 If any method is not implemented, then that sub class should be declared as „abstract‟
 Abstract class reference can be used to refer to the objects of its sub classes
 Abstract class references cannot refer to the individual methods of sub classes
 A class cannot be both „abstract‟ & „final‟

1.20. Inner Class and Nested Class


A class can be defined inside of another class. These inside class is called Inner class.
Such inner class is call Nested class. The another class is called outside class.

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:

1. Define Class and objects


2. What is Abstract class?
3. Tell about JVM.
4. What is API?
5. Define Encapsulation and Abstraction.
6. List out Access Specifiers.
7. Write the use of this keyword.
8. What is Recursion?
9. What is Constructor?
10. State Constants.
11. What is Method?
12. Define Variable.

Descriptive Type Questions:

1. Explain the basic concepts of OOPs.


2. Describe the Features of Java.
3. Write about the Java API.
4. Discuss about the Data Types in Java.
5. Explain the Constructors and its types.
6. Construct the Method Overloading.
7. Explain the Class and object with example
8. Discuss about the operators in Java.
9. Illustrate the various structure of if statements.
10. Describe the Loop statements.
11. Discuss about the Static class members.

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.

2.1. ARRAYS (One & Multi dimensional array)


Define Arrays:
 An array is a group of data items that share a common name.
 All data items are same data type.
 Each data item of an array is called an element.
 Each elements of array can be accessed using index (subscript) value
Example: int a[5];
Array can be classified into three type:
a) One dimensional array
b) Two dimensional array
c) Multi dimensional array

[Link] Dimensional Array


The Collection of data items are stored under a one variable name using only one subscript,
such a variable is called one-dimensional array.
Declaration of array:
Syntax: Data-type array-name[]; (or )
Data-type array-name = new Data-type[ size ];
Example: int a[]; (or)
int a = new int[5];
Where, a is array name , 5 is size of array
Storage location:

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

[Link] Dimensional Array


Two dimensional array is known as matrix. The two dimensional array are used two subscripts.
It is used to arrange the in table format or matrix format.
Syntax
Data-type array-name = new Data-type[row][column];

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

Positions of 2-D array elements in an array are as below

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

2,1.3. Multi-Dimensional Array


Multi dimensional array have three or more subscripts to arrays.
Syntax
Data-type array-name[size1][size2] [size3]….. [size n] ;
Example:-
int a[][][] = new int[3][3] [3];

Reading 3-D Array

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]();
}
}}

2.1.3. String of Array

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‖

2.2. STRING CLASS AND STRING HANDLING METHOD


2.2.1 String Classes
The String class is used to represent constant strings. The String class has less overhead than
StringBuffer, which means you should try to use it if you know that a string is constant. The String
creation methods for the String class follow:

• 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:

Example : String creations

String s1 = new String(); ///Empty String objects

String s2 = new String(―Hello‖); // a String create


char cArray[] = {‗H‘, ‗o‘, ‗w‘, ‗d‘, ‗y‘}; // String create as array

String s3 = new String(cArray);


String s4 = new String(cArray, 1, 3);

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.

[Link] Handling Methods


Once you have some String objects created, you are ready to work with them using some of the
powerful methods implemented in the String class. Some of the most useful methods provided by
the String class follow:

a) Length()) Method

The length() method is used to find the length of given strings.


Syntax: int length()
Example: String s1 = new String(―Hello‖);
[Link]([Link]());

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

f.) toLowerCase() & toUpperCase()


This methods convert the string lower string to upper string and reverse.
• String toLowerCase()
• String toUpperCase()
String s1=‖annai‖
[Link](toUpper(‘));
Output: ANNAI

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:

String s1 = new String(―This is a string!‖);


String sb1 = new StringBuffer();
String sb2 = new StringBuffer(25);
String sb3 = new StringBuffer(s1);

Methods of StringBuffer follow:

• 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.

Super Class Student

Sub Class Mark

Example: Class A
{
int a;
}
Class B extends A
{
A=10;
}
Where , A is base class, B is a derived(subclass) class

2. Multilevel Inheritance: A class derived is created rom another derived class.

Super Class Student

Sub Class 1 Mark

Sub Class 2 Result

Example: Class A
{
int a;
}
Class B extends A

Page 59
{
Int b;
A=10;
}
Class C extends B
{
c=a+10;
}

Where , A is base class, B and Cis a derived(subclass) class

3. Hierarchical Inheritance: More than one Class is derived from a single base class.

Super Class Book

Sub Class 1 Sub Class 2 Staff Student

Example: Class A
{
int a;
}
Class B extends A
{
A=10;
}
Class C extends A
{
int c=a+10;
}

B,C derived classes are created from one base class A

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

Derived Class Result

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.

Base Class 1 Base Class 2 Student Sports

Derived class 1 Mark

Derived 2 Result

Example Program for Multi level Inheritance

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](); ;
}}

2.5. Method Overriding and Polymorphism


2.5.1. Method Overriding
The method Overriding is the creation of methods in the Subclass, its name has same name
of Super class method with same signature ( same number of arguments and types of arguments) .
The subclass method hidden the supper class methods. The Method hidden process is called the
method Overriding.

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

a) Compile Time Polymorphism


The Compile Time Polymorphism is implemented by method overloading. In Method
overloading, A class has multiple methods having same name but different in parameters, it
perform different task, Here , The method calling is decided in compile time, Which method is
called, it is known as method overloading

Void Add(int, int);


Void Add(int, float);
b.) Run Time Polymorphism
The Run time polymorphism is implemented by Dynamic method Dispatch. The method
is created in the Subclass, its name has same name of Super class method with same signature it
perform different task,
The Dynamic method dispatch is resolved the method overriding at Run Time.
Here , The method calling is decided in Run time, Which method is called, it is known as
Polymorphism.
Here is How, When an overridden method is called through a superclass reference.
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[])
{
SuperC sp = new SuperC();

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

2.6. Interface and it Implementation


An interface is a reference type in Java, it is similar to class, it is a collection of abstract methods. A
class implements an interface, thereby inheriting the abstract methods of the interface.
 Along with abstract methods an interface may also contain constants, default methods, static
methods, and nested types. Method bodies exist only for default methods and static
methods.
 Writing an interface is similar to writing a class. But a class describes the attributes and
behaviours of an object. And an interface contains behaviours that a class implements.
 Unless the class that implements the interface is abstract, all the methods of the interface
need to be defined in the class.
 An interface is similar to a class in the following ways:
 An interface can contain any number of methods.
 An interface can extend multiple interfaces.

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.

Class Class_name implements interface-name-1, interface-2,…


{
// body of class
}

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

Interfaces have the following properties:


 An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
 Methods in an interface are implicitly public.

However, an interface is different from a class in several ways, including:


 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
 An interface is not extended by a class; it is implemented

[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

2.7. Package Creation and Importing packages


Package Contain classes. interface and its methods, The packages will import in
other application program to access the class and interface.
Packages are java‘s way of grouping a variety of class and/or interfaces together. The grouping is
usually done according to functionality. In fact, packages act as ―containers‖ for classes. By
organizing our classes into packages we achieve the following benefits:
1. The classes contained in the packages of other programs can be easily reused.
2. In packages, classes can be unique compared with classes in other packages. That is, two
classes in two different packages can have the same name. They may be referred by their fully
qualified name, comprising the package name and the class name.
3. Packages provide a way to ―hide‖ classes thus preventing other programs orpackages
from accessing classes that are meant for internal use only.
4. Packages also provide a way for separating ―design‖ from ―coding‖. First we can design
classes and decide their relationships, and then we can implement the java code needed for the
methods. It is possible to change the implementation of any method without affecting the rest of the
design.
Java packages are therefore classified into two types. The first category is known as Java
API packages and the second is known as user defined packages.

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.

2.7.2. USER DEFINED PACKAGES:

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];

2.7.3 IMPORTING A PACKAGE:


We use the import statement when there are many references to a particular package or the
package name is too long and unwieldy.
The same approaches can be used to access the user-defined packages as well. The import
statement can be used to search a list of packages for a particular class. The general form of import
statement for searching a class is as follows:

Import package1 [.package2] [.package3].classname;

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.

Now consider the listing shown below:


import [Link]; / import user defined package
public class Sample
{
public static void main(String args[])
{
BCA ob=new BCA();
[Link]();
}}
This listing shows a simple program that imports the class BCA from the package Annai.
The source file should be saved as [Link] and then compiled. The source file and the
compiled file would be saved in the directory of which Annai was a subdirectory. Now we can
run the program and obtain the results.

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.

1. The first call the superclass constructor.


2. The second is used to access a member of the superclass that has been hidden by a
member of a subclass.
1. Super call superclass constructors.
A subclass can call a constructor method defined by its superclass by use of following form
of super:
super(parameter-list);

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()
}}

2.9. final Keyword


The final keyword is a not-access modifier. The final can be used in variable,
class and method, Which makes them non-changeable.
They are
a) final variable
b) final class
c) final method
a) final variable
A variable can be declared as final. The value of final variable can not be
changed. The value is initialized to final variable when it is declared. Final is
similar to const.
The value of variable is not necessarily known at compile time, but the value
of const is known at compile time.
Example
Class sample
{
final int a=10;
public final int b;
sample( int x)
{
b=x;
}}

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.

Descriptive type questions


1. Explain the different type of arrays.
2. Describe the String Handling methods
3. Discuss about the String and StringBuffer class
4. Illustrate the various type of Inheritance
5. Explain the Method Overriding with example.
6. Describe the Interface and its implementation.
7. Explain a creation of user defined Package.
8. Describe the Multiple Inheritance using interface.

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.

3.1. Exception Handling


What is Exception?
 An exception is a Runtime error that arises during the program execution . When
an Exception occurs the normal flow of the program is disrupted and the program
terminates abnormally, which is not recommended, therefore, these exceptions are to be
handled runtime error..
 An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run
out of memory.
ADVANTAGE:

 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

1. try – catch Block


The try—catch is a block of code that handle exception. If an exception occurs within the try
block, it is thrown to catch block. The catch bloc can catch this exception (using catch) and handle it
in some rational manner.

 System-generated exception are automatically thrown by the java run-time system. It


occurs in try block.
 To manually throw an exception, use the keyword throw.
 Any exception that is thrown out of a method must be specified as such by a throws clause.
 Any code that absolutely must be executed before a method returns is put in a finally block.

Syntax of try – catch:


try
{
statement;
}
catch (Exception-type e)
{
statement;
}
Example :
class exe
{
public static void main (String args[])
{
try
{
int a = 10,b=0;
int c = a /b;
[Link](―divide value is ―+c);
}
catch( ArithmeticException e)
{
[Link](―Divide by zero‖);

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.

2. Multiple Catch and Finally Block


We can use more than one catch block in a try block and also use the finally block. A
exception occur within try block, these exception match with any on catch block exception,
that block catch it, otherwise any catch bloc is not matched then execute the finally block.

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

Example: IOException, SQLException , FileNotFoundException, etc. Checked exceptions are


checked at compile-time.

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.

 All exception classes are subtypes of the [Link] class.

 The exception class is a subclass of the Throwable class

Page 79
A hierarchy of Java Exception classes are given below

Common Built-in Java Exception

Exception type Cause Of Exception

ArithmeticExceptin Arithmetic errors such as division by zero


IOException Caused by general I/O failures, such as inability to
Read from a file
InterruptedException One thread has been interrupted by another thread
ClassNotFoundException class not found
NullPointerException Invalid use of null reference
ArrayIndexOutOfBoundsException Array index out of bounds
ArrayStoreException Assignment to an array element of an incompatible type
ClassCastException Invalid cast
NegativeArraySizeException Array created with a negative size.
FileNotFoundException Caused by an attempt to access a non existent file
NumberFormatExceptoin Invalid conversion of a string to a numeric format

3.1.3. User-Defined Exceptions:


You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes:

 All exceptions must be a child of Throwable.


 If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
 If you want to write a runtime exception, you need to extend the RuntimeException class.
Page 80
Thus, all exception, including user-defined have the methods defined Throwable available them,
they are methods
1. String toString()
2. String getMessage()
3. String getlocalizedMessage()
4. Void printStacTrace()
We can define our own Exception class as below:
Syntax:
class MyException extends Exception
{
MyException(parameter-list)
{
}}
Example:
class MyException extends Exception
{
Private int detail;
MyException(int a)
{
Detail=a;
}
Public String toString()
{
Return ―MyExcption = ―+detail ;
}}
Class ExpSample {
static void DispExp( int a) throws MyException {
[Link](―Call DespExp =‖+a);
If(a>15)
Throw new MyException(a);
[Link](―No exception‖+a);
}
Public static void main(String arg[]) {
try {
DispExp(5);
DispExp(18);
}catch(MyException e)
{
[Link](―Catch ‖+e);
}}
}
Output: Call DespExp = 5
No exception =5
Call DespExp = 18
Catch MyException=18

Page 81
[Link] Programming
Introduction to Thread and Main thread

What is thread and Multithread?


Java provides built-in support for Multithread programming. A Multithread program contains
two or more parts that can run concurrently . That is , A program is divided into more than part
for execution, each part is called Thread and each thread defined a separate path of execution.
The more than one threads are run concurrently is called Multithread. Thus multithread is a
specialised form of multitasking.

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.

The Main Thread:


When a java program starts up, one thread begins running immediately. This is usually called
the main thread of your program, because it is the one that is executed when your program begins.
The main thread is important for two reasons
It is the thread from which other ― child‖ threads will be spawned.
Often it must be the last thread to finish execution because it performs various
shutdown actions.
Although the main thread is created automatically when your program is started, it can be
controlled through a Thread object. To do so, you must obtain a reference to it by calling the
method currentThread( ), which is a public static member of Thread. Its general form is shown
here,
static Thread currentThread( )
Example:
class th1
{
public static void main(String args[])
{
Thread t1=[Link]();
Page 82
[Link]("current thread :"+t1);
[Link]("My Thread ");
[Link]("After name change" +t1);
try
{
for(int i=1;i<=5;i++)
{
[Link](i);
[Link](1000);
}}
catch(InterruptedException e)
{
[Link]("main thread interrupted");
}}
}
The argument(1000) to sleep( ) specifies the delay time in milliseconds
Output
Current thread: Thread[main, 5, main]
After name change: Thread[My Thread,5,main]
1
2
3
4
5
Thread Methods:
 Thread class has following important methods. Method

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

currentThread() It is used to know currently executed Thread status.

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

a) Runnable interface implementing


The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ) , which is
declared like this:
Public void run( )

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
}

Steps to create thread


1. Define a class implement Runnable interface
2. Create a object of Thread class in contractor of class
3. Implement the run() method
Page 84
4. Write the code of child thread in run() method
5. Create a new thread in main() method by calling constructor
6. Now , execute run() method by Start() method.

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

b) Thread class extending


The second way to create a thread is to create a new class the extends Thread, and then to
create an instance of that class. It includes the following steps:
1. Declare the class as extending the Thread class.
2. Implement the run( ) method that is responsible for executing the sequence of code that
the thread will execute.
3. Create a thread object and call the start( ) method to initiate the thread execution.

Declaring the Class:


The Thread class can be extended as follows:
Class MyThread extends Thread
{
………….
}
Now we have a new type of thread MyThread.

Implementing the run( ) Method:


The run( ) method has been inherited by the class MyThread. We have to override this
method in order to implement the code to be executed by our thread. The basic implementation of
run( ) will look like this:
Public void run( )
{
//body of thread…..
}
When we start the new thread, java calls the thread‘s run( ) method, so it is the run( ) where all the
action takes place.

Starting New Thread:


To actually create and run an instance of our thread class, we must write the following:
MyThread obThread = new MyThread( );
[Link]( );
The first line instantiates a new object of class MyThread. Note that this statement just creates the
object. The thread that will run this object is not yet running. The thread is in a new born state.
The second line calls the start( ) method causing the thread to move into the runnable state.
Then, the java runtime will schedule the thread to run by invoking its run( ) method. Now, the thread is
said to be in the running state.

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");
}}

Example: Program for Creation of Multithread


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");
}}
class Bth extends Thread
{
public void run()
{
for(int j=10;j<=15;j++)
{
[Link]("\t from thread B :j = "+j);
}
[Link]("exit from B");
}}
class Cth extends Thread
{
public void run()
{
for(int k=15;k<=20;k++)
{
[Link]("\t from thread C :k = "+k);
}
[Link]("Exit from C");
}}
class Demothr
{
public static void main(String args[])
{
Ath T1= new Ath(); [Link]();

Page 87
Bth T2=new Bth(); [Link]();
Cth T3=new Cth() ; T3..start();
}}

3.2.2. Life Cycle of Thread


A thread life cycle can be in one of the following states,
1. New born state(New)
2. Ready to run state (Runnable)
3. Running state(Running)
4. Blocked state
5. Dead state

New Born State:--


 The thread enters the new born state as soon as it is created. The thread is created using the
new operator.
 From the new born state the thread can go to ready to runnable mode or dead state.

Ready to run mode (Runnable Mode):--


 If the thread is ready for execution but waiting for the CPU the thread is said to be in ready
to running mode.
 All the events that are waiting for the processor are queued up in the ready to run mode and
are served in FIFO manner or priority scheduling.

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.

3.2.3. Thread Priority


In java, each thread is assigned apriority, which affects the order in which it is scheduled for
running.

 Each thread has a priority.


 Priorities are represented by a number between 1 and 10.
 We can be assigned a priority to each Thread for order ( schedule) execution, they share the
processor on first-serve basis.

Syntax of thread priority


[Link](intNumber);
The intNumber is an integer value to which the thread‘s priority is set. The Thread class defines
Three priority constants:

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();

TestPriority m2=new TestPriority();


[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}

3.2.4. Synchronization and Join Thread


When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization.
The synchronization can be done in two way:
a) Using synchronized method
b) Using synchronized Statements
a) Using Synchronized method
A method can be defined as synchronized method , this method do not allow any thread for
execution until that method is completed .
Syntax:
synchronized type MethodName( parameter)
{ ----
}
Example
class sync
{
public static synchronized void display()
{

Page 90
for(int x=200;x<203;x++)
{
[Link]("a thread x value is"+x);
}}}
b) Using synchronized Statements
Syntax:
synchronized (object)
{ }

Example: program for Synchronize


class a extends Thread
{
public void run()
{
try
{
[Link]();
[Link](250);
}
catch(InterruptedException e)
{
[Link]("Interrupted");
}
[Link]("exit form a");
}}
class sync
{
public static synchronized void display()
{
for(int x=200;x<203;x++)
{
[Link]("a thread x value is"+x);
}}}
class b extends Thread
{
public void run()
{
try
{
for(int j=1;j<5;j++)
{
[Link]("b thread j value is "+j);
[Link](500);
}}
catch(InterruptedException e)
{
[Link]("interrupted");
}

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.

[Link] Join() Method

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.

 public final void join() throws InterruptedException


 public void join(long millis) throwsInterruptedException

Example: Program for Join() method

public class JoinExample1 extends Thread


{
public void run()
{
for(int i=1; i<=4; i++)
{
try
{
[Link](500);
}catch(Exception e){[Link](e);}
[Link](i);
}
}
public static void main(String args[])
{
// creating three threads
JoinExample1 t1 = new JoinExample1();
JoinExample1 t2 = new JoinExample1();
JoinExample1 t3 = new JoinExample1();
// thread t1 starts
[Link]();
// starts second thread when first thread t1 is died.
try
Page 92
{
[Link]();
}catch(Exception e){[Link](e);}
// start t2 and t3 thread
[Link]();
[Link]();
}
}
Daemon Thread in Java
 Daemon thread in java is a service provider thread that provides services to the user thread.
Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.
 There are many java daemon threads running automatically e.g. gc, finalizer etc.
 You can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.
NOTES

 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

 public void setDaemon(boolean status)


 public boolean isDaemon()

3.3. I/O Stream and File Classes


What is Stream?

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.

3.3.1. Byte Stream Classes:


Byte streams provide a convenient means fro handling input and output of bytes. Byte
streams are used, for example, when reading or writing binary data. Byte streams are defined by
using two classes hierarchies.
At the top are two abstract classes : InputStream and OutputStream. Each of these
abstract classes has several concrete subclasses, that handle the differences between various
devices, such as disk files, network connections and even memory buffers.
All I/O and File class are available in [Link] package
The byte stream classes are as bellow:
Stream Classes Meaning
BufferedInputStream Buffered input stream
BufferedOutputStream Buffered output stream
ByteArrayInputStream Input stream that reads from a byte array
ByteArrayOutputStream Output stream that writes to a byte array
DataInputStream An input stream that contains methods for reading
the java standard data types
DataOutputStream An output stream that contains methods for writing
The java standard data types
FileInputStream Input stream that reads from a file.
FileOutputStream Output stream that writes to a file
InputStream Abstract class that describes stream input
OutputStream Abstract class that describes stream output
PrintStream Output stream that contains print( ) &println( )
RandomAccessFile s supports random access File I/O

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");
}
}

3.3.2. Character Stream Classes:


Character streams are defined by using two class hierarchies. At the top are two abstract
classes, Reader & Writer. These abstract classes handle Unicode character streams. Java has
several concrete subclasses of each of these. The character stream classes are below:

Stream Classes Meaning


BufferedReader Buffered input character stream
BufferedWriter Buffered output character stream
CharArrayReader Input stream that reads from a character array
CharArrayWriter Output stream that writes to a character array
FileReader Input stream that reads from a file
FileWriter Output stream that writes to a file
InputStreamReader Input stream that translates bytes to characters
PrintWriter Output stream that contains print( ) & println( )
StringReader Input stream that reads from a string

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]();

Reading console Input:


In java, console input is accomplished by reading from [Link]. to obtain a character-based
stream that is attached to the console, you wrap [Link] in a BufferedReader object, to create
character stream. BufferedReader supports a buffered input stream. It is most commonly used
constructor is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being
created. Reader is abstract class. One of its concrete subclasses is InputStreamReader, which
converts bytes to charcters. To obtain an InputStreamReader object that is linked to [Link],
use the following constructor
InputStreamReader(InputStream inputStream)
Because [Link] refers to an object of type InputStream, it can be used for inputStream. Putting
it all together, the following line of code creates BufferedReader that is connected to the keyword:

BufferedReader br=new BufferedReader(new InputStreamReader([Link]));


After this statement executes, br is a character based stream that is linked to the console

Page 96
through [Link].

Example: (String Functions)


import [Link].*;
class str
{
public static void main (String args[])throws IOException
{
InputStreamReader br=new InputStreamReader([Link]);
BufferedReader r=new BufferedReader(br);
String name,a,b,c;
[Link]("Enter the first string");
name=[Link]();
[Link]("Enter the string");
a=[Link]();
[Link]("given name is "+ name);
[Link]("given name is "+ a);
[Link]("comp"+[Link](a));
int l;
l=[Link]();
[Link]("given name length is "+l);
[Link](" ");
[Link]("given name length is "+ [Link]());
[Link](" ");
[Link]("concat string is "+ [Link](a));
[Link](" ");
[Link]("Equal string " +[Link](a));
[Link](" ");
[Link]("Upper case letter of the given name"+[Link]());
[Link](" ");
[Link]("Upper case letter of the given name"+[Link]());
[Link](" ");
StringBuffer x=new StringBuffer(a);
[Link]();
String y=new String(x);
[Link]("Reverse of the string is: "+y);
if([Link](y)==0)
[Link]("Given String is polyndrome");
else
[Link]("not polyndrome strig is ");
}}

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.

USING THE FILE CLASS:


The [Link], package includes a class known as the file class that provides support for
creating files and directories. The class includes several constructors for instantiating the File
objects. This class also contains several methods for supporting the operations such as
Creating a File , Opening a File, Closing a File, Deleting a File, Getting the name of the
File, Renaming a File, checking whether the file is readable, checking whether the file is writable.
Class Meaning
FileInputStream Input stream that reads from a file.
FileOutputStream Output stream that writes to a file
FileReader Input stream that reads from a file
FileWriter Output stream that writes to a file

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.

READING / WRITING CHARACTES:


As pointed out earlier, subclasses of Reader & Writer implement streams that can handle
characters. The two subclasses used for handlingcharacters in files are FileReader (for reading
characters) and FileWriter(for writing characters).
Create and Open data file
File infile=new File("[Link]"); // create fie object
File outfile=new File("[Link]");
FileReader ins= new FileReader(infile); // create file input stream
FileWriter outs= new FileWriter(outfile);
Page 98
The method for read and write data in file use read() & write() methods
String str = [Link]() ;
[Link](―student‖);
INPUT / OUTPUT EXCEPTIONS:
When creating files and performing i/o operations on them, the system may generate i/o related
exceptions. The basic i/o exception classes and their functions are given below
I/O Exception class Function
EOFException Signals that an end of the file or end of stream has been reached unexpectedly
during input
FileNotFoundException -Informs that a file could not found
InterruptedIOException -Warns that an I/O operations has be interrupted
IOException -signals that an I/O exception of some sort has occurred.

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.

3.3.4. Random Access Files And Sequential File:


a) RandomAccessFile
The stream classes examined in the previous sections can only use sequential access to read
and write data in File. The RandomAccessFile class allows you to write programs that can seek to
any location in a file and read or write data at the point. It also supports positioning requests- that is,
you can position the file pointer within the file. It has two constructors:

RandomAccessFile(File fileobj, String access) throws FileNotFoundException


RandomAccessFile(String filename, String access) throws FileNotFoundException
In the first form, fileobj specifies the name of the file to open as a File object. In the second form,
the name of the file is passed in filename. In both cases, access determines what type of file access
is permitted. If it is “r” , then the file can be read, but not written. If it is “rw” , then the file is
opened in read-write mode.
The method seek( ) shown here, is used to set the current position of the file pointer within the file:
void seek(ling newpos) throws IOException

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

1. Explain the Exception Handling Techniques.


2. Describe the Try .. Catch block of Exception methods.
3. Short notes on Throw and Throws Keyword.
4. Explain the Two type of Exception in java.
5. Explain the User-Defined Exception.
6. Describe the two type of Thread creation Techniques.
7. Discuss about the Life Cycle of Thread.
8. Write about the Thread Priority.
9. Illustrate the Thread Synchronization.
10. Explain the Byte and Character Stream Classes.
11. Describe the file creation, read and write the data on file in java.
12. Illustrate the Random Access file.

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.

4.1. Applet Fundamentals


What is Applet?
Applets are small java Internet programs that are primarily used in Internet computing. They
can be transported over the Internet from one computer to another and run using the Applet
Viewer or any web browser that supports java. An applet, like any application program, can do
many things for us. It can perform arithmetic operations, display graphics, play sounds, accept user
input, create animation and play interactive games.

We can embed applets into web pages in two ways.


1. we can write our own applets and embed them into web pages.
2. we can download an applet from a remote computer and then embed it into a web page.

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.

How Applets Differ From Applications Program:


Although both the applets and stand-alone applications are java programs, there are
significant differences between. Applets are not full-featured application program. They are
usually written to accomplish a small task or a component of a task. Since they are usually
designed for use on the internet, they impose certain limitations and restrictions in their design.

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++.

The Applet Class:


The Applet provides all necessary support for applet execution, such as starting and stopping. It
also provides methods that load and display images, and methods that load and play audio clips.
Applet extends the AWT class Panel. In turn, Panel extends Container, which extends
Component. These classes provide support for java‘s window-based, graphical interface.

4.2. LIFE CYCLE OF APPLET:


FIVE methods in the Applet class give you the framework on which you build any serious
applet:
1. Init( ) → Initialize a variable. Called when an applet begins execution. It is the first method
called for any applet.
[Link]( ) → After the init( ) method the program should be started. Called By browser when
an applet should start(or resume) execution. It is automatically called after
init( ) when an applet first begins.
3. Paint( ) →drawing, writing and colour creation. The paint( ) method is called each time
your applet‘s output must be redrawn. Paint( ) is also called when the applet begins execution.
This method has one parameter of type Graphics. It contain the Graphics context, which
describes the graphics environment. This context is used whenever output to the applet.
4. Stop( ) →Halt of the running applet. Called by browser to suspend execution of the applet.
Once stopped , an applet is restarted When the browser calls start( ).
5. Destroy( ) -> terminated Applet running. Called by browser just before an applet is
terminated.
6. Repaint( ) →call update method, That update information on applet windows.

Init() Start() Paint() Stop() Destroy()

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>

The following attributes of applet tag used for


[Link]:
It is an optional attribute that specifies the base URL of the applet code, which is the
directory that will be searched for the applet‘s executable class file. The HTML document‘s URL
directory is used as the CODEBASE if this attribute is not specified.

[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] AND HEIGHT:


WIDTH and HEIGHT are required attributes that give the size ( in pixels) of the applet
display area.

[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.

[Link] NAME AND VALUE:


The PARAM tag allows you to specify applet specific arguments in an HTML page.
Applets access their attributes with the getParameter( ) method.

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.

How to run an Applet?


There are two ways to run an applet
1. By html file in Web Browser.
2. By appletViewer tool (for testing purpose).

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
}}

In this program save [Link].

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]

public class app1 extends Applet


{
public void paint(Graphics g)
{
[Link]("Hello World",30,30);
}}

2. Create a HTML with Applet Tag : sava as [Link]


<html>
<body>
<applet code="[Link]" height = 400 width = 200 >
</applet>
</body>
</html>
Double click this HTML file to run this on browser or open this html file on browser.
Display above output.

4.5. Passing Parameters in APPLET:


The APPLET tag in HTML allows you to pass parameters to your applet. To retrieve a
parameter, use the getParameter( ) method. It returns the value of the specified parameter in the
form of String object. Thus, for numeric and Boolean values, you will need to convert their string
representations into their internal formats. Here the example of passing parameters

1. To pass a value to Applet tag of html program, use <param> tag


<param name=no value = 100>
Wher name, value are attributes and no,100 are values.
2. To get parameter value use getParameter() method.
na=getParameter("no");

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);
}}}

Example program of Student Mark.


import [Link].*;
import [Link].*;
/*
<applet code="app3" width =400 height = 500>
<param name=name value="Kannan">
<param name=RegNo value = 101>
<param name=m1 value=75>
<param name=m2 value=70>
</applet>
*/
public class app3 extends Applet
{
Font f=new Font("TimesRoman",[Link],20);
String name;
int no,m1,m2,tot;
public void init()
{
name=getParameter("name");
String na,ma1,ma2;
na=getParameter("RegNo");
no=[Link](na);
ma1=getParameter("m1");
m1=[Link](ma1);
ma2=getParameter("m2");
m2=[Link](ma2);
tot=m1+m2;
}
public void paint(Graphics g)
{
[Link](f);
[Link]([Link]);
[Link](name,50,50);
[Link]("number :"+no,50,80);
[Link]("mark1 :"+m1,50,110);
[Link]("mark2 :"+m2,50,140);
[Link]("total :"+tot,50,170);
}}

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.

4.7. Applet Graphics using AWT Methods


Graphics in Applet
The [Link] class provides many methods for graphics programming. All
method are declared as public abstract .
Commonly used methods of Graphics class:

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.

Example of Graphics in applet:

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> */

Compile: D:\RM> javac [Link]


Run : D:\RM> appletviewer [Link]

[Link] Image in Applet


An applet can display images of the format GIF, JPEG, BMP, and others. To display an
image within the applet, you use the drawImage() method found in the [Link] class.
Applet is mostly used in games and animation. For this purpose image is required to be displayed.
The [Link] class provide a method drawImage() to display the image.
Syntax of drawImage() method:
1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is
used draw the specified image.

How to get the object of Image:


The [Link] class provides getImage() method that returns the object of Image. Syntax:

1. public Image getImage(URL u, String image){}


Other required methods of Applet class to display image:
1. public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.

Example of displaying image in applet:


import [Link].*;
import [Link].*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
Page 114
picture = getImage(getDocumentBase(),"[Link]");
}
public void paint(Graphics g) {
[Link](picture, 30,30, this);
}
}
/*<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.

4.9. Playing Audio and Animation in applet


An applet can play an audio file represented by the AudioClip interface in the [Link]
package. The AudioClip interface has three methods, including:

• 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.

Example for playing audio.


Following is the example showing all the steps to play an audio:
import [Link].*;
import [Link].*;
import [Link].*;
public class AudioDemo extends Applet
{
private AudioClip clip;
private AppletContext context;
public void init()
{
context =[Link]();
String audioURL =[Link]("audio");
if(audioURL ==null)
{
audioURL ="[Link]";

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]();
}}}

Now, let us call this applet as follows:


<html>
<appletcode="[Link]"width="0"height="0">
<paramname="audio"value="[Link]">
</applet>
</html>
4.9.1. Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be moved.
Example of animation in applet:
import [Link].*;
import [Link].*;
public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif");
}
public void paint(Graphics g) {
for(int i=0;i<500;i++){
[Link](picture, i,30, this);
try{[Link](100);}catch(Exception e){}
} } }
/*<applet code="[Link]" width="300" height="300">
</applet> */

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.

4.11. AWT and GUI


Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based
and event-driven application programs in java.
The AWT contains numerous classes and methods that allow you to create and manage
windows. The AWT when creating your own applets or stand-alone programs. The main purpose
of the AWT is to support applet windows, it can also be used to create stand-alone windows that
run in a GUI environment, such as windows.
JAVA AWT provides a rich set of libraries to create Graphical User Interface program in
platform independent way. In this article we'll look in AWT (Abstract Window Toolkit).

a) Graphical User Interface (GUI)

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.

b) GUI based Applications


Following are some of the examples for GUI based applications.
 Automated Teller Machine (ATM)
 Airline Ticketing System
 Information Kiosks at railway stations
 Mobile Applications
 Navigation Systems
c) Advantages of GUI over CUI
 GUI provides graphical icons to interact while the CUI (Character User Interface) offers
the simple text-based interfaces.
 GUI makes the application more entertaining and interesting on the other hand CUI does
not.
 GUI offers click and execute environment while in CUI every time we have to enter the
command for a task.
 New user can easily interact with graphical user interface by the visual indicators but it is
difficult in Character user interface.
 GUI offers a lot of controls of file system and the operating system while in CUI you have
to use commands which is difficult to remember.
 Windows concept in GUI allow the user to view, manipulate and control the multiple
applications at once while in CUI user can control one task at a time.
 GUI provides multitasking environment so as the CUI also does but CUI does not provide
same ease as the GUI do.
 Using GUI it is easier to control and navigate the operating system which becomes very
slow in command user interface. GUI can be easily customized.

4.12. AWT Component Classes

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.

Java AWT component classes are given below.

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.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below

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

void add(Component c) inserts a component on this component.


void setSize(int width,int height) sets the size (width and height) of the component.
void setLayout(LayoutManager m) defines the layout manager for the component.
void setVisible(boolean status) changes the visibility of the component, by default false.

4.12.1. Create a Window using AWT Frame

Working with Frame Windows:


After the applet, the type of window you will most often create is derived from Frame. You
will use it to create child windows with applets, and top-level or child windows for applications.
Here are two of Frame‟s constructors:
Frame( )
Frame( String title)
The first form creates a standard window that does not contain a title. The second form
creates a window with the title specified by title.
Hiding and Showing a Window:
After a frame window has been created, it will not be visible until you call setVisible( ). Its
signature is shown here:
void setVisible(Boolean visible flag)
The component is visible if the argument to this method is true. Otherwise, it is hidden.
Setting a Window‟s Title:
You can change the title in a frame window using setTitle( ), which has this general form:

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.

 By extending Frame class (inheritance)


 By creating the object of Frame class (association)

Simple example of AWT by inheritance


import [Link].*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
[Link](30,100,80,30); // setting button position
add(b); //adding button into frame
setSize(300,300); //frame size 300 width and 300 height
setLayout(null); //no layout manager
setVisible(true); //now frame will be visible, by default not visible
}
public static void main(String args[])
{
First f=new First();
}}

4.13.. AWT Layout Manager


The Layout Managers are used to arrange components in a particular manner. Layout
Manager 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.
There are the following 5 layout managers
1. Border Layout
2. Flow Layout
3. Grid Layout
4. Card Layout
5. Grid Bag Layout
There are following classes that represents the layout managers:
1. [Link] 2. [Link] 3. [Link]
4.. [Link] 5. [Link]

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

void setLayout(LayoutManager layout obj)

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

Constructors of BorderLayout class:

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.

Example of BorderLayout class:

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:

• CardLayout() -Creates a new card layout with gaps of size zero.


• CardLayout(int hgap, int vgap) -Creates a new card layout with the specified
horizontal and vertical gaps.
To add cardLayout on form use add() methods.
Void add(Componet panelobj, Object name);
This Layout provide the following methods to activate the card.
void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck) &
void Show(Container deck, String cardname)
Example:

CardLayoutExample1()
{
cPane = getContentPane();
crd = new CardLayout();
[Link](crd);

// creating the buttons


btn1 = new JButton("Apple");
btn2 = new JButton("Boy");
btn3 = new JButton("Cat");

// 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);
}

4.14.. AWT Controls


AWT Controls are components that allow a user to interact with your application in various
ways – for example, a commonly used control is the push button. A layout manager automatically
positions components within a container.
Control Fundamentals:
The AWT supports the following types of controls:
Labels, Push buttons, Check boxes, Choice lists, Lists, Scroll bars, Text editing.
These controls are subclasses of Component.
Sr. Control & Description
No.

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.

2 Button -This class creates a labeled button.

3 Check Box - A check box is a graphical component that can be in either


an on (true) or off (false) state.

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.

8 Choice -A Choice control is used to show pop up menu of choices. Selected


choice is shown on the top of the menu.

9 Canvas -A Canvas control represents a rectangular area where application can


draw something or can receive inputs created by user.

10 Image - An Image control is superclass for all image classes representing


graphical images.

11 Scroll Bar - A Scrollbar control represents a scroll bar component in order to


enable user to select from range of values.

12 Dialog - A Dialog control represents a top-level window with a title and a


border used to take some form of input from the user.

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.

Scrollbar sb=new Scrollbar([Link],0,0,0,100);

[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;
}}

2. Calculator using button and event


import [Link].*;
import [Link].*;
import [Link].*;
/* <applet code="Cal" width=300 height=300>
</applet> */
public class Cal extends Applet
implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");

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

5.1. Introduction to Java Swing


Unlike AWT, Java Swing provides platform-independent and lightweight components. It
is used to create the Window Based & Event-driven application programs.
The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

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.

No. Java AWT Java Swing


1) AWT components are platform- Java swing components are platform-
dependent. independent.
2) AWT components are heavyweight. Swing components are lightweight.
3) AWT doesn't support pluggable look Swing supports pluggable look and feel.
and feel.
4) AWT provides less components than Swing provides more powerful
Swing. componentssuch as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.
5) AWT doesn't follows MVC(Model Swing follows MVC.
View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.

What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development
of desktop applications.

5.1.2. JApplet class in Applet


As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The
JApplet class extends the Applet class.

Example of EventHandling in JApplet:


import [Link].*;
import [Link].*;
import [Link].*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init()
{
tf=new JTextField();
[Link](30,40,150,20);
b=new JButton("Click");
[Link](80,150,70,40);
add(b);add(tf);
[Link](this);
Page 143
setLayout(null);
}
public void actionPerformed(ActionEvent e){
[Link]("Welcome");
}
}

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.

There are following classes that represents the layout managers:


1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link] etc.

All layout are worked as similarly as AWT layout .

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

1 JLabel -A JLabel object is a component for placing text in a container.

2 JButton -This class creates a labeled button.

3 JColorChooser -A JColorChooser provides a pane of controls designed to allow a


user to manipulate and select a color.

4 JCheck Box -A JCheckBox is a graphical component that can be in either an on(true)


or off (false) state.

5 JRadioButton -The JRadioButton class is a graphical component that can be in either


an on (true) or off (false) state. in a group.

6 JList -A JList component presents the user with a scrolling list of text items.

7 JComboBox - A JComboBox component presents the user with a to show up menu of


choices.

8 JTextField A JTextField object is a text component that allows for the editing of a
single line of text.

9 JPasswordField -A JPasswordField object is a text component specialized for


password entry.

10 JTextArea -A JTextArea object is a text component that allows for the editing of a
multiple lines of text.

11 ImageIcon A ImageIcon control is an implementation of the Icon interface that paints


Icons from Images

12 JScrollbar -A Scrollbar control represents a scroll bar component in order to enable


user to select from range of values.

13 JOptionPane -JOptionPane provides set of standard dialog boxes that prompt users
for a value or informs them of something.

14 JFileChooser -A JFileChooser control represents a dialog window from which the


user can select a file.

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

1 JButton() -Creates a button with no set text or icon.

2 JButton(Action a) -Creates a button where properties are taken from the Action
supplied.

3 JButton(Icon icon) -Creates a button with an icon.

4 JButton(String text) -Creates a button with text.

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.

3 boolean isDefaultButton() -Gets the value of the defaultButton property, which if


true means that this button is the current default button for its JRootPane.

4 boolean isDefaultCapable() -Gets the value of the defaultCapable property.

5 protected String paramString() -Returns a string representation of this JButton.

6 void removeNotify() -Overrides [Link] to check if this button

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.

7 void setDefaultCapable(boolean defaultCapable) -Sets the defaultCapable


property, which determines whether this button can be made the default button for
its root pane.

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

1 JTextField() - Constructs a new TextField.

2 JTextField(Document doc, String text, int columns) -Constructs a new JTextField


that uses the given text storage model and the given number of columns.

3 JTextField(int columns) -Constructs a new empty TextField with the specified


number of columns.

4 JTextField(String text) -Constructs a new TextField initialized with the specified


text.

5 JTextField(String text, int columns) -Constructs a new TextField initialized with


the specified text and columns.
Class methods
S.N. Method & Description

1 protected void actionPropertyChanged(Action action, String propertyName)


Updates the textfield's state in response to property changes in associated action.

2 void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this textfield.

3 protected void configurePropertiesFromAction(Action a)

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.

5 protected Document createDefaultModel() -Creates the default implementation


of the model to be used at construction if one isn't explicitly given.

6 protected void fireActionPerformed()


Notifies all listeners that have registered interest for notification on this event type.

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.

9 ActionListener[] getActionListeners() -Returns an array of all the ActionListeners


added to this JTextField with addActionListener().

10 Action[] getActions()- Fetches the command list for the editor.

11 int getColumns() -Returns the number of columns in this TextField.

12 protected int getColumnWidth()- Returns the column width.

13 int getHorizontalAlignment()- Returns the horizontal alignment of the text.

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.

Example of JTextField class:


import [Link];
import [Link].*;
public class TArea {
JTextArea area;
JFrame f;
TArea(){
f=new JFrame();
area=new JTextArea(300,300);
[Link](10,30,300,300);
[Link]([Link]);
[Link]([Link]);
[Link](area);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String[] args) {
new TArea();
} }

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.

Example of JTable class:


import [Link].*;
public class MyTable {
JFrame f;
MyTable(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
[Link](30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
[Link](sp);
[Link](300,400); // [Link](null);
[Link](true);
}
public static void main(String[] args) {
new MyTable();
} }

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.

Commonly used Constructors of JSlider class:


o JSlider(): creates a slider with the initial value of 50 and range of 0 to 100.
o JSlider(int orientation): creates a slider with the specified orientation set by either
[Link] or [Link] with the range 0 to 100 and initial value 50.
o JSlider(int min, int max): creates a horizontal slider using the given min and max.
o JSlider(int min, int max, int value): creates a horizontal slider using the given min, max
and value.
o JSlider(int orientation, int min, int max, int value): creates a slider using the given
orientation, min, max and value.
Commonly used Methods of JSlider class:
1) public void setMinorTickSpacing(int n): is used to set the minor tick spacing to the slider.
2) public void setMajorTickSpacing(int n): is used to set the major tick spacing to the slider.
3) public void setPaintTicks(boolean b): is used to determine whether tick marks are painted.
4) public void setPaintLabels(boolean b): is used to determine whether labels are painted.
5) public void setPaintTracks(boolean b): is used to determine whether track is painted.
Simple example of JSlider class:

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.

Fig. JDBC API connect to Database

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:

1. Application: It is a java applet or a servlet that communicates with a data source.

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

1) JDBC-ODBC bridge 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.

PreparedStatement -This represents a precompiled SQL statement. An SQL statement is compiled


and stored in a prepared statement and you can later execute this multiple times. You can get an
object of this interface using the method of the Connection interface named prepareStatement().
This provides methods such as executeQuery(), executeUpdate(), and execute() to execute the
prepared statements and getXXX(), setXXX() (where XXX is the datatypes such as long int float
etc..) methods to set and get the values of the bind variables of the prepared statement.

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.

5.8. Steps of Java Database Connectivity


There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.
Syntax:
public static void forName(String className)throws ClassNotFoundException

Example to register the MySql Driver class


Here, Java program is loading oracle driver to esteblish database connection.

[Link]("[Link] ");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the
database.
Syntax :
1) public static Connection getConnection(String url) throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the SQL database
1. Connection con=[Link](
" jdbc:mysql://localhost:3306/Employ","root","root"); );

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]();

4)Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax : public ResultSet executeQuery(String sql) throws SQLException


Example :
ResultSet rs=[Link]("select * from emp");
while([Link]()) {
[Link]([Link](1)+" "+[Link](2));
}
5)Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.

Syntax : public void close() throws SQLException


Example : [Link]();

5.9. JDBC Program using MySQL and MS-Access Database


1. Example program for MySQL
Let's first create a table in the mysql database, but before creating table, we need to create database
first.
import [Link].*;
class MysqlCon{
public static void main(String args[])
{
try{
[Link]("[Link]");
Connection con=[Link](
"jdbc:mysql://localhost:3306/Employ","root","root");
Statement stmt=[Link]();
ResultSet rs=[Link]("select * from Emp");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}catch(Exception e){ [Link](e);}
} }
Page 160
Database Table Structure
2. Create a Database:
Mysql:> Create database Epmploy;
3. Create a Table:
Mysql:> Create table Emp(EmpNo int(5), Empname varchar(15), Salary float(8,2));

Field Name Type


EmpNo Int(5)
Empname Varchar(15)
Salary Float(82)
Record of Data:
EmpNo Empname Salary
101 Kannan 24000.0
102 SenthilKumar 23000.0
103 Priyanka 20000.0

2. Example program for MS-Access

Connectivity with Access without DSN


There are two ways to connect java application with the access database.
a) Without DSN (Data Source Name)
b) With DSN
Java is mostly used with Oracle, mysql, or DB2 database. So you can learn this topic only
for knowledge.

a) Example to Connect Java Application with access without DSN


In this example, we are going to connect the java program with the access database. In such
case, we have created the login table in the access database. There is only one column in the table
named name. Let's get all the name of the login table.
Program:
import [Link].*;
class Test{
public static void main(String ar[]){
try{
String database="[Link]";
//Here [Link] is database exists in the current directory
String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};
DBQ=" + database + ";DriverID=22;READONLY=true";
[Link]("[Link]");
Connection c=[Link](url);
Statement st=[Link]();
ResultSet rs=[Link]("select * from login");
while([Link]()){
[Link]([Link](1));
}
}catch(Exception ee){[Link](ee);}
}}
Page 161
b) Example to Connect Java Application with access with DSN
Connectivity with type1 driver is not considered good. To connect java application with
type1 driver, create DSN first, here we are assuming your dsn name is mydsn.

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

2. Create a FILE DSN (DATA SOURCE NAME) or Systen DSN


For link database to DSN
a) CLICK ― Control panelAdministrative tools Data sources(ODBC) 
File DSN  ADD microsoft access driver(*.mdb) -> next.

b).. Select a location to save DSN name as ―DNS1 (D:\RM\DSN1)


c).. Select the database name and table name

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:

String databaseURL = "jdbc:ucanaccess://d://RM//[Link]";

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 (?, ?, ?)";

PreparedStatement preparedStatement = [Link](sql);


[Link](1, "Jim Rohn");
[Link](2, "rohnj@[Link]");
[Link](3, "0919989998");
int row = [Link]();
if (row > 0) {
[Link]("A row has been inserted successfully.");
}
sql = "SELECT * FROM Contacts";
Statement statement = [Link]();
ResultSet result = [Link](sql);
while ([Link]()) {
int id = [Link]("Contact_ID");
String fullname = [Link]("Full_Name");
String email = [Link]("Email");
String phone = [Link]("Phone");
[Link](id + ", " + fullname + ", " + email + ", " + phone);
}
} catch (SQLException ex) {
[Link]();
}
}}

Page 163
Sample Questions

Two Mark questions


1. What is Swing?
2. Define JDBC
3. What is JDBC Driver?
4. Write the use of JprogressBar.
5. Define Look-and-Feel.
6. Write the use of Jtable.
7. Write the use of Jslider.
8. Write the use of ResultSet interface.
9. Define the JDBC API.
10. Write use of DriverManager.
11. Tell about JDBC-ODBC bridge

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

You might also like