1 Java 289
1 Java 289
1 Java 289
RAJKOT – INDIA
CURRICULAM
FOR
B.C.A.
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.
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 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
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
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
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
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
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
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
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
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
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.
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
R. P. BHALODIA - RAJKOT P a g e | 28
• The interpreter parses and runs each Java instruction on the
computer.
• 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,
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
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
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.
Eclipse 3.0 (released on 21 June 2004) selected the OSGi Service Platform
specifications as the runtime architecture.
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 ()
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.
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 :
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.
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 :
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
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
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.
These operators are unique in that they can appear in prefix (++x) and
postfix (x++) form. For example:-
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 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)
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)
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)
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)
Program
class RightShift {
public static void main(String[] args) {
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
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.
1. Implicit casting
2. Explicit casting
This is done implicitly by the JVM. The lower size is widened to higher
size. This is also named as automatic type conversion.
Examples:
byte –> short –> int –> long –> float –> double
This is not done implicitly by the JVM and requires explicit casting; a
casting operation to be performed by the programmer.
R. P. BHALODIA - RAJKOT P a g e | 46
double x = 10.5; // 8 bytes
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.
Decision Statements
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;
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
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.
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.
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.
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
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];
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
or
int x = 5;
int y = 5;
R. P. BHALODIA - RAJKOT P a g e | 56
arr1[0][x] = "hello";
arr1[0][y] = "rpbc";
Jagged Array
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 );
}
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.
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]);
}
}
javac test1.java
java test1 hi hello bye
output
Argument 0: hi
Argument 1: hello
Argument 2: bye
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.
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();
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.
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.
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
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();
}
}
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);
}
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();
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.
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);
}
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,
// 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)
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);
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).
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);
}
}
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.
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:-
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:-
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);
}
}
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();
}
}
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. P. BHALODIA - RAJKOT P a g e | 89
r.callme();
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();
}
}
R. P. BHALODIA - RAJKOT P a g e | 91
}
}
FinalBlankVarialbeConstructor
{
speedlimit=70;
System.out.println(speedlimit);
}
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.
Abstract Class:-
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()
{
……
……
}
}
R. P. BHALODIA - RAJKOT P a g e | 95
interface Drawable
{
void draw();
}
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");
}
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:
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.
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.
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);
}
}
JAVA Packages
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.
static import can be defined and static member fields can not refere
any class name and use directly without classname.
It will always good idea to define for each static member(Math.E) instead
of all static members(Math.*) in static import declaration
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.
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.
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.
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.
import java.lang.*;
sb.delete(3, 7);
System.out.println("\n\nThe Use of Delete 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);
}
}
import java.util.*;
class RandomNumber
{
public static void main(String args[])
{
Random ran = new Random();
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).
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
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.
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);
for(int row=0;row<6;row++)
{
for(int col=0;col<7;col++)
{
if(dom
>MonthCalendar.dayInMonth[month] )
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.
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]);
}
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.
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.
Constructor Description
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
SortedSet<E> 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.
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.
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.
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.
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.
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.
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
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.
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.
}
}
Output:-
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.
}
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
{
}
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
{
}
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");
}
}
//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:-
Multithreading
1) It doesn't block the user because threads are independent and you can
perform multiple operations at same time.
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.
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[])
{
New
Runnable
Blocked
Waiting
Timed_Waiting
Terminated
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)
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);
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);
}
}
}
}
class Thread3 extends Thread
{
}
}
class Syn_example
{
public static void main(String arg[])
{
Demo d = new Demo();
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.
}
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
1) File(String path)
2) File(String directoryPath,String filename)
3) File(File obj,String filename)
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:-
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");
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.
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);
//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);
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.
}
}
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.
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.
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");
}
}
}
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.
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)
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.
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)
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);
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.
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
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)
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.
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.
System.out.println(pin.read());
}
Serialization in Java
java.io.Serializable interface
import java.io.Serializable;
int id;
String name;
this.id = id;
this.name = name;
ObjectOutputStream
ObjectOutputStream class
Constructor
1) public ObjectOutputStream(OutputStream out) throws IOException {}
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
Deserialization in java
ObjectInputStream class
Constructor
1) public creates an ObjectInputStream that
ObjectInputStream(InputStream in) reads from the specified
throws IOException {} InputStream.
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.
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()
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");
<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
(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( ).
(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;
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
//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);
}
}
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.
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.
//Example of String
import java.applet.*;
import java.awt.*;
}
}
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.
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);
}
}
}
}
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);
}
}
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
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);
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);
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>*/
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
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));
}
}
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);
}
}
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));
Text Area
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.
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
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:
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.
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.
import java.awt.*;
import java.applet.*;
/* <applet code="BorderLayoutDemo2" width=200
height=200></applet>*/
}
}
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.
}
public boolean mouseDown(Event event,int x,int y)
{
cardDeck.next(canvasCards);
return true;
}
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>*/
GridBagConstraints()
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
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");
}
}
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();
} }
.
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.
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.
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()
{
myFrame.setVisible(true);
}
public class Terminator extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
myFrame.dispose();
}
}
Event Handling
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.
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
ContainerEvent ContainerListener
FocusEvent FocusListener
ItemEvent ItemListener
KeyEvent KeyListener
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
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.
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)
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.
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
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:
AdjustmentListner Interface
This interface defines the adjustmentValueChanged( ) method that is
invoked when an adjustment event occurs. Its general form is shown here
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)
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)
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)
case KeyEvent.VK_F2:
msg += "<F2>";
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);
}
}
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);
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>
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()
{
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.
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.
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
AWT is a thin layer of code Swing is much larger. Swing also has very
on top of the OS. much richer functionality.
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.
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.
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);
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);
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.
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.
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);
}
}
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);
}
}
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.
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
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());
}
}
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.
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);
JScrollPane
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);
}
}
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.
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:-
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);
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:
import java.awt.*;
import javax.swing.*;
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.
Nested Classes
Class Description
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.
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);
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).
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);
groupLayout.setHorizontalGroup(groupLayout.createSequentialGr
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;
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);
}
}
Constructor Description
Method Description