1 Java 289

Download as pdf or txt
Download as pdf or txt
You are on page 1of 289

SAURASHTRA UNIVERSITY

RAJKOT – INDIA

CURRICULAM

FOR

B.C.A.

Bachelor of Computer Application

(Semester III and Semester IV)

Effective From June – 2020

R. P. BHALODIA - RAJKOT Page |1


B.C.A. (Semester – IV)
NO. OF LECT.
SR.NO SUBJECT CREDIT
PER WEEK
CS – 19
1 Programming with 5 5
JAVA
CS – 20
2 Programming with 5 5
C#
CS – 21
3 Network Technology 5 5
and Administration
CS –22
Operating Systems
4 5 5
Concepts With Unix /
Linux
CS – 23
5 Practical (Based On 5 5
CS-19, CS-22)
CS – 24
6 Practical (Based On 5 5
CS-20)
Total Credit 30

Note:
1. Credit of each subject is 5. Total credit of semester is 30.
2. Total marks of each theory paper are 100 (university examination 70
marks + internal examination 30 marks).
3. Total marks of each practical paper are 100. No internal examination
marks in practical papers.

R. P. BHALODIA - RAJKOT Page |2


CS – 19 PROGRAMMING WITH JAVA
Marks
Min
No Topics Details weight
Lec.
In %
1 History, - History and Features of Java
Introduction - Java Editions
and - JDK, JVM and JRE
Language, - JDK Tools
Basics - Compiling and Executing basic
Classes and Java Program
Objects - Java IDE (NetBeans and
Eclipse)
- Data Type (Integer, Float,
Character, Boolean)
- Java Tokens (Keyword,
Literal, Identifier, Whitespace,
Separators, Comments,
Operators)
- Operators (Arithmetic,
Relational, Boolean Logical,
Bitwise Logical, Assignment,
Unary, Shift, Special
20 10
operators)
- Java Keywords (assert, strictfp,
enum)
- Type Casting
- Decision Statements (if,
switch)
- Looping Statements (for,
while, do..while)
- Jumping Statements (break,
continue, return)
- Array (One Dim., Rectangular,
Jagged)
- Command Line Argument
Array
- OOP Concepts (Class, Object,
Encapsulation, Inheritance,
Polymorphism)
- Creating and using Class with
R. P. BHALODIA - RAJKOT Page |3
members
- Constructor
- finalize() method
- Static and Non-Static Members
- Overloading (Constructor &
Method)
- Varargs, IIB (Instance
Initialization Block) in Java
2 Inheritance, - Universal Class (Object Class)
Java Packages - Access Specifiers (public,
private, protected, default,
private protected)
- Constructors in inheritance
- Method Overriding
- Interface, Object Cloning,
- Nested and Inner Class
- Abstract and Final Class
- Normal import and Static
Import
- Introduction to Java API
Packages and imp. Classes
o java.lang
o java.util
o java.io
20 15
o java.net
o java.awt
o java.awt.event
o java.applet
o java.swing
- java.lang Package Classes
(Math, Wrapper Classes,
String, String Buffer)
- java.util Package Classes
(Random, Date,
GregorianCalendar,
StringTokenizer, Collection in
Java - Vector, HashTable,
LinkedList, SortedSet, Stack,
Queue, Map
- Creating and Using

R. P. BHALODIA - RAJKOT Page |4


UserDefined package and sub-
package

3 Exception - Introduction to exception


Handling, handling
Threading and - try, catch, finally, throw,
Streams (Input throws
and Output) - Creating user defined
Exception class
- Thread and its Life Cycle
(Thread States)
- Thread Class and its methods
- Synchronization in Multiple
Threads (Multithreading)
- Deamon Thread, Non-Deamon
Thread
- Stream and its types (Input,
Output, Character, Byte)
- File and RandomAccessFile
Class
20 10
- Reading and Writing through
Character Stream Classes
(FileReader, BufferedReader,
FileWriter, BufferedWriter)
- Reading and Writing through
Byte Stream Classes
(InputStream, FileInputStream,
DataInputStream,
OutputStream,
FileOutputStream,
DataOutputStream)
- StreamTokenizer Class
- Piped Streams, Bridge Classes
: InputStreamReader and
OutputStreamWriter
- ObjectInputStream,
ObjectOutputStream
4 Applets - Introduction to Applet
- Applet Life Cycle 20 10
- Implement & Executing
R. P. BHALODIA - RAJKOT Page |5
Applet with Parameters
- Graphics class
Layout - FlowLayout
Managers - BorderLayout
- CardLayout
- GridLayout
- GridBagLayout with
GridBagConstraints
- Intro. to BoxLayout,
SpringLayout, GroupLayout
- Using NO LAYOUT Manager
5 GUI using - Introduction to AWT and
SWING Swing
Event Handling - Difference Between AWT and
Swing Components
- Swing Components
o JFrame, JPanel
o JLabel, JButton,
JRadioButton, JCheckBox,
JProgressBar, JFileChooser
o JTextField, JPasswordField,
15
JTextArea
o JScrollBar, JComboBox,
JList
o Menus (JMenuBar, JMenu,
JMenuItem) 20
- Introduction to Event Handling
- Event Delegation Model
- Event Packages
o AWT Event Package
o Swing Event Package
- Event Classes (ActionEvent,
ItemEvent, FocusEvent,
MouseEvent,
MouseWheelEvent,
AdjustmentEvent TextEvent,
WindowEvent, etc.)
- Listener Interfaces
(ActionListener, ItemListener,
FocusListener,

R. P. BHALODIA - RAJKOT Page |6


AdjustmentListener,
KeyListener, MouseListener,
MoutMotionListener,
TextListener, WindowListener,
etc.)
- Adapter Classes
(FocusAdapter, KeyAdapter,
MouseAdapter,
MouseMotionAdapter
Total 100 60

Students seminar - 5 Lectures.


Expert Talk - 5 Lectures
Students Test - 5 Lectures.
TOTAL LECTURES 60+15=75

Reference Books:
1. Java: A Beginner's Guide – Jul 2014 by Herbert Schildt
2. Java Programming (Oracle Press) by Poornachandra Sarang
3. Java The Complete Reference, 8th Edition –by Herbert Schildt
4. Ivor Horton's “Beginning Java 2” JDK 5 Edition, Wiley Computer
Publishing.
5. Ken Arnold, James Gosling, David Holmes, “The Java
Programming Language”, Addison-Wesley Pearson Education.
6. Cay Horstmann, “Big Java”, Wiley Computer publishing (2 nd edition
– 2006).
7. James Gosling, Bill Joy, Guy Steele, Gilad Bracha, “The Java
Langauge Specifications”, Addison-Wesley Pearson Education (3rd
edition) Download at http://docs.oracle.com/javase/specs/

R. P. BHALODIA - RAJKOT Page |7


CS – 20 PROGRAMMING WITH C#
Marks
Min
No Topics Details weight
Lec.
In %
1 .NET Framework Introduction to .NET
and Framework
Visual Studio Features / Advantages
IDE, CLR, CTS and CLS
Language Basics BCL / FCL / Namespaces
Assembly and MetaData
JIT and types
Managed Code and
Unmanaged Code
Introduction to .NET
Framework and IDE versions
Different components
(windows) of IDE
Types of Projects in IDE 20 10
(Console, Windows, Web,
Setup, etc.)
Data Types (Value Type &
Reference Type)
Boxing and UnBoxing
Operators (Arithmetic,
Relational, Bitwise, etc.)
Arrays (One Dimensional,
Rectangular, Jagged)
Decisions (If types and switch
case)
Loops (for, while, do..while,
foreach)

R. P. BHALODIA - RAJKOT Page |8


2 Class and Concept of Class, Object,
Inheritance, Encapsulation, Inheritance,
Property, Polymorphism
Indexer, Creating Class and Objects
Pointers, Methods with “ref” and “out”
Delegates, parameters
Event, Static and Non-Static
Collections Members
Constructors
Overloading Constructor,
Method and Operator
Inheritance
Sealed Class & Abstract Class
Overriding Methods 20 15
Interface inheritance
Creating and using Property
Creating and using Indexer
Creating and using Pointers
(unsafe concept)
Creating and using Delegates
(Single / Multicasting)
Creating and using Events
with Event Delegate
Collections (ArrayList,
HashTable, Stack, Queue,
SortedList) and their
differences.
3 Windows Creating windows Application
Programming MessageBox class with all
types of Show() method
Basic Introduction to Form
and properties
Concept of adding various
Events with event parameters 20 15
Different Windows Controls
- Button
- Label
- TextBox
- RadioButton
- CheckBox

R. P. BHALODIA - RAJKOT Page |9


- ComboBox
- ListBox
- PictureBox
- ScrollBar
- TreeView
- Menu (MenuStrip,
ContextMenuStrip)
- ToopStrip
- Timer
- Panel and GroupBox
Dialog Boxes (ColorDialog,
FontDialog, SaveFileDialog
and OpenFileDialog)
MDI Concept with MDI
Notepad
Concept of Inheriting Form
4. Database Concept of Connected and
Programming Disconnected Architecture
with ADO.NET Data Providers in ADO.NET
Connection Object
Connected Architecture
- Command
- DataReader
Disconnected Architecture
- DataAdapter 20 12
- DataSet
- DataTable
- DataRow
- DataColumn
- DataRelation
- DataView
Data Binding
GridView Programming

R. P. BHALODIA - RAJKOT P a g e | 10
5 User Controls Creating User Control with
(Components), - Property
Crystal Reports, - Method
Setup Project - Event
Using User Control in
Windows, Projects as
component,
Creating Crystal Reports
Types of Reports
20 8
Report Sections
Formula, Special Field and
Summary in Report
Types of Setup Projects
Creating Setup Project
- File System Editor
- User Interface Editor
- Launch Conditions
Editor
Total 100 60

Students seminar - 5 Lectures


Expert Talk - 5 Lectures
Students Test - 5 Lectures
TOTAL LECTURES 60+15=75

REFERENCE BOOKS
1. Pro C# 5.0 and .NET 4.5 Framework (By: Andrew Troelsen )
2. Head First C# - (By: Jennifer Greene, Andrew Stellman )
3. C# 5.0 Unleashed - (By: Bart De Smet )
4. Adaptive Code Via C# (By: Gary McLean Hall )
5. C#.NET Programming Black Book - steven holzner –dreamtech
publications
6. Introduction to .NET framework - Wrox publication
7. Microsoft ADO. Net - Rebecca M. Riordan, Microsoft Press

R. P. BHALODIA - RAJKOT P a g e | 11
CS – 21 NETWORK TECHNOLOGY AND ADMINISTRATION
No Topics Details Marks Min
weight Lec.
In %
1 Basics of  Network concepts 20 12
Network, - What is network
Network Models - Use of network
and LAN  Network model
Sharing -peer – to – peer
-client – server
 Network Services
- File service,
- Print service,
- Comm. service,
- Data base service,
- Security service,
- Application service
 Network Access Methods
- csma / cd, csma / ca,
- Token passing
- Polling
 Network Topologies
- Bus, Ring, Star,
Mesh,Tree,Hybrid
 Advanced Network
Topologies
Ethernet,CDDI,FDDI
 Communication Methods
- Unicasting
- Multicasting
- Broadcasting
 OSI reference model with 7
layers
 TCP/IP network model with 4
layers
 File And Print Sharing in
LAN.
 aping of network drive
 Disk quota

R. P. BHALODIA - RAJKOT P a g e | 12
 Encryption
 Compression
 Net meeting

2 Transmission  Transmission Media 20 15


Media - Types of Transmission
Multiplexing & media
Switching - Guided media
Concepts - Co – Axial Cable,
Network devices - Twisted Pair Cable,
- Crimping of Twisted pair
cable
- Fiber Optic Cable
 Unguided media
- Infrared, Laser, Radio,
Microwave,
Bluetooth tech.
 Different Frequency Ranges
 Multiplexing &
Demultiplexing
 Multiplexing Types
- FDM,
- TDM,
- CDM,
- WDM
 Switching Tech.
- Circuit Switching,
- Message Switching,
- Packet Switching
 CABLE NETWORK
DEVICES
 LAYER1 DEVICES
- LAN CARD,
- MODEM ,
- DSL & ADSL
- HUB(Active,Passive,Smart
hub)
- REPEATER
 LAYER2 DEVICES

R. P. BHALODIA - RAJKOT P a g e | 13
- SWITCH(Manageable,
nonmanagable)
- BRIDGE(Source route,
Transactional)
 LAYER3 DEVICES
- ROUTER
- LAYER3 SWITCH
- BROUTER
- GATEWAY
- Network Printer
 WIRELESS NETWORK
DEVICES
Wireless switch
Wireless router,
ACCESSPOINT

R. P. BHALODIA - RAJKOT P a g e | 14
3 Network  Packets &Protocols 20 10
Protocols,  Conn. Oriented protocols -
Network Routing TCP& connection less
protocols-UDP
 TCP/IP STACK
- HTTP
- FTP
- SMTP
- POP3
- SNMP
- TELNET
- ARP
- RARP
 IPX/SPX
 AppleTalk,
 NetBIOS Name PROTOCOL
 L2CAP, RFCOMM Protocol
 What is routing
 Requirements of routing
 Types of Routing
- static
- dynamic
- default
 Routing protocols
- Exterior Routing protocol
1)BGP
- Interior Routing protocol
(1)Distance vector routing
- RIP
- IGRP
- EIGRP
(2)Link state routing
- OSPF
- IS IS

R. P. BHALODIA - RAJKOT P a g e | 15
4 IP  What is ip address? 20 11
ADDRESSING,  Types of ip address
Windows 2008  ipv4
server - Class structure
- subneting,supernetting
 ipv6
- Basic structure of ipv6
- Implementation of ipv6
 Migration from ipv4 to ipv6
 Installation of 2008 enterprise
server
 Various editions of windows
2008 server
 Installation & Configuration
of Active Directory
- Domains, Trees, Forests
concept
 Accounts(User,
Group,Computer)
 Policy (Security and audit)
 Logging Events
 MMC(Microsoft
Management console)

R. P. BHALODIA - RAJKOT P a g e | 16
5 Basics of  Fundamental of Network 20 12
Network Security
Security,  Requirements of network
Internet Security
connection &  Policies, Standard,
Sharing Procedures, Baselines, Guide
lines
 Security methods
- Encryption
- Cryptography
- Authentication
 Security Principle –CIA
Model
 Basics of Internet
 How internet is connecting
with computer
 Technology related internet
- Dial up tech.
- ISDN network tech.
- Lease line tech.
 VPN
- Types of VPN
- Use of VPN
- VPN protocols (PPTP,
L2TP, IPsec.)
 Proxy server, Firewall
 GPS, GPRS
 CCTV tech.
Total 100 60

Students seminar - 5 Lectures


Expert Talk - 5 Lectures
Students Test - 5 Lectures
TOTAL LECTURES 60+15=75

Reference Books:
1. Networking Essential - Glenn Berg Tech. Media
2. MCSE Self-Paced Training Kit (Server 2003)
3. Data Communication and Networking - B A Forouzan
R. P. BHALODIA - RAJKOT P a g e | 17
CS – 22 : Operating Systems Concepts With Unix / Linux
Mark
s App
N
Topics Details weigh .
o
t In Lect
%
1 Introduction,  Meaning of OS 20 12
Process  Functions of OS
Management  Features of OS
,  OS Types (User Point of View)
Memory  OS Types (Features Point of
Management View)
 Introduction of OS process
 Process State Transition Diagram
 Process Scheduling
o FCFS
o SJN
o Round Robin
o Priority Base Non Preemptive
o Priority Base Preemptive
 Physical Memory and Virtual
Memory
 Memory Allocation
 Contiguous Memory Allocation
 Noncontiguous Memory
Allocation
 Virtual Memory Using Paging
 Virtual Memory Using
Segmentation
2 Getting  Unix Architecture 20 17
Started with  Unix Features
Unix,  Types Of Shell ( C, Bourn, Korn )
Unix Shell  Unix File System
Command,  Types Of Files
Text Editing o Ordinary Files
With vi o Directory Files
Editor, o Device Files
 Unix File & Directory Permissions

R. P. BHALODIA - RAJKOT P a g e | 18
 Connecting Unix Shell : Telnet
 Login Commands passwd, logout,
who, who am i, clear
 File / Directory Related Command
ls, cat, cd, pwd, mv, cp, ln, rm,
rmdir,
mkdir, umask, chmod, chown,
chgrp,
find,pg,more,less,head,tail,wc,touc
h
 Operators in Redirection & Piping
o <
o >
o <<
o >>
o |
 Advance Tools
 Finding Patterns in Files
grep,fgrep,egrep
 Working with columns and fields
cut,paste,join
 Tools for sorting
sort,uniq
 Comparing files :
cmp,comm.,diff
 Changing Information in Files :
tr,sed,
 Examining File Contents : od
 Tools for mathematical
calculations bc,factor
 Monitoring Input and Output
tee,script
 Tools For Displaying Date and
Time cal,date
 Communications
telnet,wall,mtod,write,mail,news,fi
nger
 Process Related Commands :
ps, command to run process in

R. P. BHALODIA - RAJKOT P a g e | 19
background,
nice,kill,at,batch,cron,
crontab,wait,sleep
 Concept of Mounting a File
System
mount command
 Concept of DeMounting a File
System
umount command
 Introduction of vi editor
 Modes in vi
 Switching mode in vi
 Cursor movement
 Screen control commands
Entering text, cut, copy, paste in vi
editor
3 Shell  Shell Keywords 20 16
Programmin  Shell Variables
g  System variables
Getting PS2, PATH, HOME,LOGNAME,
Started with MAIL, IFS, SHELL, TERM,
Linux, MAILCHECK
Linux  User variables
Booting set, unset and echo command with
shell
variables
 Positional Parameters
 Interactive shell script using read
and echo
 Decision Statements
o if then fi
o if then else fi
o if then elif else fi
o case esac
 test command
 Logical Operators
 Looping statements
o for loop
o while loop
R. P. BHALODIA - RAJKOT P a g e | 20
o until loop
o break, continue command
 Arithmetic in Shell script
 Various shell script examples

 History of Linux
 GNU, GPL Concept
 Open Source & Freeware
 Structure and Features of Linux
 Installation and Configuration of
Linux
- Using with Ubuntu
 Startup, Shutdown and boot
loaders of Linux
 Linux Booting Process
- LILO Configuration
- GRUB Configuration
 User Interfaces (GUI and CUI)
4 Working  Layered Structure of X 20 7
with X- - Window Manager
Windows - Desktop Environment
(Ubuntu) - Start Menu
- User Configuration
- startx Command
 Window Managers
- GNOME
- KDE
- Purpose of window manager
 The KDE Desktop
- KDE Panel
- Desktop Icons
- Managing Windows
- The KDE Control Panel
 The GNOME Desktop
- The GNOME Panel
- Desktop Icons
- Managing Windows
- The GNOME Control Panel
 Configuring X
R. P. BHALODIA - RAJKOT P a g e | 21
- /etc/X11/Xorg.conf file
- Tuning Xorg.conf
- Choosing a Window Manager
 Create, Delete, Rename, Copy files
and folders
 Install / Uninstall Software
5. Linux Admin  Creating Linux User Account and 20 8
(Ubuntu) Password
 Installing and Managing Samba
Server
 Installing and Managing Apache
Server
 Optimizing LDAP Services
 Optimizing DNS Services
 Optimizing FTP Services
 Optimizing Web Services
 Configure Ubuntu's Built-In
Firewall
 Working with WINE
Total 100 60

Students seminar - 5 Lectures.


Expert Talk - 5 Lectures
Students Test - 5 Lectures.
TOTAL LECTURES 60+15=75

Reference Books
1. Stalling W, “Operating Systems”, 7th edition, Prentice Hall India.
2. Silberschatz, A., Peter B. Galvin and Greg Gagne, “Operating System
Principles”, Wiley-Indian Edition, 8th Edition
3. Unix Shell Programming - Y. Kanetkar- BPB Publications
4. Unix concepts and applications- Sumitabha Das

Hands-On (Not to be asked in the examination)


 Installation of Unix / Linux
 User and Group Creation
 Demo of Various Applications available in Unix / Linux like Star
Office, Games and other productivity tools.
 Demo of GNOME, KDE Desktops in Linux.

R. P. BHALODIA - RAJKOT P a g e | 22
CS - 23 : Practical based on CS – 19 & CS – 22
Sessions Topics Marks
I  CS – 19 50
II  CS – 22 50

Note : Each session is of 3 hours for the purpose of practical


examination.

CS - 24 : Practical Based on CS –20


Sessions Topics Marks
I  CS – 20 100

Note : Each session is of 3 hours for the purpose of practical


examination.

R. P. BHALODIA - RAJKOT P a g e | 23
CS – 19 PROGRAMMING WITH JAVA

R. P. BHALODIA - RAJKOT P a g e | 24
UNIT – 1: History, Introduction and Language, Basics Classes and
Objects
History of Java
• Java is General purpose object oriented Programming Language.
Developed by Sun Microsystems of U.S.A
• Mr. James Gosling one Of the Developer of the Language “OAK‟.
• initially java was Develop for Making the software for consumer
Electronic Devices like TV, microwave(sensor technology)
• The Developer team has reviewed the existing Language like c and
c++ and combine the advantage of both language and remove the
limitation and then develop the simple ,reliable ,portable and power
tool language that is called Java as we can show in below figure

 Explain java features


1. Compiler and interpreter
• Usually any programming language will be either compiler or
interpreter but java has combine both the approaches
• so become two stage system in it first stage java compiler translate
source code to machine independent byte code in the second stage
java interpreter will run this byte code in the destination machine.
• Compiler: - C, C++, VB, FOXPRO….
• Interpreter: - Scripting language, HTML, PHP

2.Platform independent
• This is the most important and power full future of JAVA program
can run anyway any time changes on upgrade in operation system or
any other system recourses will not affect the JAVA program to run.

R. P. BHALODIA - RAJKOT P a g e | 25
• This is the reason why JAVA become most popular language on the
internet because on internet each and every pc will have different
configuration.

3. Object oriented
• Java is pure object oriented programming and that‟s while
everything in java is an object

4.Secure and robust


• When we have a language for internet base programming security is
the first and for most issues security in the sense of protection from
wireless or security of data
• Java does not support * pointer so direct access of memory will not
allow and that why ever program and data will become secure and
robust

5. Distributed
• JAVA programming language has the ability to run program on
distributed network so that it allow us that multiple location can
develop a single project

6.Simple, small & familiar


• JAVA is simple language because all the feature like if condition
,for loop ,while loop , switch case, and so on of the most popular
language like C,C++
• JAVA is small language because it consists of only six packages.
The package is same feature combination of C and C++ which we
can familiar this language.

7. Dynamic
• JAVA is dynamic language because one can add new feature all new
feature all new classes.
• To the java itself we can also call it as extension language which can
be extend whenever needed.

R. P. BHALODIA - RAJKOT P a g e | 26
8.Multithreading
• Multithreading meaning handling of multiple task at a time.
• Java supports multithreaded programming this means that we does
not have to wait for a process to complete instead of that we can
start new process while the current process running.

9.High performance
• When you develop at require very much less memory as well as high
speed that‟s while its give us high performance.

 Milestone of Java [JAVA Edition]


• 1990
• Sun Micro System has desired to develop a software for
consumer electronic device
• 1991: The team has given a name to the new language “OAK”
• 1992: The team has been given a name called “green project team”
• 1993
• The internet and www has given authority to develop the
language for then also
• 1994
• The team has develop a new web browser called “HOT
JAVA”
• 1995
• “OAK” was rename to java due to some legal problem in the
same year Microsoft announce support to JAVA
• 1996 : sun has release “JAVA Development kit (jdk 1.0)
• 1997 : sun has release JDK1.1
• 1998 : sun has release JDK1.2
• 1999 : sun has release J2EE
• 2000 : sun has release JDK1.3
• 2002 : sun has release JDK1.4
• 2004 : sun has release JDK5.0
• 2007 : sun has release JDK6.0
• 2012 : Latest version is JDK10.0 (64 bits)

R. P. BHALODIA - RAJKOT P a g e | 27
 What is JDK?
The Java Development Kit (JDK) is an implementation of either one of
the Java SE, Java EE or Java ME platforms released by Oracle
Corporation in the form of a binary product aimed at Java developers on
Solaris, Linux, Mac OS X or Windows.
JDK Tool Meaning Use
Javac Java Compiler Compiles the source code (.java file) &
translates it into Bytecode.
Java Java Interpreter Interprets Bytecode & generates output.
Javadoc Java Used to create documentation for java
Documentation source code in HTML format.

Javah Java Header files It produces header files for the program
which uses native methods. This file is
included in your program which calls
this native method

Javap Java disassemble It converts Bytecode file (.class file) to


program description

Jdb Java debugger Used to debug your program


applerviewer Applet Viewer Used to execute java Applets.

 Bytecode & JVM Machine


• With most programming languages, you either compile or interpret a
program so that you can run it on your computer.

• The Java programming language is unusual in that a program is both


compiled and interpreted.

• With the compiler, first you translate a program into an intermediate


language called Java

• The platform-independent codes interpreted by the interpreter on the


Java platform.

R. P. BHALODIA - RAJKOT P a g e | 28
• The interpreter parses and runs each Java instruction on the
computer.

• Compilation happens just once; interpretation occurs each time the


program is executed.
• The following figure illustrates how this works.

• You can think of Java bytecodes as the machine code instructions


for the Java Virtual Machine (JVM).
• Every Java interpreter, whether it's a development tool or a Web
browser that can run applets, is an implementation of the JVM.

• Java byte codes help make "write once, run anywhere" possible.

• You can compile your program into bytecodes on any platform that
has a Java compiler.

• The byte codes can then be run on any implementation of the JVM.

• That means that as long as a computer has a JVM, the same program
written in the Java programming language can run on
Windows 2000, a Solaris workstation, or on an iMac.

R. P. BHALODIA - RAJKOT P a g e | 29
 Java Runtime Environment (JRE)
 The Java Runtime Environment (JRE), also known as Java Runtime,

 The Java Development Kit (JDK), a set of programming tools for


developing Java applications.

 The Java Runtime Environment provides the minimum requirements


for executing a Java application;

 It consists of the Java Virtual Machine (JVM), core classes, and


supporting files.

 Compiling & Executing basic java program


Step1:
Open the Windows Command prompt and type this command .Here we
are opening notepad with the filename Class1.java (Please remember the
.java extension)

Steps for compiling and running your first java program using the Java
Development kit from Sun Microsystems

Step2:
Notepad would ask if you want to create the file. Click on Yes. This would
create the file and you can type the code in it

R. P. BHALODIA - RAJKOT P a g e | 30
Step3:
Type the following code. All this code does is print Hello World! on the
screen. Remember Java is case sensitive

class a1
{
public static void main(String[] args){
System.out.println("Hello RPBC");
}
}

Step4:
Compilation Now Save the file and get back to the command prompt and
type the following command as shown.

javac a1.java

This command would compile a1.java and produce a1.class which


contains Java byte code which is machine independent.

Step5:
Running the program If you have any errors, you would see them on
the screen.

java a1

Please go back to notepad and correct the errors and resave the file.
If you see a blank output after the javac command,
it means there were no errors and you are ready to run the program. You
could run the program using the command as shown in the screen shot.

Hello RPBC

R. P. BHALODIA - RAJKOT P a g e | 31
JAVA IDE
 NetBeans

 NetBeans is an integrated development environment (IDE) for


developing primarily with Java, but also with other languages, in
particular PHP, C/C++, and HTML5.
 It is also an application platform framework for Java desktop
applications and others.
 The NetBeans IDE is written in Java and can run on Windows, OS X,
Linux, Solaris and other platforms supporting a compatible JVM.
 NetBeans IDE 7.4 was released in October 15 2013.
 NetBeans IDE is a free, open-source, cross-platform IDE with built-in-
support for Java Programming Language.
Feauter of netbeans.

 Fast & Smart Coding


 Easy & Efficient Project Management.
 Rapid User Interface Development.
 Bug Free Code.
 User interface management (e.g. menus and toolbars)
 User settings management.
 Storage management (saving and loading any kind of data)
 Window management.
 Wizard framework (supports step-by-step dialogs)
 NetBeans Visual Library.
 Integrated development tools.

 Eclipse IDE

The Eclipse is another very powerful editor for so many languages such as
Java, PHP, C, C++ etc.

The Eclipse IDE for Java Developers contains everything that you will
need to build java application.

R. P. BHALODIA - RAJKOT P a g e | 32
It provides greater java editing with validation, incremental compilation,
cross-referencing, code assistance, an XML Editor & so many others
following are some debugging support with hyperlink stepping.

1. Great debugging support with hyperlink stepping.


2. A new Quick Access feature to enhance IDE navigation.
3. Quick Fix/Assist support.
4. Task-focused development.

Eclipse 3.0 (released on 21 June 2004) selected the OSGi Service Platform
specifications as the runtime architecture.

The Association for Computing Machinery recognized Eclipse with the


2011 ACM Software Systems Award on 26 April 2012.

Data Type in Java


Data Type Range Size (Byte)
Byte -128 to 127 1
Short -32768 to 32767 2
Int -2147483648 to 2147483647 4
Long -9223372036854775808 to 8
9223372036854775807
Float 3.4*10-38 to 3.438 4
Double 1.7*10-308 to 1.7*10+308 8
Char Single character 2
Boolean Either true or false 1

 Explain the Structure of java OR

Question : Explain the following line in JAVA

public static void main(String args[])

Answer :

R. P. BHALODIA - RAJKOT P a g e | 33
First of follow we can see bellow example

Example:-
class xyz
{
public static void main (String args [])
{
System.out.println (“hello”);
}
}

In above example we can see xyz is a class name and the description of
public static void main (String args []) as we can see bellow.

public:-
The public keyword is access specified which means that the contain
of the following block accessible from all other classes.

static:-
The keyword static allow main to be called without having instance
of class (duplication copy of object).

void:-
The keyword void tell to the compiler that main () does not return
value.

main ()

main () is method called when Java application begin Java is case


sensitive main is different from MAIN Java compiler will compile classes
that doesn‟t contain a main method but Java has no may to run is classes.

String args []

R. P. BHALODIA - RAJKOT P a g e | 34
Declare a parameter name which is an array of instance of the
class string args receive and command line argument precision when the
program is executed.

System.out.println()
System is predefining classes that provide access to the system.
Out is the output stream that is connecting to the console. Output is
a complies by the build in println method.

 Explain Basic Structure of Java program.


Basic structure of a Java program is as under.
1. Documentation section
2. Package statement
3. Import statement
4. Class definition
5. Main method

1. Documentation section
In this section you can write the documentation for your program
like, program definition, author information, the logic of your
program etc. this is optional section.
It is written in comment lines (//) or (/* …………..*/)

2. Package statement
If you want to save your program in a package(directory) then the
package statement is included. This is also an optional section.

3. Import statement
If you want to import any library or user-defined package, the import
statement is used. Now from this imported package, you can use its
classes & methods. This is also an optional section.

Ex : import java.util.Date;

R. P. BHALODIA - RAJKOT P a g e | 35
4. Class Definition
You can define classes in this section. Use class keyword to declare
a class. There can be member variable & methods in this class. This
is required & its compulsory section.

5. Main method
In your program, you can more than one class, but there should be
one class that contains the main method.
This class is run to generate output because the main method is the
entry point for program execution. This is compulsory section.

Java Tokens
 Comments
There are three types of comment in java.
1. Single line comments : Double slashes are used to indicate single line
comment.
Ex. //This is a single line comment.
2. Multi-line comments :
The text written between /* and */ are considered comments.
Ex : /*
This is documentation comment
Rpbc
*/
 Identifiers
An identifier is a name given to a variable, a method or a class. To declare
an identifier we must follow some rules :

1. Identifier may consist of letters (uppercase or lowercase), digits,


underscore or dollar sign.
2. It must not start with a number.
3. No white space is allowed.
4. No keyword can be used as identifier.
Some valid examples of identifiers :
Var1, sub1, marks1, first_value, $price
R. P. BHALODIA - RAJKOT P a g e | 36
Some invalid examples of identifiers :
In valid, 1marks, first-value

 Literals
In java, any constant value is known as literal. The literal can be any one
of the following.

Integer literal :
Ex : int x=300;
Here x is variable & 300 is value which is integer literal.

Floating-point literal :
Ex. double d=39.86;
Here 39.86 is floating-point literal.

Character literal :
Ex char c=‟A‟;
Here „A‟ is a character literal.

Some other are shown in below.


Escape Meaning
sequence
\n To give new line
\b Backspace
\t To give space as much as a tab
\‟ To print single quote
\” To print double quotes
\\ To print back slash

String literal :
Ex : String str=”java”;
Here “java” is a String literal
To print “I like “java”
System.out.println(“ I like \” java \” “);

Boolean literal :
R. P. BHALODIA - RAJKOT P a g e | 37
Boolean literal can be true or false.
Ex. boolean flag=true;
Here true is boolean literal.

White-spaces
The white space can be a space, a tab or new line. The extra white spaces
are ignored by java compiler. Therefore if you write program in a single
line it makes no difference.

Separators
The separator are used to separate the statements from each other.
For ex. , the semicon (;) is used to terminate a statement. The list of
various separator is shown below :

Separator Name Use


; Semicolon Used to terminate a statement
. Dot or period Used to access variable or method of a
class through object. Also used to separate
package from sub package.
: Colon Used to specify a label.
() Parenthesis Used in method declaration & method call.
Also used in if conditions & loops.
{} Braces Used to enclose statements of methods,
class or any block of code. Also used to
initialize an array
[] Brackets Used to declare array & access array
elements

Keywords :
There are 49 keywords in java are reserved & each one has its unique
meaning. They can not be used as identifier.
They are listed below:

R. P. BHALODIA - RAJKOT P a g e | 38
Abstract Continue goto* package synchronized
assert Default If private this
Boolean Do implements protected throw
Break Double Import public throws
Byte Else instanceof return transient
Case Extends int short try
Catch Final interface static void
Char Finally Long strictfp volatile
Class Float Native super while
const* For New switch enum

Some are default initial value for data types


Data Type Default Initial value
Byte 0
Short 0
Int 0
Long 0L
Float 0.0f
Double 0.0d
Char „\0‟
Boolean False

Operator in Java
Operators
In java language there are same operators which we was used in the C and
C++.
There are
Arithmetic Operators
Arithmetic operators are used in mathematical expression in the same way
that they are used in algebra. The following table lists the arithmetic
operators:

R. P. BHALODIA - RAJKOT P a g e | 39
Operator Result
+ Addition
- Subtraction(also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition Assignment
-= Subtraction Assignment
/= Division Assignment
%= Modulus Assignment
*/ Multiplication Assignment
-- Decrement

The Modulus Operators


The modulus operation, % returns the remainder of a division operation. It
can be applied to floating-point types as well as integer types. The
following example program demonstrates the %:

In Arithmetic Assignment Operators


Java provides special operators that can be used to combine an arithmetic
operation with an assignment. As you probably know, statements like the
following are quite common in programming.
a = a + 4;

In java, you can rewrite this statement as shown here;


a+=4;

This version uses the += compound assignment operator. Both statements


perform the same operation: they increase the value of a by 4. Another
example:
a = a / 4; a /= 4;
a = a % 4; a %= 4;
a = a - 4; a -= 4;

R. P. BHALODIA - RAJKOT P a g e | 40
The compound assignment operator provides two benefits. First, they save
you a bit of typing, because they are “shorthand” for their equivalent long
forms. Second, they are implemented more efficiently by the java run-time
system than are their equivalent long forms. For these reasons, you will
often see the compound assignment operators used in professionally
written java programs.

Increment and Decrement Operators


The ++ and -- are Java‟s increment and decrement operators.
The ++ (Increment Operators) increase its operand by one.
The -- (decrement Operators) decrease its operand by one. For example,
this statement.
x = x + 1; x = x – 1;
can be rewritten like this by use of the
x++; ++x; x--; --x;

These operators are unique in that they can appear in prefix (++x) and
postfix (x++) form. For example:-

The Bitwise Operators


Bitwise and bit shift operators are used on integral types (byte, short, int
and long) to perform bit-level operations.
Java Bitwise and Bit Shift Operators
Operator Description
| Bitwise OR
& Bitwise AND
~ Bitwise Complement
^ Bitwise XOR
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift

R. P. BHALODIA - RAJKOT P a g e | 41
Bitwise OR
Bitwise OR is a binary operator (operates on two operands). It's denoted
by |.
The | operator compares corresponding bits of two operands. If either of
the bits is 1, it gives 1. If not, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)

Bitwise AND
Bitwise AND is a binary operator (operates on two operands). It's denoted
by &.
The & operator compares corresponding bits of two operands. If both bits
are 1, it gives 1. If either of the bits is not 1, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)

Bitwise Complement
Bitwise complement is an unary operator (works on only one operand). It
is denoted by ~.
The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to
0.
35 = 00100011 (In Binary)

R. P. BHALODIA - RAJKOT P a g e | 42
Bitwise complement Operation of 35
~ 00100011
________
11011100 = 220 (In decimal)

Why are we getting output -36 instead of 220?

It's because the compiler is showing 2's complement of that number;


negative notation of the binary number.

Bitwise XOR
Bitwise XOR is a binary operator (operates on two operands). It's denoted
by ^.
The ^ operator compares corresponding bits of two operands. If
corresponding bits are different, it gives 1. If corresponding bits are same,
it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
| 00011001
________
00010101 = 21 (In decimal)

The Left Shift


The left shift operator << shifts a bit pattern to the left by certain number
of specified bits, and zero bits are shifted into the low-order positions.
212 (In binary: 11010100)

212 << 1 evaluates to 424 (In binary: 110101000)


212 << 0 evaluates to 212 (In binary: 11010100)
212 << 4 evaluates to 3392 (In binary: 110101000000)

R. P. BHALODIA - RAJKOT P a g e | 43
The Right Shift
The right shift operator >> shifts a bit pattern to the right by certain
number of specified bits.
212 (In binary: 11010100)

212 >> 1 evaluates to 106 (In binary: 01101010)


212 >> 0 evaluates to 212 (In binary: 11010100)
212 >> 8 evaluates to 0 (In binary: 00000000)

Program
class RightShift {
public static void main(String[] args) {

int number = 212, result;

System.out.println(number >> 1);


System.out.println(number >> 0);
System.out.println(number >> 8);
}
}

The Unsigned Right Shift


The unsigned right shift operator >>> shifts zero into the leftmost position.
Negative input value show the max range of the datatype.

Bitwise Operator Assignments


I just going through code someone has written and I saw |= usage, looking
up on Java operators, it suggests bitwise or and assign operation.
number1 |= number2; same as number1 = number1 | number2. Result is
also same.

R. P. BHALODIA - RAJKOT P a g e | 44
Relational Operators
The relational Operators determine the relationship that one operand has to
another. Specifically, they determine equality and ordering. The relational
operators are shown here.
Operator Result
== Equal to
!= Not Equal to
> Greater than
< Less than
>= Greater than or Equal to
<= Less than or Equal to

The relational operators have always BOOLEAN value either true or


false. These operators are use in control statement line IF condition and
loop. It is same as C and C++.

 Symbolic constant in java


• In C and C++ we where declaring symbolic constant by using #
define symbolic constant are use full for getting a constant value.
Though out the program.
• Here in java we does not have the keyword like #define so
instead of that they have given special keyword called final
,which is use full for defining symbolic constant as we can show
below

• Syntax final_datatype_variable name =value


• Example: final float pi=3.14;

 Type Casting in Java

Java supports two types of castings – primitive data type casting and
reference type casting.

R. P. BHALODIA - RAJKOT P a g e | 45
Reference type casting is nothing but assigning one Java object to another
object.

It comes with very strict rules and is explained clearly in Object Casting.

Java data type casting comes with 2 flavors.

1. Implicit casting
2. Explicit casting

1. Implicit casting (widening conversion)

A data type of lower size (occupying less memory) is assigned to a data


type of higher size.

This is done implicitly by the JVM. The lower size is widened to higher
size. This is also named as automatic type conversion.

Examples:

int x = 10; // occupies 4 bytes


double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.0

In the above code 4 bytes integer value is assigned to 8 bytes double


value.

byte –> short –> int –> long –> float –> double

2. Explicit casting (narrowing conversion)

A data type of higher size (occupying more memory) cannot be assigned


to a data type of lower size.

This is not done implicitly by the JVM and requires explicit casting; a
casting operation to be performed by the programmer.

The higher size is narrowed to lower size.

R. P. BHALODIA - RAJKOT P a g e | 46
double x = 10.5; // 8 bytes

int y = x; // 4 bytes ; raises compilation error

In the above code, 8 bytes double value is narrowed to 4 bytes int value. It
raises error. Let us explicitly type cast it.

double x = 10.5;
int y = (int) x;

The double x is explicitly converted to int y. The thumb rule is, on both
sides, the same data type should exist.

In the above statement, left to right can be assigned implicitly and right to
left requires explicit casting.

That is, byte can be assigned to short implicitly but short to byte requires
explicit casting.

Following char operations are possible.

public class Demo


{
public static void main(String args[]) {
char ch1 = 'A';
double d1 = ch1;
System.out.println(d1); // prints 65.0
System.out.println(ch1 * ch1); // prints 4225 , 65 * 65
double d2 = 66.0;
char ch2 = (char) d2;
System.out.println(ch2); // prints B }
}

 Decision Statements

The decision statements also known as selection statements in java. There


are two decision statements are if and switch.

R. P. BHALODIA - RAJKOT P a g e | 47
if statements:-
If statements in Java are used to control the program flow based on some
condition, it‟s used to execute some statement code block if expression is
evaluated to true, otherwise it will get skipped. This is a simplest way to
modify the control flow of the program.

Syntex:-
if(condition)
{
Statement;
}

Nested ifs:-
A nested if is a statement that is the target of another if or else. Nested if
are very commonly in programming. When you nest ifs, the main thing to
remember is that an else statement always refers to the nearest if statement
that is within the same block as the else not already associated with an
else. Example:-
if(i == 100)
{
if(j < 20) a=b;
if(k > 100) c=d;
else a =c;
}
else
a = d;

The if-else-if Ladder:-


A common programming construct that I based upon a sequence of nested
ifs is the if-else-if ladder. It look like this:

if(condition)
statements;
else if(condition)
statements;

R. P. BHALODIA - RAJKOT P a g e | 48
else if(condition)
statements;
.
.
.
else
statement;

Switch..case
A switch statement allows a variable to be tested for equality against a list
of values. Each value is called a case, and the variable being switched on
is checked for each case.
Syntax
switch(expression) {
case value :
// Statements
break; // optional

case value :
// Statements
break; // optional

// You can have any number of case statements.


default : // Optional
// Statements
}

The following rules apply to a switch statement −


 The variable used in a switch statement can only be integers,
convertable integers (byte, short, char), strings.
 You can have any number of case statements within a switch. Each
case is followed by the value to be compared to and a colon.
 The value for a case must be the same data type as the variable in the
switch and it must be a constant or a literal.

R. P. BHALODIA - RAJKOT P a g e | 49
 When the variable being switched on is equal to a case, the
statements following that case will execute until a break statement is
reached.
 When a break statement is reached, the switch terminates, and the
flow of control jumps to the next line following the switch
statement.
 Not every case needs to contain a break. If no break appears, the
flow of control will fall through to subsequent cases until a break is
reached.
 A switch statement can have an optional default case, which must
appear at the end of the switch. The default case can be used for
performing a task when none of the cases is true. No break is needed
in the default case.

 Looping Statement

There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The
first statement in a function is executed first, followed by the second, and
so on.
Programming languages provide various control structures that allow for
more complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times and following is the general form of a loop statement in
most of the programming languages
Java programming language provides the following types of loop to handle
looping requirements. Click the following links to check their detail.
Sr.No. Loop & Description

while loop
1 Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body.

R. P. BHALODIA - RAJKOT P a g e | 50
for loop
2 Execute a sequence of statements multiple times and abbreviates the
code that manages the loop variable.

do...while loop
3 Like a while statement, except that it tests the condition at the end of
the loop body.

While loop:-
A while loop statement in Java programming language repeatedly executes
a target statement as long as a given condition is true.
Syntax
The syntax of a while loop is −

while(Boolean_expression) {
// Statements
}
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non zero value.

When executing, if the boolean_expression result is true, then the actions


inside the loop will be executed. This will continue as long as the
expression result is true.
When the condition becomes false, program control passes to the line
immediately following the loop.

for loop;-
A for loop is a repetition control structure that allows you to efficiently
write a loop that needs to be executed a specific number of times.
A for loop is useful when you know how many times a task is to be
repeated.
Syntax
The syntax of a for loop is −
for(initialization; Boolean_expression; update) {

R. P. BHALODIA - RAJKOT P a g e | 51
// Statements
}
Here is the flow of control in a for loop −
 The initialization step is executed first, and only once. This step
allows you to declare and initialize any loop control variables and
this step ends with a semi colon (;).
 Next, the Boolean expression is evaluated. If it is true, the body of
the loop is executed. If it is false, the body of the loop will not be
executed and control jumps to the next statement past the for loop.
 After the body of the for loop gets executed, the control jumps back
up to the update statement. This statement allows you to update any
loop control variables. This statement can be left blank with a
semicolon at the end.
 The Boolean expression is now evaluated again. If it is true, the loop
executes and the process repeats (body of loop, then update step,
then Boolean expression). After the Boolean expression is false, the
for loop terminates.

For-each loop (Advanced or Enhanced For loop):


As of Java 5, the enhanced for loop was introduced. This is mainly used to
traverse collection of elements including arrays. The advantage of for-each
loop is that it eliminates the possibility of bugs and makes the code more
readable.
Syntax
Following is the syntax of enhanced for loop −
for(declaration : expression) {
// Statements
}
 Declaration − The newly declared block variable, is of a type
compatible with the elements of the array you are accessing. The
variable will be available within the for block and its value would be
the same as the current array element.

R. P. BHALODIA - RAJKOT P a g e | 52
 Expression − This evaluates to the array you need to loop through.
The expression can be an array variable or method call that returns
an array.

class For1
{
public static void main(String a[])
{
int numbers[]={10,20,30,40,50};
for(int x : numbers)
{
if(x==30)
break;
System.out.println(x);

}
}
}

do…while Loop;-
A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
Syntax
Following is the syntax of a do...while loop −
do {
// Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the
statements in the loop execute once before the Boolean is tested.

If the Boolean expression is true, the control jumps back up to do


statement, and the statements in the loop execute again. This process
repeats until the Boolean expression is false.

 Jumping Statement

R. P. BHALODIA - RAJKOT P a g e | 53
Break:-
The break statement in Java programming language has the following two
usages −
 When the break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
 It can be used to terminate a case in the switch statement (covered in
the next chapter).
Syntax
The syntax of a break is a single statement inside any loop −
break;
continue:-
The continue keyword can be used in any of the loop control structures. It
causes the loop to immediately jump to the next iteration of the loop.
 In a for loop, the continue keyword causes control to immediately
jump to the update statement.
 In a while loop or do/while loop, control immediately jumps to the
Boolean expression.
Syntax
The syntax of a continue is a single statement inside any loop −
continue;

Array

An array stores a group of data items all of the same type.

Declare an array variable by specifying the type of data to be stored,


followed by square brackets [].

dataType[] variableName;

Instantiating Arrays

Instantiate an array object using new, the data type, and an array size in
square brackets
R. P. BHALODIA - RAJKOT P a g e | 54
int[] nums;
nums = new int[10];

The second line constructs a new array object with 10 integer elements, all
initialized to 0, and stores the reference into nums.

int[] moreNums;
int size = 7;
moreNums = new int[size];

You can declare and instantiate all at once:

String[] names = new String[3];

The elements of the array, String references, are initialized to null.

As objects, arrays also have a useful property: length:

 In the above example, names.length would be 3.


 The property is fixed (i.e., it is read-only).

You can reassign a new array to an existing variable:

int[] nums;
nums = new int[10];
nums = new int[20];

R. P. BHALODIA - RAJKOT P a g e | 55
The original ten-element array is no longer referenced by nums, since it
now points to the new, larger array.

Initializing Arrays

An array can be initialized when it is created

The notation looks like this:

String[] names = { "hello", "rpbc", "student" };

or

String[] names = new String[]{ "hello", "rpbc", "student" };

This automatically creates an array of length 3, because there were 3 items


supplied.

int[] nums = new int[] { 2, 4, 6, 8, 10, 12 };

This array will have a length of 6.

If a new array is being assigned to an existing variable,

Two Dimensional Array [Rectangular Array]

Java doenot truely support multidimensional arrays.

In java ,a two dimensional array is simply an array of arrays,

We can see in bellow example

int x = 5;
int y = 5;

String[][] arr1 = new String [x][y];

R. P. BHALODIA - RAJKOT P a g e | 56
arr1[0][x] = "hello";
arr1[0][y] = "rpbc";

Jagged Array

A jagged array is an array whose elements are arrays. The elements of a


jagged array can be of different dimensions and sizes. A jagged array is
sometimes called an array-of-arrays.

As we can shown in below example.

class test
{
public static void main( String args[] )
{
int [][]arr = new int[5][];
arr[0] = new int[5];
arr[1]= new int[6];
System.out.println(arr[0].length + " " + arr[1].length );
}

Command –line arguments

You can pass argument to the main() method. This can be done at runtime.

As we know that the main() method takes array of string as argument, the
arguments given to the main() method will be assigned to this array.

Thus giving commands-line argument is quite easy in java.

Following program shows how to give & receive command-line arguments


in a program.

R. P. BHALODIA - RAJKOT P a g e | 57
class test1
{
public static void main(String args[]) {
for(int i=0;i<arrg.length;i++)
{
System.out.println(“argument are :”+i+ “
:”+args[i]);
}
}

How to run program

 javac test1.java
 java test1 hi hello bye

output
Argument 0: hi
Argument 1: hello
Argument 2: bye

Command Line Argument Array


 Sometimes you will want to pass information into a program when
you run it.
 This is accomplished by passing COMMAND-LINE ARGUMENTS
TO MAIN().
 A commang0line argument is the information that directly follows
the program‟s name on the command line when it is executed.
 To access the command-line argument inside a java program is quite
easy they are stored as strings in a String array passed to the args
parameter of main().
 The first command-line argument is stored at args[0], the second at
args[1], and so on.

R. P. BHALODIA - RAJKOT P a g e | 58
 Class
To define a class class keyword is used. Following is the general form
of a class definition.

class className
{
dataType var1;
dataType var2;
…………….
dataType varn;
className(type param1, type param2,..) //Constructor
{ //statements..
}
returnType method1(type param1,type param2,..)
{
//statements..
}
returnType methodN(type param1,type param2,..)
{
//statements…..
}
 Here, className can be any valid identifier. Var1,var2,varN are
instance variables class className.
 Instance variables are also known as member variables or data.
 Method1, methodN are methods that return value of type returnType.
 The formal parameters are specified with the data type in parenthesis.
These methods are also known as member functions.
 The constructor is a method that has same name as class name.
 Note that in general form we have not specified the main method
because the main method is not compulsory for all classes.

R. P. BHALODIA - RAJKOT P a g e | 59
 Only one class of your program can contain main method which is the
starting point of program execution.
Example
class bank
{
double p,r,n;
}
class prg1 {
public static void main(String args[]) {
bank b1=new bank();
b1.p=5000;
b1.r=12;
b1.n=5;
double si=b1.p*b1.r*b1.n/100;
System.out.println(“simple Interest of b1 :”+si);
}
}

 Creating objects
Here, the class bank has three instance variable. So after creating it
object can access these variables.

The object of class is declared by the statement:

bank b2=new bank();

this is a combination of two statements


bank b1; //declare object b1 of bank
b1=new bank(); //allocate memory to b1

R. P. BHALODIA - RAJKOT P a g e | 60
 new keyword
 Here, the new keyword is used to allocate memory equal to the size of
instance variables of class bank. Before using new keyword the object
can not be used.
 So you can say that the object gets physical existence after the memory
allocation by new keyword.
 The new keyword allocates memory dynamically-at run-time to object.
So you can create as many objects as you want.
 You can assign a reference to object:
bank b1=new bank();

to access the member variables of clas, dot(.) operator is used.


b1.p=5000;
b1.n=5;
 adding method to class
the main strength of a class is in its methods. The general form of a
method is:

returnType methodName(parameter-list) {
//statement
//optional return statement
}
Here, returnType is the type of value or express the method will return. If
the method doesn‟t return a value, the returnType should be void.
Parameter list is the list of parameter that the method takes separated by
commas.

We can see example adds a method to bank class.

class bank
{ double p,r,n;
void simpleinterest()

R. P. BHALODIA - RAJKOT P a g e | 61
{ double si;
si=p*r*n/100;
System.out.println(“simple Interest of b1 :”+si);
}
}

class prg1 {
public static void main(String args[]) {
bank b1=new bank();
b1.p=5000;
b1.r=12;
b1.n=5;
b1. simpleinterest(); //calling method on object b1
}
}
Encapsulation:-

 For any computer program, two core elements are data and function.
 Structured/Procedural programming views these two core elements
as two separate entities; whereas object-oriented programming views
them as single entity.
 In procedural programming, data can be altered by any component
of the program. It is not protected from modification.
 In object-oriented programming, this problem can be solved
using encapsulation.
 Here, data and the methods that manipulate data are guarded against
modification of program is called ENCAPSULATION.
 This is possible by wrapping data and methods into a single unit
known as class and declaring them as private.
 Private members of the class are not available directly to outside
world. If necessary, the data is made available via public methods.

 If necessary, the data is made available via public methods.


 Thus, encapsulation provides data hiding capability.

R. P. BHALODIA - RAJKOT P a g e | 62
 Encapsulation keeps the data safe from unintended (accidental)
actions and unintended access by outside objects.
 Unlike procedural programming where common data are as are often
used for sharing information, object-oriented programming
discourages direct access to common data by other programs.

Abstraction
 Hiding internal details and showing functionality is known as
abstraction. For example: phone call, we don't know the internal
processing.
 In java, we use abstract class and interface to achieve abstraction.

Inheritance:-
 Inheritance can be defined as the process where one class acquires
the properties (methods and fields) of another. With the use of
inheritance the information is made manageable in a hierarchical
order.
 The class which inherits the properties of other is known as subclass
(derived class, child class) and the class whose properties are
inherited is known as super class (base class, parent class).
 Extends is the keyword used to inherit the properties of a class.
Following is the syntax of extends keyword.
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

 Constructors
 The constructor is a special method which has the same name as its
class. It initializes the object of its class automatically at the time of
creation.
 One important point about constructor is that they have no return
type. Not even void.

R. P. BHALODIA - RAJKOT P a g e | 63
 This is because they actually return the object of its class. When we
create an object, we call the constructor after new keyword. So the
statements written in the constructor are executed at that time.
 There are three types of Constructors

1) Default Constructor
2) Parameterize Constructor
3) Copy Constructor

We can see in example.

class bank {
double p,r,n;
bank()
{
System.out.println(“executing constructor..”);
p=10000;
r=12;
n=5;
}
double simpleinterest()
{
return (p*r*n/100);
}
}
class prg1
{
public static void main(String args[])
{
bank b1=new bank(); //calling constructor
double si=b1.simpleinterest(); //calling method on object
System.out.println(“simple interest is”+si);
}
}

Copy Constructor
There is no copy constructor in java. But, we can copy the values of one
object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java.
They are:
R. P. BHALODIA - RAJKOT P a g e | 64
o By constructor
o By assigning the values of one object into another
class student
{
int d;
String name;
student(int i,String n)
{
id=i;
name=n;
}
student(student s)
{
id=s.id;
name=s.name;
}
void display()
{
System.out.println(id+ " "+name);
}
public static void main(String arg[])
{
student s1 = new student(30,"RPBC");
student s2 = new student(s1);
s1.display();
s2.display();
}
}

 Explain this keyword


 „this‟ keyword refers to the object of the current class. So when you
want to access to the instance member of the current class in a
method of current class, „this‟ keyword is used.
 Somethime you have same name of instance variables & other local
variable. In this case, „this‟ keyword is used to distinguish them.
 We can see in example.

R. P. BHALODIA - RAJKOT P a g e | 65
class Point
{
int x,y;
void init(int x,int y)
{
this.x=x;
this.y=y;

}
void display()
{
System.out.println("X="+x);
System.out.println("Y="+y);
}

}
class This_Keyword
{
public static void main(String arg[])
{
Point p = new Point()
p.init(4,3);
p.display();

}
}

Method overloading
 As we know that polymorphism is an important feature of oop.
 Method overloading is a way by which java achieves
polymorphism.
 In a class you can define more than one method.
 When in a class there is more than one method with same name but
different number & types of parameters, the method is said to be
overloaded & this process is known as method overloading.
 We can see in below example.
class area
{
void area()

R. P. BHALODIA - RAJKOT P a g e | 66
{
System.out.println(“area is zero”);
}

void area(double r)
{
double a=3.14*r*r;
System.out.println(“area of circle is”+a);
}

void area(double l,double w)


{
double a= l *w;
System.out.println(“area of rectangle is:”+a);
}
}
class prg1
{
public static void main(String args[])
{
area a=new area();
a.area(); //area() with no parameters
a.area(10.0); //area() with one parameter
a.area(15,10); //area() with two parameter
} }
 Constructor overloading
We can also overload constructor in java. When we create more than one
constructor with different parameters, it is called constructor overloading.
Sometimes it is needed to create objects with less or no parameter.
We can see in example.
class bank {
double p,r,n;
bank()
{
p=0; r=0;n=0;
}
bank(double p)
{
this.p=p;
this.r=12;

R. P. BHALODIA - RAJKOT P a g e | 67
this.n=1;
}
double simpleinterest()
{
return (p*r*n/100);
}

class prg1
{
public static void main(String args[])
{
bank b1=new bank();
bank b2=new bank(10000);
double si=b1.simpleinterest();

System.out.println(simple interest is b1 :”+si);


System.out.println(simple interest is b2:”+b2. simpleinterest(););
}
}

finalize() Method
 In C++ we have a special function called destructor to free the
memory utilized by the variable and methods.
 We also know that java does not support destructor.
 So that java has given a special method called finalize() which will
work same as the destructor.
 This method comes from java.lang.Object.finalize().
 This method called garbage collector clearing the memory.
 In java, garbage means unreferenced objects.
 Garbage Collection is process of reclaiming the runtime unused
memory automatically. In other words, it is a way to destroy the
unused objects.
 To do so, we were using free() function in C language and delete() in
C++. But, in java it is performed automatically. So, java provides
better memory management.

R. P. BHALODIA - RAJKOT P a g e | 68
 The finalize() method is invoked each time before the object is
garbage collected. This method can be used to perform cleanup
processing. This method is defined in Object class as:
protected void finalize(){}
 Note: The Garbage collector of JVM collects only those objects that
are created by new keyword. So if you have created any object
without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).
 gc() method The gc() method is used to invoke the garbage collector
to perform cleanup processing. The gc() is found in System and
Runtime classes.
 Note: Garbage collection is performed by a daemon thread called
Garbage Collector (GC). This thread calls the finalize() method
before object is garbage collected.

Advantage of Garbage Collection


 It makes java memory efficient because garbage collector removes
the unreferenced objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM) so
we don't need to make extra efforts.

class TestGarbage1{
public void finalize()
{
System.out.println("object is garbage collected");
}
void display()
{
System.out.println();
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
s1.display();
}
}

R. P. BHALODIA - RAJKOT P a g e | 69
Static and non-static Member

static member:-
 Static member is also known as class variable or class method.
 What is the reason static member known as class variable &
method??
 Answer is that, static member shared common value of the all object.
 Static member invokes in memory only one time when class is
created.
 Static member of class are stored in class.
 How to declare static member :-
 static int a;
 static void display()
 static member accessing by name of the class. Her do not use the
object of the class for the static member.

non-static member:-
 non static member classified by in two category.
 Instance variable and local variable.
 Instance variable:-
o These types of variable are always define in class but outside
the any method.
o These variables access by the object of the class.
o These variables are allocated memory from heap where
object is created.
 Local variable:-
o Local variable are always define in method or block of any
class.
o Local variable are not initialized by the default value.
o They are created when the method or bock is started &
destroyed when the method or block has completed.

class Counter
{
int count=0;
static int b=0;
Counter()
{
b++;
count++;

R. P. BHALODIA - RAJKOT P a g e | 70
System.out.println("B="+b);
System.out.println("Count="+count);
}

public static void main(String a[])


{
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
}
}

Difference B/W non-static and static variable :-

Non – Static Variable Static Variable


Memory is allocated for these Memory is allocated for these
variable whenever an object is variable only once in the program.
created.
Memory is allocated multiple time Memory is allocated for these
whenever a new object is created variable at the time of loading of the
class.
Non-static variable also known as Memory is allocated at the time of
instance variable because memory loading of class so that these are also
is allocated whenever instance is known as class variable.
created.
Non-static variable are specific to Static variable are common for every
an object. object that means there memory
location can be sharable by every
object reference or same class.
Non-static variable can access Static variable can access with class
with object reference. reference.
Syntax Syntax
Obj.variablename Class_name.variablename

varargs
 In JDK 5, Java has included a feature that simplifies the creation of
methods that need to take a variable number of arguments. This
R. P. BHALODIA - RAJKOT P a g e | 71
feature is called varargs and it is short-form for variable-length
arguments.
 A method that takes a variable number of arguments is a varargs
method.
Prior to JDK 5, variable-length arguments could be handled two
ways.
 One using overloaded method(one for each) and another put the
arguments into an array, and then pass this array to the method. Both
of them are potentially error-prone and require more code.
 The varargs feature offers a simpler, better option.
 Syntax of varargs:-
A variable-length argument is specified by three periods(…). For
Example,

public static void fun(int ... a)


{
// method body
}
 This syntax tells the compiler that fun( ) can be called with zero or
more arguments. As a result, here a is implicitly declared as an array
of type int[]. Below is a code snippet for illustrating the above
concept :
class VarArgs
{
// A method that takes variable number of intger args.
static void fun(int ...a)
{
System.out.println("Number of arguments: " + a.length);

// usin g for each loop to display contents of a


for (int i: a)
System.out.print(i + " ");
System.out.println();
}

// Driver code
public static void main(String args[])
{
// Calling the varargs method with diff no. of parameters
fun(100); // one parameter

R. P. BHALODIA - RAJKOT P a g e | 72
fun(1, 2, 3, 4); // four parameters
fun(); // no parameter
}
}
 IIB (Instance Initializer block)

Instance Initializer block is used to initialize the instance data member. It


run each time when object of the class is created.
The initialization of the instance variable can be done directly but there
can be performed extra operations while initializing the instance variable
in the instance initializer block.

Rules for instance initializer block :

There are mainly three rules for the instance initializer block. They are as
follows:
1) The instance initializer block is created when instance of the class is
created.
2) The instance initializer block is invoked after the parent class
constructor is invoked (i.e. after super() constructor call).
3) The instance initializer block comes in the order in which they appear.

R. P. BHALODIA - RAJKOT P a g e | 73
UNIT – 2 INHERITANCE, JAVA PACKAGES

R. P. BHALODIA - RAJKOT P a g e | 74
Universal Class (Object Class)
 The Object Class is known as universal super class of Java.
 This is so because Every class you create in Java automatically inherits the
 The Object class is super class of all the classes in Java either directly or
 You can find the definition of the Object class in java.lang package
And there are a few useful methods in this class which you can override in
Method Description
returns the Class class object of this object.
public final Class getClass() The Class class can further be used to get
the metadata of this class.
returns the hashcode number for this
public int hashCode()
object.
public boolean equals(Object compares the given object to this object.
obj)
protected Object clone() throws creates and returns the exact copy (clone)
CloneNotSupportedException of this object.
returns the string representation of this
public String toString()
object.
wakes up single thread, waiting on this
public final void notify()
object's monitor.
wakes up all the threads, waiting on this
public final void notifyAll()
object's monitor.
causes the current thread to wait for the
public final void wait(long
specified milliseconds, until another thread
timeout)throws
notifies (invokes notify() or notifyAll()
InterruptedException
method).
causes the current thread to wait for the
public final void wait(long
specified milliseconds and nanoseconds,
timeout,int nanos)throws
until another thread notifies (invokes
InterruptedException
notify() or notifyAll() method).
causes the current thread to wait, until
public final void wait()throws
another thread notifies (invokes notify() or
InterruptedException
notifyAll() method).
is invoked by the garbage collector before
protected void finalize()throws
object is being garbage collected.
Throwable

R. P. BHALODIA - RAJKOT P a g e | 75
class ObjectClass
{
public static void main(String[] args)
{
Object oc = new Object();
System.out.println("The Hash Code:-"+oc.hashCode());
System.out.println("To String"+oc.toString());
System.out.println("The GetClass Method"+oc.getClass());
Class cls1 = oc.wait(1000);
System.out.println(cls1);

Object oc1 = new Object();


System.out.println(oc.equals(oc1));
System.out.println(oc1.hashCode());
System.out.println(oc1.toString());
/*ObjectClass oc2 = new ObjectClass();
System.out.println(oc.equals(oc2));
System.out.println(oc2.hashCode());
System.out.println(oc2.toString());*/

Integer obj = new Integer(10);


Class cls = obj.getClass();
System.out.println("The Obj Direct Use getClass() :-
"+obj.getClass());
System.out.println("The CLS Object is :-"+cls);
System.out.println(obj.toString());
System.out.println(obj.hashCode());
}
}

Access Specifies (Public, Private, Protected, Default)

Access specifies are the important concept in Object-oriented language.


These specify are control the visibility of variable and method. So that,
here some protection of variable and method.
Java provides a number of access modifiers to set access levels for classes,
variables, methods, and constructors. The four access levels are −
 Visible to the package, the default. No modifiers are needed.

R. P. BHALODIA - RAJKOT P a g e | 76
 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).

Default Access Modifier – No Keyword Needed:-


 These modifiers cannot need any keyword to use in variable, method
and constructors.
 A variable and method use this access modifier is available to any
class in the same package.
 The fields in an interface are implicitly public static final and the
methods in an interface are by default public.
class Default
{
int a, b;
void display()
{
System.out.println("The Value of A:-" +a);
System.out.println("The Value of B:-" +b);
}
}

class DefaultMain
{
public static void main(String[] args)
{
Default df = new Default();

df.a = 10;
df.b = 20;
df.display();
}
}
Private Access Modifiers – Private
 If we want to access the variable method and constructors with in the
class it is declared as private.
 Private modifier is the most restrictive access level.
 Class and interface cannot be declared as private.
 Private variable and method use outside the class by use of public
getter method.
 It is use for the data hides from the outside world.

R. P. BHALODIA - RAJKOT P a g e | 77
class PrivateKey
{
private int a, b;

PrivateKey(int x, int y)
{
a = x;
b = y;
}
PrivateKey(){}

double area()
{
return a * b;
}
void display()
{
System.out.println("The Value of A:-" +a);
System.out.println("The Value of B:-" +b);
}
}
class PrivateMain
{
public static void main(String[] args)
{
PrivateKey pk = new PrivateKey();
PrivateKey pk2 = new PrivateKey(10,15);
pk.display();
pk2.display();
System.out.println("The Value of A outside the
class is :-" +pk2.a);
System.out.println("The Value of B outside the
class is :-" +pk2.b);
}
}
Public Access Modifier – Public
 This access modifier is the universal access modifier in java.
 Its use any class and same package in java. But we want to access in
different package need to be imported.
 The security level is very low when declare as public.

R. P. BHALODIA - RAJKOT P a g e | 78
class PublicKey
{
public int a, b;

PublicKey(int x, int y)
{
a = x;
b = y;
}
PublicKey(){}

double area()
{
return a * b;
}
void display()
{
System.out.println("The Value of A:-" +a);
System.out.println("The Value of B:-" +b);
}
}
class PublicMain
{
public static void main(String[] args)
{
PublicKey publick = new PublicKey();
PublicKey publick2 = new PublicKey(10,15);
publick.display();
publick2.display();
System.out.println("The Value of A outside the
class is :-" +publick2.a);
System.out.println("The Value of B outside the
class is :-" +publick2.b);
}
}

Protected Access Modifier - Protected


 Variables, methods, and constructors, which are declared protected
in a superclass can be accessed only by the subclasses in other

R. P. BHALODIA - RAJKOT P a g e | 79
package or any class within the package of the protected members'
class.
 The protected access modifier cannot be applied to class and
interfaces. Methods, fields can be declared protected, however
methods and fields in a interface cannot be declared protected.
 Protected access gives the subclass a chance to use the helper
method or variable, while preventing a nonrelated class from trying
to use it.

Doing Inheritance
 Inheritance supports the concept of hierarchical classification. With
the use of inheritance, one can create a general class that defines a
set of related item which means that each are class is adding those
things that are unique to it.
 A class that is inherited is called a SUPERCLASS. The class that
does the inheriting is called a SUBCLASS. A subclass inherits all
instance variables and methods from its superclass and also has its
own variable and methods. One can inherit the class using the
EXTEND keyword.
 Inheritance represents the IS-A relationship, also known as parent-
child relationship.
Why use inheritance in java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
Syntax:-
Class subclass-name extends superclass-name
{
Body of class.

R. P. BHALODIA - RAJKOT P a g e | 80
}
 The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to
increase the functionality.
 In the terminology of Java, a class which is inherited is called parent
or super class and the new class is called child or subclass.

Types of inheritance in java


 On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical.

Example of Single level Inheritance:-


//Simple Example of Inheritance
//Create a superclass
class A
{
int x,y;
void showxy()
{
System.out.println("x:->"+x);
System.out.println("y:->"+y);
}
}
class B extends A
{
int z;
void showz()

R. P. BHALODIA - RAJKOT P a g e | 81
{
System.out.println("c:->"+z);
}
void sum()
{
System.out.print("sum:->"+(x+y+z));
}
}
class single
{
public static void main(String args[])
{
A a=new A();
B b=new B();
a.x=10;
a.y=20;
a.showxy();

b.x=5;
b.y=6;
b.z=7;
b.showxy();
b.showz();
b.sum();
}
}

2) Multilevel Inheritance:
When a class extends a class, which extends another class then this
is called Multilevel Inheritance.
For example Class C extends class B and class B extends class A
then this type of Inheritance is Known as Multilevel Inheritance.

Class Car
{
Public Car()
{
System.out.println(“Class Car”);

R. P. BHALODIA - RAJKOT P a g e | 82
}
Public void vehicleType()
{
System.out.println(“Class Car”);
}
}
Class Maruti extends Car
{
Public Maruti()
{
System.out.println(“Class Maruti”);
}
Public void brand()
{
System.out.println(“Brand: Maruti”);
}
Public void speed()
{
System.out.println(“Max: 90Kmph”);
}
}
Public class Maruti800 extends Maruti
{
Public Maruti800()
{
System.out.println(“Maruti Model: 800”);
}
Public void speed()
{
System.out.println(“Max:80Kmph”);
}
Public static void main(String arg[])
{
Maruti800 Obj = new Maruti800();
Obj.vehicleType();
Obj.brand();
Obj.speed();
}
}
Output:-

R. P. BHALODIA - RAJKOT P a g e | 83
3) Hierarchical Inheritance:-
When More than one classes inherit a same class then this is called
hierarchical inheritance.
Class A
{
Public void methodA()
{
System.out.println(“Method of class A..”);
}
}
Class B extends A
{
Public void methodB()
{
System.out.println(“Method of class B”);
}
}
Class C extends A
{
Public void methodC()
{
System.out.println(“Method of class C”);
}
}

Class Demo
{
Public static void main(String arg[])
{
B Obj1 = new B();
C Obj2 = new C();
Obj1.methodA();
Obj2.methodB();

}
}

R. P. BHALODIA - RAJKOT P a g e | 84
 Super Keyword:-

 The super keyword in java is a reference variable which is used


to refer immediate parent class object.
 Whenever you create the instance of subclass, an instance of parent
class is created implicitly which is referred by super reference
variable.

Usage of java super Keyword


 super can be used to refer immediate parent class instance variable.
 super can be used to invoke immediate parent class method.
 super() can be used to invoke immediate parent class constructor.

“super” can be used for two purposes:-


1) Access the hidden data variables of the super class:-

class A
{
int a;
float b;
void show()
{
System.out.println("A in Super class");
}
}
class B extends A
{
int a;
float b;
B(int p,float z)
{
a=p;
super.b=z;
}
void show()
{
super.show();
System.out.println("B in super class:"+super.b);
System.out.println("A in Sub class:"+a);

R. P. BHALODIA - RAJKOT P a g e | 85
}
public static void main(String arg[])
{
B obj = new B(10,15);
obj.show();
}
}

Output:-

2) Use of super to call super class Constructor or Method


OR (Constructor inheritance)

class A
{
int a,b,c;
A(int p,int q,int r)
{
a=p;
b=q;
c=r;
}
}
class B extends A
{
int d;
B(int m,int n,int s,int t)
{
super(m,n,s);
d=t;
}
void show()
{
System.out.println("A=="+a);
System.out.println("B=="+b);
System.out.println("C=="+c);
System.out.println("D=="+d);
}
public static void main(String arg[])
{

R. P. BHALODIA - RAJKOT P a g e | 86
B b = new B(10,20,30,40);
b.show();
}
}

Method Overriding
 We know that method defined in a base class will be inherited by the
derived class and cam be used by the objects created by the derived
class.
 But there may be the occasion when we have the method in a base
class and the same name method in derived class.
 Now the object of the derived class will always call the method
defined in the derived class. This is known as overriding of the
method.
 Remember that here the method of the base class will never be
called and the object will always call from the derived class.

class abc
{
int x;
abc(int x)
{
this.x = x;
}
void display()
{
System.out.println("Out Put from Base Class x:-" +x);
}
}

class xyz extends abc


{
int y;
xyz(int x, int y)
{
super(x);//call the base class constructor
this.y = y;
}
void display()
{

R. P. BHALODIA - RAJKOT P a g e | 87
System.out.println("Output from Deriveed Class x:-" + x +
" The Value of Y:- " +y);
}
}

class override_test
{
public static void main(String[] args)
{
xyz p1 = new xyz(100,200);
p1.display();
}
}

Difference between Method Overloading VS Method Overriding


Method Overloading Method Overriding
Method overriding is used to
Method overloading is used to provide the specific
increase the readability of the implementation of the method that
program. is already provided by its super
class.
Method overriding occurs in two
Method overloading is
classes that have IS-A (inheritance)
performed within class.
relationship.
In case of method In case of method
overloading, parameter must be overriding, parameter must be
different. same.
Method overloading is the example Method overriding is the example
of compile time polymorphism. of run time polymorphism.
In java, method overloading can't be
performed by changing return type of
the method only. Return type can be Return type must be same or
same or different in method covariant in method overriding.
overloading. But you must have to
change the parameter.

R. P. BHALODIA - RAJKOT P a g e | 88
Dynamic Method Dispatch :-
If a superclass contains a method that is overridden by a subclass
,then when different types of objects are referred through a superclass
reference variable, different versions of the method are executed. It is
called Dynamic Method Dispatch.

class A
{
void callme()
{
System.out.println("Inside A's Call Me Method");
}
}
class B extends A
{
void callme()
{
System.out.println("Inside B's Call Me Method");
}
}
class C extends A
{
void callme()
{
System.out.println("Inside C's Call Me Method");
}
}

class Dispatch
{
public static void main(String args[])
{
A a1 =new A();
B b1 = new B();
C c1 = new C();
A r; //obtain reference of type A
r = a1; //r regers to an A object
r.callme();

r = b1; //r regers to an A object

R. P. BHALODIA - RAJKOT P a g e | 89
r.callme();

r = c1; //r regers to an A object


r.callme();
}
}

Abstract and Final Keyword


Final keyword:-
The final keyword in java is used to restrict the user. The java final
keyword can be used in many contexts. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that
have no value it is called blank final variable or uninitialized final variable.
It can be initialized in the constructor only. The blank final variable can be
static also which will be initialized in the static block only. We will have
detailed learning of these. Let's first learn the basics of final keyword.
1) Java final variable
 If you make any variable as final, you cannot change the value of
final variable (It will be constant).
 Example of final variable
 There is a final variable speedlimit, we are going to change the value
of this variable, but It can't be changed because final variable once
assigned a value can never be changed.

class FinalVariable
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
FinalVariable obj=new FinalVariable();

R. P. BHALODIA - RAJKOT P a g e | 90
obj.run();
}
}
2) Java final method
If you make any method as final, you cannot override it.
class FinalMethod
{
final void run()
{
System.out.println("running");
}
}
class FinalMethodMain extends FinalMethod
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
FinalMethodMain fmm= new FinalMethodMain();
fmm.run();
}
}

3) Java final class


If you make any class as final, you cannot extend it.
final class FinalClass
{
}
class FinalClassMain extends FinalClass
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
FinalClassMain fcm= new FinalClassMain();
fcm.run();

R. P. BHALODIA - RAJKOT P a g e | 91
}
}

4) Is final method inherited?


Yes, final method is inherited but you cannot override it.
class FinalMethodInherit
{
final void run()
{
System.out.println("running...");
}
}
class FinalMethodInheritance extends FinalMethodInherit
{
public static void main(String args[])
{
new FinalMethodInheritance().run();
}
}
5) What is blank or uninitialized final variable?
 A final variable that is not initialized at the time of declaration is
known as blank final variable.
 If you want to create a variable that is initialized at the time of
creating object and once initialized may not be changed, it is useful.
For example PAN CARD number of an employee.
 It can be initialized only in constructor.
class FinalBlankVarialbeConstructor
{
final int speedlimit;//blank final variable

FinalBlankVarialbeConstructor
{
speedlimit=70;
System.out.println(speedlimit);
}

public static void main(String args[])


{
FinalBlankVarialbeConstructor fbvc = new
FinalBlankVarialbeConstructor();

R. P. BHALODIA - RAJKOT P a g e | 92
}
}
6) static blank final variable
 A static final variable that is not initialized at the time of declaration
is known as static blank final variable. It can be initialized only in
static block.

7) What is final parameter?


 If you declare any parameter as final, you cannot change the value of
it.

8) Can we declare a constructor final?


 No, because constructor is never inherited.

Abstract Class:-

A class which contains the abstract keyword in its declaration is known as


abstract class.
 Abstract classes may or may not contain abstract methods, i.e.,
methods without body ( public void get(); )
 But, if a class has at least one abstract method, then the class must
be declared abstract.
 If a class is declared abstract, it cannot be instantiated.
 To use an abstract class, you have to inherit it from another class,
provide implementations to the abstract methods in it.
 If you inherit an abstract class, you have to provide implementations
to all the abstract methods in it.

With Simple Example


abstract class Salary
{
int basic ,da;
Salary(int b,int d)
{
basic=b;
da=basic*d/100;
}
//Abstract Method does not have body

R. P. BHALODIA - RAJKOT P a g e | 93
abstract void computeSalary();
}
class GrossSalary extends Salary
{
int hra;
GrossSalary(int b,int d,int h)
{
super(b,d);
hra=basic*h/100;
}
void computeSalary()
{
System.out.println("Gross Salary From
subclass:="+(basic+da+hra));

}
}

class Basic
{
public static void main(String args[])
{
//Salary e=new Salary(5000,10);
GrossSalary e1=new GrossSalary(5000,10,20);
//Salary e;
e = e1;
e.computeSalary();
}
}
Output:-

Interface:-
 We know that java does not support multiple inheritance means that
we are not allow to write like
class a extends b, c
 Even though the developer of JAVA knows that there is much
importance of multiple inheritance of JAVA.
 So they have given a new approach called INERFACE.

R. P. BHALODIA - RAJKOT P a g e | 94
How to define Interface:-
 An Interface is basically a class which contains variables any
method but there is major difference.
 The difference is the INTERFACE DEFINES ONLY
ABSTRACT METHOD AND FINAL FIELDS.
 It means that the any codes for any method defines in the interface
are always constant variable.
 You can define interface in following way:-
interface item
{
static final int code = 101;
void display()
{
……
……
}
}

How to extends Interface:-


 Special note for Interface:-
INTERFACE TO INTERFACE = EXTENDS
CLASS TO INTERFACE = IMPLIMENTS
 Like classes we can extends interfaces also that new interface will
behave like sub class.
 We can do this when we declare all the constants in one interface
and all methods to other interface.
 For example:-
interface itemconstants
{
static final int code = 101;
static final string name = “computer”;
}
interface item extends itemconstants
{
void display()
}
 Java has given us the concept of multiple inheritances in interface
means that we can extends more than one interface in single
interface.
Simple Interface

R. P. BHALODIA - RAJKOT P a g e | 95
interface Drawable
{
void draw();
}

//Implementation: by second user


class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
//Using interface: by third user
class InterfaceDemo
{
public static void main(String args[])
{
Drawable d=new Circle();//In real scenario, object is provided by
method e.g. getDrawable()
d.draw();
Drawable d1=new Rectangle();
d1.draw();
}
}
Simple Interface with Inheritance
interface Printable
{
void print();
}
interface Showable
{
void show();

R. P. BHALODIA - RAJKOT P a g e | 96
}
class MultipleInheritnace implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
MultipleInheritnace obj = new MultipleInheritnace();
obj.print();
obj.show();
}
}

Simple Interface with interface


interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class InterfaceToInterface implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

R. P. BHALODIA - RAJKOT P a g e | 97
public static void main(String args[])
{
InterfaceToInterface obj = new InterfaceToInterface();
obj.print();
obj.show();
}
}

Object Cloning
The object cloning is a way to create exact copy of an object. The clone()
method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class
whose object clone we want to create. If we don't implement Cloneable
interface, clone() method generates CloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone()
method is as follows:

protected Object clone() throws CloneNotSupportedException

Why use clone() method ?

The clone() method saves the extra processing task for creating the exact
copy of an object. If we perform it by using the new keyword, it will take a
lot of processing time to be performed that is why we use object cloning.

Advantage of Object cloning

Although Object.clone() has some design issues but it is still a popular and
easy way of copying objects. Following is a list of advantages of using
clone() method:

o You don't need to write lengthy and repetitive codes. Just use an
abstract class with a 4- or 5-line long clone() method.
o It is the easiest and most efficient way for copying objects,
especially if we are applying it to an already developed or an old

R. P. BHALODIA - RAJKOT P a g e | 98
project. Just define a parent class, implement Cloneable in it, provide
the definition of the clone() method and the task will be done.
o Clone() is the fastest way to copy array.

Disadvantage of Object cloning

Following is a list of some disadvantages of clone() method:

o To use the Object.clone() method, we have to change a lot of


syntaxes to our code, like implementing a Cloneable interface,
defining the clone() method and handling
CloneNotSupportedException, and finally, calling Object.clone()
etc.
o We have to implement cloneable interface while it doesn't have any
methods in it. We just have to use it to tell the JVM that we can
perform clone() on our object.
o Object.clone() is protected, so we have to provide our own clone()
and indirectly call Object.clone() from it.
o Object.clone() doesn't invoke any constructor so we don't have any
control over object construction.

 Inner Class:-
Java Inner class or nested class is a class which is declared inside
the class or interface.

Advantages:-
1) Nested classes represent a special type of relationship that is IT
can access all the members(Data members and Methods) of
OUTER class including Private.
2) Nested classes are used to develop more readable and
maintainable code because it logically group classes and
interfaces in one place only.
3) Code Optimization: it requires less code to write.
Example:-
class Outer
{
R. P. BHALODIA - RAJKOT P a g e | 99
private int data=30;

class Inner
{
void display()
{
System.out.println("Data Is:-"+data);
}
}

public static void main(String arg[])


{
Outer obj = new Outer();
Outer.Inner in = obj.new Inner();
in.display();
}
}

JAVA Packages

 Normal import & static import


 Normally in java coding, if we want to use the any static member
variables or a method of a class in our code,
 we have to first import that class using normal import keyword,
after that we have to use variables/methods with class name in the
code (Math.E)).
 We can see in below example.

import java.lang.*;
class xyz
{
public static void main(String args[])
{
System.out.println("without using static import functionality" + Math.E);
}
}

 In the above program, we have used System and Math classes are used
from java.lang package.
R. P. BHALODIA - RAJKOT P a g e | 100
 In java program, we don't need to import any java.lang package as
default package imported is java.lang package for every program.

 The basic difference between normal import and static import is


normal import can call the member variables with class name in
the package.

 static import can be defined and static member fields can not refere
any class name and use directly without classname.

we can see example for static import

import static java.lang.System.*;


import static java.lang.Math.*;
class xyz
{ public static void main(String args[])
{
out.println("without using static import functionality" + E);
}
}
 out is static field in java.lang.System class and E is static member
variable for java.lang.Math class.

 For using static member variable E in Math class in java.lang Package, we


have coded by adding static import something like import static
java.lang.Math.*; or java.lang.Math.E.

 It will always good idea to define for each static member(Math.E) instead
of all static members(Math.*) in static import declaration

Advantages of Static import feature:-

To call the static members without using class name in our code. By
making static import code statements makes all the static members of that
class are available to declared java class
Static import can be used for static member variables as well as static
members without referring class name in java code.

R. P. BHALODIA - RAJKOT P a g e | 101


 It simplifies the code readability for the constants.

Disadvantages of Static import feature:-

if we are importing the two same static constants from different classes in
the same class.
 There is possibility of ambiguity for the compiler to throw error.

 Introduction to java API packages & implment classes.


java.lang This is the language package. It contains String,
StringBuffer, System, Math,Thread etc classes
java.util This is utility package. It contains the utility classes such
as Vector, Random, HashTable, Date, Calender etc.
java.io Provides for system input and output through data
streams, serialization and the file system.
java.net Provides the classes for implementing networking
applications.
java.awt This is an Abstract Window Toolkit package.
It contains the classes to implement a GUI(Graphical User
Interface). Some of its classes are : font, graphics, color,
Button etc
java.awt.event Provides interfaces and classes for dealing with different
types of events fired by AWT components.
java.applet Provides the classes necessary to create an applet and the
classes an applet uses to communicate with its applet
context.
javax.swing Provides a set of "lightweight" (all-Java language)
components that, to the maximum degree possible, work
the same on all platforms.

R. P. BHALODIA - RAJKOT P a g e | 102


 Java.lang Package
Math Class
The java.lang.Math class contains methods for performing basic numeric
operations such as the elementary exponential, logarithm, square root, and
trigonometric functions. Math.methodName()
Method Math Class
Method Description
static double abs(double a) This method returns the absolute value
of a double value.
static double ceil(double a) This method returns the smallest (closest
to negative infinity) double value that is
greater than or equal to the argument and
is equal to a mathematical integer.
static double log(double a) This method returns the natural
logarithm (base e) of a double value.
static double log10(double a) This method returns the base 10
logarithm of a double value.
static float max(float a, float b) This method returns the greater of two
float values.
static double random() This method returns a double value with
a positive sign, greater than or equal to
0.0 and less than 1.0.
static double sqrt(double a) This method returns the correctly
rounded positive square root of a double
value.
import java.lang.Math;
class MathDemo
{
public static void main(String[] args)
{
// get some doubles to find their absolute values
double x = 4876.1874d;
double y = -0.0d;
// get and print their absolute values
System.out.println("Math.abs(" + x + ")=" +
Math.abs(x));//static method

R. P. BHALODIA - RAJKOT P a g e | 103


System.out.println("Math.abs(" + y + ")=" +
Math.abs(y));//static method
System.out.println("Math.abs(-9999.555d)=" + Math.abs(-
9999.555d));//static method
System.out.println("************** Use of Ceil Method
***********************");
System.out.println("Math.ceil(" + x + ")=" + Math.ceil(x));
System.out.println("Math.ceil(" + y + ")=" + Math.ceil(y));
System.out.println("Math.ceil(-0.65)=" + Math.ceil(-0.65));
System.out.println("************** Use of Natural Log
***********************");
System.out.println("Math.log(" + x + ")=" + Math.log(x));
System.out.println("Math.log(" + y + ")=" + Math.log(y));
System.out.println("Math.log(1)=" +Math.log(1));
System.out.println("************** Use of Natural Log
Base 10 ***********************");
System.out.println("Math.log10(" + x + ")=" +
Math.log10(x));
System.out.println("Math.log10(" + y + ")=" +
Math.log10(y));
System.out.println("Math.log(1)=" +Math.log10(1));
System.out.println("************** Use of Max Method
***********************");
System.out.println("Math.max(" + x + "," + y + ")=" +
Math.max(x, y));
System.out.println("************** Use of Random
Method ***********************");
System.out.println("The Random Number is :-"
+Math.random());
System.out.println("************** Use of SQRT
Method ***********************");
System.out.println("Math.sqrt(100)=" + Math.sqrt(100));
System.out.println("Math.sqrt(625)=" + Math.sqrt(625));
}
}

R. P. BHALODIA - RAJKOT P a g e | 104


Wrapper Class
What is need to Wrapper Class in JAVA?
 Java is an object-oriented language and can view everything as an
object.
 The primitive data types are not objects; they do not belong to any
class; they are defined in the language itself. Sometimes, it is
required to convert data types into objects in Java language.

What are Wrapper classes?


 As the name says, a wrapper class wraps (encloses) around a data
type and gives it an object appearance. Wherever, the data type is
required as an object, this object can be used.
 Wrapper classes include methods to unwrap the object and give back
the data type. It can be compared with a chocolate. The manufacturer
wraps the chocolate with some foil or paper to prevent from
pollution. The user takes the chocolate, removes and throws the
wrapper and eats it.
 Since J2SE 5.0, autoboxing and unboxing feature converts
primitive into object and object into primitive automatically. The
automatic conversion of primitive into object is known as
autoboxing and vice-versa unboxing.
 The eight classes of java.lang package are known as wrapper classes
in java. The list of eight wrapper classes are given below:
Primitive Type Wrapper class
Boolean Boolean
Char Character
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double

Method of Wrapper Class:-


Method Description
valueOf() Returns an Integer object holding the value of the
specified primitive.
toString() Returns a String object representing the value of a
specified int or Integer.
parseInt() This method is used to get the primitive data type
R. P. BHALODIA - RAJKOT P a g e | 105
of a certain String.
String Returns a binary representation of l
toBinaryString(long l)
String Returns a Hex representation of l
toHexString(long l)
String Returns a Octal representation of l
toOctalString(long l)

//Primitiv to Wrapper Class


//Primitiv to Wrapper Class
class PrimitivtoWrapper
{
public static void main(String args[])
{
System.out.println("********************* Method of
valueOf() **************************************");
Integer x =Integer.valueOf(9);
Double c = Double.valueOf(5);
Float a = Float.valueOf("80");
Integer b = Integer.valueOf("444",16);

System.out.println(x);
System.out.println(c);
System.out.println(a);
System.out.println(b);

System.out.println("********************* Method of
toString() **************************************");
System.out.println(x.toString());
System.out.println(Integer.toString(12));

System.out.println("********************* Method of
parseInt() **************************************");
x =Integer.parseInt("9");
c = Double.parseDouble("5");
b = Integer.parseInt("444",16);

System.out.println(x);
System.out.println(c);
System.out.println(b);
R. P. BHALODIA - RAJKOT P a g e | 106
System.out.println("The Value of Boolean B-
"+Integer.toBinaryString(20));
System.out.println("The Value of Boolean B-
"+Integer.toHexString(20));
System.out.println("The Value of Boolean B-
"+Integer.toOctalString(20));
long i=10;
long srt = Long.parseLong(Long.toBinaryString(i));
System.out.println("The Value of Boolean B-"+srt);
}
}

String
 In c and c++ string was array of characters but in C and C++ we are
not able to perform some operation like sorting of names.
 The java.lang.String class provides a lot of methods to work on
string.
 By the help of these methods, we can perform operations on string
such as trimming, concatenating, converting, comparing, replacing
strings etc.
 Java String is a powerful concept because everything is treated as a
string if you submit any form in window based, web based or mobile
application.
 For example:-
String str;
Str = new String(Your String);
 In above example syntax str is name of the object and we have to
allocate the memory using new keyword.
String s1;
s1 = new String(“Welcome to Java”);
 Here in the object s1 the String “Welcome to Java” will be stored
now you can use this object for various purposes.
String s2;
s2 = new String(“ “);
s2 =s1;
System.out.println(“s1”);
System.out.println(“s2”);
 In above example we have used our string object for output as well
as for copying the data from one object to another object.
 Now java String object behaves like a regular variable.

R. P. BHALODIA - RAJKOT P a g e | 107


Method of String Class
Method Description
s2=s1.toLowerCase() Convert the string s1 into lower case and then
store in s2 object.
s2=s1.toUpperCase() Convert the string s1 into uppercase and then
store in s2 object.
s2=s1.replace(„x‟,‟y‟) Replace all the content of x from s1 with y and
store in s2.
s2=s1.trim() Removes leading and trailing space from s1
and store to s2.
s1.equals(s2) Return true if s1 equals to s2.
s1.equalsIgnoreCase(s2) Return true if s1 and s2 are equal without
matching the cases
s1.length() Return length of s1.
s1.charAt(n) Return nth character from s1.
s1.compareTo(s2) Return negative if s1 < s2. Return positive if
s1>s2. Return 0 if s1 =s2.
String concat(String str) Returns concat string.
s1.substing(n) Return substring from nth character.
s1.substring(n,m) Return substring from nth character to mth
character.
s1.indexOf(„x‟) Gives us first accurate position of x.

class A
{
public static void main(String args[])
{
char c1[]={'a','b','c','d','e'};
char c2[];
String s1=new String();
s1="nilesh";
String s2=new String();
s2="jayesh";
String s3=new String();
s3=" parmar";
System.out.println("charAt :->"+s1.charAt(2));
System.out.println("equal :->"+s1.equals(s2));
System.out.println("startwith :->"+s1.startsWith("n"));
System.out.println("endwith :->"+s1.endsWith("h"));
System.out.println("concate :->"+s1.concat(s3));
R. P. BHALODIA - RAJKOT P a g e | 108
System.out.println("replace :->"+s1.replace('n','j'));
System.out.println("trim :->"+s3.trim());
System.out.println("tolowercase :->"+s1.toLowerCase());
System.out.println("toupercase :->"+s1.toUpperCase());
System.out.println("indexof :->"+s1.indexOf('l'));

}
}

String Buffer
 The java.lang.StringBuffer class is a thread-safe, mutable
(changeable) sequence of characters. Following are the important
points about StringBuffer −
o A string buffer is like a String, but can be modified.
o It contains some particular sequence of characters, but the
length and content of the sequence can be changed through
certain method calls.
o They are safe for use by multiple threads.
 Important Constructors of StringBuffer class
Constructor Description
StringBuffer() creates an empty string buffer with the initial
capacity of 16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int creates an empty string buffer with the specified
capacity) capacity as length.

Difference between String and StringBuffer


String StringBuffer
String class is immutable. StringBuffer class is mutable.
String is slow and consumes more StringBuffer is fast and
memory when you concat too many consumes less memory when
strings because every time it creates you cancat strings.
new instance.
String class overrides the equals() StringBuffer class doesn't
method of Object class. So you can override the equals() method of

R. P. BHALODIA - RAJKOT P a g e | 109


compare the contents of two strings by Object class.
equals() method.

Method of String Buffer:-


Method Description
public StringBuffer append(String s) Updates the value of the object that
invoked the method. The method
takes boolean, char, int, long,
Strings, etc.
public StringBuffer reverse() The method reverses the value of
the StringBuffer object that invoked
the method.
public delete(int start, int end) Deletes the string starting from the
start index until the end index.
public insert(int offset, int i) This method inserts a string s at the
position mentioned by the offset.
replace(int start, int end, String str) This method replaces the characters
in a substring of this StringBuffer
with characters in the specified
String.

import java.lang.*;

public class StringBufferDemo


{

public static void main(String[] args)


{
StringBuffer sb = new StringBuffer("Test");
sb.append(" String Buffer");

System.out.println("\n\nThe Use of Append Method:-


"+sb);

sb.delete(3, 7);
System.out.println("\n\nThe Use of Delete Method:- "+sb);

R. P. BHALODIA - RAJKOT P a g e | 110


sb.insert(3, "123");
System.out.println("\n\nThe Use of Insert Method:- " +sb);

sb.replace(3, 8, "ZARA");
System.out.println("\n\nThe Use of replace Mathod:- "
+sb);

sb.reverse();
System.out.println("\n\nThe Use of Reverse Method:-
"+sb);
}
}

java.util Package Classes


Random
 The random class allows you to generate random double, float, int
and long numbers.
 These random numbers are very useful when we are developing
simulation to the real world system because we are needed random
number is input.
 The constructor of the random number are:-
o Random():-This creates a new random number generator.
o Random(long seed):-This creates a new random number
generator using a single long seed.

Method of Random number


Method Description
double nextDouble() Return a random double value
float nextFloat() Return a random float value
int nextInt() Return a random integer value
long nextLong() Retrun a random long number

import java.util.*;
class RandomNumber
{
public static void main(String args[])
{
Random ran = new Random();

R. P. BHALODIA - RAJKOT P a g e | 111


System.out.println("The Random number is:-"
+ran);//retunr package name class

int a = ran.nextInt();
System.out.println("The Random Integer Value is:- " +a);

float b = ran.nextFloat();
System.out.println("The Random Float Value is:- " +b);

double c = ran.nextDouble();
System.out.println("The Random Double Value is:- " +c);

long d = ran.nextLong();
System.out.println("The Random Long Value is:- " +d);
}
}

Date
 Java library also provide Date ckass in java.util package.
 Date class encapsulate both date and time and represent the value
using milliseconds precision.
 Date class support the following constructor.
o Date():- this constructor initializes the object with the current
date and time.
o Date(long millisec):- this constructor accept one argument
that equals the number of milliseconds that have elapsed since
midnight, January 1, 1970.
 The epoch is midnight on January 1,1970 GMT(Greenwich Mean
Time).

Method of Date class


Method Description
boolean after(Date d) Return true if the d is after the current date
boolean before(Date d) Return true if the d is before the current
date.
boolean equals(Date d) If the d is current date then return true else
return false.
long getTime() Return the number of milliseconds since
epoch
R. P. BHALODIA - RAJKOT P a g e | 112
void setTime(long msec) Set the date and time of current object to
represent milliseconds since epoch
String toString() Return the string equivalent of the date.
import java.util.Date;

class DateDemo
{
public static void main(String args[])
{
Date date = new Date();
java.util.Date date2 = new java.util.Date();
Date x = new Date(0); //pass the args 0 the output is 1 jan
1970

System.out.println("The output of Object 1 :-


"+date);//display current system date and time with time zone
System.out.println("The output of Object 2 :-"+date2);
System.out.println("The output of Object X :-"+x);

long msec = date.getTime();


System.out.println("Milliseconds since 1 Jan,1970 GMT:- "
+msec);
date.setTime(msec + 10000000);
System.out.println("Date and time after add 1 crore
milliseconds:- "+date.toString());

Date d = new Date(63, 0, 16); // January 16, 1963


System.out.println("Day of the week: " + d.getDay());
}
}

GregorianCalendar

Calendar:-
 Like date class, Calendar class is also provided in java.util package.
 This class can be sued to extract detailed calendar information llike
year, month, date, hour, minute and second.
 Here, we will see the use of GregorianCalendar subclass of Calendar
class.
 Calendar class has no public constructor.

R. P. BHALODIA - RAJKOT P a g e | 113


GregorianCalendar

The java.util.GregorianCalendar class is a concrete subclass of Calendar


and provides the standard calendar system used by most of the world.
Class constructors
GregorianCalendar() This constructs a default
GregorianCalendar using the current
time in the default time zone with the
default locale.
GregorianCalendar(int year, int This constructs a GregorianCalendar
month, int dayOfMonth) with the given date set in the default
time zone with the default locale.
GregorianCalendar(int year, int This constructs a GregorianCalendar
month, int dayOfMonth, int with the given date and time set for the
hourOfDay, int minute) default time zone with the default
locale.
GregorianCalendar(int year, int This constructs a GregorianCalendar
month, int dayOfMonth, int with the given date and time set for the
hourOfDay, int minute, int default time zone with the default
second) locale.
GregorianCalendar(TimeZone This constructs a GregorianCalendar
zone) based on the current time in the given
time zone with the default locale.

import java.util.*;
class MonthCalendar
{
static String dayName[] =
{"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
static String monthName[] =
{"January","Feruary","March","April","May","June","July","August","Sep
tember","October","November","December"};
static int dayInMonth[]= {31,28,31,30,31,30,31,31,30,31,30,31};

}
class GregorianCal
R. P. BHALODIA - RAJKOT P a g e | 114
{
public static void main(String args[])
{
GregorianCalendar gc = new GregorianCalendar();
int year = gc.get(Calendar.YEAR);
int month = gc.get(Calendar.MONTH);
int date = gc.get(Calendar.DATE);
int dow = gc.get(Calendar.DAY_OF_WEEK);
System.out.println("The Year is :"+year);
System.out.println("The Month is
:"+MonthCalendar.monthName[month]);
System.out.println("The Day is :"+date);
System.out.println("The Day_Of_Week is :"+dow);
//handle leap year
MonthCalendar.dayInMonth[1] += gc.isLeapYear(year) ? 1
: 0;
//change to the first day of month
gc.add(Calendar.DATE, -date + 1);
//Determine the day of week
int fdow = gc.get(Calendar.DAY_OF_WEEK);

//Compute the variable dom


int dom = 2 - fdow;
//display column headings
for(int i=0;i<7;i++)
{
String s = MonthCalendar.dayName[i];
System.out.print(s + " ");
}
System.out.println(" ");
//display date

for(int row=0;row<6;row++)
{
for(int col=0;col<7;col++)
{
if(dom
>MonthCalendar.dayInMonth[month] )

R. P. BHALODIA - RAJKOT P a g e | 115


{
break;
}
if(dom > 0)
{
//display date in the fird cell
if(dom < 10 )
{
System.out.print(" " +dom+"
" );
}
else
{
System.out.print(" " +dom+"
" );
}
}
else
{
System.out.print(" ");
}
++dom;
}
System.out.println(" ");
}
}
}

Vector
Vector implements a dynamic array. It is similar to ArrayList, but with
two differences −
 Vector is synchronized.
 Vector contains many legacy methods that are not part of the
collections framework.
Vector proves to be very useful if you don't know the size of the array in
advance or you just need one that can change sizes over the lifetime of a
program.
Following is the list of constructors provided by the vector class.

R. P. BHALODIA - RAJKOT P a g e | 116


Constructor & Description
Vector( )
This constructor creates a default vector, which has an initial size of 10.
Vector(int size)
This constructor accepts an argument that equals to the required size, and
creates a vector whose initial capacity is specified by size.
Vector(int size, int incr)
This constructor creates a vector whose initial capacity is specified by size
and whose increment is specified by incr. The increment specifies the
number of elements to allocate each time that a vector is resized upward.
Vector(Collection c)
This constructor creates a vector that contains the elements of collection c.

Method of Vector Class


Method Description
addElement() It will add the specified item at the end of
vector
elementAt() It will gives us data at the nth elelment
Size() Return the size of vector.
removeElement() It will remove element with the name e
removeElementAt() Remove nth element from the vector.
removeAllElements() Remove all the element of vector
copyInto() Copies all the items into the array
insertElementAt() Insert the item at nth position

import java.util.*;

class VectorDemo
{
public static void main(String args[])
{
Vector v1 = new Vector();
int length = args.length;
for(int i =0; i<length;i++)
{
v1.addElement(args[i]);
}

R. P. BHALODIA - RAJKOT P a g e | 117


v1.insertElementAt("Cobol",2);
int size = v1.size();
String str1[] = new String[size];
v1.copyInto(str1);
System.out.println("List of Language");
for(int i=0;i<size;i++)
{
System.out.println(str1[i]);
}
}
}

ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList increments 50% of Vector increments 100% means doubles the
current array size if number of array size if total number of element exceeds
element exceeds from its capacity. than its capacity.
3) ArrayList is not a legacy class, it Vector is a legacy class.
is introduced in JDK 1.2.
4) ArrayList is fast because it is Vector is slow because it is synchronized i.e.
non-synchronized. in multithreading environment, it will hold
the other threads in runnable or non-runnable
state until current thread releases the lock of
object.

HashTable
 HashTable class is very much useful in java programming. It allows us to
easily store and retrieve the object.
 Each entry in the HashTable contains a key and the values are objects.
The keys must be unique and to retrieve elements from the HashTable.
 Another name of this type of data structure is associative array. This class
has a constructor which allows us to initialize its object.
 Constructor as follows:-
o Hashtable( ):-This is the default constructor of the hash table it
instantiates the Hashtable class.
o Hashtable(int size):-This constructor accepts an integer parameter and
creates a hash table that has an initial size specified by integer value size.
o Hashtable(int size, float fillRatio):-This creates a hash table
that has an initial size specified by size and a fill ratio
R. P. BHALODIA - RAJKOT P a g e | 118
specified by fillRatio. This ratio must be between 0.0 and 1.0,
and it determines how full the hash table can be before it is
resized upward.
o Hashtable(Map < ? extends K, ? extends V > t):-This
constructs a Hashtable with the given mappings.

Method of Hash Table


Method Description
Boolean contains(Object o) Return true if the Hash Table
contains obj as one of its values.
Boolean containsKey(Object obj) Return true if the hash table contains
obj as one of its keys otherwise
return false.
Boolean containsValue(Object obj) Return true if the hash table contains
obj as one of its value otherwise
false.
Enumeration e() Return an enumeration of elements.
Object get(Object x) Return the value associated with the
key x.
Boolean isEmpty() Return true if the hash table is empty
otherwise false
Enumeration keys() Return an enumeration key.
Object put(object k, object v) Puts a key and value pair in the hash
table where k is the key and v is the
value
Object remove(object k) Removes the key and value pair form
the hash table which key=k
Int size() Return number of keys in the hash
table

import java.util.*;
class HashTableClass
{
public static void main(String args[])
{
Hashtable hs = new Hashtable();

hs.put("Apple","Red");
hs.put("Grapes","Green");
hs.put("Mango","Orange");
R. P. BHALODIA - RAJKOT P a g e | 119
Enumeration e = hs.keys();
while(e.hasMoreElements())
{
Object k = e.nextElement();
Object v = hs.get(k);
System.out.println("The Value of Key is:- "+k);
System.out.println("The Value of Value is:- "+v);
}
System.out.println("The Color of Apple is:-");
Object x = hs.get("Apple");
System.out.println(x);
}
}

LinkedList class
Java LinkedList class uses a doubly linked list to store the elements. It
provides a linked-list data structure. It inherits the AbstractList class and
implements List and Deque interfaces.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting
needs to occur.
o Java LinkedList class can be used as a list, stack or queue.

LinkedList class declaration

Let's see the declaration for java.util.LinkedList class.

public class LinkedList<E> extends AbstractSequentialList<E> impleme


nts

R. P. BHALODIA - RAJKOT P a g e | 120


List<E>, Deque<E>, Clone

Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection<? extends E> c) It is used to construct a list containing


the elements of the specified collection,
in the order, they are returned by the
collection's iterator.

Methods of Java LinkedList

Method Description
boolean add(E e) It is used to append the specified
element to the end of a list.
void add(int index, E element) It is used to insert the specified
element at the specified position
index in a list.
void addFirst(E e) It is used to insert the given element
at the beginning of a list.
void addLast(E e) It is used to append the given
element to the end of a list.
void clear() It is used to remove all the elements
from a list.
Object clone() It is used to return a shallow copy
of an ArrayList.
boolean contains(Object o) It is used to return true if a list
contains a specified element.
Iterator<E> descendingIterator() It is used to return an iterator over
the elements in a deque in reverse
sequential order.
E element() It is used to retrieve the first
element of a list.
E get(int index) It is used to return the element at
the specified position in a list.
E getFirst() It is used to return the first
element in a list.
E getLast() I t is used to return the last element

R. P. BHALODIA - RAJKOT P a g e | 121


in a list.
int indexOf(Object o) It is used to return the index in a
list of the first occurrence of the
specified element, or -1 if the list
does not contain any element.
int lastIndexOf(Object o) It is used to return the index in a list
of the last occurrence of the
specified element, or -1 if the list
does not contain any element.
ListIterator<E> listIterator(int It is used to return a list-iterator
index) of the elements in proper
sequence, starting at the specified
position in the list.
E peek() It retrieves the first element of a
list
E peekFirst() It retrieves the first element of a list
or returns null if a list is empty.
E peekLast() It retrieves the last element of a
list or returns null if a list is
empty.

SortedSet<E> interface

A set is used to provide a particular ordering on its element. The elements


are ordered either by using a natural ordering or by using a Comparator.
All the elements which are inserted into a sorted set must implement the
Comparable interface.

The set's iterator will traverse the set in an ascending order. Several other
operations are provided in order to make best use of ordering. All the
elements must be mutually comparable.

comparator() Returns the comparator which is used to order


the elements in the given set. Also returns null
if the given set uses the natural ordering of the
element.
first() Returns the first element from the current set.
headSet(E toElement) Returns a view of the portion of the given set
whose elements are strictly less than the to
Element.

R. P. BHALODIA - RAJKOT P a g e | 122


last() Returns the reverse order view of the mapping
which present in the map.
spliterator() Returns a key-value mapping which is
associated with the least key in the given map.
Also, returns null if the map is empty.
tailSet(E fromElement) Returns a view of the map whose keys are
strictly less than the toKey.

SortedSet Interface :-

The SortedSet interface extends Set and declares the behavior of a set
sorted in an ascending order. In addition to those methods defined by Set,
the SortedSet interface declares the methods summarized in the following
table −
Several methods throw a NoSuchElementException when no items are
contained in the invoking set. A ClassCastException is thrown when an
object is incompatible with the elements in a set.
A NullPointerException is thrown if an attempt is made to use a null
object and null is not allowed in the set.

Sr.No Method & Description


1 Comparator comparator( )
Returns the invoking sorted set's comparator. If the natural
ordering is used for this set, null is returned.
2 Object first( )
Returns the first element in the invoking sorted set.
3 SortedSet headSet(Object end)
Returns a SortedSet containing those elements less than end
that are contained in the invoking sorted set. Elements in the
returned sorted set are also referenced by the invoking sorted
set.
4 Object last( )

R. P. BHALODIA - RAJKOT P a g e | 123


Returns the last element in the invoking sorted set.
5 SortedSet subSet(Object start, Object end)
Returns a SortedSet that includes those elements between start
and end.1. Elements in the returned collection are also
referenced by the invoking object.
6 SortedSet tailSet(Object start)
Returns a SortedSet that contains those elements greater than
or equal to start that are contained in the sorted set. Elements
in the returned set are also referenced by the invoking object.

Stack
The stack is a linear data structure that is used to store the collection of
objects. It is based on Last-In-First-Out (LIFO). Java collection framework
provides many interfaces and classes to store the collection of objects. One
of them is the Stack class that provides different operations such as push,
pop, search, etc.

The stack data structure has the two most important operations that are
push and pop. The push operation inserts an element into the stack and pop
operation removes an element from the top of the stack.

In Java, Stack is a class that falls under the Collection framework that
extends the Vector class.
It represents the LIFO stack of objects. Before using the Stack class,
we must import the java.util package.

Method Method Description

empty() The method checks the stack is empty or not.

push(E item) The method pushes (insert) an element onto the top of the stack.

pop() The method removes an element from the top of the stack and
returns the same element as the value of that function.
peek() The method looks at the top element of the stack without
removing it.

R. P. BHALODIA - RAJKOT P a g e | 124


Queue

A queue is another kind of linear data structure that is used to store


elements just like any other data structure but in a particular manner. In
simple words, we can say that the queue is a type of data structure in the
Java programming language that stores elements of the same kind. The
components in a queue are stored in a FIFO (First In, First Out) behavior.
There are two ends in the queue collection, i.e., front & rear.

Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each
key and value pair is known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the


basis of a key.

StringTokenizer
 The string tokenizer class allows you to convert your string into
words or tokens.
 We have to specify the delimiter character.
 This functionality is very much useful when you need to develop a
program which process the formatted file.
 This class gives you a constructor in which you have to pass string
and the delimiter character.
 It doesn't provide the facility to differentiate numbers, quoted
strings, identifiers etc. like StreamTokenizer class.
 The constructor of the class are as below.
o StringTokenizer(String str):-creates StringTokenizer with
specified string.
o StringTokenizer(String str, String delim):-creates
StringTokenizer with specified string and delimeter.
o StringTokenizer(String str, String delim, boolean
returnValue):-creates StringTokenizer with specified string,
delimeter and returnValue. If return value is true, delimiter
characters are considered to be tokens. If it is false, delimiter
characters serve to separate tokens.

R. P. BHALODIA - RAJKOT P a g e | 125


Method of Stringtokenizer Class:-
Method Description
Int countTokens() Return the number of tokens in the string
Returns true if there are more tokens in the
Boolean hasMoreTokens()
string otherwise false.
String nextToken() Return the next token.
import java.util.*;
class StringTokenizerClass
{
public static void main(String args[])
{
String str = "123/45.3/-11.2./-90.10/100/99.99/-50/20";
StringTokenizer st = new StringTokenizer(str,"/");
while(st.hasMoreElements())
{
String s = st.nextToken();
System.out.println(s);
}
}
}
Creating and Using User Defined package and sub-package
Packages
• Packages are container for classes that are used to keep the class
name space compartmentalized.
• Packages are stored in a hierarchical manner and are explicitly
imported into new class definition.
• Java provides a mechanism for partitioning the classname space into
more manageable chunk. This mechanism is the package.
• The package is both a naming and a visibility control mechanism.
You can define classes inside a package that are not accessible by
code outside that package. You can also define class member that
are only exposed to other members of the same package. This allows
your classes to have intimate knowledge of each-other but not
expose that knowledge to the rest of the world.
Defining a Package
 To create a package, simply include a package command as the first
statement in java source file.

R. P. BHALODIA - RAJKOT P a g e | 126


 Any classes declared within that file will belong to the specified
package.
 The package statement defines a name space in which classes are
stored.
 If you omit the package statement, the class names are put into the
default package, which has no name.
• General form of package statement:
Package pkg;
 Where, pkg is the name of the package. For example following
statement creates a package called MyPackage must be stored in
directory called MyPackage. The directory name must match the
package name exactly.
 More than one file can include the same package statement.
 You can create a hierarchy of packages. To do so, simply separate
each package name from the one above it by use of a period. The
general form of multileveled package statement:
Package pkg1[.pkg2[.pkg3]];
For example:
Package java.awt.image;
 This package needs to be stored in java/awt/image, java\awt\image
or java:awt:image on your system.
 You can not rename a package without renaming the directory in
which the classes are stored.
Finding Packages and CLASSPATH
 How dose the java run-time system know where to look for
packages that you create? – the answer has two parts:
1. by default, the java run-time system uses the current working
directories as its starting point. Thus, if your package is in the
current directory, or a subdirectory of the current directory, it will be
found.
2. you can specify a directory path or paths by setting the
CLASSPATH environmental variable.
 For example, consider the following package specification:

R. P. BHALODIA - RAJKOT P a g e | 127


Package MyPack;
 In order for a program to find MyPack, one of two things must be
true. Either the program is executed form a directory immediately
above MyPack or CLASSPATH must be set to MyPack.
package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name=n;
bal=b;
}
void show()
{
if (bal>0)
System.out.println("Name is:"+name +":$" +bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[]=new Balance[3];

current[0]=new Balance("K.J.Fielding",123.23);
current[1]=new Balance("will tell",157.02);
current[2]=new Balance("Tom",-12.33);
for(int i=0;i<3;i++)
{
current[i].show();
}
}
}
 Compilation of program:
C:\javaprogs\MyPack>javac AccountBalance.java
C:\javaprogs>java MyPack.AccountBalance

R. P. BHALODIA - RAJKOT P a g e | 128


 You will need to be in the directory above MyPack when you
execute this command, or your CLASSPATH environment variable
set appropriately.
C:\javaprogs>javac p\*.java
C:\javaprogs>java p.PackageDemo
Javac –d . P\*.java

Package
• Package is a very important concept of java.
• Simply saying a package is just a container or collection of classes.
• So it is a directory or folder which contains the source files & its class
files.
• Generally you have to take care about duplicate class names.
• But using package you can have more than one class of same name.
• That is you can have same name of class in different packages.
• You can define class & members that can not be accessed by other classes
or packages.

How to define a package?


• To create a package keyword is used as the first statement of your
program after package keyword you have to give the package name.
• In this package.
• I.e. directory your class files & source files will be stored and if you do
not specify any package as we did earlier, the files will be stored in the
default package.
• But it is good define a package for your classes.
• As we can shown in bellow.
package packagename

R. P. BHALODIA - RAJKOT P a g e | 129


Ex: package mypack;
• Here your class files must be in the directory named mypack. You can
also create a hierarchy of packages. It can be done as follow.
Package p1.p2.p3;
• Here the hierarchy shows that p1 is the main package, p2 is its sub
package & p3 is sub package of p2. So the p3 directory should be in p2
& p2 should be in p1. The path of your class files should be like this..
• p1/p2/p3/class file & you can not rename any of these directory names
without changing the package name.
• If your program contains a package statement, it must be the first
statement of the program.

• Access control for package

Specified Private Default Protected Public

Same class Yes Yes Yes Yes

Same package No Yes Yes Yes

Different package,subclasses No No Yes yes

Different package, no-sub class No No No Yes

Private : any private member can be accessed by the member of its


class only. Private member can not be accessed from outside the
class.

R. P. BHALODIA - RAJKOT P a g e | 130


Default(No specifier) : The default members are accessed by the
members of the current package only. So the members of other class
but same package can be accessed.

Protected : if a member is defined as protected, it can be accessed


from other class & other packages but only the subclass in the case
of different package. So when you want to allow a member to be
accessed from other package.
• But only those members which belong to the subclass of this class,
use protected specifier.

Public :
• The public members can be accessed from anywhere, means any
class & any package.
• Remember that these access specifiers can be applied to any
members of classes but a class can have only public or default
access.
How to import package?
• After creating a package, you can use its classes in other java files.
• To do this you have to import that package in which the class is
resided.
• Importing a package is similar to including header file in C or C++.
• Syntax :import pack1 [.pack2].classname/*;
• Here pack1 is the name of main package or directory. Pack2 is the
sub package of package pack1.
You can have as many sub packages as you want . After the package name
you have to specify the class name that you want to use.

R. P. BHALODIA - RAJKOT P a g e | 131


UNIT – 3: Exception Handling, Threading and Streams
(Input and Output)

R. P. BHALODIA - RAJKOT P a g e | 132


Part-1
Exception Handling

R. P. BHALODIA - RAJKOT P a g e | 133


Introduction to exception handling
During the execution of an application, there are many times when
an error condition arises within the application. In java, all kinds of error
conditions are called as exceptions. In other words we can say that In
General; it is in the rare case that our program will run successfully in its
first attempt.
There are mainly two types of exceptions:
(1) Compile Time Exceptions (Syntax Errors)
All the syntax Errors are known as Compile Time Errors.
These types of errors are detected and displayed by the java compiler
therefore they are known as Compile Time Errors. This type of
errors can be solved before running the program so that after solving
this type of errors we are sure that our program is syntactically
correct.
Remember that: Whenever the compiler will display the error it
will not generate the .class file.

Compile Time Errors Examples:


 Missing Semicolons
 Missing Brackets
 Misspell of Keywords of Variables
 Missing of double quotes in strings
 Use of undeclared variables
 Incompatible type conversion / assignment
 use of = in place of ==
 use of non initialized variable in keyboard reading

(2)Run Time Exceptions (Logical Errors)


Run time errors are those types of errors in which the program
may compiled successfully and the .class file also generated but
when we run that program it will produce the wrong result.
This will happened due to poor understanding of the logic or
sometimes due to misuse of the system resources.
Exception Handling:
The mechanism for Exception handling can be summarizing in the
following steps:
(1) Find the problem (Hit)
(2) Inform that an error has occurred (Throw)
(3) Receive the error information (Catch)
(4) Take the corrective Actions (Handle)

R. P. BHALODIA - RAJKOT P a g e | 134


Java exception handling is managed via five keyword names are:
 Try
 Catch
 Finally
 Throw
 Throws

1) Try: - program statements that you want to monitor for exception


are contains within a try block.
2) Catch: -if an exception occurs within the try block it is thrown.
Your code can catch this exception and handle it in come rational
manner. System generated exception hand by java run-time system.
3) Throw: - if want to throw manually at that time throw key word is
used.
4) Throws: - any exception that is thrown out of a method must be
specified as such by throws clause.
5) Finally: - any code that must be executed after try block completes
is put in a finally block.
Format: -
try
{
//block of code to monitor for error
}
catch(Exception e)
{
//exception handler for error
}
catch(Exception e)
{
//exception handler for error
}
finally
{
//block of code must executed after try
}

R. P. BHALODIA - RAJKOT P a g e | 135


Type of Exception: -
 All types of exception are the subclass of the built-in class
throwable.
 Throwable is at the top of the exception class hierarchy.

Exception: -exception is the sub-class of the throwable. This class helps to


create your own custom exception type.
Error: -the exceptions that are not exception be caught under normal
circumstances by your program.
Here we are not going to discuss of the topic.
Uncaught Exception: -
Before we learn how to handle exception in your program, it is useful to
see that what happens when we don‟t handle EXCEPTION.
class exe1
{
public static void main(String args[])
{
int d=0;
int a = 400/d;
System.out.println("The Anwer of A is : "+a);

}
}

Output:-

Exception in thread "main" java.lang.ArithmeticException: / by zero


at exe1.main(exe1.java:6)

R. P. BHALODIA - RAJKOT P a g e | 136


Try, catch, finally and throws
 Now exe1 is terminated automatically and display the run-time error.
 How to solve this problem?
 Answer is that to write try and catch block in the program.
 try block contain the code which we want to monitor for exception.
 catch block catch the exception that is generated in try block.
class exe2
{
public static void main(String args[])
{
int d=0;
try
{
int a = 400/d;
System.out.println("This will not be printed");
}
catch(Exception e)
{
System.out.println("Division by zero");
//System.out.println("The Exception is:"+e);
}
System.out.println("After catch statement");
}
}

In this program try block and catch block statement form a unit. In try
block is monitor for error. In the try contain any exception, the try block
throw the exception to the catch block. When program control to the catch
that never goes back to the try block.

Multiple Catch Clauses


 In one program may contain more than one exception.
 So, we handle this type of problem; write the more than two catch
block.
 Each catch block catching the different exception.
 When exception is thrown, each catch statement is inspected
(survey) in order and the first one whose type matches that of the
exception is executed. After one catch statement executes, the other
are bypass, and execution continues after the try/catch block.

R. P. BHALODIA - RAJKOT P a g e | 137


class MultipleCatch
{
public static void main(String arg[])
{
try
{
int arr[]={1,2,3};
arr[4]=6/0;

}
catch(Arithmetic Exception e)
{
System.out.println("Divide by Zero");
}
catch(ArrayIndexOutOfBoundException ex)
{
System.out.println("Array Index out of Bound
Exception");
}
}
}
Nested try statement
 The try statement can be nested. That is, a try statement can be
inside the block of another try.
 Each time a try statement is entered, the context of that exception is
pushed on the stack.
 If an inner try statement does not have a catch handler for a
particular exception, the stack is slow down and the next try
statement‟s catch handlers are inspected for a match.
 This continues until one of the catch statements succeeds, or until
the entire nested try statements are exhausted.
 If no catch statement matches, then the java run-time system will
handle the exception.
//an example of nested try statements
class NestedTry
{
public static void main(String arg[])
{
try
{

R. P. BHALODIA - RAJKOT P a g e | 138


int arr[]={10,20,30,40};
try
{
int x = arr[3]/arr[1];

}
catch(ArithmeticException e)
{
System.out.println("Divide by Zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundException ex)
{
System.out.println("Array Index out of
Bound");
}
}
}

throw
 throw keyword use for manually throw the exception to the
exception handler.
 Generally java run-time systems throw the exception implicitly.
 Use of throw keyword to throw an exception explicitly, using the
throw statement.
 Syntax :
throw <ThrowableInstance>;
 here, throwable instance must be an object of type throwable or a
subclass of throwable.
 There are two ways can obtain a throwable object.
o Using parameter into catch clause
o Creating one with the new operator.
Example of throw:
//DEONSTRATE THROW
class Throw_keyword
{

static void avg()

R. P. BHALODIA - RAJKOT P a g e | 139


{
try
{
throw new ArithmeticException("throw Demo");
}
catch(ArithmeticException e)
{
System.out.println("Explict Exception");
}
}
public static void main(String arg[])
{
avg();
}

}
throws:
 If a method is capable of causing an exception that it does not
handle, it may specify this behavior. So that callers of the method
can guard them solve again that exception.
 You do this including a throws clause in the method‟s declaration.
 A throws clause lists the type of exception that a method might
throw.
Example:
//this program contains an error and will not compile
import java.io.*;
class Demo
{
public static void main(String arg[])throws IOException
{
char g;
g=(char)System.in.read();
if(g=='F'||g=='f')
System.out.println("Female");
else
System.out.println("Male");
}
}

R. P. BHALODIA - RAJKOT P a g e | 140


finally
 The finally block always run if exception is generated or not.
 This block helps to close the file, free resources when we use in
method.
 The finally block is optional.
 Operations are..
1) Closing a file
2) Closing a record set
3) Closing the connection with database.
4) Terminating Network Connection.

//Demonstrate finally
class Finally_Block
{
public static void main(String arg[])
{
try
{
int a=5;
int b=0;
int c=a/b;
System.out.println("division="+c);

}
catch(ArithmeticException e)
{
System.out.println("This will be always Executed");
}
finally
{
System.out.println("Finally Block");
}
}
}
OutPut:-

R. P. BHALODIA - RAJKOT P a g e | 141


Creating user defined exception class
Java provides built-in Exception to handle most common errors. Then
also
java provides user to create exception,which are called custom
exception
or user defined exception. User can create their own exception classes
so application-specific problems can be handled.This can be done
simply by
extending java Exception class.
class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
class TestException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
{
throw new InvalidAgeException("not eligible for
vote");
}
else
{
System.out.println("welcome to vote");
}
}
}
class CustomException
{
public static void main(String args[])
{
int age = Integer.parseInt(args[0]);
try
{
TestException1.validate(age);
}

R. P. BHALODIA - RAJKOT P a g e | 142


catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}

Multithreading

Thread and its life cycle (thread states)


Introduction:
 Multithreading in java is a process of executing multiple threads
simultaneously.
 Thread is basically a lightweight sub-process, a smallest unit of
processing. Multiprocessing and multithreading, both are used to
achieve multitasking.
 But we use multithreading than multiprocessing because threads
share a common memory area. They don't allocate separate memory
area so saves memory, and context-switching between the threads
takes less time than process.
 Java Multithreading is mostly used in games, animation etc.
Advantages of Java Multithreading:

1) It doesn't block the user because threads are independent and you can
perform multiple operations at same time.

2) You can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception


occur in a single thread.

What is Thread in java?


 A thread is a lightweight sub process, a smallest unit of processing.
It is a separate path of execution.

 Threads are independent, if there occurs exception in one thread, it


doesn't affect other threads. It shares a common memory area.

R. P. BHALODIA - RAJKOT P a g e | 143


 As shown in the above figure, thread is executed inside the process.
There is context-switching between the threads. There can be
multiple processes inside the OS and one process can have multiple
threads.

Thread Life Cycle:


A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5
states.
The life cycle of the thread in java is controlled by JVM. The java thread
states are as follows:
1. New Thread
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

R. P. BHALODIA - RAJKOT P a g e | 144


 When we create any thread object, it is said to be in newborn state.
At this stage we can do two things (1) start (2) stop.

 The Runnable state means that the thread is ready for execution
and is waiting for availability of the processor. The thread is in
queue now and waiting for execution. Generally they will be
executed in FCFS(First Come First Serve) manner.

R. P. BHALODIA - RAJKOT P a g e | 145


 In Running state means the processor has given its time to thread
for its execution. The thread runs till it gives control to another.
 There is one method called suspend() which can be again put in
running by resume() method.

 We can make a thread to sleep. We can put a thread to sleep by


using sleep(time) where time is in miliseconds. The thread will re-
enter into the runnable state as soon as the time is over.

 It has been told to wait until some event occurs. This is done using
wait() method. The thread can be scheduled to run again using
notify() method.

Example:-

class Thread_life
{
public static void main(String arg[])
{

R. P. BHALODIA - RAJKOT P a g e | 146


Thread.State states[] = Thread.State.values();
for(Thread.State s:states)
System.out.println(s);
}
}
Output:-

New
Runnable
Blocked
Waiting
Timed_Waiting
Terminated

Thread class and its methods


 Java multithreading system is built upon the Thread class, its
methods, and its companion interface, Runnable.
 To create a new thread, your program will either extend Thread or
implement the Runnable interface.
 The thread class defines several methods that help manage threads.
The ones that will be used in this chapter are shown here:
Method Description
void destroy() To destroy the Thread from the memory
String getName() Returns the name of the thread.
int getPriority() Returns the priority of the thread.
void interrupt() Interrupts the current thread.
boolean Tests whether the thread is interrupted or not
interrupted()
boolean isAlive() Tests whether the thread is alive or not
void join() Wait for the calling thread to die.
void join(long Wait atmost <millis> millisecond for this thread to
millis) die.

R. P. BHALODIA - RAJKOT P a g e | 147


void resume() Resumes the thread execution
void setPriority(int Change the priority of the thread
newPriority)
void sleep(long Causes the currently executing thread to sleep
millis) (temporarily cease execution) for the specified
number of milliseconds.
void start() Causes this thread to begin execution; the Java
Virtual Machine calls the run method of this thread.
void stop() Stops the execution of current thread
void suspend() Suspends the current thread execution until the
resume method has been called.
void yield() Causes the currently executing thread object to
temporarily pause and allow other threads to
execute.

Creation of New Thread:


 Java provides two ways to create a new thread.
 By Extending the Thread class which is available in package
java.lang.Thread
Example:
class myThread extends Thread
{
……..
……..
}
//Write a program to create thread in java
class Thread1 extends Thread
{
public void run()
{
for(int i=0;i<100;i++)
System.out.println("Thread1:="+i);
}
}
public class Thread_Demo
{
R. P. BHALODIA - RAJKOT P a g e | 148
public static void main(String arg[])
{
Thread1 t1 = new Thread1();
t1.start();
for(int i=0;i<100;i++)
System.out.println("Main:="+i);
}
}
Output:- Output cannot be predicted Exactly…

Thread Priority:
 In Java each thread will be assigned a priority, which affects the
order of its execution.
 If the two or more threads have same priority then they have been
given equal treatment by Java scheduler and they will be processed
on FCFS basis.
 On the other hand we – the programmers can also set the priority by
using setPriority() method.
 In setPriority() method we have to pass integer no. or constant
according to our requirement just like
threadname.setPriority(intnumber)

 Thread class has sevelral constants also they are


MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
 Remember that the default setting is NORM_PRIORITY
 When java program gets a new thread with higher priority than
presently running thread then the presently running thread will move
into the runnable state and new thread will come in to execution.
//demo of priority method min,norm,max using thread class
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("From Thread A : i = "+i);
}

R. P. BHALODIA - RAJKOT P a g e | 149


System.out.println("Exit From Thread A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("From Thread B : j = "+j);
}
System.out.println("Exit From Thread B");
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("From Thread C : k = "+k);
}
System.out.println("Exit From Thread C");
}
}

class ThreadDemo2
{
public static void main(String args[])
{
A thread_a=new A();
B thread_b=new B();
C thread_c=new C();
System.out.println("Thread A Started");
thread_a.setPriority(Thread.MAX_PRIORITY);
thread_a.start();

System.out.println("Thread B Started");
thread_b.setPriority(Thread.NORM_PRIORITY);

R. P. BHALODIA - RAJKOT P a g e | 150


thread_b.start();

System.out.println("Thread C Started");
thread_c.setPriority(Thread.MIN_PRIORITY);
thread_c.start();
}
}
Runnable Interface:
From the first we know that threads can be created in two ways:
(1) By extending Thread class
(2) By implementing Runnable Interface.
Runnable Interface will work same as extending thread class. But
it is useful when we need to extend some other class at that time this
implementation will be much useful.
class Thread1 implements Runnable
{
public void run()
{
for(int i=0;i<100;i++)
System.out.println("Thread1:="+i);
}
}
public class Runnable_Demo{
public static void main(String arg[]){
Thread1 t1 = new Thread1();
Thread t2 = new Thread(t1);
t2.start();
for(int i=0;i<100;i++)
System.out.println("Main:="+i);
}
}

Synchronization in multiple threads (Multithreading)


In java, the threads are executed independently to each other.These types
of threads are called as Asynchronous threads.While working with
multiple threads,it may be possible that more than one threads share the
same data at a time.For example one thread might try to read the data
when other thread tries change it.This might generate error in result.In this
case,it is necessary to allow one thread to finish its task completely and

R. P. BHALODIA - RAJKOT P a g e | 151


then allow next thread to execute.This can be done with the help of
synchronized() Method.
 An example consider a bank account that shared by multiple
customers. Each of the customer can make deposited or withdrawal
in his account.
 Consider a situation in which you have developed individual thread
for individual customers.
 If we have thread a or customer A. now customer A want to deposit
Rs 10000 in his account and the present balance is zero.
 At the same time customer B also deposit Rs 1000 in his bank
account. So that he also gets the balance 0(zero).
 This solution to the above problem is to access the common data.
For this purpose java has given us a special keyword called
synchronized which makes a lock on the method which is executes.
So that the second thread will not get control of CPU until the first
thread over.
class Demo
{
synchronized void test()
{
for(int i=1;i<100;i++)
System.out.println("Demo:"+i);
}
}
class Thread2 extends Thread
{
Demo d;
Thread2(Demo d)
{
this.d=d;
}
public void run()
{
d.test();

}
}
class Thread3 extends Thread
{

R. P. BHALODIA - RAJKOT P a g e | 152


Demo d;
Thread3(Demo d)
{
this.d=d;
}
public void run()
{
d.test();

}
}

class Syn_example
{
public static void main(String arg[])
{
Demo d = new Demo();

Thread2 t2 = new Thread2(d);


Thread3 t3 = new Thread3(d);
t2.start();
t3.start();
}
}

Deadlock:-

When two thread have circular dependency on objects a major problem


arise.

This type of error is known as “deadlock”

In deadlock, one thread is waiting for other thread & the other thread is
waiting for the first thread.

Thus, both threads go in waiting (blocked) state & can not continue their
execution

Each class has a synchronized method & both by creating two different
thread objects.

R. P. BHALODIA - RAJKOT P a g e | 153


Each class has a synchronized method & both classes.
Objects access the synchronized method.
The result of deadlock is a blocked condition.
You have to press ctrl + c to come out from this blocked situation.
//example of deadlock
class A
{
synchronized void test1()
{
System.out.println("Start Test");
try
{
wait();
}
catch(InterruptedException ex)
{
System.out.println(ex);
}
System.out.println("End");
}
synchronized void release()
{
notify();
}
synchronized void releaseAll()
{
notifyAll();
}

}
class Thread1 extends Thread
{
A a1;
Thread1(A a1)
{
this.a1=a1;
}
public void run()
{
R. P. BHALODIA - RAJKOT P a g e | 154
a1.test1();
}
}
class Thread2 extends Thread
{
A a1;
Thread2(A a1)
{
this.a1=a1;
}
public void run()
{
a1.test1();
}
}
class DeadLoack
{
public static void main(String arg[])
{
A a1 = new A();
A a2 = new A();
Thread1 t1 = new Thread1(a2);
Thread1 t2 = new Thread1(a2);
t1.start();
t2.start();
try
{
Thread.sleep(10000);
}
catch(InterruptedException ex)
{
System.out.println(ex);
}
System.out.println("Releasing");
a1.releaseAll(); //a2.releaseAll();
}
}
Output:-
DeadLoack Releasing Deadloack Condition
Start Test Start Test

R. P. BHALODIA - RAJKOT P a g e | 155


Start Test Start Test
Releasing Releasing
End(execution will not got over) End
End

Daemon thread, Non-Daemon Thread


In Java, any thread can be a Daemon thread. Daemon threads are like a
service providers for other threads or objects running in the same process
as the daemon thread. Daemon threads are used for background supporting
tasks and are only needed while normal threads are executing.
If normal threads are not running and
remaining threads are daemon threads then the interpreter exits.
Daemons are used for background tasks that make sense only when there
are other threads that are doing the real work. The garbage collector is an
excellent example of a proper use of daemons. You can set the daemon
flag on or off as your program requires with thread.setDaemon(), but you
can only do this before you call start(). You cannot change the status
of a running thread. You can also check the status of a thread with
isDaemon(). You will probably never use daemons.
There are two methods of thread for daemon
(1) void setDaemon (Boolean daemon)
(2) boolean isDaemon()
class DaemonThread extends Thread
{
public void run()
{
System.out.println("Entering run method");
try
{
System.out.println("In run Method: currentThread()
is" + Thread.currentThread());
while (true)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException x)
{
R. P. BHALODIA - RAJKOT P a g e | 156
}
System.out.println("In run method: woke up
again");
}
}
catch(Exception e)
{
}
finally
{
System.out.println("Leaving run Method");
}
}
public static void main(String[] args)
{
System.out.println("Entering main Method");
DaemonThread t = new DaemonThread();
t.setDaemon(true);
t.start();
try
{
Thread.sleep(3000);
}
catch (InterruptedException x)
{
}
System.out.println("Leaving main method");
}
}

R. P. BHALODIA - RAJKOT P a g e | 157


Part-2
File Handling

R. P. BHALODIA - RAJKOT P a g e | 158


Stream and its types(Input,Output, Character, Byte)
 Java‟s stream-based I/O is built upon four abstract classes:
InputStream, OutputStream, Reader and Writer.
 Streams are the most important part in creating the applications like
Data Input from keyboard and output on the System Output Devices.
 Actually, until now we have used input and output streams in our
applications but we don‟t know explicitly that we are using streams.
 In java, for the Input / Output (IO) operations, we have two major
packages. One is the java.io package which was available from java
1.0 and then later from java 1.4 we get java.nio package (New IO
Package).
Remember that: the java.nio package is not a replacement of
the java.io package.
Both are different ways of performing IO operations. The java.io
package has classes and interfaces which help in file management and
stream-based IO, and the java.nio has classes and interfaces for the buffer-
based IO. Various important classes of java.io package are given in next
table.
The Java I/O Classes and Interfaces:
BufferedInputStream FileWriter PipedInputStream
BufferedOutputStrea FileInputStream PipedOutputStream
m
BufferReader FileOutputStream PipedReader
BufferedWriter FilterReader PipedWriter
ByteArrayInputStrea FilterWriter PrintStream
m
ByteArrayOutputStrea InputStream PrintWriter
m
CharArrayReader InputStreamReader PushbackInputStrea
m
CharArrayWriter LineNumberReader PushbaclReader
DataInputStream ObjectInputStream RandomAccessFile
DataOutputStream ObjectInputStream.GetFiel Reader
d
File ObjectOutputStream SequenceInputStrea
m
FileDescriptor ObjectOutputStream.PutFi SerializablePermissi
eld on
FileInputStream ObjectStreamClass StreamTokenizer

R. P. BHALODIA - RAJKOT P a g e | 159


FileOutputStream ObjectStreamField StringReader
FilePermission OutputStream StringWriter
FileReader OutputStreamWriter Writer

The Following interface are define by java.io


DataInput FileNameFilter ObjectOutput
DataOutput ObjectInput ObjectStreamConstants
Externalizable ObjectInputValidation Serializable
FileFilter

File and Random Access File Class


The File class is used to get the information of a file, such as the length of
file, its permissions, directory path etc.You can also create a directory ,
delete a file and directory using the File class. The File class has many
useful methods and
constants that can be used to get such kind of information about file. The
File class has following constructors.

1) File(String path)
2) File(String directoryPath,String filename)
3) File(File obj,String filename)

The Methods defined by the File class are given below.

1) String getName()
it returns the name of the file.
2) String getParent()
it returns the name of the parent Directory.
3) String getPath()
it returns the path of the file.
4) boolean canRead()
It returns true if the file exists and can be read,else returns false.
5) boolean canWrite()
It returns true if the file exists and can be Written,else returns
false.
//Demonstrate File
import java.io.File;
class FileDemo
R. P. BHALODIA - RAJKOT P a g e | 160
{
static void p(String s)
{
System.out.println(s);
}
}

class FileDemoMain
{
public static void main(String args[])
{
File f1 = new
File("D:/RPBC/MRK_Java/Practicle/CH_3/Part-2/");
FileDemo.p("File Name :"+f1.getName());
FileDemo.p("Path :"+f1.getPath());
FileDemo.p("Abs Path :"+f1.getAbsolutePath());
FileDemo.p("Parent :"+f1.getParent());
FileDemo.p(f1.exists()?"exists":"is not exists");
FileDemo.p(f1.canWrite()?"is writeable":"is not
writeable");
FileDemo.p(f1.canRead()?"is readable":"is not readable");
FileDemo.p("is"+(f1.isDirectory() ? "Yes": "not" + "a
directory"));
FileDemo.p(f1.isAbsolute() ? "is normal file":"moght name
piped");
FileDemo.p("File last modified
:"+f1.lastModified());
FileDemo.p("File Size :"+f1.length() +"size");
}
}

RandomAccessFile:
RandomAccessFile class is used to read and write data from a file
randomly.
This class is not a subclass of InputStream or OutputStream but it is
directly the subclass of Object class.This class implements DataInput and
DataOutput interfaces.
Its Constructors are:-

R. P. BHALODIA - RAJKOT P a g e | 161


RandomAccessFile(File obj,String mode) throws IOException
RandomAccessFile(String filename,String mode) throws IOException

Some Methods of RandomAccessFile class are :-

1) void seek(long numOfBytes) throws IOException


It positions the file pointer after the numOfBytes bytes.
Now the Reading or writing of bytes is Done from this location.
This method is the most important method of RandomAccessFile
as it allows random access to a file.
2) int read()
it reads and returns a byte from the input stream.
3) long getFilePointer()
It returns the current position of the file pointer.
4) long length()
it returns the length of the file in bytes.

import java.io.*;
class RandomAccessFileDemo
{
public static void main(String[] args)
{
try
{
// create a new RandomAccessFile with filename
test its automatic creating
RandomAccessFile raf = new
RandomAccessFile("D:/RPBC/MRK_Java/Practicle/CH_3/Part-2/test.txt",
"rw");

// write something in the file


raf.writeUTF("Hello World");

// set the file pointer at 0 position


raf.seek(0);

// read and print the contents of the file


System.out.println("" + raf.readUTF());

R. P. BHALODIA - RAJKOT P a g e | 162


// close the strea and release resources
System.out.println("Closing Stream...");
// set the file pointer at 4rth position
raf.seek(4);

// read the first byte and print it


System.out.println("" + raf.read());
raf.close();
System.out.println("Stream Closed.");
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}

Reading and Writing Through Byte Stream Classes


The byte stream classes provide a rich environment for handling byte-
oriented I/O. A stream can be used with any type of object, including
binary data. This versatility makes byte streams important to many types
of programs. Since the byte stream classes are topped by InputStream
and OutputStream, our discussion will begin with them

InputStream
InputStream is an abstract class that defines java‟s model of streaming
byte input. All of the method in this class will throw an IOException on
error condition.
Methods Defined by InputStream
Method Description
Int available() Return the number of bytes of input
currently
Void close() Closes the input source. Further read
attempts will generate an IOException
Void mark(int numBytes) Places mark at the current point in the
input stream that will remain valid until
numBytes bytes are read.
Boolean markSupported() Return true if mark()/reset() are supported
by the invoking stream
Int read() Returns an integer representation of the
R. P. BHALODIA - RAJKOT P a g e | 163
available byte of input. -1 is return when
the end of the file is encountered.
Int read(byte buffer[]) Attempts to read up to buffer.length bytes
into buffer and returns the actual number
of bytes that were successfully read. -1 is
returned when the end of the file is
encountered
Int read(byte buffer[], int Attempts to read up to numbytes bytes
offset, int numByte) into buffer starting at buffer, returing the
number of bytes successfully read. -1 is
returned when the end of file is
encountered
Void reset() Resets the input pointer to the previously
Long skip(long numBytes) Ignor(that is,skips) numBytes bytes of
input, returning the number of byte
actually ignored.

R. P. BHALODIA - RAJKOT P a g e | 164


OutputStream
OutputStream is an abstract class that deinfes streaming byte output. All
of the method in the class return a void value and throw an IOException
in the case of error. Table shows the method in OutputStream.

Methods Defined by OutputStream


Method Description
void close() Closes the output stream. Further
write attempts will generate an
IOException
void flush() Finalizes the output state so that any
buffers are cleared. That is, it
flushes the output buffers.
Void write(int b) write a single byte to an output
stream. Note that the parameter is an
int, which allows you to call write()
with expressions without having to
cast them.
void write(byte buffer[]) writes a complete array of bytes to
an output stream.
void write(byte buffer[], int offset, writes a sub range of name
int numBytes) nameBytes bytes from the array
buffer, beginning at buffer[offset]/

FileInputStream
The FileInputStream class creates an InputStream that can use to read
bytes from a file.
It two most common constructors are shown here:
FileInputStream(String filepath)
FileInputStream(File fileObject)
Either can throw a FileNotFoundExcetpion. Here, filepath is the fill path
name of a file, and fileObj is a File object that describes the file.
The following example creates two FileInputStream that use the same
disk file and each of the two constructors.
FileInputStream fis = new FileInputStream(“/autoexces.bat”);
File f = new File(“/autoexec.bat”);
FileInputStream f1 = new FileInputStream(f);

R. P. BHALODIA - RAJKOT P a g e | 165


Method Of FileInputStream
Method Description
int available() It is used to return the estimated number of bytes that
can be
read from the input stream.
int read() It is used to read the byte of data from the input
stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the
input stream.
int read(byte[] b, It is used to read up to len bytes of data from the input
int off, int len) stream.
long skip(long x) It is used to skip over and discards x bytes of data
from the input
stream.
FileChannel It is used to return the unique FileChannel object
getChannel() associated
with the file input stream.
FileDescriptor It is used to return the FileDescriptor object.
getFD()
protected void It is used to ensure that the close method is call when
finalize() there is
no more reference to the file input stream.
void close() It is used to closes the stream.

//Demonstrate FileInputStream.
import java.io.*;
class FileInputStreamEx
{
public static void main(String arg[])
{
try
{
File file = new File(arg[0]);
FileInputStream f = new FileInputStream(file);
System.out.println("The Contents of the file:");
int ch;
do
{
ch = f.read();
if(ch!=-1)
R. P. BHALODIA - RAJKOT P a g e | 166
System.out.print((char)ch);
}while(ch!=-1);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("File not Found");}
catch(FileNotFoundException e){
System.out.println("File not Found");}
catch(IOException e){
System.out.println("IO Exception Generated");
}
}
}

FileOutputStream
The FileOutputStream class create an OutputStream that you can use to
write bytes from a file. Its two most common constructors are show here:
FileOutputStream(String filePath);
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
They can throw a FileNotFoundException or a SecurityException. Here,
filePath is the fill path name of a file, and fileObj is a file object that
describes the file. If append is true, the file opened in append mode.
Creation of FileOutputStream is not dependent on the file already
existing. FileOutputStream will create the file before opening it for
output when you create the object. In the case where you attempt to open a
read-only file, an IOException will be thrown.
Method of FileOutputStream

Method Description
protected void finalize() It is sued to clean up the connection with the file
output stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte
array to the file output stream.
void write(byte[] ary, int It is used to write len bytes from the byte array
off, int len) starting at offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file
output stream.
FileChannel getChannel() It is used to return the file channel object
associated with the file output stream.
R. P. BHALODIA - RAJKOT P a g e | 167
FileDescriptor getFD() It is used to return the file descriptor associated
with the stream.
void close() It is used to closes the file output stream.

//Demonstrate FilOutputStream
import java.io.*;
class FileOutputStreamEx
{
public static void main(String arg[])
{
try{
FileOutputStream f = new
FileOutputStream("test.txt",true);
//Append Mode
byte buffer[]={97,98,99,100}; //ASCII values of a to d
f.write(buffer);

for(int i=65;i<=70;i++) //ASCII values of A to F


{ f.write(i);
}
f.close();
}
catch(IOException e)
{
System.out.println("IO exception Occurred");
}
System.out.println("Data Written in the file");
}
}

BufferedInputStream
Buffering I/O is a very common performance optimization. Java‟s
BufferedInputStream class allows to “wrap” any InputStream into a
buffered stream and achieve this performance improvement.
BufferedInputStream has two constructors:
BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize)

The first form creates a buffered stream using a default buffer size.
R. P. BHALODIA - RAJKOT P a g e | 168
In the second, the size of the buffer is passed in bufSize. Use of sizes that
are multiples of memory pages, disk block, and so on can have a
significant positive impact on performance.

//Use Buffered input


import java.io.*;
class BufferedInputStreamEx
{
public static void main(String arg[])
{
try
{
FileInputStream f = new
FileInputStream("test.txt");
BufferedInputStream b = new
BufferedInputStream(f);
System.out.println("the contents of the file");
int ch;
do
{
ch=b.read();
if(ch!=-1)
System.out.print((char)ch);
}while(ch!=-1);
}
catch(FileNotFoundException e)
{
System.out.println("File Not Found");
}
catch(IOException e)
{
System.out.println("IO Exception generated");
}

}
}

R. P. BHALODIA - RAJKOT P a g e | 169


BufferedOutputStream
A BufferedOutputStream is similer to any OutputStream with the
exception of added flush( ) method that is used to ensure that data buffers
are physically written to the actual output device.
Since the point of a BufferedOutputStream is to improve performance
by reducing the number of times the system actually writes data, you may
need to call flush( ) to cause any data that is in the buffer to get written.
Unlike buffered input, buffering output does not provide additional
functionality. Buffers for output in java are there to increase performance.
Here are the two available constructors.
BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int size)
The first form creates a buffered stream using a buffer of 512 bytes. In the
second form, the size of the buffer is passed in bufsize.

import java.io.*;
class BufferedOutputStreamDemo
{
public static void main(String args[])throws Exception
{
FileOutputStream fout=new
FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new
BufferedOutputStream(fout);
String s="Welcome to RPBC College.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
DataOutputStream
data output stream lets an application write primitive Java data types to an
output stream in a portable way. An application can then use a data input
stream to read the data back in.
Constructor and Description :
 DataOutputStream (OutputStream out) : Creates a new data
output stream to write data to the specified underlying output stream.

R. P. BHALODIA - RAJKOT P a g e | 170


Method of DataOutputStream
int size() It is used to return the number of bytes written
to the data output stream.
void write(int b) It is used to write the specified byte to the
underlying output stream.
void write(byte[] b, int off, It is used to write len bytes of data to the output
int len) stream.
void writeBoolean(boolean It is used to write Boolean to the output stream
v) as a 1-byte value.
void writeChar(int v) It is used to write char to the output stream as a
2-byte value.
void writeChars(String s) It is used to write string to the output stream as
a sequence of characters.
void writeByte(int v) It is used to write a byte to the output stream as
a 1-byte value.
void writeBytes(String s) It is used to write string to the output stream as
a sequence of bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream
using UTF-8 encoding in portable manner.
void flush() It is used to flushes the data output stream.

R. P. BHALODIA - RAJKOT P a g e | 171


import java.io.*;
public class DataOutputStreamDemo
{
public static void main(String[] args) throws IOException
{
FileOutputStream file = new
FileOutputStream("DataOutputStream.txt");
DataOutputStream data = new DataOutputStream(file);

for(int i=65;i<=96;i++)
{
data.writeInt(i);
}
data.flush();
data.close();
System.out.println("Succcess...");
}
}

DataInputStream
A data input stream enable an application read primitive Java data types
from an underlying input stream in a machine-independent way(instead of
raw bytes). That is why it is called DataInputStream – because it reads
data (numbers) instead of just bytes.

An application uses a data output stream to write data that can later be read
by a data input stream. Data input streams and data output streams
represent Unicode strings in a format that is a slight modification of UTF-
8.
DataInputStream is not necessarily safe for multithreaded access. Thread
safety is optional and is the responsibility of users of methods in this class.

Constructor:
DataInputStream(InputStream in) : Creates a DataInputStream that uses
the specified underlying InputStream.

R. P. BHALODIA - RAJKOT P a g e | 172


Method of DataInputStream
Method Description
int read(byte[] b) It is used to read the number of bytes from the
input stream.
int read(byte[] b, int off, int It is used to read len bytes of data from the input
len) stream.
int readInt() It is used to read input bytes and return an int
value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char
value.
double readDouble() It is used to read eight input bytes and returns a
double value.
boolean readBoolean() It is used to read one input byte and return true if
byte is non zero, false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input
stream.
String readUTF() It is used to read a string that has been encoded
using the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and
store them into the buffer array.
void readFully(byte[] b, int It is used to read len bytes from the input stream.
off, int len)

import java.io.*;
class DataOutputStreamEx
{
public static void main(String arg[])
{
try
{
FileOutputStream f = new
FileOutputStream("file4.txt");
DataOutputStream d = new DataOutputStream(f);
d.write(123);
d.writeBoolean(true);
d.writeUTF("Hello BCA 4 Students");
f.close();
}
R. P. BHALODIA - RAJKOT P a g e | 173
catch(IOException e)
{
System.out.println("IO Exception");
}
}
}
Second Program
import java.io.*;
//First Execute DataOutputStream class than after execute
DataInputStream class
class DataInputStreamEx
{
public static void main(String arg[])
{
try
{
FileInputStream f = new
FileInputStream("file4.txt");
DataInputStream d = new DataInputStream(f);
System.out.println("The Contents of File4 are");
System.out.println(d.read());
System.out.println(d.readBoolean());
System.out.println(d.readUTF());
f.close();
}
catch(IOException e)
{
System.out.println("IO Exception");
}
}
}

Reading and Writing through Character Stream classes


While the byte stream classes provide sufficient functionality to handle
any type of I/O operation, they cannot work directly with Unicode
characters.
Since one of the main purposes of java is to support the “write once, run
anywhere” philosophy, it was necessary to include direct I/O support for
character.

R. P. BHALODIA - RAJKOT P a g e | 174


In this section, several of the character I/O classes are discussed.
As explained earlier, at the top of the character stream hierarchies are the
Reader and Writer abstract classes. We will begin with them.

Reader
Reader is an abstract class that define Java‟s model of streaming
character input. All of the method in this class return an IOException on
error condition.

Writer
Writer is an abstract class that define streaming character output.
All of the methods in this class return a void value and through
IOException in the case of errors.

FileWriter
FileWriter creates a Writer that you can use to write to a file. Its most
commonly used constructors are shown here:
FileWriter(String filePath)
FileWriter(String filePath, booleanAppend)
FileWriter(File fileObj)
They can throw an IOException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file. If append is true,
then output is appended to the end of the file.
Creation of FileWriter is not depended on the file already existing.
FileWriter will create the file before opening if for output when you create
the object. In the case where you attempt to open a read-only file, an
IOException will be thrown.

R. P. BHALODIA - RAJKOT P a g e | 175


Method defined by Writer
Method Description
Abstract void close( ) Closes the output tream. Further write
attempt will generate an IOException.
Abstreact void flush( ) Finalizes the output state so that any
buffers are cleared. That is, it flushes the
output buffers.
Void write(int ch) Writes a single character to the invoking
output stream. Note that the parameter is
an int, which allows you to call write
with expressions without having to cast
them back to char.
Void write(char buffer[]) Writes a complete array of character to
the invoking output stream.
Abstreact void write(char Writes a subrange of numChars
buffer[], int offset, int characters from the array buffer,
numChars) beginning at biffer[offset] to the
invoking output stream.
Void write(String str) Writes str to the invoking output stream.
Void write(String str, int offset, Writes a subrange of numChars
int numChars) characters from the array str, beginning
at the specified offset.

FileReader
The FileReader class creates a Reader that you can use to read the
contents of file. Its two most commonly used constructors are shown here.
FileReader(String filePath)
FileReader(File fileObj)

The Methods Defined by Reader


Method Description
abstract void close( ) Closes the input source. Futher read
attempts will generate an IOException.
void mark(int numChars) places a mark at the current point in the
input stream that will remain valid until
numChars characters are read.
boolean makrSupported( ) returns true if mark()/reset() are supported
on this stream.
R. P. BHALODIA - RAJKOT P a g e | 176
int read( ) returns an integer representation of the next
available character from the invoking input
stream. -1 is returned when the end of the
file is encountered
int read(char buffer[ ] ) attempts to read up to buffer length
characters into buffer and returns the actual
number of characters that were successfully
read. -1 is returned when the end of the file
encountered.
abstract int read( char attempts to read up to numChars characters
buffer[ ], int offset, int into buffer starting at buffer[offset],
numChars) returning the number of characters
successfully read. -1 is returned when the
end of the file is encountered.
boolean ready( ) returns true if the next input request will not
wait. Otherwise, it return false.
void reset( ) resets the input pointer to the previously set
mark.
long skip(long numChars) skips over numChars characters of input,
returning the number of characters actually
skipped.
Either can throw a FileNotFoundException. Here, filePath is the Full path
name of a file, and fileObj is a File object that describes the file.

Buffered Character Stream


This section describes how you can buffer input and output for character
stream. The following classes are outline: BufferedWriter and
BufferedReader.
The advantage of buffering is that the number of reads and writes to a
physical device is reduced. This improves perforamce.

BufferedWriter
The BufferedWriter class extends Writer and buffers output to a
character stream. Its constructors are as follows:
BufferedWriter(Writer w)
BufferedWriter(Writer w, int bufSize)
The first form creates a buffered stream using a buffer with a default size.
In the second, the size of the buffers is specified by bufSize.

R. P. BHALODIA - RAJKOT P a g e | 177


This class implements all of the methods define by Writer. In addition, it
provides the newLine( ) method to output a line separator. Its signature is
shows below:
Void newLine( ) throws IOException
Example of BufferdWriter
//Demonstrate BufferdWrite
import java.io.*;
class BufferedWriterDemo
{
public static void main(String args[])
{
try
{
//Create a file write
FileWriter fw= new FileWriter(args[0]);

//Create strings buffered writer


BufferedWriter bwf = new BufferedWriter(fw);

//write a string to the file


for(int i =0; i<25;i++)
{
bwf.write("Line"+i+"\n");
}
bwf.close();
}
catch(Exception e)
{
System.out.println("The Exception:"+e);
}
}
}

Buffered Reader
The BufferedReader class extends Reader and buffered input form a
character stream. Its constructors are as follows:
BufferedReader(Reader r)
BufferedReader(Reader r, int bufSize)

R. P. BHALODIA - RAJKOT P a g e | 178


The first form creates a buffered stream using a buffer with a default size.
In the seconds, the size of the buffer specified by bufSize.
This class implements all of the functionality defined by Reader. In
addition, the readLine( ) methods reads new line-terminated strings from
a character stream. Its signature is
String readLine() throws IOException

Example of BufferedReader
//demonstrate Bufferd Reader
import java.io.*;
class BufferedReaderDemo
{
public static void main(String args[])
{
try{
//create a file reader
FileReader fr = new FileReader(args[0]);
//create a bufferd reader
BufferedReader bf = new BufferedReader(fr);

//read and display lines from file


String s;
while((s = bf.readLine()) != null)
{
System.out.println(s);
}
fr.close();
}
catch(Exception e){
System.out.println("The Exception :"+e);
}
}
}

StreamTokenizerClass
The StreamTokenizer class parses the data from a character input stream
and generates a sequence of tokens. Tokens is a group of character that
represent a number or word. This functionality can be very valuable if you
need to build parsers, compilers, or any program that processes character
input. A constructor for this class is as follows.

R. P. BHALODIA - RAJKOT P a g e | 179


StreamTokenizer(Reader r)
Here, r is a reader
The class defines four consants. TT_EOF menace end_of_file and
TT_EOL menace end-of-line conditions, respectively. TT_NUMBER
and TT_WORD indicate that a number of words have been read.
Three instance variables provide valuable information. If the current token
is a number, nval contains value and ttype equals TT_NUMBER. If the
current token is a string, sval contains its value and ttype equals
TT_WORD. Otherwise, ttytpe contains the character that has been read.
Method of StreamTokenizer class:
Method Description
void commentChar(int ch) Specified that the character argument starts
a single-line comment.
void eolIsSignificant(boolean This method determines whether or not
flag) ends of line are treated as tokens.
int lineno() This method returns the current line
number.
void This method determines whether or not
lowerCaseMode(boolean fl) word token are automatically lowercased.
int nextToken() This method parses the next token from the
input stream of this tokenizer.
void ordinaryChar(int ch) This method specifies that the character
argument is "ordinary" in this tokenizer.
void ordinaryChars(int low, This method specifies that all characters c
int hi) in the range low <= c <= high are
"ordinary" in this tokenizer.
void parseNumbers() This method specifies that numbers should
be parsed by this tokenizer.
void pushBack() This method causes the next call to the
nextToken method of this tokenizer to
return the current value in the ttype field,
and not to modify the value in the nval or
sval field.
void quoteChar(int ch) This method specifies that matching pairs
of this character delimit string constants in
this tokenizer.
void resetSyntax() This method resets this tokenizer's syntax
table so that all characters are "ordinary."
See the ordinaryChar method for more
information on a character being ordinary.
R. P. BHALODIA - RAJKOT P a g e | 180
void This method determines whether or not the
slashSlashComments(boolean tokenizer recognizes C++ style comments.
flag)
void This method determines whether or not the
slashStarComments(boolean tokenizer recognizes C style comments.
flag)
String toString() This method returns the string
representation of the current stream token
and the line number it occurs on.
void wordChars(int low, int This method specifies that all characters c
hi) in the range low <= c >= high are word
constituents.

Example:
//Streamtokenizer classpublic class STDemo
import java.io.*;
class StreamTokenizerDemo
{
public static void main(String args[]) throws IOException
{
//First Create the rpbc.txt file and write some contents..
FileReader freader = new FileReader("rpbc.txt");
StreamTokenizer st = new StreamTokenizer(freader);

double sum = 0;
int numWords = 0, numChars = 0;
while(st.nextToken() != st.TT_EOF)
{
if(st.ttype == StreamTokenizer.TT_NUMBER)
{
sum += st.nval;
}
else if(st.ttype == StreamTokenizer.TT_WORD)
{
numWords++;
numChars += st.sval.length();
}
}
System.out.println("Sum of total numbers in the file: " +
sum);
R. P. BHALODIA - RAJKOT P a g e | 181
System.out.println("Total words (does not include
numbers) in the file: " + numWords);
System.out.println("No. of characters available in words: "
+ numChars);
}
}

PipedStream
PipedInputStream and PipedOutputStream classes

The PipedInputStream and PipedOutputStream classes can be used to read


and write data simultaneously. Both streams are connected with each other
using the connect() method of the PipedOutputStream class.

PipedInputStream
The Java.io.PipedInputStream class is a piped input stream that can be
connected to a piped output stream, the piped input stream then provides
whatever data bytes are written to the piped output stream.Following are
the important points about PipedInputStream −
 The piped input stream contains a buffer, decoupling read operations
from write operations, within limits.
 Attempting to use both objects from a single thread is not
recommended, as it may deadlock the thread.
 A pipe is said to be broken if a thread that was providing data bytes
to the connected piped output stream is no longer alive.
Class constructors
Constructor & Description
PipedInputStream()
This creates a PipedInputStream so that it is not yet connected.

PipedInputStream(int pipeSize)
This creates a PipedInputStream so that it is not yet connected and uses the
specified pipe size for the pipe's buffer.

PipedInputStream(PipedOutputStream src)

R. P. BHALODIA - RAJKOT P a g e | 182


This creates a PipedInputStream so that it is connected to the piped output
stream src.

PipedInputStream(PipedOutputStream src, int pipeSize)


This creates a PipedInputStream so that it is connected to the piped output
stream src and uses the specified pipe size for the pipe's buffer.
Class methods
Method & Description
int available()
This method returns the number of bytes that can be read from this input
stream without blocking.
void close()
This method closes this piped input stream and releases any system resources
associated with the stream.
void connect(PipedOutputStream src)
This method causes this piped input stream to be connected to the piped
output stream src.
int read()
This method reads the next byte of data from this piped input stream.
int read(byte[] b, int off, int len)
This method reads up to len bytes of data from this piped input stream into an
array of bytes.
protected void receive(int b)
This method receives a byte of data.

PipedOutputStream
The Java.io.PipedOutputStream class is a piped output stream that can
be connected to a piped input stream to create a communications
pipe.Following are the important points about PipedOutputStream −
 The piped output stream is the sending end of the pipe.
 Attempting to use both objects from a single thread is not
recommended as it may deadlock the thread.

R. P. BHALODIA - RAJKOT P a g e | 183


 Data is written to a PipedOutputStream object by one thread and
data is read from the connected PipedInputStream by some other
thread.
 The pipe is said to be broken if a thread that was reading data bytes
from the connected piped input stream is no longer alive.
Class constructors
S.N. Constructor & Description

1 PipedOutputStream()
This creates a piped output stream that is not yet connected to a piped
input stream.
2 PipedOutputStream(PipedInputStream snk)
This creates a piped output stream connected to the specified piped
input stream.
Class methods
Method & Description

void close()
This method closes this piped output stream and releases any system
resources associated with this stream.

void connect(PipedInputStream snk)


This method connects this piped output stream to a receiver.
void flush()
This method flushes this output stream and forces any buffered output bytes to
be written out.
void write(byte[] b, int off, int len)
This method writes len bytes from the specified byte array starting at offset
off to this piped output stream.
void write(int b)
This method writes the specified byte to the piped output stream.

R. P. BHALODIA - RAJKOT P a g e | 184


import java.io.*;
class PipedWR
{
public static void main(String args[])throws Exception
{
final PipedOutputStream pout=new PipedOutputStream();
final PipedInputStream pin=new PipedInputStream();

pout.connect(pin);//connecting the streams

//creating one thread t1 which writes the data


Thread t1=new Thread()
{
public void run()
{
for(int i=65;i<=90;i++)
{
try
{
pout.write(i);
Thread.sleep(1000);
}
catch(Exception e)
{}
}
}
};

//creating another thread t2 which reads the data


Thread t2=new Thread()
{
public void run()
{
try
{
for(int i=65;i<=90;i++)
{

System.out.println(pin.read());
}

R. P. BHALODIA - RAJKOT P a g e | 185


}
catch(Exception e){}
}
};
//starting both threads
t1.start();
t2.start();
}
}

Serialization in Java

Serialization in java is a mechanism of writing the state of an object into


a byte stream.

It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization.

Advantage of Java Serialization

It is mainly used to travel object's state on the network (known as


marshaling).

java.io.Serializable interface

Serializable is a marker interface (has no data member and method). It is


used to "mark" java classes so that objects of these classes may get certain
capability. The Cloneable and Remote are also marker interfaces.

It must be implemented by the class whose object you want to persist.

R. P. BHALODIA - RAJKOT P a g e | 186


The String class and all the wrapper classes
implements java.io.Serializable interface by default.

//Object Outputstream class

import java.io.Serializable;

public class Student implements Serializable

int id;

String name;

public Student(int id, String name)

this.id = id;

this.name = name;

ObjectOutputStream
ObjectOutputStream class

The ObjectOutputStream class is used to write primitive data types and


Java objects to an OutputStream. Only objects that support the
java.io.Serializable interface can be written to streams.

Constructor
1) public ObjectOutputStream(OutputStream out) throws IOException {}

creates an ObjectOutputStream that writes to the specified OutputStream.


Important Methods
Method Description
1) public final void writes the specified object to the
writeObject(Object obj) throws ObjectOutputStream.

R. P. BHALODIA - RAJKOT P a g e | 187


IOException {}

2) public void flush() throws flushes the current output stream.


IOException {}
3) public void close() throws closes the current output stream.
IOException {}
import java.io.*;
class ObjectOututStreamDemo
{
public static void main(String args[])throws Exception
{
Student s1 =new Student(211,"ravi");
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);

out.writeObject(s1);
out.flush();
System.out.println("success");
}
}

Deserialization in java

Deserialization is the process of reconstructing the object from the


serialized state.It is the reverse operation of serialization.

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written


using an ObjectOutputStream.

Constructor
1) public creates an ObjectInputStream that
ObjectInputStream(InputStream in) reads from the specified
throws IOException {} InputStream.

R. P. BHALODIA - RAJKOT P a g e | 188


Important Methods
Method Description
1) public final Object readObject() reads an object from the input stream.
throws IOException,
ClassNotFoundException{}
2) public void close() throws closes ObjectInputStream.
IOException {}
import java.io.*;
class ObjectInputStreamDemo
{
public static void main(String args[])throws Exception
{

ObjectInputStream in=new ObjectInputStream(new


FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name);
in.close();
}
}

InputStreamReader
The Java.io.InputStreamReader class is a bridge from byte streams to
character streams.It reads bytes and decodes them into characters using a
specified charset.
Class constructors
Constructor & Description

InputStreamReader(InputStream in)
This creates an InputStreamReader that uses the default charset.

InputStreamReader(InputStream in, Charset cs)


This creates an InputStreamReader that uses the given charset.

R. P. BHALODIA - RAJKOT P a g e | 189


InputStreamReader(InputStream in, CharsetDecoder dec)
This creates an InputStreamReader that uses the given charset decoder.

InputStreamReader(InputStream in, String charsetName)


This creates an InputStreamReader that uses the named charset.
Class methods
Method & Description
void close()
This method closes the stream and releases any system resources associated
with it.
String getEncoding()
This method returns the name of the character encoding being used by this
stream.
int read()
This method reads a single character.
int read(char[] cbuf, int offset, int length)
This method reads characters into a portion of an array.
boolean ready()
This method tells whether this stream is ready to be read.
import java.io.*;
class InputStreamReaderEx
{
public static void main(String arg[])throws IOException
{
InputStreamReader i = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(i);
System.out.println("Enter the num 1:");
Double n1= new Double(b.readLine());
System.out.println("Enter the num2:");
Double n2= new Double(b.readLine());
double sum=n1+n2;
double mul=n1*n2;
System.out.println("The Sum is:="+sum);
System.out.println("The Multiplication is:="+mul);

R. P. BHALODIA - RAJKOT P a g e | 190


}
}
OutputStreamWriter
The Java.io.OutputStreamWriter class is a bridge from character
streams to byte streams. Characters written to it are encoded into bytes
using a specified charset.
Class constructors
S.N. Constructor & Description

1 OutputStreamWriter(OutputStream out)
This creates an OutputStreamWriter that uses the default character
encoding.
2 OutputStreamWriter(OutputStream out, Charset cs)
This creates an OutputStreamWriter that uses the given charset.
3 OutputStreamWriter(OutputStream out, CharsetEncoder enc)
This creates an OutputStreamWriter that uses the given charset
encoder.
4 OutputStreamWriter(OutputStream out, String charsetName)
This creates an OutputStreamWriter that uses the named charset.
Class methods
Method & Description

void close()

This method closes the stream, flushing it first.


void flush()
This method flushes the stream.
String getEncoding()
This method returns the name of the character encoding being used by this
stream.

R. P. BHALODIA - RAJKOT P a g e | 191


void write(char[] cbuf, int off, int len)
This method writes a portion of an array of characters.
void write(int c)
This method writes a single character.
void write(String str, int off, int len)
This method writes a portion of a string.

import java.io.*;
class OutputStreamWriterDemo
{
public static void main(String[] args)
{
char[] arr = {'H', 'e', 'l', 'l', 'o'};
try
{
// create a new OutputStreamWriter
OutputStream os = new FileOutputStream("test.txt");
OutputStreamWriter writer = new OutputStreamWriter(os);
// create a new FileInputStream to read what we write
FileInputStream in = new FileInputStream("test.txt");

// write something in the file


writer.write(arr, 0, 3);

// flush the stream


writer.flush();

// read what we write


for (int i = 0; i < 3; i++)
{
System.out.print("" + (char) in.read());
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}}
R. P. BHALODIA - RAJKOT P a g e | 192
UNIT – 4 APPLETS & LAYOUT MANAGERS

R. P. BHALODIA - RAJKOT P a g e | 193


Applet
Introduction to Applet
Applet is a special type of program that is embedded in the
webpage to generate the dynamic content. It runs inside the browser
and works at client side.
An applet is a program that can be reference by the HTML source
code of a web page. It is dynamically downloaded from a web server to a
browser. The applet then executes within the environment provided by the
browser. Alternatively we may use a tool such as the appletviewer to run
it.
Applets are created using the Applet class which is in java.applet
package.
To create an applet program, you must extend the applet class.
First Java Applet
As we are at the starting point of applets let‟s create our first applet and
understand it line by line.
//First Application of Applet
import java.applet.Applet;
import java.awt.Graphics;
/*<applet code="FirstApplet" width=200 height=200></applet>*/
pulibc class FirstApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("This is my first applet program!!!",20,100);
}
}

<html>
<head>
<title> My First Applet </title>
</head>
<body>
<applet code="FirstApplet" width=200 height=200>
</applet>
</body>
</html>
The first and second lines import the java.applet.Applet and
java.awt.Graphics classes. Remember that applet class is the super class of

R. P. BHALODIA - RAJKOT P a g e | 194


all Applets. The Graphics class is provided by the Abstract Window
Toolkit (AWT).
Next four lines define a Java comment. Within that comment is Hyper
Text Markup Language (HTML) source code. The applet tag specifies
which class contains the code for this applet. It also defines the width and
height in pixels of the display area. Remember that here the given
HTML is not a part of java code but it is just for the understanding of
appletviewer.
The next line declares our first applet which extends Applet. Each applet
that you create must extends this class.
Next a method called paint( ) is defined. This method is
responsible for generating the output of the applet. It accepts a Graphics
object as its one argument. The paint method is automatically invoked
whenever the applet needs to be displayed.
The actual output of the string is done by calling the drawString( )
method of the Graphics object. Its first argument is String to be displayed.
The second and third arguments are the x and y coordinates at which to
begin the string. Remember that here the top-left corner of the applet
is always the origin at 0, 0. The x coordinates increase as you move to
the right and the y coordinates increase as you move down.

 The Life Cycle of an Applet :-

We already know that a Java application begins execution at the


main( ) method of a class. However, an applet executes within an
environment provided by a web browser or a tool such as the appletviewer.
Therefore it does not have a main( ) method. Instead there are four
methods that are called during the life cycle of an applet. They are:
(1)init( )
The init( ) method is the first method to called. This is where you
should initialize variables. This method is called only once during the
run time of your applet.

(2)start( )
The start( ) method is called after init( ). It is also called to restart an
applet after it has been stopped. Where as init( ) is called once-the first
time an applet is loaded –start( ) is called each time an applet‟s HTML
document is displayed onscreen. So, if a user leaves a web page and
come back, the applet resumes execution at start( ).

R. P. BHALODIA - RAJKOT P a g e | 195


(3)stop( )
The stop( ) method is called when a web browser leaves the HTML
document containing the applet-when it goes to another pages, for
example.When stop( ) is called, the applet is probably running. You
should use stop( ) to suspend threads that don‟t need to run when the
applet is not visible. You can restart them when start() is called if the
user returns to the page.

(4)destroy( )
The destroy( ) method is called when the environment determine that
your applet needs to be removed completely from memory. At this
point, you should free up any resources the applet may be using. The
stop( ) method is always called before destroy( ).

import java.applet.Applet;
import java.awt.Graphics;

/*<applet code="AppletLifeCycle" width=300 height=50></applet>*/

public class AppletLifeCycle extends Applet


{
String str = "";
public void init()
{
str += "init;";
}
public void start()
{
str += "start;";
}
public void stop()
{
str += "stop;";
}
public void destroy()
{
System.out.println("destroy");
}

R. P. BHALODIA - RAJKOT P a g e | 196


public void paint(Graphics g)
{
g.drawString(str,10,25);
}
}

The Graphics Class


The graphics object encapsulates a set of methods that can perform
graphics output. Specifically, it allows you to draw lines, ovals,
rectangles, strings, images, characters and arcs.
Method Usage
void drawArc(int x, int y, int w, Draws an arc between deg0 and deg1.The
int h, int deg0, int deg1) center of the arc is the center of a rectangle
with upper-left corner at coordinates x and y,
width w and height h. Remember that zero
degree is at position 3 pm on a watch. The
angle increases in a counterclockwise
direction.
void drawImage(Image img, int Draws the image img so its upper-left corner
x, int y) is at x, y
void drawLine(int x0, int y0, int Draws a line between x0, y0 and x1, y1.
x1, int y1)
void drawOval(int x, int y, int w, Draws an oval. The center of the shape is
int h) center of a rectangle with upper-left corner at
coordinates x and y, width w and height h.
void drawPolygon(int x[], int y[], Draws a polygon with n corners.The
int n) coordinates are given by the elements of x and
y. The first and last points are automatically
connected.
void drawPolyline(int x[], int y[], Draws a polyline with n corners. The
int n) coordinates are given by the elements of x and
y. The first and last points are not
automatically connected.
void drawRect(int x, int y, int w, Draws a rectangle with upper-left corner
int h) at coordinates x and y and width w, and
height h.
void drawString(String str, Draws str at location x, y.
int x, int y)

R. P. BHALODIA - RAJKOT P a g e | 197


void fillArc(int x, int y, int w, int Draws a filled arc with given
h, int deg0, int deg1) parameters – works same as drawArc method
void fillOval(int x, int y, int w, Draws a filled oval. Works same as
int h) drawOval method
void fillePolygon(int x[], int y[], Draws a filled polygon with n corners.
int n) Works same as drawPolygon method
void fillRect(int x, int y, int w, Draws a filled rectangle. Works same
int h) as drawRect method
Color getColor() Gets the color of the current object
Font getFont() Gets the font of the current object
FontMetrics getFontMetrics() Gets the font metrics of the current
object.

//Example of Graphic class


import java.applet.*;
import java.awt.*;
/*<applet code="GraphicClassDemo" height=550 width=550></applet>*/
public class GraphicClassDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Shape Example",10,20);
g.drawString("Line",10,40);
g.drawLine(120,40,220,40);
g.setColor(Color.blue);
g.drawString("Rectange",10,80);
g.drawRect(120,60,100,50);
g.setColor(Color.red);
g.drawString("Fill Rectange",10,140);
g.fillRect(120,120,100,50);
g.setColor(Color.red);
g.drawString("Ellipse",10,200);
g.drawOval(120,180,100,50);
g.setColor(Color.blue);
g.drawString(" Fill-Cicle",10,280);
g.fillOval(120,280,75,75);
g.setColor(Color.red);
g.drawString("Arc",10,370);
R. P. BHALODIA - RAJKOT P a g e | 198
g.drawArc(120,370,75,75,0,180);
g.setColor(Color.red);
g.drawString("Pentagon/Polygon",10,480);
int x[] = {170,220,220,120,120};
int y[] = {400,430,480,480,430};
g.drawPolygon(x,y,5);
showStatus("Shape Example");
}
}

Use of Colors
The java.awt.Color class is used to work with colors. Each instance of
this class represents a particular color. This section demonstrates how to
draw colored strings, lines and shapes in an applet. It is possible to fill a
shape such as an oval or rectangle with a color. This class has three
consturctors.
(1)Color(int red, int green, int blue)
(2)Color(int rgb)
(3)Color(float r, float g, float b)
Here red, green and blue are int values that range between 0 and 255
(inclusive). The argument rgb contains encoding of a color in which the
read, green and blue components are specified in bits 23 to 16, 15 to 8 and
7 to 0 respectively. Finally r,g and b are float values that range between
0.0 and 1.0f inclusive.
The Color class also defines several constants that represent specific
colors. These are black, blue, cyan, darkGray, gray, green, lightGray,
magenta, orange, pink, red, white and yellow.
Various methods of the class are as follows :
Method Usage
Color brighter() Returns the brighter version of the current color
object
Color darker() Returns the darker version of the current color
object
boolean equals(Object o) Returns true if the current object and obj represents
the same color value.
int getBlue() Returns the blue component of the current object

R. P. BHALODIA - RAJKOT P a g e | 199


int getGreen() Returns the green component of the current object
int getRGB() Retrns an int encoding of the current object
int getRed() Returns the red component of the current object.
//Applet using Color method
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
/*<applet code="BlueString" width=300 height=100></applet>*/
public class BlueString extends Applet
{
public void paint(Graphics g)
{ g.setColor(Color.blue);
g.drawString("Blue String",100,50);
}
}

//Color applet
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
/*
<applet code="colorApplet" width=200 height=200>
</applet>
*/
public class colorApplet extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawString("Welcome To Java In Blue",10,50);
g.fillRect(10,10,20,20);
g.setColor(Color.red);
g.fillOval(20,20,20,20);
}
}

R. P. BHALODIA - RAJKOT P a g e | 200


Displaying of Text
We already know that drawString() method of Graphics class is
used for displaying the text.
A font determines the size and appearance of characters in a string.
Information about a font is encapsulated by the java.awt.Font class. This
class has only one constructor :
Font (String name,int style, int ps)

Here the name identifies the font. The style may be constant like
BOLD, ITALIC or PLAIN. The ps will represent the point size of the
font.
After the font has been created we can use it in our graphics context. This
is possible by calling the setFont() method of the Graphics class as follows
:
void setFont(Font f)
Here f is the object of Font class. Now any string with that get the
output with drawString() will be displayed with that font.
The java.awt.FontMetrics class allows us to get several metrics about the
size of a font. In addition we can also determine the size of a string that is
displayed in that font. Remember that : All these values will be in
pixels. This class has one constructor :
FontMetrics(Font f)
Here f is the object of Font Class for which we need the metrics.

Various methods of the class are as follows:

Method Usage
int charWidth(char c) Returns the width of c
int getAscent() Returns the ascent (Value above the given
baseline)
int getDescent() Returns the descent (value below the given
baseline)
int getHeight() Returns the height
int getLeading() Returns the leading
int stringWidth(String str) Returns the width of str.

R. P. BHALODIA - RAJKOT P a g e | 201


import java.applet.*;
import java.awt.*;

/*<applet code="FontMetricsDemo" width=300 height=100></applet>*/


public class FontMetricsDemo extends Applet
{
public void paint(Graphics g)
{
//Draw baseline
int baseline = 100;
g.setColor(Color.lightGray);
g.drawLine(0,baseline,300,baseline);
//Draw String
Font fnt = new Font("Serif",Font.BOLD,36);
g.setFont(fnt);
g.setColor(Color.black);
g.drawString("Wxyz",5,baseline);
g.setColor(Color.lightGray);
}
}

Use of Applet Dimensions


Till now we have seen that how to display strings, lines and shapes
in an applet by using various methods of Graphics class. In all that
methods we explicitly specify the output position.
The main problem in that was when we resize the applet then our
output will become improper.
Now we will see that how we can do program in such a way that
even if our applet size goes changed then also the output remains same.
For example, if we want to display a circle at the center of an applet.
If the applet is resized, the circle remains positioned at its center.
The getSize() method is used to determine the size of an applet. It
has following form :
Dimension getSize()
A Dimension object is useful to manipulate the height and width.

R. P. BHALODIA - RAJKOT P a g e | 202


//use of getSize()
import java.applet.*;
import java.awt.*;

/*<applet code="Circle" width=300 height=500></applet>*/

public class Circle extends Applet


{
public void paint(Graphics g)
{
Dimension d = getSize();
int xc = d.width/2;//g.drawString();
int yc = d.height/2;
int radius = (int)((d.width < d.height)? 0.4 * d.width : 0.4 *
d.height);
g.drawOval(xc - radius, yc - radius, 2*radius, 2 * radius);
}
}

//Example of String
import java.applet.*;
import java.awt.*;

/*<applet code="CenterString" width=300 height=500></applet>*/

public class CenterString extends Applet


{
String s = "Welcome to RPBC, Rajkot- Annual Function-2019";
public void paint(Graphics g)
{
Font fnt = new Font("Monotype Corsiva",Font.BOLD,20);
g.setFont(fnt);
FontMetrics fm = g.getFontMetrics();
Dimension d = getSize();
int x = d.width/2 - fm.stringWidth(s)/2;
int y = d.height/2 - fm.getDescent();
g.drawString(s,x,y);
}
}

R. P. BHALODIA - RAJKOT P a g e | 203


Using Applet in A Web Page
It is also possible to embed an applet in a web page. You can then supply
the URL for that web page to browser and it presents the applet. The
complete syntax for an applet tag in HTML is shown in the following
listing.
<htm>
<applet
Codebase=url
Code = .class file name
Alt=text
Name = appname
Width=wpixel
Height=wpixel
<param name=param1 value=value1>
<param name=param2 value=value2>
</applet>
</html>

The Applet Class


All the applets extends the java.applet.Applet class. Here we see
the inheritance relationship among the superclasses of Applet
The figure shows the inheritance relationship among the superclass
of Applet. State and behavior are inherited from java.lang.Object,
java.awt.Component, java.awt.Container and java.awt.Panel.
The abstract Component class represents many of the different types
of elements that you can include in a graphical user interface. Some of
them are : buttons, choices, lists, scrollbars etc. There are more than 100
methods provided by this class but we take some of them as per our
requirements.
The abstact Container class is a component that may contain other
compoentns.

R. P. BHALODIA - RAJKOT P a g e | 204


Applet Hierarchy

Method of Component Class


Method Usage
Image createImage(int w, int h) Returns an image object of dimenstion
width and height
Font getFont() Returns the current font
FontMetrics getFontMetrics(Font f) Returns the font metrics of given font
Color getForeground() Returns the foreground color
Dimension getSize() Returns the size of the component
Public void paint(Graphics g) Paints the component on g
void repaint() Requests the JVM to schedule a call to
update()
void setBackground(Color c) Sets the background color with c
void setFont(Font f) Sets the font to f
void setForeground(Color c) Sets the foreground color with c
public void update(Graphics g) Fills the component with its
background color and calls paint()
Method Of Applet

R. P. BHALODIA - RAJKOT P a g e | 205


void distroy() Destroys the applet
AppletContext getAppletContext() Returns the Applet Context
Image getImage(URL u) Returns an image object for the image
at u
String getParameter(String pname) Returns the value of parameter pname

void init() Initializes the applet


void showStatus() Displyes str on the status line
void start() Starts this applet
void stop() Stops this applet

//Example of background and foreground color


import java.applet.*;
import java.awt.*;

/*<applet code="BackgroundForeground" width=300


height=500></applet>*/

public class BackgroundForeground extends Applet


{
String s = "Welcome to RPBC, Rajkot- Annual Function-2019";
public void paint(Graphics g)
{
setBackground(Color.yellow);
setForeground(Color.blue);
g.drawLine(0,0,200,200);
g.fillRect(100,40,50,50);

}
}

//using getParameter method


import java.applet.*;
import java.awt.*;
/*<applet code="AppletPerameter" width=300 height=300>

R. P. BHALODIA - RAJKOT P a g e | 206


<param name="background" value="0xffffff">
<param name="foreground" value="0x000000">
<param name="message" value="Wel-Come Applet Program">
</applet>*/
public class AppletPerameter extends Applet
{
public void paint(Graphics g)
{
String background = getParameter("background");
String foreground = getParameter("foreground");
String msg = getParameter("message");
setBackground(Color.decode(background));
setForeground(Color.decode(foreground));
Font fnt = getFont();
FontMetrics fm = getFontMetrics(fnt);
Dimension d = getSize();
int x = (d.width - fm.stringWidth(msg))/2;
int y = d.height/2;
g.drawString(msg,x,y);
}
}

Use of Images
We can display various images into our applet. For that we need to
use Image class. We also need to use getImage() method of applet class
which returns a java.awt.Image object.
(1)Image getImage(URL u)
(2)Image getImage(Url , String filename)
Here the first fom accepts one argument that is absolute URL to
identify the image resource. The second form uses two arguments, in
which first argument is URL to identify the base location from where the
image file can be downloaded and second is the name of that file.
The drawImage() method of Graphics class initiates the
downloading of an image and displayes subsets of the image data as it is
like :
boolean drawImage(Image img, int x, int y, ImageObserver io)
Here the img is reference to the Image object, the coordinates will
be decided by the x and y and the last parameter is an object of
ImageObserver interface (java.awt.image). We will use our applet itself as
a ImageObserver.

R. P. BHALODIA - RAJKOT P a g e | 207


ImageObserver interface (java.awt.image):
An asynchronous update interface for receiving notifications about
Image information as the Image is constructed.

import java.applet.*;
import java.awt.*;
/*<applet code="DrawImage" width=300 height=300>
<param name="file1" value="1.jpg"></applet>
*/
public class DrawImage extends Applet
{
Image img;
public void init()
{
img =
getImage(getDocumentBase(),getParameter("file1"));
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,this);
}
}

Use of Threads in Applets


In our earlier discussion we have seen the use of threads in simple
applications. Now we can use threads in applets to display some kind of
animation.
The most important thing that we have to remember here is
Threads must need to update the display after a particular period of time.
You cannot invoke the paint method directly to update the display.
The reason is that the JVM schedules a number of important tasks.
Updating a display is only one of these. Garbage collection, I / O
and thread management are others.
Therefore your applet must invoke the
repaint()(java.awt.component.repaint) method to request an update of
the applet display. When the JVM determines that it is appropriate to
perform this work at that time it will call the update() method.
The default implementation of the update() method will clears the
applet display with the background color and then invokes the paint().
//example of counter

R. P. BHALODIA - RAJKOT P a g e | 208


import java.applet.*;
import java.awt.*;

/*<applet code="Counter" width=300 height=300></applet>*/


public class Counter extends Applet implements Runnable
{
int counter;
Thread t;
public void init()
{
counter=0;
t = new Thread(this);
t.start();
}
public void run()
{
try
{
while(true)
{
repaint();
Thread.sleep(100);
++counter;
}
}
catch(Exception e)
{

}
}
public void paint(Graphics g)
{
g.setFont(new Font("Vladimir Script",Font.BOLD,36));
FontMetrics fm = g.getFontMetrics();
String str = " "+counter;
Dimension d = getSize();
int x = d.width/2 - fm.stringWidth(str)/2;
g.drawString(str,x,d.height/2);
}
}

R. P. BHALODIA - RAJKOT P a g e | 209


The Abstract Window Toolkit (AWT) And Layout

The abstract component class was


introduced in applets. This class is important from user point of view
because in each and every user interface we need to have component.

All the components that we have seen the previous figure are must be
added to the container of the applet. For that applet has provided a special
class called container. Various methods of the class are as follows:

Method Description
Component add(Component c) Adds c to the container and returns c
Void Registers cl to receive container events
addContainerListener(Contain
erListener cl)
Insets getInsets Returns the insets object for the container

R. P. BHALODIA - RAJKOT P a g e | 210


Void remove(Component c) Removes c from the container
Void Unregister cl to receive the container events
removeContainerListener(Con
tainerListener cl)
void Sets lm as the layout manager for the container
setLayout(LayoutManager lm)
Labels
A label is a string that appears on a graphical user interface. It can
be changed by your program but cannot be changed by the user. Labels
are very frequently used in programs. The most common example where
we find the labels is before the text field to inform the user about the input
that is expected. The constructors of the class are as follows :
(1)Label()
(2)Label(String str)
(3)Label(String str, int align)
Here, str is the text for the label. The argument align is a constant that
indicates if the label should be left justified, centered or right justified.
The constants LEFT, CENTER and RIGHT will be used to set the value of
the align. To get the information about the alignment we have two
methods
(1) int getAlignment()
(2) void setAlignment(int align)
The methods for reading and writing the text are as follows :
(1) String getText()
(2) void setText(String str)

import java.applet.*;
import java.awt.*;
/*<applet code="Labels" width=200 height=120>
</applet>*/
public class Labels extends Applet
{
public void init()
{
String str = "This is a very Long Label";
Label lbl1 = new Label(str, Label.LEFT);
add(lbl1);
Label lbl2 = new Label(str, Label.CENTER);

R. P. BHALODIA - RAJKOT P a g e | 211


add(lbl2);
Label lbl3 = new Label(str, Label.RIGHT);
add(lbl3);
}
}

Buttons
A Button is a component that simulates the appearance of a push
button on an electronic instrument. When the user clicks the mouse inside
its boundaries, the button changes appearance to provide feedback for the
user.
This class has two constructors are as follows
(1) Button()
(2) Button(String str)
Here the str is the text for the button.
Here str is the string to be used as a label for the button. We have to
implement java.awt.event.ActionListener interface which defines one
method i.e. actionPerformed which is as follows :
void actionPerformed(ActionEvent ae)
Here ae is the action event.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="Buttons" width=200 height=120>
</applet>*/
public class Buttons extends Applet implements ActionListener
{
Label lbl;
public void init()
{
Button btn1 = new Button("Apple");
btn1.addActionListener(this);
add(btn1);
Button btn2 = new Button("Mango");
btn2.addActionListener(this);
add(btn2);
Button btn3 = new Button("Orange");
btn3.addActionListener(this);
add(btn3);

R. P. BHALODIA - RAJKOT P a g e | 212


Button btn4 = new Button("Banana");
btn4.addActionListener(this);
add(btn4);
lbl = new Label();
add(lbl);
}
public void actionPerformed(ActionEvent ae)
{
lbl.setText(ae.getActionCommand());
}
}

Canvases
A canvas provides a rectangular area on which you can draw. This is
valuable because you can create graphs and other diagrams on the canvas
by using all the methods of Graphics class. This class has only one
constructor i.e. canvas()
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code="CanvasDemo" height=150 width=200></applet>*/

public class CanvasDemo extends Applet


{
Canvas c;
public void init()
{
c=new Canvas();
setBackground(Color.red);
setSize(50,90);
add(c);
}
}

CheckBoxes
A check box is a component that combines a label and a small box.
Depending on the state of the option represented by that checkbox. There
may be or may not be a check mark in the check box. The state of check

R. P. BHALODIA - RAJKOT P a g e | 213


box is changed by clicking the mouse on the box. This class has five
constructors as follows :
(1)Checkbox()
(2)Checkbox(String str)
(3)Checkbox(String str, boolean state)
(4)Checkbox(String str, boolean state, CheckboxGroup grp)
(5)Checkbox(String str, CheckboxGroup grp, boolean state)

Here the str is the text for the check box. If state is true, a check mark
appears in the box. Otherwise the box is cleared. The last two forms of
constructors uses a group of several checkboxes together. The parameter
grp is the reference of the checkbox group.
An item event is generated when the state of a checkbox changes.
For that following are the methods that we have to register
(1)void addItemListener(ItemListener il)
(2)void removedItemListener(ItemListener il)
We can read and write the state of checkbox by using the following
methods :
(1)boolean getState()
(2)void setState(boolean value)
here if the value is true, a check mark is placed inside the box.
Otherwise the box will be cleared.
We can read and write the label of checkbox via following
methods :
(1)String getLabel()
(2)void setLabel(String str)
import java.awt.*;
import java.applet.*;
/* <applet code="CheckboxDemo" width=200 height=150></applet>*/
public class CheckboxDemo extends Applet
{
public void init()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
add(new Checkbox("BCA"));
add(new Checkbox("BBA"));
add(new Checkbox("BCOM",null,true));

}
}

R. P. BHALODIA - RAJKOT P a g e | 214


CheckBox Groups
A CheckBox group is a set of check boxes. Only one of these may
be set at any time. If the user clicks on one element in a checkbox group,
that checkbox is set. Other members of the same group are automatically
cleared.
In otherwords, a checkbox with group is just like a radio button.
We may get the selected member from the group by calling
following method
Checkbox getSelectedCheckbox()
We may also set a particular checkbox in a group via the following method
void setSelectedCheckBox(Checkbox cb)
here cb is the checkbox to be set.
import java.applet.*;
import java.awt.*;
/*<applet code="ChechkBoxGroupDemo" width=200 height=120>
</applet>*/
public class ChechkBoxGroupDemo extends Applet
{
CheckboxGroup cbg = new CheckboxGroup();
public void init()
{
Checkbox c1 = new Checkbox("BCA");
c1.setCheckboxGroup(cbg);
c1.setState(false);
add(c1);
Checkbox c2 = new Checkbox("BBA",cbg,false);
add(c2);

Checkbox c3 = new Checkbox("BCOM",cbg,true);


add(c3);
}
}
Choice
A Choice is a component that provides a type of menu (Combo
Box). When user click on a choice, it displays all of the allowed
selections. When the user selects one of those items, the choice menu will
return into normal position and displays our selected choice.

R. P. BHALODIA - RAJKOT P a g e | 215


Choices are valuable because they need minimum amount of space
on our display area. This class has only one constructor i.e. Choice()
Method Description
void add(String str) Adds str as an item
void addItem(String str) Adds str as an item
void Register il to receive item events generated
addItemListener(ItemListener il) by this choice.
String getIndex(int i) Returns the string at index i in the choice
int getSelectedIndex() Returns the index of the selected item
String getSelectedItem() Returns the selected item
Object[] getSelectedObjects() Returns an array with one object,which is
the selected item.
void insert(String str, int i) Inserts str before the item at index i
void removeAll() Removes all the items from the choice
void Unregister il to receive item events.
removeItemListener(ItemListener
li)
void select(int i) Selects the item at index I
void select(String str) Select the item str.

import java.applet.*;
import java.awt.*;
/*<applet code="ChoiceDemo" width=200 height=120>
</applet>*/
public class ChoiceDemo extends Applet
{
public void init()
{
Choice c = new Choice();
c.addItem("BCA");
c.addItem("BBA");
c.addItem("BCOM");
add(c);
}
}
R. P. BHALODIA - RAJKOT P a g e | 216
Lists
List object can be constructed to show any number of choices in the
window. It also allows multiple selections.

Constructors:
1) List() : Select only one item at a time
2) List(int numRows) : number of entries in the list
3) List(int numRows, boolean multiselect) : it can be set as true or false. If
true user can select two or more items at a time.

Methods
1) void add(String name)
2) void add(String name, int index) : adds item at the specified index.
3) String getSelectedItem() : returns String containing the name of the
item.
4) int getSelectedIndex() : It returns the index of the item.
5) getSelectedItems() : returns an array containing the name of currently
selected items.
6) getSelectedIndexes() : returns an array containing the indexes of
currently selected items.
import java.awt.*;
import java.applet.*;
/*<applet code="ListDemo" width=200 height=150></applet>*/
public class ListDemo extends Applet
{
public void init()
{
List s=new List(5,true);
s.addItem("CDR");
s.addItem("CDRW");
s.addItem("DVD");
s.addItem("Pendrive");
s.addItem("FlopyDisk");
s.addItem("ROM");
add(s);
}
}

R. P. BHALODIA - RAJKOT P a g e | 217


Text Field

TextField is a class which implements a single line text area usually called
and edit control. We can enter strings to it and also edit the text using the
arrow key, cut ,copy, paste and mouse selections.

Constructors:
1) TextField() : Default text field.
2) TextField(int numChars) : specifies the number of characters it can
hold.
3) TextField(String str) : It initializes the textfield with the string specified.
4) TextField(String str, int numChars) : initializes a textfield and sets it
width.

Methods:
1) String getText() : to obtain the string currently in the textfield.
2) void setText(String str) : to set the text.
3) select() : you can select portion of text under program control.
4) getSelectedText() : to obtain the currently selected text.
5) setEditable() : allows you to control a textfield may be modified by the
user.
void setEditable(Boolean canEdit)
6) isEditable() : to deteremine whether it is editable or not.
Boolean isEditable()
7) setEchoChar() : to set echoing of character as they are typed.
void setEchoChar(char ch)
8) getEchoChar() : to retrieve the echochar
char getEchoChar()

import java.awt.*;
import java.applet.*;
/*<applet code="TextFieldDemo" width=400 height=400></applet>*/
public class TextFieldDemo extends Applet
{
public void init()
{
add(new Label("Enter Your Name:"));
add(new TextField("",45));
add(new Label("Enter Your Phone Number:"));
add(new TextField(12));

R. P. BHALODIA - RAJKOT P a g e | 218


add(new Label("Enter Your Password:"));
TextField t = new TextField(20);
t.setEchoCharacter('*');
add(t);
}
}

Text Area

It is a multi line editor by AWT.

Constructors:

1) TextArea() : default.
2) TextArea(int numlines, int numchars) : specifies the height and number
of characters.
3) TextArea(String str):sets the default string.
4) TextArea(String str, int numlines, int numchars):specifies width and
characters.
5) TextArea(String str, int numlines, int numchars,int sBars):specifies the
scroll bars that you want to control.

Possible values for sBars:


SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY

Methods:
1) getText()
2) setText()
3) getSelectedText()
4) select()
5) isEditable()
6) setEditable()
7) void append(String str):appends a string to the end of current text.
8) void insert(String str,int index):insert the string passed.
9) void replaceRange(String str,int startIndex,int endIndex):it replaces the
characters from the index specified.
//Demonstrate TextArea

R. P. BHALODIA - RAJKOT P a g e | 219


import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/*<applet code="TextAreaDemo" width=250 height=50></applet>*/

public class TextAreaDemo extends Applet


{
public void init()
{
String val =
"Javal SE 6 is the lastese version of the most \n"+
"widely-used computer language for internet
programming."+
"Building on a rich heritage, java have advanced both\n"+
"the art and science of computer language design.\n\n"+
"One of the reasons for java's ongoing success is its\n"+
"constant, steadly rate of evolution. Java has never stood"+
"repidly changing landscape of the networked world.\n"+
"Moreover, java has often led the way, charting the \n"+
"course for others to follow.";

TextArea txtArea = new TextArea(val,10,30);


add(txtArea);
}
}

Layout Managers
Layout means the arrangement of components within the container. In
other way we can say that placing the components at a particular position
within the container. The task of layouting the control is done
automatically by the Layout Manager.
 The Layout Mangers are used to arrange components in particular
manner.
 Layout Manager is an interface that is implemented by all the classes
of layout managers.
 The layout manager set by the SetLayout() method. If we don‟t use
this method then default layout manager is used.
 There are following classes that represents the layout managers:

R. P. BHALODIA - RAJKOT P a g e | 220


1)java.awt.BorderLayout
2)java.awt.FlowLayout
3)java.awt.GridLayout
4)java.awt.CardLayout
Layout Manager Classes
Layout Description Constants
Manager
Arranges components to the
NORTH, SOUTH, EAST,
top, bottom, left, right, and WEST, CENTER –
BorderLayout center of a positions in the container.
container.
It is used to arrange the LEFT, CENTER, RIGHT –
components in a line, one these tell it how to align the
FlowLayout after another (in a flow) components in
from left to right. each row.
Divide the container into GridLayout(int rows, int
equal-sized rectangles and columns) To specify the
GridLayout arrange each component into number of rows and columns
one of these cells. in the grid.
It manages the components CardLayout(int hgap, int
in such a vgap):
way that only one creates a card layout with the
CardLayout component is visible at a given horizontal and vertical
time. gap.

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.
 FlowLayout arranges swing component from left to right until there‟s
no more space available.
 Then it begins a new row below it and moves from left to right again.
 LEFT, CENTER, RIGHT – these tell it how to align the
components in each row.
 It can be used like FlowLayout.LEFT.

R. P. BHALODIA - RAJKOT P a g e | 221


Constructor of FlowLayout
Constructor Description
Create a flow layout with centered alignment and a
FlowLayout() default 5 unit
horizontal and vertical gap.
FlowLayout(int Create a flow layout with the given alignment and a
align) default 5 unit horizontal and vertical gap.
FlowLayout(int Create a flow layout with the given alignment and given
align, int horizontal and
hgap, int vgap) vertical gap.

Here, the align indicates how the components are aligned in a row.
The horizontal and vertical gap in pixels between will be set through hgap
and vgap
The FlowLayout class also defines three constants that can be used
as alignment i.e. LEFT, CENTER and RIGHT.
Methods
int getAlignment():-Gets the alignment for this layout.
int getHgap():-Gets the horizontal gap between components.
int getVgap():-Gets the vertical gap between components.
void layoutContainer(Container target):- Lays out the container.

import java.applet.*;
import java.awt.*;
/*
<applet code="FlowLayoutDemo" width=650 height=350>
</applet>
*/
public class FlowLayoutDemo extends Applet
{
public void init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT,50,50));
for(int i=0;i<20;i++)
{
if(i<9)
add(new Button("Button 0"+(i+1)));
R. P. BHALODIA - RAJKOT P a g e | 222
else
add(new Button("Button "+(i+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: NORTH,
SOUTH, EAST, WEST, CENTER.
 These constants are used like BorderLayout.NORTH.
 While adding the component these constants are used by using
following form of add() method. add (Component compObj,
Object region);

Constructors of BorderLayout

Constructor Description
BorderLayout() Creates a border layout with no gaps between the
components.
BorderLayout(int hgap, Creates a border layout with the given horizontal
int and vertical gaps
vgap) between the components.

R. P. BHALODIA - RAJKOT P a g e | 223


With BorderLayout class gives a different form of add method
used which is as follows :

void addLayoutComponent(Component comp, Object constraints)


Adds the specified component to the layout, using the specified constraint
object.
int getHgap()
Returns the horizontal gap between components.
float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
void removeLayoutComponent(Component comp)
Removes the specified component from this border layout.

import java.awt.*;
import java.applet.*;
/* <applet code="BorderLayoutDemo2" width=200
height=200></applet>*/

public class BorderLayoutDemo2 extends Applet


{
public void init()
{
setLayout(new BorderLayout());
add(new Button("one"),BorderLayout.NORTH);
add(new Button("Two"),BorderLayout.SOUTH);
add(new Button("Three"),BorderLayout.CENTER);
add(new Button("Four"),BorderLayout.EAST);
add(new Button("Five"),BorderLayout.WEST);

}
}

R. P. BHALODIA - RAJKOT P a g e | 224


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.
Constructors of CardLayout

Constructor Description
CardLayout() Creates a card layout with zero horizontal and
vertical gap.
CardLayout(int hgap, int Creates a card layout with the given horizontal and
vgap) vertical gap.
Methods of the CardLayout

Methods Description
void first(Container a) It is used to flip to the first card of the given
container.
void last(Container a) It is used to flip to the last card of the given
container.
void next(Container a) It is used to flip to the next card of the given
container.
void previous(Container It is used to flip to the previous card of the given
a) container.
void show(Container a,
String It is used to flip to the specified card with the given
cardName) name.
 „a‟ is a reference to the container (usually a panel) that holds the
cards, and cardName is the name of a card.

R. P. BHALODIA - RAJKOT P a g e | 225


import java.awt.*;
import java.applet.*;
/* <applet code="CardLayoutDemo" width=200 height=200></applet>*/
public class CardLayoutDemo extends Applet
{
Panel canvasCards = new Panel();
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
CardLayout cardDeck = new CardLayout();
public void init()
{
canvasCards.setLayout(cardDeck);
p1.setLayout(new BorderLayout());
p2.setLayout(new BorderLayout());
p3.setLayout(new BorderLayout());
Canvas c1 = new Canvas();
Canvas c2 = new Canvas();
Canvas c3 = new Canvas();
c1.setBackground(Color.black);
c2.setBackground(Color.red);
c3.setBackground(Color.green);
p1.add("Center",c1);
p2.add("Center",c2);
p3.add("Center",c3);
canvasCards.add("p1",p1);
canvasCards.add("p2",p2);
canvasCards.add("p3",p3);
setLayout(new BorderLayout());
add("Center",canvasCards);

}
public boolean mouseDown(Event event,int x,int y)
{
cardDeck.next(canvasCards);
return true;
}

R. P. BHALODIA - RAJKOT P a g e | 226


GridLayout
GrideLayout lays out components in a 2d grid. When you instantiate a
GridLayout, you define the number of rows and columns.

Constructors of GridLayout

Constructor Description
Creates a grid layout with one column per
GridLayout () component in a
row.
Creates a grid layout with the given rows and
GridLayout (int rows, columns but
int columns) no gaps between the components.
GridLayout (int rows, Creates a grid layout with the given rows and
int columns, int columns along
hgap, int vgap) with given horizontal and vertical gaps.
import java.awt.*;
import java.applet.*;
/* <applet code="GridLayoutDemo" width=200 height=200></applet>*/

public class GridLayoutDemo extends Applet


{
public void init()
{
setLayout(new GridLayout(3,2));
add(new Button("one"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
add(new Button("Six"));
}
}

R. P. BHALODIA - RAJKOT P a g e | 227


GridBagLayout with GridBagConstraints
The GridBagLayout is very flexible layout Manager. It is an extension of
GridLayout that provides
some more features than the GridLayout. In the GridLayout all the cells
have same height and width
which is not necessary in the GrideBagLayout. here,you can have cells of
arbitrary width and height.
This can be done by specifying constraints.To specify constraints you have
to create an object of
GridBagConstraints. Its Constructor is:

GridBagConstraints()

The Constructor for the GridBagLayout is:


GridBagLayout()

gridx and gridy: gridx specifies the horizontal position and the gridy
specifies the vertical position
of the component. The left most components have the gridx=0 and the
upper most components have the gridy=0
The default value is GridBagConstraints.RELATIVE which places the
component just right to the previously
added component for gridx and just below to the previously added
component for gridy.

GridBagConstraints defines several fields that you can set to govern the
size, placement and spacing of a component. These are shown in table.
Several are describe in greater detail in the following discussion.
Field Purpose
int anchor specifies the location of a component within a cell. The
default is GridBagConstraints.CENTER
int fill Specifies how a component is resized if the component is
small than its cell. Valid values are
GridBagConstraints.NONE,
GridBagConstraints.HORIZONTAL,
GridBagConstraints.VERTICAL,
GridBagConstraints.BOTH.
int specifies the height of component in terms of cells. The
R. P. BHALODIA - RAJKOT P a g e | 228
gridheight default is 1.
int specifies the width of component in terms of cells. The
gridwidth default is 1.
int gridx specifies the X coordinate of the cell to which the component
will be added. The default value is
GridBagConstraints.RELATIVE
int gridy specifies the Y coordinate of the cell to which the component
will be added. The default value is
GridBagConstraints.RELATIVE
Insets This field specifies the external padding of the component,
insets the minimum amount of space between the component and
the edges of its display area.
int ipadx Specific extra horizontal space that surrounds a component
within a cell. The default size 0.
int ipady Specific extra vertical space that surrounds a component
within a cell. The default size 0.
double Specific a weight value that determines the horizontal
weightx spacing between cells and the edge of the container that holds
them. The default value is 0.0. the greater the weight, the
more space that is allocated if all values are 0.0, extra space
is distributed evenly between the edges of the window.
double Specific a weight value that determines the vertical spacing
weighty between cells and the edge of the container that holds them.
The default value is 0.0. the greater the weight, the more
space that is allocated if all values are 0.0, extra space is
distributed evenly between the edges of the window.
GridBagConstraints also defines several static fields that contain standard
constraint values, such as GridBagConstraints.CENTER and
GridBagConstraints.VERTICAL.
When a component is smaller than its cell, you can use the anchor field to
specify where within the cell the component‟s top-left corner will be
located. There are three types of values that you can give to anchor.

GridBagConstraints.CENTER GridBagConstraints..SOUTH
GridBagConstraints.EAST GridBagConstraints.SOUTHEAST
GridBagConstraints.NORTH GridBagConstraints.SOUTHWEST
GridBagConstraints.NORTHEAST GridBagConstraints.WEST
GridBagConstraints.NORTHWEST

R. P. BHALODIA - RAJKOT P a g e | 229


import javax.swing.*;
import java.awt.*;
/* <applet code="GridBagLayoutEx" width=300 height=200></applet>*/
public class GridBagLayoutEx extends JApplet
{
JButton b1,b2,b3,b4,b5;
public void init()
{
Container pane =getContentPane();
pane.setLayout(new GridBagLayout());
GridBagConstraints con = new GridBagConstraints();
b1 = new JButton("Button1");
b2 = new JButton("Button2");
b3 = new JButton("Button3");
b4 = new JButton("Button4");
b5 = new JButton("Button5");
con.fill=GridBagConstraints.HORIZONTAL;
con.gridx=0; //First row
con.gridy=0; //First Column
con.weightx=0.5;
pane.add(b1,con);
con.gridx=1;//second column
con.gridy=0;//first row
pane.add(b2,con);
con.gridx=2;//Third column
con.gridy=0;//first row
pane.add(b3,con);
con.ipady=30;//this cell will be taller
con.gridwidth=3;//3 cell wide
con.weightx=0.0;
con.gridx=0;//First column
con.gridy=1;
pane.add(b4,con);
con.ipady=0;//reset the height
con.gridx=0;//First column
con.gridy=2;
con.gridwidth=3;//3 cell wide
pane.add(b5,con);
}
}

R. P. BHALODIA - RAJKOT P a g e | 230


Panels
Panel class is subclass of Container . Panel does not contain title
bar,menu bar or borde. It appears as a rectangular area in which other
components are arranged. A layout manager is associated with a panel and
determines the placement of those components. You can set the layout
manager that is used for a panel.
It is also possible to nest the panel within other panels. This can be
done because a Panel object is also a Component. Here we can use
different layout managers to arrange different areas of the display.

import java.applet.*;
import java.awt.*;
/*
<applet code="PanelDemo" width=200 height=300>
</applet>
*/
public class PanelDemo extends Applet
{
public void init()
{
setLayout(new BorderLayout());
Panel pn=new Panel();
Checkbox cb1=new Checkbox("Red",true);
pn.add(cb1);
Checkbox cb2=new Checkbox("Green",false);
pn.add(cb2);
Checkbox cb3=new Checkbox("Blue",false);
pn.add(cb3);
add(pn,"North");
Panel pc=new Panel();
pc.setLayout(new GridLayout(3,2));
for(int i=1;i<=6;i++)
pc.add(new Button("Button "+i));
add(pc,"Center");
Panel ps=new Panel();
Label l=new Label("This is the south panel");
ps.add(l);
add(ps,"South");
}
}

R. P. BHALODIA - RAJKOT P a g e | 231


Windows and Frames
The window class extends Container and provides a separate
window without a tile or menu bar. This class has two subclasses, Frame
and Dialog, that are commonly used in applets and windows based
applications.
This class has only one constructor i.e.
Window(Frame parent)

The Frame class extends Window and provids title and menu bar.
This is equivalent to what you have seen as a standard window in
graphical user interface. It has following constructors
(1) Frame()
(2) Frame(String title)
Here title is the string to be displayed in the title bar. We can also have
menubar with following methods
(1) MenuBar getMenuBar()
(2) void setMenuBar(MenuBar mb)
We may get and set the title with the help of following methods.
(1) String getTitle()
(2) void setTitle(String str)
here, str is the string that is used in the title bar of the frame.

import java.awt.*;
import java.awt.event.*;
public class FrameDemo extends Frame
{
public FrameDemo()
{
Button btn = new Button("RPBC");
add(btn);
setSize(250,300);
setTitle("BCA Sem4");
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String arg[])
{
FrameDemo d = new FrameDemo();

} }

R. P. BHALODIA - RAJKOT P a g e | 232


Menus and MenuBars
A Menu is a Component of AWT but it is Different from other
Components because it can‟t be added to ordinary container and laid out
by layout manager.
Menu can be added only to a Menu container. A top-level window can
have MenuBar, which displays a list of top-level Menu choice and each
choice is associated with a drop-down Menu.

Here, the MenuComponent class is the superclass of all other


classes:

.
The MenuBar class encapsulates the functionality of a menu bar. It has
this constructor : Menubar()

There is one method called add() which allows the Menu objectes to be
added to the menu bar.
Menu add(Menu m)
Here m is the Menu to be added to the MenuBar.

The Menu class encapsulates the functionality of a drop-down set of menu


items. Its constructor is :
Menu (String str)
Here str is the string to be displayd.

R. P. BHALODIA - RAJKOT P a g e | 233


In MenuItem also we have one method called add() to add MenuItems to
the menu
MenuItem add(MenuItem mi)
void add(String str)
Here mi is the MenuItem to be added to the menu and str is a string
to be added to the menu.

The MenuItem class encapsulates an item in a menu. Its constructor is


MenuItem(String str)
here str is the string to be displayed.

All the menu items will generate actions events when they are selected or
deselected for that we need to register ActionListener like :
void addActionListener(ActionListener al)
void removeActionListener(ActionListener al)
here al is the action listener.

We can also enable or disable any menuitem with the help of following
method
void setEnabled(boolean flag)
if the flag is true then menu item is enabled otherwise disabled.

The CheckBoxMenuItem class allows us to create Menu Item with


checkbox for that constructors are :
CheckboxMenuItem(String str)
CheckboxMenuItem(String str, boolean flag)
Here str is the string to be displayed for the checkbox menu item.
If flag is true, the item is checked otherwise not checked.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="MenubarDemo" width=200 height=200></applet>*/
public class MenubarDemo extends Applet
{
private Frame myFrame;
public void init()
{

R. P. BHALODIA - RAJKOT P a g e | 234


myFrame=new Frame();
myFrame.addWindowListener(new Terminator());
myFrame.setBounds(200,200,300,300);
//place MyMenubar at top of MyFrame
MenuBar myMenuBar =new MenuBar();
myFrame.setMenuBar(myMenuBar);

Menu fileMenu = new Menu("File");


myMenuBar.add(fileMenu);

Menu editMenu = new Menu("Edit");


myMenuBar.add(editMenu);

myFrame.setVisible(true);

}
public class Terminator extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
myFrame.dispose();
}
}

Event Handling

The Event Delegation Model


The main difference between application and applet is
applications provide console applications while Applets provides GUI. No
doubt this is the difference between applications and applets but the other
difference is GUI based programs are event-driven while applications are
not.
Our applets are also event-driven. That is the code to handle a
particular type of event is invoked only when such an event occurs.
The java runtime system notifies the applet about an event by
calling an event handler that has been supplied by the applet. Upon receipt
of the event, the applet handles the event and then returns control to the
run-time system.
R. P. BHALODIA - RAJKOT P a g e | 235
There are various ways in which an event-driven interface can be
defined, and the specific mechanism is determined by the event model.
Java Development Kit (JDK 1.1) introduces the delegation event model.
This model provides an efficient way for an event to be sent from a
source to one or more listeners. This model also provides a standard
mechanism for a source to generate an event and send it to a set of
listeners.

What is Event?
An event is an object that describes some state change in a source.
It can be generated when a person interacts with an element in a GUI. For
example, pressing a button, clicking the mouse, double clicking on a list
box entry, or closing a window.
A source generates events. It has mainly three responsibilities.
First, it must provide methods that allow listeners to register and
unregister for notifications about a specific type of event.
Second, it must generate the event.
And finally, it must send the event to all the registered listeners.
Sometimes it may happen that a source may generate several types of
events in that case multiple methods would be provided.
We can add / remove the listener in the following way :
(1)public void addTypeListner(TypeListner el)
(2)public void removeTypeListener(TypeListener el)
Here the type is the type of the event and el is the event listener.

What is The Listener?


The listener receives event notifications. It has three main
responsibilities. First, it must register to receive notifications about
specific events. It is possible by calling the appropriate registration
method of the source. Second it must implement an interface to receive
events of that type. And finally, it must unregister if it no longer wants to
receive those notifications.
The Event Delegation Model can be described through the
following figure.

R. P. BHALODIA - RAJKOT P a g e | 236


The Event Delegation Model

Various Event Classes


A set of classes are provided to represent the various types of
AWT events. Which can be summarized through the following figure.
The EventObject class extends Object and is a part of java.util
package. Its constructor is :
EventObject (Object src)
Here, src is the object that generates the events.

R. P. BHALODIA - RAJKOT P a g e | 237


Event Generated When
ActionEvent A Button is pressed, a list item is double-clicked, or a menu
item is selected
AdjustmentEvent A Scroll bar is manipulated

ComponentEvent A component is hidden, moved, resized or becomes visible

ContainerEvent A component is added to or removed from a container

FocusEvent A component gains or loses keyboard focus

InputEvent A mouse or key event occurs

ItemEvent A checkbox or list item is clicked, a choice selection is


made, or a checkable menu item is selected or deselected.
KeyEvent Input is received from the keyboard

MouseEvent The mouse is dragged or moved, clicked, pressed or


released. Also generated when the mouse enters or exists a
component
TextEvent The value of text area or text field is changed

WindowEvent A window is activated, closed, deactivated, deiconified,


iconified, open, or quit.

Event Listeners
The java.util.EventListener interface does not define any
constants or methods but exists only to identify those interfaces that
process events. All event listeners interface must extends this interface.
Various listeners for the various events are summarized in the following
table.
Remember that all the listeners are defined in java.awt.event
package.
Event Class Listener Interface

ActionEvent ActionListener
AdjustmentEvent AdjustmentListener

R. P. BHALODIA - RAJKOT P a g e | 238


ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

ItemEvent ItemListener
KeyEvent KeyListener

MouseEvent MouseListener, MouseMotionListener


TextEvent TextListener

WindowEvent WindowListener

Source of Events
Event Source Description
Button Generates action events when the button is
pressed.
Checkbox generates item events when the check box is
selected or deselected
Choice Generate item events when the choice is
changed
List Generate action when events an item is
double clicked; generate item events when an
item is selected or deselected.
Scrollbar generate adjustment events when the scroll
bar is manipulated.
text components generate text events when the user enters a
characters
Window generates window events when a window is
activated, close, deactivated, deiconified etc.

Event Class
ActionEvent
 AN ActionEvent is generated when a button is pressed, a list item is
double-clicked, or a menu item is selected.
 The ActionEvent class defines four interger constants that can be
used to identify any modifiers associated with an action event.
R. P. BHALODIA - RAJKOT P a g e | 239
ALT_MASK, CTRL_MASK, META_MASK and
SHIFT_MASK.
 In addition, there is an integer constant, ACTION_PERFORMED,
which can be used to identify action events.
 ActionEvent has these 2 constructors:
o ActionEvent(Object src, int type, String cmd)
o ActionEvent(Object src, int type String cmd, int modifiers)
 Here src is a reference to the object that generated this event. The
type of the event is specified by type, and its command string is
cmd. The argument modifiers indicates which modifier keys (ALT,
CTRL, META and/or SHIFT) were pressed when the event was
generated.
 Obtain command name for the invoking ActionEvent object by
using getActionCommand( ) method.
 The getModifiers( ) method returns a value that indicates which
modifiers key(ALT, CTRL, META, and/or SHIFT) were pressed
when the event was generated. Its form is shown here: int
getModifiers( )

AdjustmentEvent Class
The AdjustmentEvent is generated by a scroll bar. There are five of
adjustment events. The AdjustmentEvent class defines integer constants
that can be used to identify them. The constants and their meanings are
shown here
BLOCK_DECREMENT the user clicked inside the scroll bar to
decrease its value.
BLOCK_INCREMENT the user clicked inside the scroll bar to
increment its value.
TRACK the slider was dragged

UNIT_DECREMENT the button at the end of the scroll bar was


clicked to decrease its value.
UNIT_INCREMENT the button at the end of the scroll bar clicked
to increase its value.

Constructor of AdjustmentEvent: AdjustmentEvent(Adjustment src, int


id, int type, int data)

R. P. BHALODIA - RAJKOT P a g e | 240


Here, src is a reference to the object that generated this event. The id
specifies the event. The type of the adjustment is specified by type, and its
associated data is data.

Method of AdjustmentEvent
Adjustment getAdjustable( ) returns the object that generate the event.
int getAdjustmentType( ) returns one of the constant define by
AdjustmentEvent.
int getValue( ) the amount of the adjustment can be obtain.

ItemEvent
 An ItemEvent is generated when a check box or list item is clicked
or when a checkable menu item is selected or deselected.
 The integer Constants of ItemEvent:-
o DESELECTED:- The user deselect an item.
o SELECT:- the user select an item.
 In addition, ItemEvent defines one interger constant,
ITEM_STATE_CHANGED, which signifies a change of state.
ItemEvent constructor:
o ItemEvent(ItemSelectable src, int type, Object entry, int state)
 Here, src is a reference to the component that generated this event.
Method:
Object getItem()
Returns the item affected by the event.
ItemSelectable getItemSelectable()
(Interface) Returns the originator of the event.
int getStateChange()
Returns the type of state change (selected or
deselected).
String paramString()
Returns a parameter string identifying this item
event.

ComponentEvent Class
A componentEvent is generated when the resize, position or visibility of
component is changed. There are 4 types of component events.
The ComponentEvent class defines integer constants that can be used to
identify them. The constants and their meaning are shown here.

R. P. BHALODIA - RAJKOT P a g e | 241


COMPONENT_HIDDEN The Component was hidden
COMPONENT_MOVED The component was moved.
COMPONENT_RESIZED The component was resized.
COMPONENT_SHOWN the component became visible.

Constructor: ComponentEvent(Component src, int type)


Here, src is a reference to the object that generate this event. The type of
the event is specified by type.
ComponentEvent is the superclass either directly or indirectly of
ContainerEvent, FoucsEvent, KeyEvent, MouseEvent and WindowEvent.
Method:

Container getContainer( ) obtain reference to the container that


generated this event by using this method.
Component getChild( ) returns a reference to the component that was
added to or removed from the container
FocusEvent
 A FocusEvent is generated when a component gain or loses input
focus. These events are identified by the integer constants
FOCUS_GAINED AND FOCUS_LOST.
 FoucsEvent is a subclass of CompomentEvent and has these
constructors.
o FocusEvent(Comonent src, int type)
o FocusEvent(Component src, int type, Boolean temporary flag)
 Here, src is a reference to the component that generated this event.
The type fo the event is specified by type. The argument temporary
flag is set to true if the focus event is temporary. Otherwise is set to
false.
Method:
boolean isTemporary() - Identifies the focus change event as temporary.

MouseEvent
 There are 7 types of mouse events. The MouseEvent class defines
the following integer constants that can be used to identify them.
MOUSE_CLICKED The "mouse clicked" event.
MOUSE_DRAGGED The "mouse dragged" event.
MOUSE_ENTERED The "mouse entered" event.
MOUSE_EXITED The "mouse exited" event.
MOUSE_MOVED The "mouse moved" event.
R. P. BHALODIA - RAJKOT P a g e | 242
MOUSE_PRESSED The "mouse pressed" event.
MOUSE_RELEASED The "mouse released" event.
MouseEvent is a subclass of InputEvent and has this constructuor.
MouseEvent(Component src, int type, long when, int modifiers, int
x, int y, int clicks, boolean triggersPopup)
source - the Component that originated the event
id - the integer that identifies the event
when - a long int that gives the time the event occurred
modifiers - the modifier keys down during event (e.g. shift, ctrl, alt, meta)
Either extended _DOWN_MASK or old _MASK modifiers should be
used, but both models should not be mixed in one event. Use of the
extended modifiers is preferred.
x - the horizontal x coordinate for the mouse location
y - the vertical y coordinate for the mouse location
clickCount - the number of mouse clicks associated with event
popupTrigger - a boolean, true if this event is a trigger for a popup menu
Methods:
int getButton()
Returns which, if any, of the mouse buttons has changed
state.
int getClickCount()
Returns the number of mouse clicks associated with this
event.
int getX()
Returns the horizontal x position of the event relative to the
source component.
int getY()
Returns the vertical y position of the event relative to the
source component.
MouseWheelEvent
 An event which indicates that the mouse wheel was rotated in a
component.
 A wheel mouse is a mouse which has a wheel in place of the middle
button. This wheel can be rotated towards or away from the user.
Mouse wheels are most often used for scrolling, though other uses
are possible. The constant:
 WHEEL_BLOCK_SCROLL Constant representing scrolling by a
"block" (like scrolling with page-up, page-down keys)

R. P. BHALODIA - RAJKOT P a g e | 243


 WHEEL_UNIT_SCROLL Constant representing scrolling by
"units" (like scrolling with the arrow keys)
Methods
int getScrollAmount()
Returns the number of units that should be scrolled in response to
this event.
int getScrollType()
Returns the type of scrolling that should take place in response to
this event.
int getUnitsToScroll()
This is a convenience method to aid in the implementation
of the common-case MouseWheelListener - to scroll a ScrollPane
or JScrollPane by an amount which conforms to the platform
settings.
int getWheelRotation()
Returns the number of "clicks" the mouse wheel was
rotated.

TextEvent
 TextEvent which indicates that an object's text changed. This event
is generated by an object (such as a TextComponent) when its text
changes. The event is passed to every TextListener object which
registered to receive such events using the
component's addTextListener method. The constant is:
 TEXT_FIRST The first number in the range of ids used for text
events.
 TEXT_LAST The last number in the range of ids used for text
events.
 TEXT_VALUE_CHANGED This event id indicates that object's
text changed.
 TextEvent(Object source, int id) Constructs
a TextEvent object.
o source - the (TextComponent) object that originated the event
o id - an integer that identifies the event type

Methods
String paramString() Returns a parameter string identifying this text event.

R. P. BHALODIA - RAJKOT P a g e | 244


WindowEvent
 A event that indicates that a window has changed its status. This
event is generated by a Window object when it is opened, closed,
activated, deactivated, iconified, or deiconified, or when focus is
transferred into or out of the Window.
 The event is passed to every WindowListener object which
registered to receive such events using the
window's addWindowListener method. Each such listener object
gets this WindowEvent when the event occurs. The constant is :
WINDOW_ACTIVATED The window-activated event type.
WINDOW_CLOSED The window closed event.
WINDOW_CLOSING The "window is closing" event.
WINDOW_DEACTIVATED The window-deactivated event type.
WINDOW_DEICONIFIED The window deiconified event type.
Constructor:
WindowEvent(Window source,int id)
Constructs a WindowEvent object.
WindowEvent(Window source,int id,int oldState,int newState)
Constructs a WindowEvent object with the specified previous and
new window states.
WindowEvent(Window source,int id, Window opposite)
Constructs a WindowEvent object with the specified
opposite Window.
WindowEvent(Window source, int id, Window opposite, int oldState,
int newState)
Constructs a WindowEvent object.

Method:
int getNewState()
For WINDOW_STATE_CHANGED events returns the
new state of the window.
int getOldState()
For WINDOW_STATE_CHANGED events returns the
previous state of the window.
Window getOppositeWindow()
Returns the other Window involved in this focus or

R. P. BHALODIA - RAJKOT P a g e | 245


activation change.
Window getWindow()
Returns the originator of the event.
String paramString()
Returns a parameter string identifying this event.

ContainerEvent
A ContianerEvent is generated when a component is added to or removed
from a container.
There are two types of container events. The ContainerEvent class defines
int constants that can identify them; COMPONENT_ADDED and
COMPONENT_REMOVED. They indicate that a component has been
added to or remove from the container.
Constructor: ContainerEvent(Component src, int type, Component
comp)
Src: is reference to the container that generated this event.
Type: of the event is specified by type.
Comp: that has been added to or removed from the container is comp.
Method
Container getContainer( ) obtain a reference to the container that
generated this event by using.
Component getChild( ) returns to the component that was added to or
removed from the container.

InputEvent
The abstract class InputEvent is a subclass of CompoentEvent and is the
subclass for component input events.
Its subclass are KeyEvent and MouseEvent. The InputEvent class defines
that following 8 integer constants that can be used to obtain information
about any modification associated with this event:

ALT_MASK BUTTON2_MA META_MASK ALT_GRAPH_MASK


SK
BUTTON3_ SHIFT_MASK BUTTON1_MA CLRL_MASK
MASK SK

R. P. BHALODIA - RAJKOT P a g e | 246


This isAltDown( ), isAltGraphDown( ), isContorlDown( ), isMetaDown( )
and isShiftDown( ) methods test if these modifiers were pressed at the
time this event was generated. This all methods return a Boolean value.
KeyEvent
A KeyEvent is generated when keyboard input occurs. There are 3 types of
key events, which are identified by these integer constants:
KEY_PRESSED KEY_RELEASED KEY_TYPED
The first two events are generated when any key is pressed or released.
The last event occurs only when a character is generated. Remember, not
all key presses result in character. Like shift key press.
There are many other integer constants that are define by KeyEvent. For
example, VK_0 through VK_9 and VK_A through VK_Z define the
ASCII equivalents of the number and letters. Here are some others.

VK_ENTER VK_ESCAPE VK_CANCLE


VK_DOWN VK_LEFT VK_RIGHT
VK_PAGE_DOWN VK_PAGE_UP VK_SHIFT
VK_ALT VK_CONTROL VK_UP
The VK constants specify virtual key code and are independent of any
modifiers, such as control, shift or alt.
Constructors are:
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code,
char ch)
Src: is reference to the component that generated the event.
Type: of the event is specified by type.
When: the system time at which the key was pressed is passed in when.
Modifiers: argument indicates which modifiers were pressed when this key
event like VK_A etc.
Code: for KEY_TYPED events, code will contain VK_UNDEFINED.
Ch: the character equivalent is pressed in ch. If no valid charcter exists,
then ch contains CHAR_UNDEFINED.
Methods
Char getKeyChar
Int getKeyCode

R. P. BHALODIA - RAJKOT P a g e | 247


Listener Interface
ActionListerner
This interface defines the actionPerformed() method that is invoked an
action event occurs. Its general form is shown here:
Void actionPerformed(ActionEvent ae)

AdjustmentListner Interface
This interface defines the adjustmentValueChanged( ) method that is
invoked when an adjustment event occurs. Its general form is shown here

Void adjustmentValueChanged(AdjustmentEvent ae)

ComponentListner Interface
this interface defines four method that are invoked when a component is
resized, moved, show or hidden. Their general forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)

ContainerListner Interface
This interface two methods. When a component is added to a container,
componentAdded( ) is invoked. When a component is removed from a
container, componentRemoved() is invoked. Their general forms are show
here:
Void compoentAdded(ContainerEvent ce)
Void compoentRemoved(ContainerEvent ce)

FocusListner Interface
This interface defines 2 methoda. When a component obtains keyboard
focus, focusGained( ) is invoked. When a component loses keyboard
focus, focusLost( ) is called. Their general forms are shown here:
Void focusGained(FocusEvent fc)
Void focusLost(FocusEvent fc)

ItemListerner
This intrefece defines the itemStateChanged( ) method that is invoked
when the state of an item changes. Its general form is shown here:
Void itemStateChanged(ItemEvent ie)

R. P. BHALODIA - RAJKOT P a g e | 248


KeyListerner
This interface define 3 method. The keyPress( ) and keyReleased( )
methods are invoked when a key is pressed nad released, respectively. The
keyTyped( ) method is invoked when a character has been entered.
For example, if a user pressed and releases the A key, three events are
generated in sequence: key pressed, type, and released. If a presses and
releases the HOME key, two key events are generated in sewuence:key
pressed and released.
The general forms of these methods are shown here:
Void keyPressed(KeyEvent ke)
Void keyReleased(KeyEvent ke)
Void keyTyped(KeyEvent ke)

MouseListerner
This interface defines five method. If the mouse is pressed and released at
the same point, mouseClicked( ) is invoked. When the mouse enters a
component the mouseEntered( ) method is called. When it leaves,
mouseExited( ) is called. The mousePressed( ) and mouseReleased ( )
methods are invoked when the mouse is pressed and released, respectively.
The general forms of these methods are shown here:
Void mouseClicked(MouseEvent me)
Void mouseEntered(MouseEvent me)
Void mouseExited(MouseEvent me)
Void mousePressed(MouseEvent me)
Void mouseReleased(MouseEvent me)

MouseMotionListerner
This interface defines two methods. The mouseDragged( ) method is
called multiple times as the mouse is dragged. The mouseMoved ( )
method is called multiple times as the mouse is moved. Their general
forms are shown here:
Void mouseDragged(MouseEvent me)
Void mouseMoved(MouseEvent me)

MouseWheelListener Interface
This interface defines the mouseWheelMoved( ) method that is invoked
when the mouse wheel is moved. Its general forms are shown here:
Void mouseWheelMoved(MouseWheelEvent mw)

R. P. BHALODIA - RAJKOT P a g e | 249


TextListerner
This interface define the textChanged( ) method that is invoked when a
change occure in a text area or text field. Its general form is shown here.
Void textChanged(TextEvent te)

WindowFocusListener Interface
This interface define 2 methods:windowGainedFocus( ) and
windowLostFocus( ). These are called when a window gains or loses input
focus. Their general forms are shown here:
Void windowGainedFocus(WindowEvent we)
Void WindowLostFocus(WindowEvent we)

WindowListerner
This intereface defines 7 methods. The windowActivated( ) and
windowDeactivated( ) methods are invoked when a window is activated or
deactivated, respectively.
If a widow is iconified, the windowIconified( ) method called. When a
window is deiconified, the windowDeiconified( ) method is called.
When a window is opened or closed, the windowOpended( ) or
windowClosed( ) metod are called.
The window windowClosing( ) method is called when a window is being
closed. The general forms of these methods are
Void windowActivated(WindowEvent we)
Void windowDeactivated(WindowEvent we)
Void windowClose(WindowEvent we)
Void windowCloseing(WindowEvent we)
Void windowDeiconified(WindowEvent we)
Void windowIconified(WindowEvent we)
Void windowOpened(WindowEvent we)

Example of Mouse Event


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="MouseEvents" width=200 height=120>
</applet>*/
public class MouseEvents extends Applet implements MouseListener,
MouseMotionListener
{
public void init()

R. P. BHALODIA - RAJKOT P a g e | 250


{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
setBackground(Color.blue);
showStatus("Mouse Clicked");
repaint();
}
public void mouseEntered(MouseEvent me)
{
setBackground(Color.green);
showStatus("Mouse Enter");
repaint();
}
public void mouseExited(MouseEvent me)
{
setBackground(Color.red);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent me)
{
setBackground(Color.white);
showStatus("Mouse Pressed");
repaint();
}
public void mouseReleased(MouseEvent me)
{
setBackground(Color.yellow);
showStatus("Mouse Released");
repaint();
}
public void mouseDragged(MouseEvent me)
{
setBackground(Color.black);
showStatus("Dragging Mouse");
repaint();
}

R. P. BHALODIA - RAJKOT P a g e | 251


public void mouseMoved(MouseEvent me)
{
setBackground(Color.gray);
showStatus("Mouse Moved");
repaint();
}
}

//Another Program Key Event


//Demonstrate some virtual key code.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=KeyEventDemo height=500 width=500></applet>*/

public class KeyEventDemo extends Applet implements KeyListener


{
String msg = "";
int x =10, y=20; //output coordinates

public void init()


{
addKeyListener(this);
requestFocus();//request input focus
}

public void keyPressed(KeyEvent ke)


{
showStatus("Key Down");
int key = ke.getKeyCode();
switch(key)
{
case KeyEvent.VK_F1:
msg += "<F1>";
break;

case KeyEvent.VK_F2:
msg += "<F2>";
break;

R. P. BHALODIA - RAJKOT P a g e | 252


case KeyEvent.VK_F3:
msg += "<F3>";
break;

case KeyEvent.VK_PAGE_DOWN:
msg += "<Page Down>";
break;

case KeyEvent.VK_PAGE_UP:
msg += "<Page Up>";
break;

case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;

case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}

R. P. BHALODIA - RAJKOT P a g e | 253


Adapter Classes
In last example we have seen that the MouseListener interface
declares five methods. These are called when the mouse is clicked,
pressed or released. Mouse events also occur when the mouse enters or
exits a component.
The main problem here is it has to implement all the five methods
declared by that interface even though we don‟t require them. This is very
much inconvenient.
Adapter classes make it easy to deal with this situation. An adapter
class provides empty implementation of all methods in a particular listener
interface. It can be useful if you want to override only some of the
methods defined by the interface.
Various adapter classes for various listener interfaces are as
follows :
Adapter Class Listener Class

ComponentAdapter ComponentListener
ContainerAdapter ContainerListener

FocusAdapter FocusListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

WindowAdapter WindowsListener

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="MouseAdapterDemo" width=200 height=120>
</applet>*/
public class MouseAdapterDemo extends Applet
{
public void init()
{
setBackground(Color.green);

R. P. BHALODIA - RAJKOT P a g e | 254


addMouseListener(new MyMouseAdapter(this));
}
}

class MyMouseAdapter extends MouseAdapter


{
MouseAdapterDemo mad;
public MyMouseAdapter(MouseAdapterDemo mad)
{
this.mad = mad;
}
public void mousePressed(MouseEvent me)
{
mad.setBackground(Color.red);
mad.repaint();
}
public void mouseReleased(MouseEvent me)
{
mad.setBackground(Color.green);
mad.repaint();
}
}

Inner Classes
An inner class is defined within the scope of an expression
or another class. Therefore it has access to the variables and methods in
that scope.
We have already learned about the inner classes in previous unit
no. 2. Here we will see how we can use inner classes with adapter for
mouse events.
Here we will define the adapter class inside the main class.
When we compile the above file It will generate two .class files. These
are MouseInnerDemo.class and
MouseInnerDemo$MyMouseAdapter.class
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/*
<applet code="MouseInnerDemo" width=100 height=100></applet>

R. P. BHALODIA - RAJKOT P a g e | 255


*/
public class MouseInnerDemo extends Applet
{
public void init()
{
setBackground(Color.green);
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent me)
{
setBackground(Color.red);
repaint();
}
public void mouseReleased(MouseEvent me)
{
setBackground(Color.green);
repaint();
}
}
}

An anonymous inner class is an inner class that does not have a name.
Anonymous inner class will be declared generally inside the
method by using new keyword with the class.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="MouseAnonymousDemo" width=100
height=100></applet>
*/
public class MouseAnonymousDemo extends Applet
{
public void init()
{
setBackground(Color.green);
addMouseListener(new MouseAdapter()
{

R. P. BHALODIA - RAJKOT P a g e | 256


public void mousePressed(MouseEvent me)
{
setBackground(Color.red);
repaint();
}
public void mouseReleased(MouseEvent me)
{
setBackground(Color.green);
repaint();
}
});
}
}

R. P. BHALODIA - RAJKOT P a g e | 257


UNIT – 5 : GUI using SWING Event Handling

R. P. BHALODIA - RAJKOT P a g e | 258


Introduction
After learning AWT, lets now see what's Swing? Well, Swing is
important to develop Java programs with a graphical user interface (GUI).
Modern operating systems such as Microsoft‟s Windows, Apple‟s MacOS,
and the different Unix-based versions such as Linux or Solaris use a
graphical interface to communicate with the user. The communication
consists of information displayed by programs and actions and commands
issued by the user.

Swing is a new feature provided by the JFC(Java Foundation Classes) 1.1.


Swing extends AWT by supplying many more types of GUI
components,providing 100% pure java implementations of these
components,and gives the capability to change the appearnce and behavior
of these components on different platforms. The Swing components are
100% pure Java. This means that they don't depend on the native window
implementation to support them. Swing components are available and
consistent across all platforms.Swing Components do not use AWT
components. In Fact, all the traditional AWT components are re-
implemented as Swing components.

Swing Features:-
1) Light Weight:- Swing component are independent of native Operating
Systems API as swing API Controls are rendered mostly using pure
JAVA code instead of underlying operating system calls.
2) Rich Controls:- Swing provides a rich set of advanced controls like
Tree,TabbedPane,Slider colorpicker,table controls.

3) Highly Customizable:- Swing Controls can be customized in very easy


way as visual apperance is independent of internal representation.
4) Pluggable Look-and-feel:- SWING based GUI Application look and
feel can be change at run time based on available values.

R. P. BHALODIA - RAJKOT P a g e | 259


Difference Between AWT and Swing Components :-
AWT Swing

AWT stands for Abstract Swing is also called as JFC‟s (Java


windows toolkit. Foundation classes).

AWT components are called Swings are called light weight component
Heavyweight component. because swing components sits on the top
of AWT components and do the work.

AWT components require Swing components require javax.swing


java.awt package. package.

AWT components are Swing components are made in purely java


platform dependent. and they are platform independent.

This feature is not supported We can have different look and feel in
in AWT. Swing.

These feature is not available Swing has many advanced features like
in AWT. JTabel, Jtabbed pane which is not available
in AWT. Also. Swing components are
called "lightweight" because they do not
require a native OS object to implement
their functionality. JDialog and JFrame are
heavyweight, because they do have a peer.
So components like JButton, JTextArea,
etc., are lightweight because they do not
have an OS peer.

With AWT, you have 21 With Swing, you would have only one
"peers" (one for each control peer, the operating system's window
and one for the dialog itself). object. All of the buttons, entry fields, etc.
A "peer" is a widget provided are drawn by the Swing package on the
by the operating system, such drawing surface provided by the window
as a button object or an entry object. This is the reason that Swing has
field object. more code. It has to draw the button or
other control and implement its behavior

R. P. BHALODIA - RAJKOT P a g e | 260


instead of relying on the host operating
system to perform those functions.

AWT is a thin layer of code Swing is much larger. Swing also has very
on top of the OS. much richer functionality.

Using AWT, you have to Swing has them built in.


implement a lot of things
yourself.

AWT components are not Swing components are better in look and
very good in look and feel as feel as compared to AWT. See the button
compared to Swing in below image, its look is better than
components. See the button button created using AWT.
in below image, its look is
not good as button created
using Swing.

Components and Containers


Swing consist of two main items. Components and containers.
The term component is an independent visual control like push button or
text box. On other hand a container holds a group of components.
All the swing components derived from Jcomponent and
Jcontainer classes. Both of these classes are part of package javax.swing.

R. P. BHALODIA - RAJKOT P a g e | 261


JApplet JButton JCheckBox JCheckBoxMenuItem

JColorChooser JComboBox JComponent JDailog

JFileChooser JFrame JLabel JList

JMenu JMenuBar JMenuItem JOptionPane

JPanel JPasswordField JProgressBar JRadioButton

JScrollBar JSeprator JSlider JTable

JTextArea JTextField JToggleButton JToolBar

JToolTip JTree JWindow

Containers
 Swing defines 2 types of containers.
 The first are top-level containers: JFrame, JApplet, JWindow and
JDailog. These containers do not inherit JComponent.
 They do, however, inherit the AWT classes Component and
Container. Unlike Swing‟s other components, which are lightweight,
the top-level containers are heavyweight. This makes the top-level
containers a special case in the swing.
 As the name implies, a top-level container must be at the top of a
containment hierarchy. A top-level container is not contained within
any other container.
 Furthermore, every containment hierarchy must begin with the top-
level container. The one most commonly use for application is
JFrame.
 The second type of container supported by Swing are lightweight
container. Lightweight container do inherit JComponent.

R. P. BHALODIA - RAJKOT P a g e | 262


JFrame
The frame in java works like the main window where
your components (controls) are added to develop an
application. In the Java Swing, top-level windows are
represented by the JFrame class.
Constructor Description
JFrame() It constructs a new frame that is initially invisible.

JFrame(GraphicsConfiguration It creates a Frame in the specified GraphicsConfiguration


gc) of a screen device and a blank title.
JFrame(String title) It creates a new, initially invisible Frame with the
specified title.
JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen device.

Method:
protected void frameInit()
Called by the constructors to init the JFrame properly.
Graphics getGraphics()
Creates a graphics context for this component.
void remove(Component comp)
Removes the specified component from the container.
void setIconImage(Image image)
Sets the image to be displayed as the icon for this window.
void setLayout(LayoutManager manager)
Sets the LayoutManager.
void update(Graphics g)
Just calls paint(g).

import javax.swing.*;
public class JFrameDemo extends JFrame
{
public JFrameDemo()
{
JLabel hello = new JLabel("Hello RPBC");
getContentPane().add(hello,"Center");
setSize(200,200);
setTitle("JFrame Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

R. P. BHALODIA - RAJKOT P a g e | 263


setVisible(true);
}
public static void main(String arg[])
{
new JFrameDemo();
}
}

JPanel
The JPanel is a simplest container class. It provides space in which
an application can attach any other component. It inherits the
JComponents class.
It doesn't have title bar.
Constructor Description
JPanel() It is used to create a new JPanel with a double buffer and a flow
layout.
JPanel(boolean It is used to create a new JPanel with FlowLayout and the specified
isDoubleBuffered) buffering strategy.
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout manager.

Method
Method Description
AccessibleContext Gets the AccessibleContext associated with this
getAccessibleContext() JPanel.
PanelUI getUI() Returns the look and feel (L&F) object that
renders this component.
protected String paramString() Returns a string representation of this JPanel.
void setUI(PanelUI ui) Sets the look and feel (L&F) object that renders
this component.

import java.awt.*;
import javax.swing.*;
public class JPanelDemo
{
JPanelDemo()
{ JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);

R. P. BHALODIA - RAJKOT P a g e | 264


JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1);
panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new JPanelDemo();
}
}

JLabel
The object of JLabel class is a component for placing text in a
container. It is used to display a single line of read only text. The text can
be changed by an application but a user cannot edit it directly. It inherits
JComponent class.
Constructor Description
JLabel( ) Creates a JLabel instance with no image and with
an empty string for the title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified
image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,
horizontalAlignment) image, and horizontal alignment.
Methods:
Methods Description
String getText() It returns the text string that a label displays.
void setText(String It defines the single line of text this component will
text) display.

R. P. BHALODIA - RAJKOT P a g e | 265


void It sets the alignment of the label's contents along the X
setHorizontalAlignment axis.
(int alignment)
Icon getIcon() It returns the graphic image that the label displays.

int It returns the alignment of the label's contents along the


getHorizontalAlignment X axis.
()

import javax.swing.*;
import java.awt.*;
/*<applet code="JLabelDemo" width=200 height=200></applet>*/
public class JLabelDemo extends JApplet
{
public JLabelDemo()
{ setLayout(new GridLayout(3,1));
JLabel plainLabel = new JLabel("RPBC Rajkot");
add(plainLabel);
JLabel fanceyLabel = new JLabel("Fancy Big Label");
Font fancyFont = new Font("Serif",Font.BOLD |
Font.ITALIC,32);
fanceyLabel.setFont(fancyFont);
add(fanceyLabel);
}
}

JButton
JButton component will work same as AWT button. The main
difference is we can add Icons on the buttons as well as we can change the
text of button.
Constructors:
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.

R. P. BHALODIA - RAJKOT P a g e | 266


Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the
button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the
button.
void It is used to add the action listener to this
addActionListener(ActionListener a) object.

import javax.swing.*;
import java.awt.*;
/*<applet code="JButtonDemo" width=200 height=200></applet>*/
public class JButtonDemo extends JApplet
{
public JButtonDemo()
{
setLayout(new GridLayout(3,2));
JButton b1 = new JButton("Add");
JButton b2 = new JButton("OK");
add(b1);
add(b2);
}
public static void main(String arg[])
{
JButtonDemo b = new JButtonDemo();
b.setVisible(true);
}
}

R. P. BHALODIA - RAJKOT P a g e | 267


JRadioButton
The JRadioButton class is used to create a radio button. It is used to
choose one option from multiple options. It is widely used in exam
systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Constructors:
Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.
JRadioButton(String s, Creates a radio button with the specified text and
boolean selected) selected status.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/*<applet code="JRadioButtonDemo" width=200 height=200></applet>*/
public class JRadioButtonDemo extends JApplet
{
JRadioButton m,f;
ButtonGroup gender;
public void init()
{
Container pane=getContentPane();
pane.setLayout(new FlowLayout());
m=new JRadioButton("Male");
f=new JRadioButton("Female");
gender = new ButtonGroup();
gender.add(m);
gender.add(f);
pane.add(m);
pane.add(f);
}
}

R. P. BHALODIA - RAJKOT P a g e | 268


JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a CheckBox changes its state
from "on" to "off" or from "off" to "on ".It inherits JToggleButton class.
Constructors:
Constructor Description
JCheckBox() Creates an initially unselected check box button with
no text, no icon.

JChechBox(String s) Creates an initially unselected check box with text.


JCheckBox(String text, boolean Creates a check box with text and specifies whether or
selected) not it is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from


the Action supplied.

Methods:
Methods Description
AccessibleContext It is used to get the AccessibleContext
getAccessibleContext() associated with this JCheckBox.
protected String paramString() It returns a string representation of this
JCheckBox.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/*<applet code="JCheckboxDemo" width=200 height=200></applet>*/
public class JCheckboxDemo extends JApplet implements ItemListener
{
JLabel n1;
JTextField text;
JCheckBox bca,bba,bcom;
String str="";
public void init()
{
Container pane=getContentPane();
pane.setLayout(new FlowLayout());
n1=new JLabel("Qualification");
bca=new JCheckBox("BCA");
bba=new JCheckBox("BBA");
bcom=new JCheckBox("BCOM");
R. P. BHALODIA - RAJKOT P a g e | 269
text=new JTextField(15);
bca.addItemListener(this);
bba.addItemListener(this);
bcom.addItemListener(this);
pane.add(n1);
pane.add(bca);
pane.add(bba);
pane.add(bcom);
pane.add(text);
}
public void itemStateChanged(ItemEvent e)
{
JCheckBox cb=(JCheckBox)e.getItem();
if(cb.isSelected())
str=str+""+cb.getText();
text.setText(str);
}
}

JTextField
The object of a JTextField class is a text component that allows the
editing of a single line text. It inherits JTextComponent class.
Constructors:
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the
specified text.
JTextField(String text, int Creates a new TextField initialized with the
columns) specified text and columns.
JTextField(int columns) Creates a new empty TextField with the specified
number of columns.

R. P. BHALODIA - RAJKOT P a g e | 270


Methods:
Methods Description

void It is used to add the specified action listener to receive


addActionListener(ActionListener l) action events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that it


removeActionListener(ActionListener no longer receives action events from this textfield.
l)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="JTextDemo" width=200 height=200></applet>*/
public class JTextDemo extends JApplet implements ActionListener
{

JTextField name;
JLabel n1,n2;
public void init()
{
Container pane=getContentPane();
pane.setLayout(new FlowLayout());
name = new JTextField(10);
n1=new JLabel("Name:=",JLabel.LEFT);
n2=new JLabel();
pane.add(n1);
pane.add(name);
pane.add(n2);
name.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
n2.setText("The Name is:-"+e.getActionCommand());
}
}

R. P. BHALODIA - RAJKOT P a g e | 271


JTextArea :-

The object of a JTextArea class is a multi line region that displays


text. It allows the editing of multiple line text. It inherits JTextComponent
class.

Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text initially.
JTextArea(int row, int Creates a text area with the specified number of rows
column) and columns that displays no text initially.
JTextArea(String s, int Creates a text area with the specified number of rows
row, int column) and columns that displays specified text.

Methods Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int It is used to set specified number of columns.
cols)
void setFont(Font f) It is used to set the specified font.
void insert(String s, int It is used to insert the specified text on the specified
position) position.
void append(String s) It is used to append the given text to the end of the
document.

JPasswordField
The object of a JPasswordField class is a text component specialized
for password entry. It allows the editing of a single line of text. It inherits
JTextField class.

R. P. BHALODIA - RAJKOT P a g e | 272


Constructor Description
JPasswordField() Constructs a new JPasswordField, with a default
document, null starting text string, and 0 column
width.
JPasswordField(int Constructs a new empty JPasswordField with the
columns) specified number of columns.
JPasswordField(String Constructs a new JPasswordField initialized with the
text) specified text.
JPasswordField(String Construct a new JPasswordField initialized with the
text, int columns) specified text and columns.

Method:
Method Description
char[]getPassword() Returns the text contained in this
TextComponent.
String getText() Deprecated. As of Java 2 platform v1.2,
replaced by getPassword.
String getText(int offs, Deprecated. As of Java 2 platform v1.2,
int len) replaced by getPassword.
void setEchoChar(char c) Sets the echo character for this
JPasswordField.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/*<applet code="JPasswordDemo" width=200
height=200></applet>*/
public class JPasswordDemo extends JApplet implements
ActionListener
{
JLabel n1,n2,n3,n4;
JTextArea text;
JPasswordField pass;
public void init()
{
R. P. BHALODIA - RAJKOT P a g e | 273
Container pane=getContentPane();
pane.setLayout(new FlowLayout());
text=new JTextArea(3,15);
pass=new JPasswordField(10);
n1=new JLabel("Address");
n2=new JLabel("Password");
n3=new JLabel();
n4=new JLabel();
pane.add(n1);
pane.add(text);
pane.add(n2);
pane.add(pass);
pane.add(n3);
pane.add(n4);

pass.addActionListener(this);

}
public void actionPerformed(ActionEvent e)
{
JPasswordField p = (JPasswordField)e.getSource();
String password = new String(p.getPassword());
n4.setText("Your Password is:"+password);
n3.setText("Address:="+text.getText());
}
}

JScrollBar
The object of JScrollbar class is used to add horizontal and vertical
scrollbar. It is an implementation of a scrollbar. It inherits JComponent
class.
Commonly used Constructors:
Constructor Description
JScrollBar() Creates a vertical scrollbar with the initial values.
JScrollBar(int orientation) Creates a scrollbar with the specified orientation
and the initial values.
JScrollBar(int orientation, Creates a scrollbar with the specified orientation,
int value, int extent, int min, value, extent, minimum, and maximum.
int max)
R. P. BHALODIA - RAJKOT P a g e | 274
Methods:
Method Description
int getOrientation() Returns the component's orientation
(horizontal or vertical).
int getValue() Returns the scrollbar's value.
void setValue(int value) Sets the scrollbar's value.
void Adds an AdjustmentListener.
addAdjustmentListener(Adjustmen
tListener l)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="JScrollBarDemo" width=200 height=200></applet>*/
public class JScrollBarDemo extends JApplet implements
AdjustmentListener
{
int x=0,y=0;
JLabel n1,n2;
JScrollBar v,h;
public void init()
{
Container pane = getContentPane();
v=new JScrollBar(JScrollBar.VERTICAL,1,1,1,100);
h=new JScrollBar(JScrollBar.HORIZONTAL,1,1,1,100);
pane.setLayout(new FlowLayout());
n1=new JLabel();
n2 = new JLabel();
pane.add(v);
pane.add(h);
pane.add(n1);
pane.add(n2);
v.addAdjustmentListener(this);
h.addAdjustmentListener(this);

R. P. BHALODIA - RAJKOT P a g e | 275


public void adjustmentValueChanged(AdjustmentEvent e)
{
x=h.getValue();
y=v.getValue();
n1.setText("Horizontal:="+x);
n2.setText("Vertical:="+y);
}
}

JScrollPane

A JscrollPane is used to make scrollable view of a component. When


screen size is limited, we use a scroll pane to display a large component or
a component whose size can change dynamically.

Constructors
Constructor
JScrollPane()
JScrollPane(Component)
JScrollPane(int, int)
JScrollPane(Component, int, int)

import java.awt.*;
import javax.swing.*;
/*<applet code="JScrollDemo" width=200 height=200></applet> */
public class JScrollDemo extends JApplet
{
public void init()
{
Container pane = getContentPane();
ImageIcon i = new ImageIcon("Penguins.jpg");
JLabel n1 = new JLabel(i);
JScrollPane scroll = new JScrollPane(n1);
pane.add(scroll);
}
}

R. P. BHALODIA - RAJKOT P a g e | 276


JComoboBox
The object of Choice class is used to show popup menu of choices.
Choice selected by user is shown on the top of a menu. It inherits
JComponent class.
Constructors:
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in
the specified array.

JComboBox(Vector<?> Creates a JComboBox that contains the elements in


items) the specified Vector.

Methods:
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the
list.
void setEditable(boolean b) It is used to determine whether the
JComboBox is editable.
void addActionListener(ActionListener It is used to add the ActionListener.
a)
void addItemListener(ItemListener i) It is used to add the ItemListener.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/*<applet code="JComboBoxDemo" width=200
height=200></applet>*/
public class JComboBoxDemo extends JApplet
{
JLabel n1;
R. P. BHALODIA - RAJKOT P a g e | 277
JComboBox city;
public void init()
{
Container pane = getContentPane();
pane.setLayout(new FlowLayout());
city = new JComboBox();
city.addItem("Rajkot");
city.addItem("Baroda");
city.addItem("Ahmedabad");
pane.add(city);
}
}

JList
The object of JList class represents a list of text items. The list of text
items can be set up so that the user can choose either one item or multiple
items. It inherits JComponent class.
Constructors:
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
JList(ListModel<ary> Creates a JList that displays elements from the specified,
dataModel) non-null, model.

Methods:
Methods Description
Void addListSelectionListener It is used to add a listener to the list, to be notified
(ListSelectionListener listener) each time a change to the selection occurs.

int getSelectedIndex() It is used to return the smallest selected cell


index.

R. P. BHALODIA - RAJKOT P a g e | 278


ListModel getModel() It is used to return the data model that holds a list
of items displayed by the JList component.

void setListData(Object[] It is used to create a read-only ListModel from an


listData) array of objects.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="JListDemo" width=200 height=200></applet>*/
public class JListDemo extends JApplet
{

JList list;
String city[]={"Rajkot","Navsari","Surat"};
public void init()
{
Container pane = getContentPane();
pane.setLayout(new FlowLayout());
list=new JList(city);
pane.add(list);
}
}

JMenu,JMenuBar and JMenuItem:-

These classes provide funcationalities to create a menu bar which contains


menus. These menus in turn have menu items. The menu bar is created
using JMenuBar class, menu is created using JMenu class and the
JMenuItem creates menu Items.
To create a manu, follow the steps given below.
-> Create a JMenuBar Object.
-> Then set the menu bar using setMenuBar() method.
-> Create menu objects of JMenu class.
-> create menu item objects using JMenuItem class.
-> Add the menu items to the particular menus.
-> Add the menus to the menu bar.

R. P. BHALODIA - RAJKOT P a g e | 279


JMenuBar:-
The JMenuBar class creates a menu bar which contains the menus. Its
constructor is JMenuBar()

JMenu:-
The JMenu class is a Container of menus. Its Construcors are:-
JMenu()
JMenu(String name)
here , the name spacifies the caption of the menu.

JMenuItem :-
The JMenuItem class is used to create menu items. These menu items will
be added to the menu. The COnstructors of JMenuItem are :-
JMenuItem()
JMenuItem(String itemName)
JMenuItem(Icon icn)
JMenuItem(String itemName,Icon icn)

import javax.swing.*;
import java.awt.event.*;
public class MenuExample implements ActionListener
{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;

MenuExample()
{
f=new JFrame();
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);

R. P. BHALODIA - RAJKOT P a g e | 280


mb=new JMenuBar();
file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");

edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
mb.add(file);mb.add(edit);mb.add(help);
ta=new JTextArea();
ta.setBounds(5,5,360,320);
f.add(mb);f.add(ta);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args)
{
new MenuExample();
}
}

Layout Manager
BoxLayout:-
The BoxLayout is a general purpose layout manager which is an extension
of Flowlayout. It places the components on top of each other or places
them one after another in a row. Its Constructor is:-
BoxLayout(Container obj,int placement)
here, the obj is the object of a Container such as a panel and the placement
can be one of the following:

R. P. BHALODIA - RAJKOT P a g e | 281


BoxLayout.PAGE_AXIS: It places the components like a stack i.e. On
top of each other.
BoxLayout.LINE_AXIS: It places the components in a line, i.e. one after
another.

import java.awt.*;
import javax.swing.*;

public class BoxLayoutDemo extends Frame


{
Button btn[];
public BoxLayoutDemo()
{
btn = new Button[5];
for (int i = 0;i<5;i++)
{
btn[i] = new Button ("Button " + (i + 1));
add(btn[i]);
}
setLayout (new BoxLayout (this, BoxLayout.X_AXIS));
//X=PAGE Y=LINE
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
BoxLayoutDemo bLayout=new BoxLayoutDemo();
}
}

SpringLayout
A SpringLayout arranges the children of its associated container according
to a set of constraints.Constraints are nothing but horizontal and vertical
distance between two component edges. Every constrains are represented
by a SpringLayout.Constraint object.

Each child of a SpringLayout container, as well as the container itself, has


exactly one set of constraints associated with them.

R. P. BHALODIA - RAJKOT P a g e | 282


Each edge position is dependent on the position of the other edge. If a
constraint is added to create new edge than the previous binding is
discarded. SpringLayout doesn't automatically set the location of the
components it manages.

Nested Classes
Class Description

static class It is a Constraints object helps to govern


SpringLayout.Constraints component's size and position change in a container
that is controlled by SpringLayout

Fields
Field Description
static String BASELINE It specifies the baseline of a component.
static String EAST It specifies the right edge of a component's
bounding rectangle.
static String HEIGHT It specifies the height of a component's bounding
rectangle.
static String It specifies the horizontal center of a
HORIZONTAL_CENTER component's bounding rectangle.
static String NORTH It specifies the top edge of a component's
bounding rectangle.
static String SOUTH It specifies the bottom edge of a component's
bounding rectangle.
static String It specifies the vertical center of a component's
VERTICAL_CENTER bounding rectangle.
static String WEST It specifies the left edge of a component's
bounding rectangle.
static String WIDTH It specifies the width of a component's bounding
rectangle.

R. P. BHALODIA - RAJKOT P a g e | 283


import java.awt.*;
import javax.swing.*;
public class SpringLayoutExample
{
public static void main(String[] arguments)
{
// main window
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SpringLayoutExample
Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,200);
Container content = frame.getContentPane();
SpringLayout layout = new SpringLayout();
frame.setLayout(layout);
Component b1 = new JButton("Button 1");
Component b2 = new JButton("Button 2");
Component b3 = new JButton("Button 3");
Component b4 = new JButton("Button 4");
Component b5 = new JButton("Button 5");
frame.add(b1);
frame.add(b2);
frame.add(b3);
frame.add(b4);
frame.add(b5);
layout.putConstraint(SpringLayout.WEST, b1, 25,
SpringLayout.WEST, content);
layout.putConstraint(SpringLayout.NORTH, b1, 10,
SpringLayout.NORTH, content);

layout.putConstraint(SpringLayout.WEST, b2, 50,


SpringLayout.WEST, content);
layout.putConstraint(SpringLayout.NORTH, b2, 10,
SpringLayout.WEST, b1);
layout.putConstraint(SpringLayout.WEST, b3, 75,
SpringLayout.WEST, content);
layout.putConstraint(SpringLayout.NORTH, b3, 10,
SpringLayout.SOUTH, b2);

R. P. BHALODIA - RAJKOT P a g e | 284


layout.putConstraint(SpringLayout.WEST, b4, 15,
SpringLayout.EAST, b1);
layout.putConstraint(SpringLayout.NORTH, b4, 10,
SpringLayout.NORTH, content);

layout.putConstraint(SpringLayout.WEST, b5, 15,


SpringLayout.EAST, b1);
layout.putConstraint(SpringLayout.NORTH, b5, 100,
SpringLayout.SOUTH, b1);

frame.setVisible(true);
}
}

GroupLayout
GroupLayout groups its components and places them in a Container
hierarchically. The grouping is done by instances of the Group class.
Group is an abstract class and two concrete classes which implement
this Group class are SequentialGroup and ParallelGroup.
SequentialGroup positions its child sequentially one after another
where as ParallelGroup aligns its child on top of each other.
The GroupLayout class provides methods such as
createParallelGroup() and createSequentialGroup() to create groups.
GroupLayout treats each axis independently. That is, there is a group
representing the horizontal axis, and a group representing the vertical axis.
Each component must exists in both a horizontal and vertical group,
otherwise an IllegalStateException is thrown during layout, or when the
minimum, preferred or maximum size is requested.
Modifier Class Description
and Type
static class GroupLayout.Alignment Enumeration of the possible ways
ParallelGroup can align its children.
class GroupLayout.Group Group provides the basis for the two
types of operations supported by
GroupLayout: laying out components one
after another (SequentialGroup) or
aligned (ParallelGroup).

R. P. BHALODIA - RAJKOT P a g e | 285


class GroupLayout.ParallelGro It is a Group that aligns and sizes it's
up children.
class GroupLayout.SequentialG It is a Group that positions and sizes its
roup elements sequentially, one after another.

Fields
Modifier Field Description
and Type
static int DEFAULT_SIZE It indicates the size from the component or
gap should be used for a particular range
value.
static int PREFERRED_SIZE It indicates the preferred size from the
component or gap should be used for a
particular range value.

Constructors
GroupLayout(Container host) It creates a GroupLayout for the specified
Container.

import javax.swing.*;
import java.awt.*;
public class GroupDemo
{
public static void main(String[] args)
{
JFrame frm = new JFrame("Group-Layout");

frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPanel = frm.getContentPane();
GroupLayout groupLayout = new
GroupLayout(contentPanel);

contentPanel.setLayout(groupLayout);

JLabel clickMe = new JLabel("Click Here");


JButton button = new JButton("This Button");

groupLayout.setHorizontalGroup(groupLayout.createSequentialGr

R. P. BHALODIA - RAJKOT P a g e | 286


oup().addComponent(clickMe).addGap(10,20,100).addComponent(button)
);
groupLayout.setVerticalGroup(groupLayout.createParallelGroup(GroupLa
yout.Alignment.BASELINE).addComponent(clickMe).addComponent(but
ton));
frm.pack(); //The pack method packs the components
within the window based on the component‟s preferred sizes.
frm.setVisible(true);
}
}

No Layout Manager:
To absolute positioning components, passing null to the setLayout method
of a container.

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class NoLayoutDemo extends JFrame


{

public static void main(String[] args)


{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frm = new JFrame("NoLayout Test");

frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLayout(null);
JLabel lbl = new JLabel("First Name:");
lbl.setBounds(20, 20, 100, 20);
JTextField txtField = new JTextField();
txtField.setBounds(124, 25, 100, 20);
frm.add(lbl);
frm.add(txtField);
frm.setSize(300, 100);
frm.setVisible(true);
}
}

R. P. BHALODIA - RAJKOT P a g e | 287


JProgressBar :-

The JProgressBar class is used to display the progress of the task. It


inherits JComponent class.

Constructor Description

JProgressBar() It is used to create a horizontal progress bar but no


string text.
JProgressBar(int min, int It is used to create a horizontal progress bar with
max) the specified minimum and maximum value.
JProgressBar(int orient) It is used to create a progress bar with the specified
orientation, it can be either Vertical or Horizontal
by using SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
JProgressBar(int orient, It is used to create a progress bar with the specified
int min, int max) orientation, minimum and maximum value.
Commonly used Methods:

Method Description

void It is used to determine whether string should be


setStringPainted(boolean displayed.
b)
void setString(String s) It is used to set value to the progress string.

void setOrientation(int It is used to set the orientation, it may be either


orientation) vertical or horizontal by using
SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
void setValue(int value) It is used to set the current value on the progress
bar.

R. P. BHALODIA - RAJKOT P a g e | 288


JFileChooser :-
The object of JFileChooser class represents a dialog window from which
the user can select file. It inherits JComponent class.

Commonly used Constructors:


Constructor Description

JFileChooser() Constructs a JFileChooser pointing to the user's


default directory.
JFileChooser(File Constructs a JFileChooser using the given File as the
currentDirectory) path.
JFileChooser(String Constructs a JFileChooser using the given path.
currentDirectoryPath)

R. P. BHALODIA - RAJKOT P a g e | 289

You might also like