Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
INTRODUCTION TO
2008
JAVA
9/29/2008
1
INTRODUCTION TO JAVA
1
2
DATA TYPES, OPERATORS & VARIABLES
8
3
FOLW CONTROLS & ARRAYS
24
4
INTRODUCTION TO CLASSES AND MODIFIERS
57
5
METHODS & CONSTRUCTORS
70
6
INHERITANCE
102
7
PACKAGES & INTERFACES
126
8
EXCEPTIONS
136
9
MULTITHREADED PROGRAMMING
150
10
STRING HANDLING
168
11
THE java.util PACKAGE
183
12
INPUT & OUTPUT
191
13
APPLETS
207
14
EVENT HANDLING
221
15
AWT COMPONENTS – I
236
16
AWT COMPONENTS – II
262
17
LAYOUT MANAGERS
280
18
IMAGES & SWINGS
291
Introduction to
Java
INTRODUCTION TO JAVA TECHNOLOGY
HOW JAVA TECHNOLOGY IS USEFUL?
JAVA VIRTUAL MACHINE (JVM)
GARBAGE COLLECTION
WHAT IS OOP?
Encapsulation
Inheritance
Polymorphism
A FIRST JAVA PROGRAM
1
BACKGROUND
Java was created by a team of programmers at Sun Microsystems in 1991. It
took 18 months to develop the first working version. This language was initially
called “Oak”, but it was renamed “Java” in 1995.
Actually, their original goal was to create a computer language that could
be used to build programs that would run in any different execution
environments. They wanted to develop a language that could be used to write
software for different consumer electronic devices.
The Internet allows many different types of computers to be connected
together, including all computers having different CPUs and operating systems.
Therefore, the ability to write a portable program is as beneficial to the Internet as
it is to consumer electronic devices. Java’s “write once, run anywhere” philosophy
provided this advantage. The inventors of java examined many different
programming languages and adopted their best features.
INTRODUCTION TO JAVA TECHNOLOGY
Java Technology is
A Programming language
A Development Environment
An Application Environment
A Deployment Environment
Java is a programming language, which is derived from C and C++. Java
programs can be either Application or Applets. An Application is a program that
runs on your computer, under the operating system of that computer. An
application created by java is more like as that created by other programming
languages. An Applet is an intelligent program that can react to user input and
dynamically change. Applets are java programs reside on web servers and to be
transmitted on the Internet. Applets are executed on client’s system by java
compatible web browsers. The java programming language is usually mentioned
in the context of the World Wide Web and applets.
Java provides a large suite of tools like compiler, interpreter,
documentation, generator, class file, packaging tool etc. as a development
environment.
Java Applications are standalone java programs using Java Runtime
Environment (JRE), which are executed without use of web browsers.
In java there are two “deployment environments” JRE and WEB
BROWSERS. Java2 SDK supplied JRE, which contains the complete set of class
files for all the java packages, which includes basic language classes, GUI
component classes, an advanced Collections API etc. Java interpreter and runtime
environment are supplied by java compatible Web Browsers.
HOW JAVA TECHNOLOGY IS USEFUL?
Java syntaxes are inherited from C/C++. In C++ many concepts are confused,
which are left out or more cleared in java. Java is easy to program because it
eliminates the pitfalls of other languages like pointers, memory management
etc. that affect code of robustness.
Java is Object Oriented language, which helps the programmers to visualize the
programs in real life terms.
Java enables users to create streamlined and clear code.
Java is called portable language because it’s single code can be run on any
operating System.
Java is platform independent, so it allows the same software to execute without
change on heterogeneous set of devices.
Java provides multi-threading, so user can run more than one thread activity at
a time.
Java codes are checked before loading and so they are secured from run-time
errors.
Java loads classes dynamically, at the time when they are actually needed.
JAVA VIRTUAL MACHINE (JVM)
Object-Oriented Programming Language C++ uses only compiler to
compile its code, and it can execute compiled code. But in java compiled code
can’t be executed directly because it is used on Internet. First java programs are
complied by compiler (javac) which generates bytecodes in .class files. Then these
bytecodes are run on JVM, which is interpreter for bytecodes.
JVM provides hardware platform specifications to which all Java
technology code is complied.
JVM reads complied bytecodes that are platform independent
JVM is implemented as software or hardware.
JVM is implemented in a java technology development tool or web browser.
C
O
a.java
M
P
JAVAC
COMPILES
I
L
E
R
a.class (BYTE CODE)
JAVA
LOADS JVM
I
N
JVM
T
E
R
P
R
E
T
UNIX / DOS /
JAVA OS
E
R
JVM
FIGURE - 1-1 JAVA TECHNOLOGY RUN TIME ENVIRONMENT
GARBAGE COLLECTION
Many programming languages allow the dynamic memory
allocation at runtime. Once the allocated memory is not required, the run time
environment should deallocate the memory. In C, C++ and some other
programming languages program developer is responsible for deallocating the
memory otherwise program may be crashed because of less memory. These
programs are said to have memory leaks.
As java provides automatic garbage collection, programmer has no
need to deallocate the memory. Java provides a system-level thread that tracks
each memory allocation. This work is done in the background by a low-priority
thread, which is called garbage collector. Thus garbage collection, which
eliminates the need to allocate and deallocate memory and memory leaks,
happens automatically during the lifetime of a java technology program.
WHAT IS OOP?
Object Oriented Programming is used to manage increasing complexity.
The java supports three key features of OOP.
Encapsulation
Inheritance
Polymorphism
The method of providing a public interface for the client-software
and of hiding certain data elements of the implementation of a class is called
Encapsulation. Encapsulation manipulates and keeps code and data safe from
outside interference and misuse.
Hides the implementation details of a class
Forces the user to use an interface to access code and data
Makes the code more maintainable
Inheritance
The process by which one object can use properties of another object is
called inheritance. The most powerful feature of the java inheritance avoids
writing the same code twice which is known as reusability.
To avoid rewriting the same code
To reuse the same code
To use the properties of one class in other class
Polymorphism
Polymorphism is the ability to access many forms. As example the manager
class can use appropriate methods of the employee class. Polymorphism means
that a call to a member function will cause a different function to be executed
depending on the type of object that invokes the function.
A FIRST JAVA PROGRAM
Java programmer has to use different method for creating and
compiling a program. Each time it is compulsory to compile the program for
implementing any changes in the program.
Steps for creating a Java Program
Create a java program in any editor i.e. Notepad, Ultraedit, Jcreater etc..
Save the program with the same name as that of the *class name .
The extension of the program name must be ‘ . java ‘
Set the classpath for \\jdkx\bin directory
Compile the program with javac, which creates class file. eg.: javac a.java
Run the program with java. eg.: java a
*
If more than one classes are created in one program
than execute this java program with the same name of the class name in which public
static void main ( ) method is included because execution of the program is started from
main( ) method in application.
First Java Example
Class first
{
/*
This program should be saved as first.java
because class name and filename should be same.
*/
public static void main (String args[ ])
{
System.out.println (“ This shows how to create a java program”);
// to display the output
}
}
Description
Like C and C++, Java is also case sensitive language.
Class first
{
As a benefit of OOP, java program is divided into different modules. The
class keyword is used to declare a new class. ‘first’ is identifier , which is the
name of the class. After class name all the members of the class must be between
opening curly braces ‘{‘ and closing curly braces ‘}’.
/*
This program should be saved as first.java
because class name and filename should be same.
*/
This is called as multi line comment. Multi line comment is started from ‘ /* ’
and ended with ‘ */ ’. During the compilation compiler ignores statements
written between these comment symbols.
public static void main (String args[ ])
{
The execution of java program is started from this public static void main ( )
method.
public
->
static
->
void
->
String args[ ] ->
The method main() can be accessed by anything
including the java technology interpreter. It is called the
access specifier.
This key word tells the compiler that main() class can be
used in the context of the class ‘first’. There is no need to
create instance of the class to execute this method.
This keyword tells that method main() does not return
any value.
This declares the single parameter to the main
method, args, and has the type of a String array. When
this method is called, the args parameter contains the
arguments type on the command line. For
Example :
java a args[0] args[1] ……
System.out.println (“ This shows how to create a java program”);
In Java System.out.println is used for displaying output as string given
between braces same as ‘ printf ‘ in C and ‘ cout ‘ in C++. The System.out will
refer to standard output stream. In-built method println is responsible for
writing the message to the standard output stream.
// to display the output
In java ‘ // ‘ symbol is used for single line comment.
Introduction to
Classes & Modifiers
CLASSES
OBJECT
ACCESS MODIFIERS
Public Access Modifier
Private Access Modifier
Protected Access Modifier
Friendly Access Modifier
Other Modifiers
STRING CLASS
COMMAND – LINE ARGUMENTS
CLASSES
2
If you are familiar with C++, you know the classes and importance of
classes in OOP. In java, classes are same as classes of C++. In the Java, class is a
type that defines the implementation of a particular kind of object. A class
definition defines instance and class variables and methods.
The class provides the basic framework of an object, so it is also known as
templates.
Class is description from which many objects or instances are constructed.
Class is a way to define new types in the java programming.
A class describes the data that each object includes
A class describes the behaviors that each object.
Classes support encapsulation, inheritance, and polymorphism.
A class with a main ( ) method can be invoked from the command line as a java
application.
A class does not hold any value until it is used for object creation.
Variables and methods defined within a class are called members of the class.
A class creates a logical framework that defines the relationship between its
members.
In C++ you can declare global variables outside the class, but in java everything
must be included in the class.
Syntax
class class_name
{
type variable1;
type variable2;
:
:
type variable n;
type method 1( parameter list )
{
}
:
:
type method n( parameter list )
{
}
}
Example
class netsal
{
int basic;
double hra;
double da;
double sal;
}
Description
This class will create new data type called as netsal. With the use of this
name, we can declare any object of type netsal.
OBJECT
The object is the principal building blocks of object-oriented programs. Each
object is a programming unit consisting of data (instance variables) and
functionality (instance methods). In java, if you want to access any members of
class, you have to create object of that class. Through this object you can access
members of that class.
Creating object
class_name object_name;
// declare reference to object
object_name = new class_name( );
or
class_name object_name = new class_name( );
An object is an actual instance of the class.
Object_name is a variable of the class type being created
New operator dynamically allocates memory for an object during runtime.
( ) with class_name specifies the default constructor for the class.
Java will automatically supply this default constructor
When we declare an object of a class, it will create an instance of that class.
Example
netsal netobj = new netsal ( );
After creating netobj object, you can access any members of the netsal class.
netobj.sal = netobj.basic + netobj.hra + netobj.da ;
Example of Class
class netsal
{
// complete program of class and object
int basic;
double hra;
double da;
double sal;
}
class salcalc
{
// this class declares object of class netsal
public static void main ( String args [ ] )
{
netsal netobj = new netsal ( );
netobj.basic = 5000;
netobj.hra = netobj.basic * 0.20;
netobj.da = netobj.basic * 0.10;
netobj.sal = netobj.basic + netobj.hra + netobj.da ;
System.out.println ( “ Net salary is : “ + netobj.sal );
}
}
Output
Net salary is : 6500.0
Note
Save this program with the name of salcalc.java because public static void main(
) is included in this class.
After compiling this program it will create two class files netsal.class and
salcalc.class
Example of creating two Objects
class netsal
{
// program of two objects of one class
int basic;
double hra;
double da;
double sal;
}
class a
{
// this class declares object of class netsal
public static void main ( String args [ ] )
{
netsal netobj1 = new netsal ( );
netsal netobj2 = new netsal ( );
netobj1.basic = 5000;
netobj1.hra = netobj1.basic * 0.20;
netobj1.da = netobj1.basic * 0.10;
netobj1.sal = netobj1.basic + netobj1.hra + netobj1.da ;
netobj2.basic = 6000;
netobj2.hra = netobj2.basic * 0.20;
netobj2.da = netobj2.basic * 0.10;
netobj2.sal = netobj2.basic + netobj2.hra + netobj2.da ;
System.out.println ( " Net salary of netobj1 is : " + netobj1.sal );
System.out.println ( " Net salary of netobj2 is : " + netobj2.sal );
}
}
Output
Net salary of netobj1 is : 6500.0
Net salary of netobj2 is : 7800.0
You can create more than one objects of a single class.
Any changes to the instance variables of one object have no effect on the instance
variables of another because each object has it’s own copy of the instance
variables.
We can also assign one object reference variable to another object reference
variable. For ex.
netsal netobj1=new netsal( );
netobj2=netobj1;
It will create only a copy of the reference not a copy of the object.
After assigning any change in the original object, netobj1 will not affect the
netobj2.
netoj1 and netobj2 will both refer to the same object at the execution time.
ACCESS MODIFIERS
Access modifiers control the use of class’ features such as the class itself, its
instance variables, methods and constructors. One of the benefits of classes is that
classes can protect their member variables and methods from access by other
objects. It is possible through access modifiers. Access modifiers are :
Public
Protected
Private
Friendly
Public Access Modifier
The easiest access specifier is public. Any class, in any package, has access to
a class's public members. Declare public members only if such access cannot
produce undesirable results if an outsider uses them. There are no personal or
family secrets here; this is for stuff you don't mind anybody else knowing. A
public class, variable or method may be used in any java program without
restrictions.
An applet is declared as a public class so that it may be instantiated by browsers.
An application declares it’s main( ) method to be public so that main( ) may be
invoked form any Java runtime environment.
A class features declared with public access modifier are available to other
classes within the same package or in a different package.
The public access modifier makes the class features publicly available to any
class at all.
Protected Access Modifier
The next access level specifier is protected, which allows the class itself,
subclasses, and all classes in the same package to access the members. Use the
protected access level when it's appropriate for a class's subclasses to have access
to the member, but not unrelated classes. Protected members are like family
secrets--you don't mind if the whole family knows, and even a few trusted friends
but you wouldn't want any outsiders to know.
The protected access modifier restricts access to a class features to a certain
extents.
A protected feature may only be accessed by a subclass of the class that owns the
feature or by a member of the same package as the class that owns the
feature.
A protected access modifier is used when user wants to restrict the access to
certain features of a class.
Private Access Modifier
The most restrictive access level is private. A private member is accessible
only to the class in which it is defined. Use this access to declare members that
should only be used by the class. Private members are like secrets you never tell
anybody.
A private feature may only be accessed by the class that owns the feature.
A top – level class in the inheritance hierarchy is never declared as private.
Friendly Access Modifier
If a feature has no access modifier, its access defaults to friendly. Friendly is
not a Java key - word. It is just the colloquial name that we humans use for the
type of access a feature gets if no modifier is specified.
A class from the same package as the class that owns the feature may only access
a friendly feature.
Friendly is not a Java key-word, it is simply a name that is given to the access
level that result from not specifying an access modifier.
Even if a class in another package inherits this class, it can’t access its friendly
methods or variables.
Same Class
Same Package - Different Class
Same Package – Sub Class
Different Package – Sub Class
Different Package – Different
Class
Private
Yes
No
No
No
No
Friendly
Yes
Yes
Yes
No
No
Protected
Yes
No
Yes
Yes
No
Public
Yes
Yes
Yes
Yes
Yes
Table 4-1 Access Modifiers in Java
Subclasses and Method Privacy
A method with some particular access type may be overridden by a method
with a different access type, provided there is a path in the figure from the
original type to the new type.
friendly
private
protected
public
Figure – 4-1 Legal overridden method access
The rules for the overriding :
A private method may be overridden by a private, friendly, protected or public
method.
A friendly method may be overridden by a friendly, protected or public method.
A protected method may be overridden by a protected or public method.
A public may only be overridden by a public method.
Other Modifiers
In java there are some other modifiers are available. Not every modifier can
be applied to every kind of features. Java does not care about order of appearance
of modifiers. For Ex. Declaring a class to be public final is no different from
declaring it final public.
Java’s other modifiers are listed below:
Final
Abstract
Static
Native
Transient
Synchronized
Volatile
Final
Final feature can be used to define an entity once and cannot change it or
derive from it later. Java provides you with a unique modifier named final.
A final class cannot be subclassed.
A final method cannot be overridden .
A final variable cannot change from its initialized value.
The final modifier can applies to classes, methods, and variables.
This modifier when used with
Variables
:- Indicates that once a value is assigned, it can’t
be changed.
Methods
:- Indicates that method body can’t be changed.
Class
:- Indicates that this class can’t be subclassed.
Objects of a class
:- Indicates that reference in the object can’t be
changed but value of the object can be changed.
Example
final int basic=5000;
final double da=500.0;
Abstract
Abstract classes provide a way to defer implementation to subclasses.
Abstract keyword is used in a class definition to specify that a class is not to be
instantiated, but rather inherited by other classes. An abstract class can have
abstract methods that are not implemented in the abstract class, but in subclasses.
The abstract modifier can be applied to classes and methods.
The class declared with abstract modifier can’t be instantiated.
The method declared with abstract modifier indicates that the implementation of
the method must be provided in the subclass of this abstract class.
A class must be declared abstract if any of the following condition is true:
The class has one or more abstract methods
The class inherits one or more abstract methods for which it doesn’t provide
implementation
The class declares that it implements an interface but does not provide
implementation details or method body to any of the abstract method
Static
static keyword is used to define a variable as a class variable. Classes
maintain one copy of class variables regardless of how many instances exist of
that class. "static" can also be used to define a method as a class method. Class
methods are invoked by the class instead of a specific instance and can only be
operated on class variables.
The static modifier can be applied to variables, methods or a block of code
A static variable, method or block of code in the class is not instance specific.
A static variable, method or block of code can be used with the class name and
there is no need to create an object of the class to access the static feature of
the class.
Static variable of a class are accessed by static methods only.
Static methods of a class are accessed by static methods only.
Static method does not have “this”.
Static method can’t be overridden by a non-static method.
To access static variables with an object is meaningless because the value
contained int the static variable is same for all the objects.
Native
Native is a keyword that is used in method declarations to specify that the
method is not implemented in the same Java source file, but rather in another
language.
Native can be used only with methods.
Like the abstract keyword, native indicates the body of a method is to be found
outside the Java Virtual Machine.
Native code is written in a non-java language and compiled for a native machine.
Transient
Transient keyword indicates that a field is not part of the serialized form of
an object. When an object is serialized, the values of its transient fields are not
included in the serial representation, while the values of its non-transient fields
are included.
Transient modifier applies only to variables.
A transient variable is not stored as part of its object’s persistent state.
Transient variables may not be final or static.
Synchronized
When this keyword applied to a method or code block guarantees that at
most one thread at a time executes that code. This modifier is used to control
access to critical code in multithreaded programs. We will see this later in
multithreading programming.
Volatile
This keyword used in variable declarations that specifies that the variable is
modified asynchronously by concurrently running threads.
Volatile is used only with variables.
Volatile indicates that the value of variable may be changed asynchronously, so
the compiler takes special precautions.
Volatile variables are of interest in multiprocessor environments.
Modifier
Top – Level
Class
Variable
Method –
Constructor
Public
Protected
Friendly (default)
Private
Final
Abstract
Static
Native
Transient
Synchronized
Volatile
Yes
No
Yes
No
Yes
Yes
Yes
No
No
No
No
Yes
Yes
Yes
Yes
Yes
No
Yes
No
Yes
No
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
No
Yes
No
Table 4 – 2 All possible modifiers for the features.
STRING CLASS
String is the most commonly used class of java’s class library.
Every string created by you is an object of the String class.
String constants are also string objects. For Ex.
System.out.println (‘how are you”); // “how are you” is a string constant
Once String object created, its contents can’t be changed means String objects are
immutable.
To change the content of the String object is possible by creating a new one that
contains the modifications.
String str=”this is a string constant”
If you want to change the content of String object str, create a same
be changed.
String str= “this is a String.”
StringBuffer allows strings to be changed and all the normal string
manipulations are still available in java. SringBuffer is a peer class of
String.
Strings can be constructed in variety of ways.
String str = “this is a simple way to construct a String”
System.out.println (str); // this is used to display the content of String
object str.
String str= “this is” + ”another way” + “to construct a “ + “String”;
/* this will result that str
Contains after concatenating the strings “this is another way to
construct a String”. */
Example of String Class
class stringex
{
public static void main(String args[ ])
{
String s1 = ”India”;
String s2 = ”Vs”;
String s3 = ”Pakistan”;
String s4 = s1+” “+s2+” “+s3;
System.out.println (s1);
System.out.println (s1+”-“+s3);
System.out.println (s4);
}
}
Output
India
India-Pakistan
India Vs Pakistan
The String class contains several methods like as equals( ) – to test equality of
two String objects, length( ) – to obtain the length of a string , charAt()- to
obtain the character at a specified index within a string , etc.
Example of Methods of String Class
class stringmethod
{
public static void main(String args[ ])
{
String s1 = "India";
String s2 = s1;
String s3 = "Pakistan";
System.out.println ("length of s1 is "+s1.length());
System.out.println ("character at index 4 in s1 is "+s1.charAt(4));
if (s1.equals(s2))
System.out.println ("s1 == s2");
else
System.out.println ("s1 != s2");
if (s1.equals(s3))
System.out.println ("s1 == s3");
else
System.out.println ("s1 != s3");
}
}
Output
length of s1 is 5
character at index 4 in s1 is a
s1 == s2
s1 != s3
COMMAND – LINE ARGUMENTS
Command – line arguments let you to pass information into a program
when you run it. In public static void main ( String args [ ] ) string args [ ] refers
the command line arguments having the type string.
Command – line arguments are stored as strings in the string array passed to
main ( ) method.
The type of command – line argument is String.
Command – line arguments are passed at run time. For ex.
java a arg[0]
arg[1] …. arg[n]
Example of Command-Line Arguments
class country
{
public static void main ( String args [ ] )
{
System.out.println("First Argument Is : " + args[0]);
System.out.println("Second Argument Is : " + args[1]);
System.out.println("Third Argument Is : " + args[2]);
}
}
Note
Run this program using this arguments
java country India America Japan
Output
First argument is : India
Second argument is : America
Third argument is : Japan
Methods &
Constructors
3
METHODS
CONSTRUCTORS
Default constructor
Parameterized constructor
“this” KEY-WORD
THE finalize( ) METHOD
THE STACK
METHOD OVERLOADING
CONSTRUCTOR OVERLOADING
RECURSION
CLOSER LOOK AT MODIFIERS
INNER CLASSES
METHODS
In C and C++, functions are called methods in the Java language. Method is
a functional element of an object. A method is also known as a function or a procedure.
Classes consist two things. Instant Variables and Methods. There are two types of
methods available in Java.
Class Methods :- A method that is invoked without reference to a particular object is
called class method. Class methods affect the class as a whole, not a particular instance
of the class. It is also called a Static method
Instance Methods :- Any method that is invoked with respect to an instance of a class
called is called as Instance Method. It is also called simply a method.
Syntax
modifier return_type name(parameter list)
{
statement or block; //body of method
}
Modifier is access modifier of the method which is optional . For Ex. public,
private, protected etc..
Type specifies the type of data returned by the method. It may be a class type or
void, if it does not return a value.
The name of the method is specified by name. It may be any legal identifier other
than those already used in the current scope.
The parameter-list contains the value of the arguments passed to the method
when it is called. It is a sequence of type and identifier pairs separated by
commas. If the method has no parameters, then parameter-list will be
empty. But the ( ) is compulsory with the method.
Method returns a value, if it is not a void, to the calling routine with the return
statement. The returned value and type of method must be same.
return value;
Example of Methods
class netsal
{
int basic;
double hra;
double da;
double sal;
//mehod calculate and display salary of a netsal
void salary( )
{
sal=basic+hra+da;
System.out.println ("salary is "+ sal);
}
}
class basic
{
public static void main ( String args [ ] )
{
netsal netobj1 = new netsal ( );
netsal netobj2 = new netsal ( );
//assigning values instance variables of netobj1
netobj1.basic = 5000;
netobj1.hra = netobj1.basic * 0.20;
netobj1.da = netobj1.basic * 0.10;
//assigning values instance variables of netobj2
netobj2.basic = 6000;
netobj2.hra = netobj2.basic * 0.20;
netobj2.da = netobj2.basic * 0.10;
// display salary of objects by using methods
netobj1.salary( ); /* control transfer to the code defined inside
the salary( ). After executing statements inside
the salary( ) control will return and will execute
the following line code . */
netobj2.salary( );
}
}
Output
salary is : 6500.0 //netobj1
salary is : 7800.0 //netobj2
Using method with return value
We can also use a method, which returns some value. The type of returned value
and type of method must be same. When method is called, the control passes to inside
the method and executes the statements inside the method. Then return the value with
the return statement to the calling statement.
Example of Method using Return Value
class netsal
{
int basic;
double hra;
double da;
//mehod calculate salary of a netsal and return its value
double salary( )
{
return basic+hra+da;
}
}
class basic
{
public static void main ( String args [ ] )
{
double sal;
netsal netobj1 = new netsal ( );
netsal netobj2 = new netsal ( );
netobj1.basic = 5000;
netobj1.hra = netobj1.basic * 0.20;
netobj1.da = netobj1.basic * 0.10;
netobj2.basic = 6000;
netobj2.hra = netobj2.basic * 0.20;
netobj2.da = netobj2.basic * 0.10;
// calculate the value of netobj1 by using methods with returned value
sal=netobj1.salary( ); /* control transfer to the code defined inside
the salary( ) after executing statements
inside the salary( ) it will returned a value of salary
assign it to the sal variable. */
System.out.println (“salary is : “ +sal);
// calculate the value of netobj2 by using methods with returned value
sal= netobj2.salary( );
System.out.println (“salary is : “ +sal);
}
}
Output
salary is : 6500.0 //netobj1
salary is : 7800.0 //netobj2
Methods with parameters
We can pass parameter with the method calling. The method then works on this
parameters and returns the calculated values using this parameters.
Example of Methods with Parameter
class netsal
{
int basic;
double hra;
double da;
double salary(double basic)
{
hra=basic*0.2;
da=basic*0.1;
return basic+hra+da;
}
}
class basic
{
public static void main ( String args [ ] )
{
double sal;
netsal netobj1 = new netsal ( );
netsal netobj2 = new netsal ( );
/* calculate the value of sal by using methods with returned value
parameter passed with the method*/
sal=netobj1.salary( 5000 );
System.out.println ("salary is : " +sal);
sal= netobj2.salary(6000);
System.out.println ("salary is : " +sal);
}
}
Output
salary is : 6500.0 //netobj1
salary is : 7800.0 //netobj2
CONSTRUCTORS
Constructors are used to initialize all of the variables in class each time when an
instance is created. We can also initializing instance variables with using the methods. In java
there is a facility to automatic initialization
is performed, when objects are created, through the use of constructors.
A constructor is a set of instructions designed to initialize an instance.
A constructor is a “method-like” construct used to initialize a new object.
Constructors have the same name as the class-name in which it is resides.
Constructor is automatically called immediately after the object is created using
“new” key-word.
Java supports name overloading for constructors so that a class can have any
number of constructors, all of which have the same name.
Constructors are not methods. They don’t have return value and they aren’t
inherited.
Example of Constructors
class netsal
{
int basic;
double hra;
double da;
//constructor for netsal named as netsal
netsal( );
{
System.out.println ("This constructor runs every time when object created");
basic=5000;
hra=basic*0.2;
da=basic*0.1;
}
//method calculates salary of a netsal and returns its value
double salary( )
{
return basic+hra+da ;
}
}
class basic
{
public static void main ( String args [ ] )
{
double sal;
//declare,allocate and automatically initialize netsal objects through
constructors
netsal netobj1 = new netsal ( );
netsal netobj2 = new netsal ( );
// calculate the value of sal by using methods with returned value
sal=netobj1.salary( );
System.out.println ("Salary is : " +sal);
sal= netobj2.salary( );
System.out.println ("Salary is : " +sal);
}
}
Output
This constructor runs every time when object created
This constructor runs every time when object created
Salary is : 6500.0 //netobj1
Salary is : 6500.0 //netobj2
Default constructor
Every class has at least one constructor, which is called default constructor. If you
don’t write a constructor with arguments in a class than and only then java provides a
one constructor for you. This constructor has not any arguments and has an empty body.
There is always at least one constructor in every class
If the programmer does not supply any constructor, the default constructor will
be present automatically
Default constructor does not take any argument and doesn’t have any body.
We can create object instance of default constructor using
new class_name( );
Parameterized constructors
Parameterized constructors are used to construct the objects of various
dimensions
All constructors share the same name in the single class, but they have different
parameter lists. The compiler differentiates these constructors based on the
number of parameters in the list and their types.
Example of Parameterized Constructors
class netsal
{
int basic;
double hra;
double da;
//constructor for netsal with parameter named as netsal
netsal(int b)
{
System.out.println ("This constructor runs every time when object created");
basic=b;
hra=basic*0.2;
da=basic*0.1;
}
//method calculates salary of a netsal and returns its value
double salary( )
{
return basic+hra+da;
}
}
class basic
{
public static void main ( String args [ ] )
{
double sal;
//declare, allocate and automatically initialize with using parameters
given with netsal objects
netsal netobj1 = new netsal (5000); // 5000 is passed to the netsal
constructor when new creates the object
netsal netobj2 = new netsal (6000);
// calculate the value of sal by using methods with return value
sal=netobj1.salary( );
System.out.println ("Salary is : " +sal);
sal= netobj2.salary( );
System.out.println ("Salary is : " +sal);
}
}
Output
This constructor runs every time when object created
This constructor runs every time when object created
Salary is : 6500.0 //netobj1
Salary is : 7800.0 //netobj2
THE “this” KEYWORD
“this” keyword is used to represent an instance of the class in which it appears.
"this" can be used to access class variables and methods.
The constructor can call upon other constructors in its class to help with its work.
The this ( ) construction does this.
The this ( ) must be positioned at the start of the constructor
One constructor can call another using the this(arguments).
Example of “this” key-word
class netsal
{
int basic;
double hra;
double da;
netsal (int basic, double hra, double da)
{
this.basic=basic; // this refers to the basic variable of netsal class and not
netsal constructor.
this.hra=hra;
this.da=da;
}
netsal (int basic, double hra)
{
this (basic, hra, null); //this keyword will call the first netsal constructor
}
netsal (int basic)
{
this (basic, null ); //this keyword will call second netsal constructor
}
}
THE finalize( ) METHOD
Some objects will need to perform some action before it is destroyed. By using
finalization, we can define some specific actions that will occur when an object is
destroyed by garbage collector.
Syntax
protected void finalize()
{
//finalization code
}
The keyword protected is used to prevent access this method by code defined
outside its class.
This method is only called just before to garbage collection.
The finalize( )method works similar to the destructor in C++.
THE STACK
A stack stores data in order first-in, last-out.
Stacks are controlled through push and pop operations.
Push will put item on the top of the stack.
Pop will take item from the top of the stack.
Example of Stack Class
class stack
{
int stk[ ] = new int[5];
int los;
//initialize the stack
stack( )
{
los=-1;
}
//push an item on the top of the stack if stck is not full
void push(int itm)
{
if (los==4)
System.out.println ("stack is full");
else
stk[++los]=itm;
}
//pop an item from the top of the stack if available
int pop( )
{
if(los<0)
{
System.out.println ("stack is empty.");
return 0;
}
else
return stk[los--];
}
}
class basic
{
public static void main ( String args [ ] )
{
stack mystk1 = new stack( );
stack mystk2 = new stack( );
//push numbers onto the mystk1
for(int i=0;i<5;i++)
mystk1.push(i);
//push numbers onto the mystk2
for(int i=4;i>=0;i--)
mystk2.push(i);
//pop inserted numbers from the mystk1
System.out.println ("numbers of mystk1 as below");
for(int i=0;i<5;i++)
System.out.print (mystk1.pop( )+" ");
System.out.println ( );
//pop inserted numbers from the mystk2
System.out.println ("numbers of mystk2 as below");
for(int i=0;i<5;i++)
System.out.print (mystk2.pop( )+" ");
}
}
Output
numbers of mystk1 as below
4 3 2 1 0
numbers of mystk1 as below
0 1 2 3 4
We can also use the length member array with stack. The value of stk.length is
used to prevent the stack from overflowing. So, we can easily use and create stacks of
any size.
Example of Stack using the length of Array
class stack
{
int stk[ ];
int los;
//initialize the stack
stack(int size )
{
stk=new int[size];
los=-1;
}
//push an item on the top of the stack if stck is not full
void push(int itm)
{
if (los==stk.length-1) //length member used
System.out.println ("stack is full");
else
stk[++los]=itm;
}
//pop an item from the top of the stack if available
int pop( )
{
if(los<0)
{
System.out.println ("stack is empty.");
return 0;
}
else
return stk[los--];
}
}
class basic
{
public static void main ( String args [ ] )
{
stack mystk1 = new stack(5); // creates stack with five elements deep
stack mystk2 = new stack(8); //creates stack with eight elements deep
//push numbers onto the mystk1
for (int i=0;i<5;i++)
mystk1.push(i);
//push numbers onto the mystk2
for (int i=7;i>=0;i--)
mystk2.push(i);
//pop inserted numbers from the mystk1
System.out.println ("numbers of mystk1 as below");
for (int i=0;i<5;i++)
System.out.print (mystk1.pop( )+" ");
System.out.println( );
//pop inserted numbers from the mystk2
System.out.println ("numbers of mystk2 as below");
for (int i=0;i<8;i++)
System.out.print (mystk2.pop( )+" ");
}
}
Output
numbers of mystk1 as below
4 3 2 1 0
numbers of mystk1 as below
0 1 2 3 4 5 6 7
Method overloading
Overloading is one identifier to refer to multiple items in the same scope. In the
Java, you can overload methods but not variables or operators. It is possible to define
two or more methods have same name within a class. But method’s parameters are
different. This is called as method overloading.
At the run time, java uses the type and number of arguments to call the
overloaded method.
Type and number of arguments of overloaded methods must differ.
When java calls the overloaded method, it will consider return type method and
number of arguments.
Only return type of overloaded methods is not sufficient to distinguish the
methods.
Example of Method Overloading
class exoverload
{
void salary( )
{
System.out.println ("Basic salary not given");
}
//overload salary with one integer parameter
void salary(int basic)
{
System.out.println (" salary is : "+basic);
}
//overload salary with two integer parameters
void salary(int basic, int da)
{
double sal;
sal=basic+(basic*da/100);
System.out.println ("salary is : " + sal);
}
// overload salary with one integer and one double parameter
void salary(int basic, double da)
{
double sal;
sal=basic+(basic*da);
System.out.println ("salary is : "+sal);
}
//overload with three parameters
double salary(int basic, int da, int hra)
{
double sal;
sal=basic+(basic*da/100)+(basic*hra/100);
return sal;
}
}
class a
{
public static void main(String args[ ])
{
exoverload ob = new exoverload( );
double netsal;
// call all the overload methods
ob.salary ( );
ob.salary (5000);
ob.salary (5000,20);
ob.salary (5000,0.1);
netsal = ob.salary (5000,20,10);
System.out.println ("net salary is : " + netsal);
}
}
Output
Basic salary not given
salary is : 5000
salary is : 6000.0
salary is : 5500.0
net salary is : 6500.0
When overloaded method is called, java looks for a match between the arguments
used to call the methods and the method’s parameters. But this match need not be
exact. Sometimes java automatic convert the type if possible.
Example of Method Overloading
class ex1overload
{
void salary( )
{
System.out.println ("basic salary not given");
}
//overload salary with one double parameter
void salary(double basic)
{
System.out.println (" salary is : "+basic);
}
}
class basic
{
public static void main(String args[ ])
{
ex1overload ob = new ex1overload( );
double netsal;
// call all the overload methods
ob.salary( );
ob.salary(5000); /* integer value of 5000 automatically converted
into double by method void salary(double basic) */
}
}
Output
Basic salary not given
Salary is : 5000.0
Constructor overloading
Constructor overloading is just like as the method overloading. When any object
created, it will execute the constructor, which match the type and number of arguments.
Example of Constructor Overloading
class netsal
{
double basic;
double da;
double hra;
//constructor used when three arguments given
netsal(double b, double d, double h)
{
basic=b;
da=basic*d;
hra=basic*h;
}
//constructor used when no argument given
netsal( )
{
basic=0;
da=0;
hra=0;
}
//constructor used when one argument given
netsal(double b)
{
basic=b;
da=0;
hra=0;
}
// calculate and return the salary
double salary( )
{
return basic + da + hra;
}
}
class basic
{
public static void main(String args[ ])
{
// create object using various constructors
netsal n1=new netsal(5000,0.1,0.2);
netsal n2=new netsal( );
netsal n3=new netsal(5000);
double netsal;
//calculate salary using n1
netsal=n1.salary( );
System.out.println ("net salary of n1 is : "+netsal);
//calculate salary using n2
netsal=n2.salary( );
System.out.println ("net salary of n2 is : "+netsal);
//calculate salary using n3
netsal=n3.salary( );
System.out.println ("net salary of n3 is : "+netsal);
}
}
Output
net salary of n1 is : 6500.0
net salary of n1 is : 0.0
net salary of n1 is : 5000.0
Object as Parameter
We can also pass object as a parameter in java programming.
Example of Object as Parameter
class netsal
{
double basic;
double da;
double hra;
//constructor used when three arguments given
netsal(double b, double d, double h)
{
basic=b;
da=basic*d;
hra=basic*h;
}
//constructor used when no argument given
netsal( )
{
basic=0;
da=0;
hra=0;
}
//constructor used when one argument given
netsal(double b)
{
basic=b;
da=0;
hra=0;
}
//constructor used when object argument given
netsal(netsal ob)
{
basic=ob.basic;
da=ob.da;
hra=ob.hra;
}
// calculate the salary
double salary( )
{
return basic+da+hra;
}
}
class basic
{
public static void main(String args[ ])
{
// create object using various constructors
netsal n1=new netsal(5000,0.1,0.2);
netsal n2=new netsal( );
netsal n3=new netsal(5000);
netsal n4=new netsal(n1);//create object with argument object n1
netsal n5=new netsal(n2);//create object with argument object n2
netsal n6=new netsal(n3);//create object with argument object n3
double netsal;
//calculate salary using n1
netsal=n1.salary( );
System.out.println ("net salary of n1 is : "+netsal);
//calculate salary using n2
netsal=n2.salary( );
System.out.println ("net salary of n2 is : "+netsal);
//calculate salary using n3
netsal=n3.salary( );
System.out.println ("net salary of n3 is : "+netsal);
//calculate salary using n4
netsal=n4.salary( );
System.out.println ("net salary of n4 is : "+netsal);
//calculate salary using n5
netsal=n5.salary( );
System.out.println ("net salary of n5 is : "+netsal);
//calculate salary using n6
netsal=n6.salary( );
System.out.println ("net salary of n6 is : "+netsal);
}
}
Output
net salary of n1 is : 6500.0
net salary of n2 is : 0.0
net salary of n3 is : 5000.0
net salary of n4 is : 6500.0 //same as output of n1
net salary of n5 is : 0.0 //same as output of n2
net salary of n6 is : 5000.0 //same as output of n3
Argument Passing
There are two ways to pass an argument to
subroutines.
Call-by-value.
Call-by-reference.
Call by value
This method copies the value of an argument into the formal parameter of the
subroutine. So changes made to the parameter of the subroutine have no effect on the
argument used to call it.
Example of Call by Value
class netsal
{
void salary(int b, int d, int h)
{
b+=1000;
d+=10;
h+=5;
}
}
class basic
{
public static void main(String args[ ])
{
netsal n=new netsal( );
int basic=5000,da=10,hra=20;
System.out.println ("basic, da and hra before calling method : " + basic + " " +
da + " " + hra);
n.salary (basic, da, hra);
System.out.println ("basic, da and hra after calling method : " + basic + " " +
da + " " + hra);
}
}
Output
basic, da and hra before calling method : 5000 10 20
basic, da and hra after calling method : 5000 10 20
Call-by Reference
The second way argument can be passed is call-by-reference. In this method, a
reference to an argument not the value of the argument) is passed to the parameter.
Inside the subroutine, this reference is used to access the actual argument specified in
the call. So, the changes made to the parameter will affect the argument used to call the
subroutine.
Example of Call by Reference
class netsal
{
int basic, da, hra;
netsal(int b, int d, int h)
{
basic=b;
da=d;
hra=h;
}
void salary(netsal ob)
{
ob.basic+=1000;
ob.da+=10;
ob.hra+=5;
}
}
class basic
{
public static void main(String args[ ])
{
netsal n=new netsal(5000,10,20);
System.out.println ("basic, da and hra before calling method : "+ n.basic + " "
+ n.da+" "+n.hra);
n.salary(n);
System.out.println ("basic, da and hra after calling method : " + n.basic + " " +
n.da + " " + n.hra);
}
}
Output
basic, da and hra before calling method : 5000 10 20
basic, da and hra before calling method : 6000 20 25
Returning objects
A method can return any type of data. It can also return class type that is created
by user.
Example of Returning Object
class netsal
{
int basic;
netsal(int b)
{
basic=b;
}
netsal incrsal( )
{
netsal salincr = new netsal(basic+1000); /*new object is created and a
reference to it is returned to the calling routine */
return salincr ;
}
netsal decrsal( )
{
netsal saldecr=new netsal(basic-1000);
return saldecr;
}
}
class basic
{
public static void main(String args[ ])
{
netsal n1=new netsal(5000);
netsal n2;
netsal n3;
n2=n1.incrsal( );
n3=n1.decrsal( );
System.out.println (" n1.basic := "+n1.basic);
System.out.println (" n2.basic after first increment := "+n2.basic);
System.out.println (" n3.basic after first decrement := "+n3.basic);
n2=n2.incrsal( );
System.out.println (" n2.basic after second increase := "+n2.basic);
n3=n3.decrsal( );
System.out.println (" n3.basic after second decrease := "+n3.basic);
}
}
Output
n1.basic :=5000
n2.basic after first increment :=6000
n3.basic after first decrement :=4000
n2.basic after second increase := 7000
n3.basic after second decrease := 3000
Recursion
Java supports recursion. Recursion is the attribute that allows method to call itself.
A method that calls itself is called as recursive.
Example of Recursion
//program for calculate the sum of 1 to given number using recursion
class sum
{
int sumn (int i) //recursive method
{
int sn;
if (i==1)
return 1;
sn=sumn(i-1)+i; //method calls itself
return sn;
}
}
class basic
{
public static void main ( String args [ ] )
{
sum s=new sum( );
System.out.println ("sum of number 1 to 5 is "+ s.sumn(5));
System.out.println ("sum of number 1 to 9 is "+ s.sumn(9));
System.out.println ("sum of number 1 to 12 is "+ s.sumn(12));
}
}
Output
sum of number 1 to 5 is 15
sum of number 1 to 9 is 45
sum of number 1 to 12 is 78
When recursive method calls itself, new local variables and parameter are
allocated storage on the stack, the method code is executed with these new variables
from the start. A recursive call does not make a new copy of the method but the
arguments are new. As each recursive call returns, the old local variables and parameters
are removed from the stack, and execution resumes at the point of the call inside the
method. The main advantage to recursive methods is that they can be used to create
clearer and simpler versions of several algorithms that can their iterative relatives. When
you writing recursive methods, you must have if statement that returns method without
the recursive call. If you don’t use if statement for return method then recursive method
goes in the infinite loop
Example of Recursion
//example which print the elements of array with use of recursive method
class recursion
{
int ar[ ];
recursion(int i)
{
ar=new int[i];
}
// display the contents of array recursively
void print(int i)
{
if (i==0)
return;
else
print(i -1);
System.out.print ("ar [ "+(i-1)+" ] = "+ar[i-1]+" ");
}
}
class basic
{
public static void main(String args[ ])
{
recursion r=new recursion(5);
int i;
for (i=0;i<5;i++)
r.ar[i]=i+1;
r.print(5); //call method recursively and prints 5 elements
System.out.println ( );
r.print(3); // it will prints 3 elements of the array
}
}
Output
ar[ 0 ]=1 ar[ 1 ]=2 ar[ 2 ]=3
ar[ 0 ]=1 ar[ 1 ]=2 ar [2 ]=3
ar[ 3 ]=4 ar[ 4 ]=5
CLOSER LOOK AT MODIFIERS
We had discussed about the access modifiers such as private, public, friendly,
static etc. earlier. Now we discuss how it is used in the class.
Example of Modifiers
class pubpri
{
int basic; // default or friendly access
public int hra ; //public access
private int da; //private access
// method to access basic and set its value
void setda(int i)
{
da=i;
}
int retda( )
{
return da;
}
}
class basic
{
public static void main(String args[ ])
{
double netsal;
pubpri ob = new pubpri( );
ob.basic=5000; //it is true because basic is not defined
ob.hra=20;// it is true because hra is defined as public
/* ob.da = 10; it will cause error becacuse private variable can't be used in
the another class but we can set the value of da through its method setda */
ob.setda(10); // this is true
netsal= ob.basic+(ob.hra+ob.retda( ))*ob.basic/100;
// retda( ) returns the value da after
// setting the value by method setda () method
System.out.println ("netsalary is : "+netsal);
}
}
Output
netsalary is : 6500
To understand how the access modifiers useful very clearly with example of
improved version of stack class, which is discussed earlier
Example of Modifiers with Stack
class stack
{
/* here stk and los both are declared as private means that their value can’t be
changed accidently */
private int stk[ ] = new int[5];
private int los;
//initialize the stack
stack( )
{
los=-1;
}
//push an item on the top of the stack if stck is not full
void push(int itm)
{
if (los==4)
System.out.println ("stack is full");
else
stk[++los]=itm;
}
//pop an item from the top of the stack if available
int pop( )
{
if(los<0)
{
System.out.println ("stack is empty.");
return 0;
}
else
return stk[los--];
}
}
class a
{
public static void main ( String args [ ] )
{
stack mystk1 = new stack( );
stack mystk2 = new stack( );
//push numbers onto the mystk1
for (int i=0;i<5;i++)
mystk1.push(i);
//push numbers onto the mystk2
for (int i=4;i>=0;i--)
mystk2.push(i);
//mystk1.los=-4; this statement causes an error because los is declared as
private
//pop inserted numbers from the mystk1
System.out.println ("numbers of mystk1 as below");
for(int i=0;i<5;i++)
System.out.print (mystk1.pop( )+" ");
System.out.println( );
//pop inserted numbers from the mystk2
System.out.println ("numbers of mystk2 as below");
for(int i=0;i<5;i++)
System.out.print (mystk2.pop( )+" ");
}
}
Output
numbers of mystk1 as below
4 3 2 1 0
numbers of mystk1 as below
0 1 2 3 4
Example of static Variables, Methods and Blocks
class staticdemo
{
static int basic=5000;
static double hra ;
static double da;
/* static method must access only static data and they can't refer
this or super */
static void display(int i)
{
System.out.println (" i= "+i);
System.out.println (" basic= "+basic);
System.out.println (" hra= "+hra);
System.out.println (" da= "+da);
}
/* static block executed exactly once when the class loaded */
static
{
System.out.println ("Static variables intialized here.");
da=basic*10/100;
hra=basic*20/100;
}
public static void main(String args[ ])
{
/*static method can only call other static methods */
display(40);
}
}
Output
i = 40
basic = 5000
hra = 1000.0;
da = 500.0;
Example of Static Modifier
/* another example for the static modifier by using static methods and variables in
class other than in which they are defined */
class staticdemo
{
static int basic=5000;
static double hra ;
static double da;
/* static method must access only static data and they can't refer
this or super */
static void display(int i)
{
System.out.println (" i= "+i);
System.out.println (" basic= "+basic);
System.out.println (" hra= "+hra);
System.out.println (" da= "+da);
}
/* static block executed exactly once when the class loaded */
static
{
System.out.println ("Static variables intialized here.");
da=basic*10/100;
hra=basic*20/100;
}
}
class disp
{
public static void main(String args[])
{
/* static method can be called from outside of the class in which they are
definedindependently of any objec. use only classname.methodname*/
staticdemo.display(40);
/* we can also use the static variable outside the class in which it is
defined with using the classname*/
System.out.println ("value of da is : "+staticdemo.da);
}
}
Output
i = 40
basic = 5000
hra = 1000.0;
da = 500.0;
value of da is : 500.0
INNER AND NESTED CLASS
An inner class is the same as any other class but is declared inside some other class
and can only be used by that outer class. It is also called as nested class. It is possible to
create a class within a method also called inner class. These inner classes were added to
JDK 1.1 and all subsequent versions.
Inner classes allow a class definition to be placed inside another class definition
Inner classes are group classes that logically belong together.
Inner classes have access to their enclosing class’s scope.
The inner class can use both static and instance variables of enclosing classes and
final local variables of enclosing blocks.
You can define the inner class as abstract.
An inner class can be an interface that is implemented by another inner class.
A static nested class must access the members of its enclosing class through an
object .it can’t refer to members of its outer class directly, so static nested
class rarely used.
A non-static nested class access directly all or the variables and methods of the
outer class even declared as private.
You can declare inner classes with any level of access protection For Ex. A
private inner class can only be accessed with outer class’s scope, a protected
inner class can be used by subclasses and so on.
Example of Inner Class
class outerclass
{
private int basic=5000;
class innerclass
{
private double da=basic*0.2; /* inner class can use the variable basic
which is declared in the outer class */
void innernetsal( )
{
double salary;
salary=basic+da; //inner class can use private variable of outer class
System.out.println ("salary of inner class is : "+salary);
}
}
void outernetsal( )
{
System.out.println ("salary of outer class is : "+basic);
}
/*
void displayda( )
{
System.out.println (“value of da is :”+da);
}
This method cause an error because we can’t use the variable in the
outer class which is declared in the inner class */
void makeinner( )
{
innerclass objinner1 = new innerclass( );
//create object of inner
class in outerclass
objinner1.innernetsal( );
}
}
class callmethod
{
public static void main(String args[ ])
{
outerclass objouter=new outerclass( );
//object created of innerclass from class other than outerclass
outerclass.innerclass objinner2=new outerclass( ).new innerclass( );
//call methods from outerclass
objouter.outernetsal( );
objouter.makeinner( );
//call methods from innerclass
objinner2.innernetsal( );
}
}
Output
salary of outer class is: 5000
salary of inner class is: 6000.0
salary of inner class is: 6000.0
Data Types, Operators
& Variables
KEYWORDS AND IDENTIFIERS
DATA TYPES
IDENTIFIERS
VARIABLES
Declaration Of A Variable
Assigning Values
Instance Variables
Local Variables
LITERALS
Example of Literals
OPERATORS
Arithmetic Operators
Unary Operators
Comparison Operators
Short – Circuit Logical Operators
Bitwise Operator
Shift Operators
Ternary Operator ( ?: )
Assignment Operators
2
KEYWORDS AND IDENTIFIERS
The java language specifies following keywords and other reserved words.
abstract
boolean
break
byte
case
const
catch
char
class
continue
default
do
double
else
extends
false
final
finally
float
for
goto
if
implement
s
import
instanceo
f
int
interfac
e
long
native
new
null
packag
e
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
TABLE 2-1 JAVA KEYWORDS AND RESERVE WORDS
The word goto and const are reserved : although they have no meanings in java,
programmers may not use them as identifiers.
DATA TYPES
There are so many kinds of data type in java. For Example,
Numbers such as 12, 234, 0, 9876
Logical or Boolean such as True or False
Strings such as “hello! How is this java”
Null, a special keyword demoting a null ( no value )
In java it is compulsory to define data types variables when we declare
variables. Data types are not converted automatically when the values are
assigned to these variables during the execution. Variable can hold only those
types of values, by which they are declared. So java is strongly typed language
because it enforces this rule. eg. In C and C++ you can assign floating-point value
to integer variable but in java you cannot do this.
In Java following data types are available.
DATA
TYPES
DESCRIPTION
RANGE
FROM
TO
Byte
Integer value ( 8 bits ) or 1 byte
-128
127
Short
Integer value ( 16 bit ) or 2 bytes
-32768
32767
Int
Integer value ( 32 bit ) or 4 bytes
-2147483648
2147483647
Long
Integer value
-9223372036854775808
-9223372036854775807
Float
Real number ( 32 bits ) or 4 bytes
The maximum is about 10
raised to the power 38
Double
Real number ( 64 bits ) or 8 bytes
The maximum is about 10
raised to the power 308
Char
Character ( 16 bits ) or 2 bytes
A single character from the Unicode character set.
Boolean
Logical Value
False or True
TABLE 2-2 DATA TYPES
IDENTIFIER
Identifier refers to the name of the variable, method, class, or label.
Rules for identifiers:
Keywords and reserve words may not be used as identifier.
An identifier must begin with a letter ( a-z, A-Z ), a dollar sign ( $ ) or an
underscore sign( _ ).
Identifiers are case sensitive eg. ‘M’ and ‘m’ are two different identifiers.
Subsequent character may be letters, dollar signs, underscores or digits.
VARIABLES
Variable is a name of memory location where temporary values are stored,
during execution of the program. Variable can be declared by assigning a value to
it.
Declaration of a Variable
Syntax :- type < variable name>
Type specifies the type of data that you want to store in variable.
Variable name is the identifier, which is the name of the variable.
Assigning Values
int a;
a=5;
int a=5;
int a, b, c;
int a=5, b, c=1;
int x=5, y=10;
int a=x + y;
Instance Variables
Variables, which are declared in the class and outside the method, are called
instance variables. These variables can be accessed by any method in same class.
Local Variables
Variables, which are declared in the method are called local variables. These
variables can’t be accessed from outside the method. The scope of any variable is
{} of the method or class.
LITERALS
A literal is a value that may be assigned to primitive or string variables or
passed as an argument to a method call. It can be of any java data types. For eg.
boolean literals, integer, literals, character literals, etc.
Example of Literals
byte b= 100;
short s= 1000;
int i = 10;
long l= 1000000;
float f= 10.2f;
double d=8.0008;
char c=’a’;
boolean ismale = false;
string s=” welcome to aye “;
Java supports a few escape sequences for denoting special characters.
New line
Return
Tab
Back Space
Form Feed
Single Quote
Double Quote
Question Mark
:
:
:
:
:
‘ \n ’
:
:
‘ \b ’
‘ \f ‘
:
‘ \” ’
‘ \? ‘
‘ \r ’
‘ \t ’
‘ \’ ’
OPERATORS
Like other languages java has also many types of operators. Java operators
are similar in style and function to those of C and C++.
Following types of operators are available in Java.
ARITHMETIC
* /
% +
-
UNARY
++ -- + - ~ ! ( )
COMPARISON
< <= > >= == != instanceof
SHORT – CIRCUIT
&& ||
BITWISE
~ & ^ |
SHIFT
<< >> >>>
TERNARY
?:
ASSIGNMENT
=
“op=”
TABLE 2-3 OPERATORS IN JAVA
ARITHMETIC OPERATORS
+
*
/
%
Addition
Subtraction
Multiplication
Division
Remainder
Example
VALUE OF X
VALUE OF Y
EXPRESSION
VALUE OF Z
10
20
Z=X+Y
30
20
10
Z=X-Y
10
10
20
Z=X*Y
200
20
10
Z=X/Y
2
10
3
Z=X%Y
1 (remainder)
TABLE 2-4 EXAMPLES OF ARITHMETIC OPERATORS
UNARY OPERATORS
There are five types of Unary operators.
The increment and decrement operators : ++ -The unary plus and minus operators : + The Bitwise inversion operator : ~
The Boolean complement operator : !
The cast operator : ( )
The increment and decrement operators : ++ -These operators modify the values of an expression by adding and
subtracting 1.
Example
INITIAL
VALUE OF X
EXPRESSION
FINAL
VALUE OF Y
FINAL
VALUE OF X
5
Y= ++X;
6
6
5
Y= X++;
5
6
5
Y= --X;
4
4
5
Y= X--;
5
4
TABLE 2-5
PRE AND POST INCREMENT AND DECREMENT OPERATORS
Example of Increment and decrement operators
class op
{
public static void main ( String args [ ] )
{
int a=5, b=5, c=5, d=5;
System.out.println ( “a= “ + ++a );
System.out.println ( “b= “ + --b );
System.out.println ( “c= “ + c++ );
System.out.println ( “d= “ + d-- );
}
}
Output
a= 6
b= 4
c= 5
d= 5
Unary Plus and Minus operators ( + - )
Unary + and - operators are different from arithmetic + and - operators.
Unary + has. No effect because by default the number is positive. Unary - makes
the number negative.
Example
X=10 or X= +10;
Y= -5;
Z= -(X + Y);
The Bitwise Inversion Operator : ~
The ~ operator performs bitwise inversion on integral types. The bitwise
operator manipulates the bits within an integer. All of the integers types are
represented by binary numbers of varying bit width. The ~ operator works by
converting all the 1 bits in a binary value to 0s and all the 0 bits to 1.
For example, applying this operator to a byte containing 0000111 would
result in the value 1111000.
Actually, this is Bitwise Operator. But it affects only one variable. So it is
also called Unary Operator.
The Boolean Complement Operator : !
The ! operator inverts the value of a Boolean expression. So !true returns
false and !false returns true.
Example of Boolean Complement Operator
class boolop
{
public static void main (String args [ ] )
{
int x=5, y=10;
if (x < y)
System.out.println (“ x is greater than y : “ + !(x<y));
else
System.out.println (“ x is greater than y : “ + !(x<y));
}
}
Output
If x = 5 and y=10, output will be “ x is greater than y : false ” .
if x=10 and y=5 , output will be “ x is greater than y : true “.
The Cast Operator : ( )
Casting means assigning a value of one type to a variable of another type.
This operator is used for explicit conversion of the type of an expression.
General rules for casting
A Boolean data type may not be converted to any other data types.
A non Boolean may be automatically converted to another non-Boolean type if
the conversion is a widening conversion.
A non Boolean may not be automatically converted to another non-Boolean type
if the conversion is a narrowing conversion. But narrowing conversion is
possible with the use of cast ( ) operator.
Widening Conversion
Widening conversion means conversion of narrow data types to wide
data types.
BYTE
SHORT
CHAR
INT
LONG
FLOAT
DOUBLE
FIGURE 2-1 WIDENING CONVERSION
This figure shows all the widening conversions. The arrow can be
taken to mean, “Can be widened to.“ Java’s widening conversions are:
From a byte to short, int, long, float or double.
From a short to int, long, float or double.
From a char to int, long, float or double.
From an int to long, float or double.
From a long to float or double.
From a float to double
Example of Widening Conversion
class wcon
{
public static void main ( String args [ ] )
{
int i=100;
char c=’a’;
byte b=65;
double d = i;
float f = c;
int n = b;
// automatically converted from int to double
// automatically converted from char to float
// automatically converted from byte to int.
System.out.println (“double value of i = “+ d);
System.out.println (“float value of c = “+ f);
System.out.println (“int value of b
= “+ n);
}
}
Output
double value of i = 100.0
float value of c
= 97.0
int value of b
= 65
Narrowing Conversion
Narrowing conversion means conversion of wide data types to narrow data types .
Narrowing conversion is possible only through cast operator ( ).
Casting is somewhat risky because narrowing conversion loses the information
about the Magnitude of the value being converted.
Java’s narrowing conversions are :
From a byte to char
From a short to byte or char.
From a char to byte or short
From an int to byte, short or char.
From a long to byte, short, char or int.
From a float to byte, short, char, int or long.
From a double to byte, short, char, int, long or float.
Example of Narrowing Conversion
class ncon
{
public static void main ( String args [ ] )
{
double d=100.9087;
float f=100.75f;
int i=65;
int n = (int) d ; // converted from double to int
char c = (char) f; // converted from float to char
byte b = (byte) i; // converted from int to byte.
System.out.println ("integer value of d =" + n);
System.out.println ("character value of f =" + c);
System.out.println ("byte value of i =" + b);
}
}
Output
integer value of d
= 100
character value of f = d
byte value of i
= 65
COMPARISON OPERATORS
These operators compare two variables and return a logical value
based on whether the comparison is true or false. These operators are also known
as relational operators or conditional operators. Output of these operations is
Boolean value. The relational operators are most frequently used in the
expressions that control the if statement and other loop statements. For Ex. int
X=10, Y=5, Z=10;
OPERATOR
EXPRESSION
RESULT
EQUALS (== )
X == Y
FALSE
X == Z
TRUE
X != Y
TRUE
X != Z
FALSE
X>Y
TRUE
X>Z
FALSE
X< Y
FALSE
X<Z
FALSE
GREATER THAN OR
EQUAL TO ( >= )
X >= Y
TRUE
X >= Z
TRUE
LESS THAN OR
EQUAL TO ( <= )
X <= Y
FALSE
X <= Z
TRUE
NOT EQUALS ( != )
GREATER THAN ( > )
LESS THAN ( < )
TABLE 2-6 RESULT OF LOGICAL OPERATORS
SHORT – CIRCUIT LOGICAL OPERATORS
The Short – Circuit Logical operators && and || provide logical AND and
OR operations on Boolean types. The short – circuit logical operators are most
frequently used in the expressions that control the if statement and other loop
statements. eg.
boolean T = TRUE
boolean F = FALSE
OPERATOR
EXPRESSION
RESULT
LOGICAL OR ( || )
F || F
FALSE
F || T
TRUE
T || F
TRUE
T || T
TRUE
F && F
FALSE
F && T
FALSE
T && F
FALSE
T && T
TRUE
LOGICAL AND ( && )
TABLE 2-7 RESULT OF SHORT-CIRCUIT OPERATORS
With AND, if all conditions are true than and only than result will be true
otherwise false
With OR, if minimum one condition is true than result will be true otherwise
false.
Example of ‘And’ (&&)
class andex
{
public static void main ( String args [ ] )
{
int x=5, y=10, z=15;
if ( z>y && z>x)
System.out.println (“ Z is greatest number “);
}
}
Example of ‘Or’ (||)
class orex
{
public static void main ( String args [ ] )
{
char g=’f ’;
if ( g==’f ‘ || g==’m’)
System.out.println (“ This is correct Gender “);
}
}
BITWISE OPERATOR
The bitwise operators ~, &, ^ and | provide bitwise INVERSION, AND,
exclusive OR (XOR), and OR operations respectively, applicable to integral types.
Bitwise operators treat their operands as a set of 32 bits (0’s and 1’s) rather than
treating them as decimal, hexadecimal or octal numbers.
In bitwise operations, each result bit is calculated on the basis of the two bits
from the same, corresponding position in the operands.
For the AND operation, a 1 bit results if the first operand bit and the second
operand bit both are 1.
For the XOR operation, a 1 bit results only if exactly one operand bit is 1.
For the OR operations, a 1-bit result if either the first operand bit or the second
operand bit is 1.
A
B
~A
A&B
A^B
A|B
0
0
1
0
0
0
0
1
1
0
1
1
1
0
0
0
1
1
1
1
0
1
0
1
TABLE 2-8 RESULT OF BITWISE OPERATORS
Example
A=1101
B=1001
~A
A&B
A^B
A|B
0010
1001
0100
1101
SHIFT OPERATORS
Left – shift operators : <<
Right – shift operators : >>
Logical or unsigned Right – shift operator : >>>
Java provides two right side shifting operators ( >> >>> ) and one
left side ( << ) shifting operators. A shift operator allows you to perform bit
manipulation on data. This table summarizes the shift operators available in the
Java programming language.
Operator
Use
>>
A >> B
Operation
shift bits of A right by distance B
0101 ( 5 ) >> 1
-> 0010 ( 2 )
11111000 (-8) >> 1 -> 11111100 (-4)
shift bits of A left by distance B
<<
A << B
0101 ( 5 ) << 1
-> 1010 ( 10 )
11111000 (-8) << 1 -> 11110000 (-16)
shift bits of A right by distance B (unsigned)
>>>
A >>> B
0101 ( 5 ) >>> 1 ->
0010 ( 2 )
11111111 11111111 11111111 11111000 (-8) >>> 1 ->
01111111 11111111 11111111 11111100 ( 2147483644 )
TABLE 2-9
SHIFT OPERATORS IN JAVA
Left – Shift (<<) operator
This shift operator shifts left side the bits of the left-hand operand over by the
number of position indicated by the right-hand operand. eg.
10 << 1
Here 10 shifts left side 1 time.
Left-shift returns values as follows :
256 << 1 returns 256 * 21 = 512
34 << 2
returns
-16 << 3 returns
N << n
returns
34 * 22 = 136
-16 * 23 = -128
N * 2n
Right – Shift (>>) operator
This shift operator shifts right side the bits of the left-hand operand over by the
number of position indicated by the right-hand operand. eg.
10 >> 1
Here 10 shifts right side 1 time.
Right-shift returns values as follows :
256 >> 1 returns
256 / 21 = 128
34 >> 2
returns
34 / 22 = 8
-16 >> 3 returns
N >> n
returns
-16 / 23 = -2
N / 2n
Logical or unsigned Right – shift (>>>) operator
This shift operator shifts right side the bits of the left-hand operand over by the
number of position indicated by the right-hand operand. This shift operator
works on the bit pattern rather than the arithmetic meaning of a value and
always places 0s in the most significant bits. eg.
1010… >> 2 gives 111010…
1010… >>>2 gives 001010…
TERNARY OPERATOR ( ?: )
The unary operators support either prefix or postfix notation. Prefix notation means
that the operator appears before its operand:
operator op
Postfix notation means that the operator appears after its operand:
op operator
All of the binary operators use infix notation, which means that the operator appears
between its operands:
op1 operator op2
The ternary operator is also infix; each component of the operator appears between
operands:
op1 ? op2 : op3
ternary operator is one that requires three operands. The Java programming
language has one ternary operator, ?:, which is a short-hand of if-else statement.
Example of Ternary Operator
class terop
{
public static void main ( String args [ ] )
{
int x=10, y=5, z=0;
z= x>y ? x : y;
System.out.println (“The biggest number is :” +z);
}
}
Output
The biggest number is : 10
In this example z= x>y ? x : y; indicates that if x>y evaluates true then
value of x will be assigned to z, otherwise value of y will be assigned to z.
ASSIGNMENT OPERATORS :
Operators, which are used to assign value of one operand to another operand are
called as Assignment operators.
Simple assignment using =, assigns the value of the right - hand operand to the left hand operand.
The value of an object is it’s reference not its contents.
The type of right-hand operand must be compatible with the type of left-hand
operand
The assignment operators return a value so that they can be used within larger
expressions. The value returned is the value that was assigned to the left-hand
operand.
The compound assignment operators like a= a op b also written as a op= b.
Compound assignment operators are also called as Short – Hand assignment
operators.
Compound operators are given in the following table.
Operator
Use
Equivalent to
+=
A += B
A = A + B
-=
A -= B
A = A – B
*=
A *= B
A = A * B
/=
A /= B
A = A / B
%=
A %= B
A = A % B
&=
A &= B
A = A & B
|=
A |= B
A = A | B
^=
A ^= B
A = A ^ B
<<=
A <<= B
A = A << B
>>=
A >>= B
A = A >> B
>>>=
A >>>= B
A = A >>> B
TABLE 2-10 EXAMPLES OF ASSIGNMENT OPERATOR
String
10
Handling
STRING
String CLASS
The String Constructors
String Literals
Methods of “STRING” class
String Conversion and toString( )
StringBuffer CLASS
StringBuffer Constructors
Methods of StringBuffer class
THE MATH CLASS
Methods of Math class
THE WRAPPER CLASSES
STRING
String is a sequence of characters. Some languages implements strings as
character array. But java implements strings as objects of type String. Java has
various methods to compare two strings, search for a substring, concatenate two
strings, change the case of letters within a string etc.
String CLASS
There are many ways to construct a String objects. Once String object
created, it can’t be changed. But you can perform all types of strings operations.
When you need to make any change in an existing string, you may do it with
creating a new String object that contains all the modifications. The original string
is left unchanged. When, you desire modifiable string there is a comparison class
to String called StringBuffer is used.
The String Constructors
Default constructor
String str = new String ( );
It will create an instance of String with no character or an empty String.
Create a String initialized by an array of characters.
String(char c[ ]);
For Example,
char c[ ]={‘a’, ’b’, ’c’, ’d’};
String str = new String (c);
This constructor initializes a string with “abcd”.
Create String initialized by a subrange of a character array.
String (char c[ ], int start, int numberofcharacters);
For example,
char c[ ]={‘a’, ’b’, ’c’, ’d’, ’e’, ’f’, ’g’, ’h’};
String str = new String(c[ ],3,2);
This constructor initializes a string with “de”.
Create a String object that contains another String object.
String ( String Strobj );
For example,
char c[ ]={‘a’, ’b’, ’c’, ’d’};
String str = new String(c);
String str1 = new String(str);
Create a String, initialized by an array of bytes.
String (byte c[]);
For example,
char c[ ]={65, 66, 67, 68};
String str = new String(c);
This constructor initializes a string with “ABCD”.
Create String initialized by a subrange of a byte array.
String (byte c[ ], int start, int numberofcharacters);
For example,
byte c[ ]={65,66,67,68,69,70,71,72};
String str = new String (c[ ], 3, 2);
This constructor initializes a string with “DE”.
Note : The contents of the array are copied whenever you create a String object
from an array. If you modify the contents of the array after you have
created the string, the String will be unchanged.
String Literals
Without use of an array of characters, you can use a string literal to initialize a
string object.
char c[ ]={‘a’,’b’,’c’,’d’};
String str = new String(c);
Instead of above two statement, you can create a String object using one statement
String str= “abcd”;
// use a string literal
You can directly use any methods with the quoted string. For example
“abcd”.length( );
// will returns value 4.
Methods of “String” Class
There are convenient methods in String class. A number of these methods
perform a transformation on a string. For Ex., toUpper( ) converts all the
characters of string to upper case. Here, original string is not modified. It would
be impossible, since strings are immutable. The
methods listed below are the
most useful methods of the String class. There are more methods than those listed
here, and some of those listed have overloaded forms that take different inputs.
char charAt ( int index )
Returns the indexed character of a string,
where the index of the initial character is 0.
String concat ( String addthis )
This returns a new string consisting of the
old string followed by addthis.
int compareTo(String therstring )
This performs a lexical comparison ; returns
an integer <0 if the current string is less
than other string, =0 if both strings are
identical, >0 if the current string is greater
than other string
boolean endsWith ( String suffix )
This returns true if the current string ends
with suffix, otherwise returns false.
boolean equals ( Object ob )
This returns true if ob is instance of String,
otherwise it returns false. (case-sensitive)
boolean equalsIgnoreCase (String
s)
This is like equals( ), but the argument is a
String, and the comparison ignores case.
void getChars (int start,int end,
char c[ ], int astart);
To extract more than one characters from a
string. start specifies the index of the
beginning of the substring. end specifies
the index of the ending of the substring. c[
] specifies the array, where you want to
receive the characters, astart specifies the
index within array of the beginning to copy
the substring.
void getBytes (int start,int end,
Same as getChars( ) but extract bytes
byte b[ ], int astart);
instead of characters
char[ ] toCharArray( )
To convert all the characters in a String
object into a character array. It will returns
an array of characters for the entire string.
int indexOf ( char ch )
This returns the index within the current
string of the first occurrence of the ‘ch’. It
starts search from start index if it is given
otherwise start from beginning.
int indexOf ( String str )
int indexOf ( char ch, int
start_index )
int indexOf ( String str, int
start_index )
int lastIndexOf (char ch )
int lastIndexOf ( String str )
int lastIndexOf (char ch, int
start_index )
This returns the index within the current
string of the last occurrence of the ‘ch’. It
starts search from start index if it is given
otherwise start from beginning.
int lastIndexOf ( String str, int
start_index )
int length( )
This returns the number of characters
(length) in the current string.
replace (char oldchar, char
newchar )
This returns a new string, generated by
replacing every occurrence of oldchar with
newchar.
boolean startsWith ( String prefix )
This returns true if the current string begins
with suffix, otherwise returns false. Start
boolean startsWith ( String prefix,
int start_index )
index indicates beginning index of the
string.
String substring ( int start_index )
This returns the substring, beginning at
startIndex of current string and extending
to the end of current string.
String substring ( int start_index,
int end_index )
end_index indicates the ending index of the
string .
String toLowerCase ( )
This converts the executing object to lower
case and returns a new string
String toString( )
This converts the executing object to string.
String toUpperCase( )
This converts the executing object to upper
case and returns a new string
String Trim( )
This returns the string that results from
removing whitespace characters from the
beginning and ending of the current string
Example of String Class
class exstring1
{
String s1, s2, s3;
public static void main(String agrs[ ])
{
a ob=new a( );
ob.trim( );
ob.charat( );
ob.concat( );
ob.concatdiff( );
ob.compareTo( );
ob.length( );
ob.replace( );
ob.toLowerCase( );
ob.toUpperCase( );
ob.equals( );
}
void trim( )
{
s1=" aye ";
System.out.println ("s1 = "+s1);
System.out.println ("s1.trim( ) = "+s1.trim( ));
}
void charat( )
{
s1="Welcome to AYE";
System.out.println ("character at index 3 is = "+s1.charAt(3));
}
void concat( )
{
s1="Welcome ";
s2="to ";
s3="AYE ";
System.out.println ("s1 + s2 + s3 = "+s1.concat(s2).concat(s3));
}
void concatdiff( )
{
s1="your salary is ";
s2="5000";
i=7000;
s3=" only";
System.out.println ("s1+s2+s3 = " + s1+s2+s3);
System.out.println ("s1+i+s3 = " + s1+i+s3);
System.out.println ("s1+i+100+s3 = " + s1+i+100+s3);
System.out.println ("s1+(i+100)+s3 = " + s1+(i+100)+s3);
}
void compareTo( )
{
s1="aye";
s2="AYe";
System.out.println ("ascii value difference between a and A = " +
s1.compareTo(s2));
s1="aye";
s2="aYe";
System.out.println ("ascii value difference between y and Y = " +
s1.compareTo(s2));
}
void length( )
{
s1="Welcome to AYE";
System.out.println ("length of s1 is(including space) = "+s1.length());
}
void replace( )
{
s1="WelcOme tO aye";
System.out.println ("O is replaced with o in s1 = "+s1.replace('O', 'o'));
}
void toLowerCase( )
{
s1="WELCOME TO AYE";
System.out.println ("lower case = " + s1.toLowerCase( ));
}
void toUpperCase( )
{
s1="welcome to aye";
System.out.println ("upper case = " + s1.toUpperCase( ));
}
void equals( )
{
s1="AYE";
s2="AYE";
s3=new String(s1);
s4="aye";
System.out.println ("s1.equals(s2) = "+s1.equals(s2));
System.out.println ("s1==s2 = "+(s1==s2));
System.out.println ("s1.equals(s3) = "+s1.equals(s3));
System.out.println ("s1==s3 = "+(s1==s3)); //it will displays false because
s1 and s3 are distinct objects
System.out.println ("s1.equals(s4) = "+s1.equals(s4));
System.out.println ("s1.equalsIgnoreCase(s4) = " + s1.equalsIgnoreCase(s4));
}
}
Output
s1 = aye
s1.trim( ) = aye
character at index 3 is = c
s1 + s2 + s3 = Welcome to AYE
s1+s2+s3 = your salary is 5000 only
s1+i+s3 = your salary is 7000 only
s1+i+100+s3 = your salary is 7000100 only
s1+(i+100)+s3 = your salary is 7100 only
ascii value difference between a and A = 32
ascii value difference between y and Y = 32
length of s1 is (including space) = 14
O is replaced with o in s1 = Welcome to aye
lower case = welcome to aye
upper case = WELCOME TO AYE
s1.equals(s2) = true
s1==s2 = true
s1.equals(s3) = true
s1==s3 = false
s1.equals(s4) = false
s1.equalsIgnoreCase(s4) = true
Example of String Class
class b
{
String s1, s2, s3;
public static void main(String agrs[ ])
{
b ob=new b( );
ob.endsWith( );
ob.startsWith( );
ob.indexOf( );
ob.lastIndexOf( );
ob.substring( );
ob.getchar( );
}
void endsWith( )
{
s1="Welcome to Aye";
System.out.println (" s1.endsWith(Aye) :"+s1.endsWith("Aye"));
System.out.println (" s1.endsWith(aye) :"+s1.endsWith("aye"));
}
void startsWith( )
{
s1="Welcome to Aye";
System.out.println("s1.startsWith(Welcome) : "+s1.startsWith ("Welcome"));
System.out.println ("s1.startsWith(Aye,11) : "+s1.startsWith("Aye",11));
}
void indexOf( )
{
s1="All of you are welcomed to Aye All of you are welcomed to Aye";
System.out.println (" first A occurs at :" + s1.indexOf('A'));
System.out.println (" first A occurs after index 3 at:" + s1.indexOf('A',3));
System.out.println (" first Aye occurs at :" + s1.indexOf("Aye"));
System.out.println (" first Aye occurs after index 29 at:" +
s1.indexOf("Aye",29));
}
void lastIndexOf( )
{
s1="All of you are welcomed to Aye All of you are welcomed to Aye";
System.out.println (" last A occurs at :" + s1.lastIndexOf('A'));
System.out.println (" last Aye occurs at :" + s1.lastIndexOf("Aye"));
}
void substring( )
{
s1="wecome to Aye everybody";
System.out.println ("s1.substring(7) = "+s1.substring(7));
System.out.println ("s1.substring(7,14) = "+s1.substring(7,14));
}
void getchar( )
{
s1="this is an Aye computer education.";
char c[ ]=new char[30];
s1.getChars(5,15,c,0);
System.out.println(c);
s1.getChars(5,15,c,11);// it will repeats 11 characters
System.out.println(c);
}
}
Output
s1.endsWith(Aye) : true
s1.endsWith(aye) : false
s1.startsWith(Welcome) : true
s1.startsWith(Aye,11) : true
first A occurs at :0
first A occurs after index 3 at: 27
first Aye occurs at : 27
first Aye occurs after index 29 at: 58
last A occurs at : 58
last Aye occurs at : 58
s1.substring(7) = to Aye everybody
s1.substring(7,14) =to Aye
is an Aye
is an Aye is an Aye
String Conversion and toString( )
Every string implements toString( ), because it is defined by object. You can
override toString( ) and provide your own string representation.
String toString( ) :- It returns a String object that contains the human readable
string, which contains description of a class.
Example of toString( )
class netsal
{
double basic;
double da;
double hra;
//constructor used when three arguments given
netsal(double b, double d, double h)
{
basic=b;
da=basic*d;
hra=basic*h;
}
public String toString( )
{
return "your salary details are basic =" +basic+", da = " + da + " and
hra = "+ hra + ".";
}
}
class a1
{
public static void main(String args[])
{
netsal n = new netsal(5000,0.1,0.2);
String str= "netsal n : " + n; //concatenate netsal to string
System.out.println (n); // convert netsal to string
System.out.println (str);
}
}
Output
your salary details are basic=5000.0, da = 500.0 and hra = 1000.0.
netsal n : your salary details are basic = 5000.0, da = 500.0 and
hra= 1000.0.
StringBuffer CLASS
The object of StringBuffer contains strings that can be modified after they
are created. String and StringBuffer classes are declared as final because we can’t
be subclassed them. Both classes are defined in java.lang. So, they are
automatically available in the programs. The contents of string instance can’t be
changed after it has been created. But a variable declared as a String reference can
be changed to point at some other object at any time. StringBuffer is a peer class of
String that provides much of the functionality of Strings. StringBuffer represents
growable and writeable character sequences. StringBuffer may have characters
and substrings inserted in the middle or appended to the end. StringBuffer will
automatically grow to make room for such additions and often has more
characters preallocated than are actually needed, to allow more room for growth.
StringBuffer Constructors
StringBuffer( )
StringBuffer(int size)
: default constructor reserves 16 characters’ room without
reallocation
: size sets the buffer size
StringBuffer(String s) : sets the initial contents of the StringBuffer object and
reserves 16 characters’ room without reallocation
Methods of StringBuffer class
int length( )
Returns the number of characters of the StringBuffer
int capacity( )
Returns the total capacity of the StringBuffer
void ensureCapacity ( int c)
To set the size of the buffer
void setLength (int l)
To set the length of the buffer within a StringBuffer
object.
char charAt (int i)
Returns character at a given index from the StringBuffer
void setCharAt (int i, char ch)
To set a given character ch at index i in the StringBuffer
void getChar ( )
Same as method of String class
StringBuffer append ( String str )
To concatenate the string representation of any other
type of data to the end of the invoking StringBuffer
object.
StringBuffer append ( int i )
StringBuffer append ( object ob )
StringBuffer reverse ( )
To reverse the characters within a StringBuffer object.
StringBuffer insert ( int i, char ch )
To insert one string into another string at a specified
index i.
StringBuffer insert(int i, String str )
StringBuffer insert (int i, object ob )
StringBuffer delete ( int s_index,
int e_index )
To delete characters starting from start index to end
index.
StringBuffer delCharAt ( int i )
To delete one character of the string placed on i index
Example of StringBuffer Class
class b
{
StringBuffer s1, s2, s3;
public static void main(String agrs[ ])
{
b ob=new b( );
ob.capacity( );
ob.length( );
ob.setcharat( );
ob.append( );
ob.reverse( );
ob.insert( );
ob.delete( );
}
void capacity( )
{
s1=new StringBuffer( );
System.out.println ("Default capacity of s1= " +s1.capacity());
s1=new StringBuffer("AYE");
System.out.println ("Capacity of s1= " +s1.capacity( ));
s1.ensureCapacity(10);
System.out.println ("New capacity of s1= " +s1.capacity( ));
}
void length( )
{
s1=new StringBuffer("Welcome to AYE");
System.out.println("s1= " +s1);
System.out.println("Length of s1= " +s1.length( ));
s1.setLength(10);
System.out.println("New length of s1= " +s1.length( ));
System.out.println("s1= " +s1);
}
void setcharat( )
{
s1=new StringBuffer("All of you are welcomed to AYE");
System.out.println ("s1=" +s1);
System.out.println ("Character at index 5=" +s1.charAt(5));
s1.setCharAt(5,'O');
System.out.println("New character at index 5=" + s1.charAt(5));
}
void append( )
{
String s;
int i=5000;
s2=new StringBuffer(40);
s=s2.append("\”Salary = ").append( i ).toString( );
System.out.println ("String s2 = " +s2+”\””);
}
void reverse( )
{
s1=new StringBuffer("Welcome to AYE");
System.out.println ("String s1=" +s1);
System.out.println ("Reverse string= "+s1.reverse( ));
}
void insert( )
{
s1=new StringBuffer("I AYE");
s2=new StringBuffer("am proud of ");
System.out.println("New string after inserting="+s1.insert(2,s2));
}
void delete( )
{
s1=new StringBuffer("Welcome to AYE");
s1.deleteCharAt (0);
System.out.println ("New string after deleting character="+s1);
s1.delete(0,8);
System.out.println ("New string after deleting characters="+s1);
}
}
Output
Default capacity of s1= 16
Capacity of s1= 19
New capacity of s1= 19
s1= Welcome to AYE
Length of s1= 14
New length of s1= 10
s1=Welcome to
s1=All of you are welcomed
Character at index 5=f
New character at index 5=F
String s2= “Salary=5000”
String s1=Welcome to AYE
Reverse string= EYA ot emocleW
New string after inserting= I am proud of AYE
New string after deleting character= elcome to AYE
New string after deleting characters= AYE
THE MATH CLASS
Java’s Math class contains a collection of methods and two constants that
support mathematical computation. As this class is final it can’t be extended. The
constructor of this class is private, so you can’t create an instance. But these
methods and constructors are static, so they can be accessed through the class
name without having to construct a Math object. The two constants of Math class
are :
Math.PI
Math.E
They can be declared as public, static, final and double.
Methods of Math class
int abs( int i )
Returns the absolute value of i
long abs( long i )
float abs( float i)
double abs( double i )
double ceil( double d )
Returns as a double the smallest integer that is
not greater than d
double floor( double d )
Returns as a double the largest integer that is
not greater than d
int max( int i1, int i2 )
Returns the greater of i1 and i2
float max( float i, float i2 )
long max( long i1, long i2 )
double max( double i1,
double i2 )
int min( int i1, int i2 )
Returns the smaller of i1 and i2
float min( float i, float i2 )
long min( long i1, long i2 )
double min( double i1,
double i2 )
double random( )
Returns a random number between 0.0 and 1.0
int round( float f )
Returns the closest int to f
long round( double f )
Returns the closest long to f
double sin( double d )
Returns the sine of d
double cos( double d )
Returns the cosine of d
double tan( double d )
Returns the tangent of d
double sqrt( double d )
Returns the square root of d
THE WRAPPER CLASSES
Each java primitive has a corresponding wrapper class. A wrapper class is
simply a class that encapsulates a single, immutable value. For Ex. the Integer
class wraps up an int value, and the Float class wraps up a float value.
Primitive Data Type
Wrapper Class
boolean
Boolean
Byte
Byte
Char
Character
short
Short
Int
Integer
Long
Long
Float
Float
double
Double
Flow Controls &
Arrays
BRANCHING STATEMENTS
IF …. ELSE
SWITCH …CASE
LOOPING STATEMENTS
For( ) loop
While( ) loop
Do( ) Loop
SPECIAL LOOP FLOW CONTROLS
Labels
Break
Continue
Return
ARRAYS
Declaration
Construction
Initialization
Examples
Non Rectangular Arrays
Resizing Arrays
Length of arrays
Copying arrays
3
When you write a program, you type Java language statements into a file.
Without flow control statements, the interpreter executes these statements in the
order they appear in the file from top to bottom, left to right. You can use flow
control statements in your programs to conditionally execute statements, to loop
over a block of statements, and so on.
In java flow controls are divided into three categories.
Branching Statements
Looping Statements
Special Loop Flow Controls
: if….else, switch….case
: for…loop, while…loop, do…loop.
: label, break, continue, return.
BRANCHING STATEMENTS
Branching statements are also called selection statements. They
control the flow of program’s execution based upon conditions.
IF …. ELSE
You can easily write simple conditional code or choice of two
execution path based on the value of a boolean expressions using if ( ) /else
although you can create nests or sequences to select between a greater range of
possibilities.
Syntax
If ( condition )
{
statements or block;
}
else if ( condition )
{
statements or block;
}
else if ( condition )
{
statements or block;
}
else
{
statements or block;
}
The if statement takes conditions as Boolean arguments in ( ).
After if ( ), the else part is optional.
Braces { } are used to create a block of statements.
If keyword used to conduct a conditional test and execute a block of
statements if the test evaluates to true.
Else keyword used to execute a block of statements in the case that the test
condition with the "if " keyword evaluates to false.
Example of If…else
class ifex
{
public static void main ( String args [ ])
{
int a=10, b=20;
if (a > b)
System.out.println (“ a is greater than b “);
else
System.out.println (“ b is greater than a “);
}
}
Output
b is greater than a
Description
Here if ( a>b ), condition evaluates true than output will be “a is greater
than b” otherwise output will be “b is greater than a”
Example of If….elseif
class grade
{
public static void main ( String args [ ] )
{
char g;
int tot=0, eng=0, sc=0;
eng=50;
sc=80;
tot=eng + sc;
if ( tot>150 && eng>=50 && sc>=50)
{
System.out.println (“ Grade is A “);
System.out.println (“ Student has got result : CREDIT” );
}
else if ( tot>100 && eng>=50 && sc>=50)
{
System.out.println (“ Grade is B “);
System.out.println (“ Student has got result : PASS” );
}
else
{
System.out.println (“ Grade is C “);
System.out.println (“ Student has got result : FAIL” );
}
}
}
Output
Grade is B
Student has got result : PASS
Description
if all three conditions (tot > 150), (eng > 50), (sc > 50) evaluates true than and only
than the output is Grade is A and Student has got result : CREDIT.
If first condition evaluates false and all three conditions (tot > 100), (eng > 50), (sc >
50) evaluates true than and only than the output is Grade is B and Student has
got result : PASS.
If both conditions are false than the output is Grade is C and Student has got result :
FAIL
Nested If
A nested if is if statement within a block of another if statements. A nested if
is if statement, that is a target of another if or else statement.
Example of Nested If
class salary
{
public static void main ( String args [ ] )
{
int sal=6000;
double hra=0.0;
char citygrade=’b’;
if (citygrade==’a’)
{
if (sal >5000)
hra=sal * 0.30;
else
hra=sal * 0.20;
}
else
{
if (sal >5000)
hra=sal * 0.25;
else
hra=sal * 0.15;
}
System.out.println (“ HRA IS : “ + hra);
}
}
Output
HRA IS : 1500
Description
If (citygrade ==a) evaluates true than
(sal > 5000) evaluate true than hra will 30% of salary
(sal > 5000) evaluate false than hra will 20% of salary
If (citygrade ==a) evaluates false than
(sal > 5000) evaluate true than hra will 25% of salary
(sal > 5000) evaluate false than hra will 15% of salary
SWITCH …CASE
Switch keyword used to evaluate a variable that can later be matched with a
value specified by the "case" keyword in order to execute a group of statements. If
you need more complex choices between multiple execution paths, and if an
appropriate argument is available to control the choice, than you can use switch( )
statement.
Syntax
Switch (Expression )
{
case value1:
{
statement or block;
break; // exit from switch…case
}
case value2:
{
statement or block;
break;
}
:
:
:
case valuen:
{
statement or block;
break;
}
default:
{
statement or block;
break;
}
}
A switch statement is usually more efficient than a set of nested if s
You can use only int, byte, short, and char expression with switch
statement.
You can’t use long, float, double, boolean or an object reference with switch
statement.
The argument to case statement must be a constant or constant expression
that can be calculated at compile time.
Only single argument can be taken by case label. To create list of values
leading same point, use multiple case statements
“default” keyword optionally used after all "case" conditions in a "switch"
statement. If all "case" conditions are not matched by the value of the
"switch" variable, the "default" keyword will be executed.
Nine out of ten switch statements will need breaks in each case block.
Forgetting the break statement is the number one programming error in
using switch statements.
Example of Switch …. Case
class switchex
{
public static void main ( String args [ ] )
{
int month = 8;
switch (month)
{
case 1:
System.out.println ("January");
break;
case 2:
System.out.println ("February");
break;
case 3:
System.out.println ("March");
break;
case 4:
System.out.println ("April");
break;
case 5:
System.out.println ("May");
break;
case 6:
System.out.println ("June");
break;
case 7:
System.out.println ("July");
break;
case 8:
System.out.println ("August");
break;
case 9:
System.out.println ("September");
break;
case 10:
System.out.println ("October");
break;
case 11:
System.out.println ("November");
break;
case 12:
System.out.println ("December");
break;
default:
System.out.println ("Hey, invalid month!");
break;
}
}
}
Output
August
Description
If month is 1 output will be “January”, month is 2 then output will be
February……….. , month is 12 then output will be December.
If month is not between 1 to 12 than output will be “Hey, invalid month!”
Example of Switch….Case
class days
{
public static void main ( String args [ ])
{
int month = 2;
int year = 2000;
int Days = 0;
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
Days = 31;
break;
case 4:
case 6:
case 9:
case 11:
Days = 30;
break;
case 2:
if (year % 4 == 0)
Days = 29;
else
Days = 28;
break;
}
System.out.println ("Number of Days = " + Days);
}
}
Output
Number of Days = 29
Description
If month is 1, 3, 5, 7, 8, 10 or 12 than days =31 and case( ) will be terminated and
output will be “Number of Days = 31”
If month is 4, 6, 9, or 11 than days =30 and case will be terminated and output will be
“Number of Days = 30”
If month is 2 than (year % 4 == 0) evaluates true than days=29 and if
(year % 4 == 0) evaluates false than days=28
Nested Switch statements
A switch statement, which is a part of another switch statement, is called as
nested switch statement. No conflicts arise between the case constants of inner
and outer switch because a switch statement defines its own block.
Example of nested Switch Statements
class switchnest
{
public static void main ( String args [ ])
{
int category=1;
char gender=’f’;
switch(gender)
{
case ‘f’:
switch(category)
{
case 1:
System.out.println (“She is a smart girl”);
break;
case 2:
System.out.println (“She is a dull girl”);
break;
}
break;
case ‘m’:
switch(category)
{
case 1:
System.out.println (“He is a smart boy”);
break;
case 2:
System.out.println (“He is a dull boy”);
break;
}
break;
default:
System.out.println (“invalid gender”);
break;
}
}
}
Output
She is a smart girl.
LOOPING STATEMENTS
Loop statements allow for the repeated execution of blocks of statements
until some conditions occur. Each loop is controlled by an expression that must be
of boolean type. Java provides three loop constructions. Taken from C, C++, these
are the
for ( ) loop
while Loop
do( ) Loop
For( ) loop
A common requirement in programming is to perform a loop so that a
single variable is incremented over a range of values between two limits. This is
frequently provided by for loop.
Syntax
for ( initialization; termination; increment)
{
statements;
}
Initialization :
Termination :
is a statement that initializes the loop--it's executed once at the
beginning of the loop.
is an expression that determines when to terminate the loop.
This expression is evaluated at the top of each iteration of the
Increment
:
loop. When the expression evaluates to false, the loop
terminates.
gets invoked for each iteration through the loop. Any (or all) of
these components can be empty statements.
The for statement provides a compact way to iterate over a range of values
The for keyword is used to declare a loop that reiterates statements.
The programmer can specify the statements to be executed, exit conditions,
and initialization variables for the loop.
In for ( ), the test occurs at the “top” of the loop, so the body might not be
executed at all.
In for loop having two control variables, comma is used between two
control variables in the initialization and iteration.
Example of For Loop
class forex
{
public static void main(String args [ ])
{
int i;
for (i=0; i<5;i++)
System.out.println (" value of i is "+ i);
}
}
Output
value of i is 0
value of i is 1
value of i is 2
value of i is 3
value of i is 4
Description
This program prints repeatedly value of i until i<5 evaluates false. When i=5
loop will be terminated.
For loop without use of initialization and increment
It is not necessary to give all three arguments initialization, termination and
increment in for loop. We can also write for loop without use of initialization or
termination or increment..
Example of For loop
class forex1
{
public static void main(String args [ ])
{
int i=0;
for (; i<5;)
{
System.out.println (i);
i++;
}
}
}
Output
0
1
2
3
4
Example of For Loop without any argument
class forex2
{
public static void main(String args [ ])
{
int i=0;
for (; ;)
{
System.out.println (i);
i++;
if (i==5)
break;
}
}
}
Output
0
1
2
3
4
Variable initialization in For Loop
We can also declare a data type of loop control variable inside the for loop.
So instead of using two statements only one for loop statement used
int i;
i=0;i<5;i++){ }
for
(int
for (i=0;i<5;i++){ }
Example of Prime Number
class primenum
{
// program for checking a given number is prime or not
public static void main(String args [ ])
{
int n=18,m=1;
for (int i=2; i<=n/2;i++)
{
if(( n % i ) == 0)
{
m=0;
break;
}
}
if (m==1)
System.out.println (" Given number is Prime ");
else
System.out.println (" Given number is not Prime ");
}
}
Output
Given number is not Prime
For loop with comma separator
You can give more than one control variables in initialization or
increment. Two control variables are separated by “ , “.
Example of For Loop with Comma Seperator
class twovar
{
public static void main(String args[ ])
{
int x, y;
for (x=1,y=1;(x*y)<20;x++,y++)
System.out.println (" x= " + x + ” y = ” + y + “ x*y= ” +
x*y);
}
}
Output
x=1 y=1 x*y=1
x=2 y=2 x*y=4
x=3 y=3 x*y=9
x=4 y=4 x*y=16
Nested for loop
Java allows nested for Loops. Nested for loop is for loop within a for loop.
In nested for loop first, if outer for loop condition evaluates true than control goes
to inner for loop. When, inner for loop condition evaluates false than and than
only control goes to outer for loop.
Example of Nested For Loop
class nestfor
{
public static void main(String args [ ])
{
for (int i=1;i<=5;i++)
{
for(int j=1; j<=i; j++)
System.out.print (j);
System.out.println ( );
}
}
}
Output
1
12
123
1234
12345
Infinite for loop
If you don’t specify the condition of termination of for loop in for
loop arguments and in block of for loop, than control will not come out from for
loop and loop will be Infinite Loop.
Example of Infinite For Loop
class infinitefor
{
public static void main(String args [ ])
{
int i=0;
for (; ;)
{
System.out.print (i);
i++;
}
}
}
Output
0 to n
While loop
“While” keyword is used to declare a loop, that iterates a block of
statements. The loop’s exit condition is specified as part of the while statement.
While loop is a simple loop of java. It repeats a statement or block of statements
until its controlling condition is false.
Syntax
While (condition or expression)
{
statement ;
block of statements ;
}
or
While is called pre-check loop because it checks condition first.
Condition or expression must be boolean.
A statement or block of statements will be executed until the condition is
false.
When condition is false, the control passes to next line immediately after the
while loop.
In while ( ), the test occurs at the “top” of the loop, so the body might not be
executed at all.
Example of While Loop
class whileex1
{
public static void main(String args[ ])
{
int i=0;
while ( i<5 )
{
System.out.println (" value of i is "+i);
i++;
}
}
}
Output
value of i is 0
value of i is 1
value of i is 2
value of i is 3
value of i is 4
Description
This program prints repeatedly value of i until i<5 evaluates false. When i=5
loop will be terminated.
Example of While Loop
class whileex2
{
public static void main ( String args [ ])
{
int i=0,j=0;
while((++i)*(++j)<20)
System.out.println (i*j);
}
}
Output
1
4
9
16
Do Loop
Do keyword used to declare a loop that will iterate a block of
statements. The loop’s exit condition can be specified with the "while" keyword.
Do loop is similar to while( ) loop but in general, do loop is probably less
frequently used than while( ) loop.
Syntax
do
{
statement; or
block of statements;
} while (condition or expression);
“do” loop is called post-check loop because it checks condition after.
In do, the test occurs at the end of the loop so the body of the loop definitely
executes at least once.
Condition or expression must be boolean.
A statement or block of statements will be executed until the condition is
false.
When condition is false, the control passes to next line immediately after the
while loop.
Example of Do Loop
class doex1
{
public static void main(String args[ ])
{
int i=10;
do
{
System.out.println (" value of i is "+i);
i++;
} while ( i<5 );
}
}
Output
value of i is 10
Description
This program prints value 10 and after that it will check while
condition. So, now i will be 11 and then loop will be terminated.
Example of Do Loop
class doex2
{
public static void main ( String args [ ])
{
int i=1,j=1;
do
{
System.out.println (i*j);
} while((++i)*(++j)<20);
}
}
Output
1
4
9
16
SPECIAL LOOP FLOW CONTROLS
These special loop flow controls are also called jump controls or branching
controls. They are used if you don’t want to follow the sequence of statements in
loops. In java, four special loop flow controls are available
label
break
continue
return
Label
The break statement and the continue statement, which are covered next, can
be used with or without a label. A label is an identifier placed before a statement.
The label is followed by a colon (:):
Label:
Statement ;
Break
Break keyword is used to resume program execution at the statement
immediately following the current statement. If followed by a label, the program
resumes execution at the labeled statement. Break statement is used to exit from
switch statements, loop statements or labeled blocks.
Syntax
break;
or
break <label>;
In nested loop break terminates that loop in which it is included.
In for loop break statement takes priority before for loop condition.
If ( ) condition can’t be terminated by break statement.
Example of Break Statement
class breakex1
{
public static void main(String args[ ])
{
for (int i=1;i<=10 ;i++)
{
if (i==5)
break;
System.out.print ( i );
}
}
}
Output
1234
Description
If i==5 condition evaluates true than for loop will be terminated whether for
loop condition i<=10 evaluates true or false.
Break with nested loop
Break statement can be used with nested loops also.
terminates that loop in which it is included.
Example of Break with nested loop
class prime
{
public static void main ( String args [ ])
{
boolean isprime;
for (int i=2; i<=10;i++)
{
isprime=true;
for (int j=2;j<=i/2;j++)
{
if(i%j==0)
{
isprime=false;
break; // terminates the inner for loop.
}
}
if (isprime==true)
System.out.println ("prime" +i);
else
System.out.println ("not prime" +i);
}
}
}
Output
prime 2
prime 3
not prime 4
prime 5
not prime 6
prime 7
not prime 8
Break
not prime 9
not rime 10
Break with labels
In nested loop, normally break statement terminates the loop in
which it is included. But If we want to terminate the other loop in which it is not
included than we can use labels. Then we can terminate any outer loop in the
program with break statement in inner loop.
Example of Break with Labels
class breakex2
{
public static void main ( String args [ ])
{
outer: for(int i=0;i<=100;i++)
{
inner: for(int j=1; <=i; j++)
{
if (i==5)
break outer; // terminates outer for loop
System.out.print (j);
}
System.out.println (" ");
}
}
}
Output
1
12
123
1234
Example of Break
class breakex2
{
public static void main ( String args [ ])
{
int i;
outer: for( i=0;i<=6;i++)
System.out.println (i);
inner: for(int j=1; <=i; j++)
{
if (i==5)
break outer; // it will display error
System.out.print (j);
}
}
}
Above program display an error message like no label definition found for
outer during compilation. Because we are using the break outer statement in inner
loop, which is not nested loop of outer loop. So we can’t break outer loop from the
inner loop.
Continue
Continue keyword is used to resume program execution at the end of the
current loop. If followed by a label, "continue" resumes execution where the label
occurs.
Syntax
continue;
or
continue <label>;
Continue statement skips the current iteration of for, while, or do-while
loop.
The unlabelled form skips to the end of the innermost loop's body and
evaluates the boolean expression that controls the loop, basically skipping
the remainder of this iteration of the loop.
Example of Continue
class even
{
public static void main ( String args [ ])
{
for(int i=1;i<=10;i++)
{
if (i%2!=0)
continue; // will skip next statements and continue with the for loop
System.out.println (“Even No. : “ + i );
}
}
}
Output
Even No : 2
Even No : 4
Even No : 6
Even No : 8
Even No : 10
Continue with labels
Continue statement is used with labels also. Through continue
statement we can continue with any outer loop and terminate the inner loop.
Example of Continue with Label
class continue
{
public static void main ( String args [ ])
{
outer: for(int i=1;i<=5;i++)
{
System.out.println (" ");
inner: for(int j=1;j<=10;j++)
{
if (j>i)
continue outer; //control terminates inner for loop and continue
with outer loop
System.out.print (j);
}
}
}
}
Output
1
12
123
1234
12345
Return
A return keyword used to finish the execution of a method. It can be
followed by a value required by the method definition. You use return to exit
from the current method and jump back to the statement within the calling
method that follows the original method call. There are two forms of return: one
that returns a value and one that doesn't. To return a value, simply put the value
(or an expression that calculates the value) after the return keyword:
return <expression or value >;
The value returned by return must match the type of method's declared
return value. When a method is declared void use the form of return that doesn't
return a value:
return ;
ARRAYS
A group of variables of the same type that can be referenced by a common
name is called an Array. An array is a collection of data items, all of the same type,
in which each item's position is uniquely designated by an integer. A java arrays
is a collection of primitives, object references, or other arrays.
Arrays provide easy way to name a set of variables. Suppose we want to
store 100 names of students, than 100 variables are required to store these names
and also required 100 declaration statements to store one by one variable for
storing a student’s name. This procedure is a very cumbersome and it increases
the length of the program. Java has an inbuilt array as data structure, which
removes this complexity. It is an arrangement to store variables by declaring a
single array and we can easily access the contained value for each variable by the
array’s name and a number, which is called an index or subscript or element of
the array. The subscript used to index, the individual array elements will always
begin from 0, and its range between greater than or equal to 0 and less than the
array length.. If we access the array element outside this range will give a runtime
error.
There are three steps to create arrays
Declaration
Construction
Initialization
Declaration
Declaration includes the name of an array and type of elements of an array.
Square brackets can be used before or after array brackets. Arrays can be either
single dimensional or multi dimensional.
array elements = [ ]*[ ]*[ ]
Syntax
Single dimensional array
type array_name [ ]
or
type[ ] array_name
Example
int array1[ ];
// single- dimensional array
double array2 [ ];
float array3 [ ];
long[ ] array4;
Multi dimensional array
type array_name [ ] [ ]
or
type[ ] [ ] array_name
or
type array_name [ ] [ ] [ ]
or
type[ ] [ ] [ ] array_name
Example
int array5[ ] [ ];
double array6 [ ] [ ] [ ];
long[ ] [ ] array7;
float [ ] [ ] [ ] array8;
//
//
two- dimensional array
three – dimensional array
Construction
Construction specifies the size of an array. Declaration does not specify the
size(no of elements) of an array. Size is specified at runtime, when the array is
allocated via the new keyword.
Syntax
array_name = new type [ ];
Example
array1 = new int[ 25];
As array size is not used until runtime, it is legal to specify size with a variable
instead of literals.
int a = 5*5;
int array1[ ];
array1 = new int [a];
Declaration and Construction can be performed in a single line also.
int array1[ ] = new int [25];
Initial value of array elements
Element Type
Initial Value
Element Type
Initial Value
byte
int
short
long
float
double
char
boolean
0.0f
0.0d
‘\u0000’
false
0
0
0
0L
Initialization
Initialization means to store different values from above initial values in
elements of an array Initializing all variables, including elements of arrays, is
essential to the security of the system. variables can’t be used without
initialization. You can also combine declaration, construction and initialization
into a single step.
Example
array1
elements
int array1[ ];
[5]
array1 = new int [5];
[4]
5
4
3
for ( int j=0; j<5; j++ )
array1[ j ] = j+1;
[2]
[ 3]
2
[1]
1
OR
int array1[ ] = {1, 2, 3, 4, 5};
OR
int array1[ ];
array1 = new int [5];
array1[ 0 ]=1;
array1[ 1 ]=2;
array1[ 2 ]=3;
array1[ 3 ]=4;
array1[ 4 ]=5;
Example of Single Dimensional Array
class result
{
public static void main ( String args [ ] )
{
double marks[ ]={90,40,50,60,80};
double sum = 0;
for(int i=0;i<5;i++)
{
sum=sum + marks[ i ];
}
System.out.println ("total marks : " + sum);
System.out.println ("percentage : " + sum/5);
}
}
Output
total marks : 320.0
percentage : 64.0
Example of Sorting Array
class sortarray
{
public static void main(String[ ] args)
{
int[ ] arr1 = { 35, 97, 100, 40, 60, 0, 5000};
for (int i = arr1.length; --i >= 0; )
{
for (int j = 0; j < i; j++)
{
if (arr1[j] > arr1[j+1])
{
int temp = arr1[j];
arr1[j] = arr1[j+1];
arr1[j+1] = temp;
}
}
}
for (int i = 0; i < arr1.length; i++)
System.out.print (arr1[i] + " ");
System.out.println ( );
}
}
Output
0 35 40 60 97 100 5000
Example of Two Dimensional Array
class twodim
{
public static void main ( String args [ ])
{
int arr[ ][ ]=new int[4][3];
int k=0;
int i, j;
for(i=0;i<=3;i++)
{
for(j=0;j<=2;j++)
arr[i][j]=++k;
}
for(i=0;i<=3;i++)
{
for(j=0;j<=2;j++)
System.out.print (" arr[" + i +"][" + j + "]=" + arr[i][j] );
System.out.println (" ");
}
}
}
Output
arr[0][0]=1
arr[1][0]=4
arr[2][0]=7
arr[3][0]=10
arr[0][1]=2 arr[0][2]=3
arr[1][1]=5 arr[1][2]=6
arr[2][1]=8 arr[2][2]=9
arr[3][1]=11 arr[3][2]=12
arr [ ] [ ]
row column
0
1
0
1
2
1
4
5
2
7
8
3
10 11
2
3
6
9
12
Non Rectangular Arrays
In java it is compulsory to allocate memory for the first
dimension in multi dimension arrays. We can allocate memory to remaining
dimension afterwards. In non-rectangular arrays number of rows elements are
fixed, but number of columns for each row are different. For Ex.
int array1[ ][ ]=new int [5][ ]; //valid statement
int array2[ ][ ]=new int[ ][5]; // invalid statement
Example of Non-Rectangular array
class nrarray
{
public static void main ( String args [ ])
{
int arr[ ][ ]=new int[5][ ];
arr[0]=new int[1];
arr[1]=new int[2];
arr[2]=new int[3];
arr[3]=new int[4];
arr[4]=new int[5];
for(int i=0;i<=4;i++)
{
for(int j=0;j<i+1;j++)
{
arr[i][j]=j+1;
System.out.print (arr[i][j]);
}
System.out.println (" ");
}
}
}
Output
1
12
123
1234
12345
Example of Multi Dimensional Array
class threedim
{
public static void main ( String args [ ])
{
int arr[ ][ ][ ]=new int[4][3][2];
int k, i, j;
for(i=0;i<=3;i++)
{
for(j=0;j<=2;j++)
{
for(k=0;k<=1;k++)
arr[i][j][k]=i+j+k;
}
}
for(i=0;i<=3;i++)
{
for (j=0;j<=2;j++)
{
for (k=0;k<=1;k++)
System.out.print ("arr["+i+"]["+j+"]["+k+"] = "+arr[i][j][k]+" " );
System.out.println (" ");
}
System.out.println (" ");
}
}
}
Output
arr[0][0][0] = 0 arr[0][0][1] = 1
arr[0][1][0] = 1 arr[0][1][1] = 2
arr[0][2][0] = 2 arr[0][2][1] = 3
arr[1][0][0] = 1 arr[1][0][1] = 2
arr[1][1][0] = 2 arr[1][1][1] = 3
arr[1][2][0] = 3 arr[1][2][1] = 4
arr[2][0][0] = 2 arr[2][0][1] = 3
arr[2][1][0] = 3 arr[2][1][1] = 4
arr[2][2][0] = 4 arr[2][2][1] = 5
arr[3][0][0] = 3 arr[3][0][1] = 4
arr[3][1][0] = 4 arr[3][1][1] = 5
arr[3][2][0] = 5 arr[3][2][1] = 6
Resizing Arrays
You can also resize arrays after construction of the arrays. By
resizing arrays you can change number of elements of the array. For Ex.
int arr[ ][ ]=new int [5][ ]; // no of rows are 5.
arr=new int[10][ ];
// no of rows are 10.
Length of Array
In java, all arrays have one instance variable length, which
holds the number of elements or size of array.
Example of Length of Array
class arrlength
{
public static void main ( String args [ ])
{
int arr[ ]={1,2,3,4,5};
int arr1[ ]={1,2,3,4,5,6,7};
int arr2[ ]={1,2,3};
System.out.println ("no of elements of arr : "+arr.length);
System.out.println ("no of elements of arr1: "+arr1.length);
System.out.println ("no of elements of arr2: "+arr2.length);
}
}
Output
No of elements of arr : 5
No of elements of arr1 : 7
No of elements of arr2 : 3
Copying arrays
You can also copy values of elements of one array into other array.
Source array elements that you want to copy must be less than or equal to
target array elements.
Syntax
System.arraycopy (source_array, start_ind, target_array, start_ind, elements )
source_array
start_ind
target_array
start_ind
elements
:::::-
array name from which you want to copy elements.
index of element in source array from which you want to start copy
array name where you want to copy elements.
index of element in target array from where you want to start copy
number of elements you want to copy in target array.
( target_array.length – start_index (target array)) must be greater than or
equal to elements otherwise it will display error message
Java.lang.ArrayIndexOutOfBoundsException
Example of Copying Array
class arrcopy
{
public static void main ( String args [ ])
{
int arr[ ]={1,2,3,4,5};
int arr1[ ]={11,12,13,14,15,16,17};
System.arraycopy (arr, 0, arr1, 0, arr.length);
for (int i=0; i<arr1.length; i++)
System.out.print (arr1[i]+” “ );
}
}
Output
1 2 3 4 5 16 17
Description
This program copies all the elements of array arr into array
arr1. if you will try to copy all elements of arr1 into arr than it will display an
error message
Java.lang.ArrayIndexOutOfBoundsException
Because number of elements you are copying, are more than number of elements
of target array.
Inheritance
6
INHERITANCE
SUBCLASS – SUPERCLASS
The “is a” relationship
The “has a” relationship
“super” Key-Word
Multi-Level Inheritance
METHOD OVERRIDING
Runtime Polymorphism
INHERITANCE
Inheritance is a very strong feature of the object-oriented programming
because it allows creating a hierarchical classification. Using this we can create a general
class, which contains common set of items. Then another classes inherits from that
general class can use its features. This general class is called as Superclass and another
class, which inherits general class, is called as Subclass. Subclass is specialized version of
the superclass, which inherits all of the instance variables and methods defined by the
superclass, and adds its own unique elements. “extends” key-word is used to inherit a
class.
Code reuse can be achieved by simply reusing classes by composition or by
inheritance.
Java allows a class to extends only one other class, which is called single
inheritance.
Java doesn’t support multiple inheritance but interfaces provide this facility.
Java supports multi-level inheritance.
SUBCLASS - SUPERCLASS
A subclass is a class that extends another class.
A subclass inherits variables and methods from its superclass and all of its
ancestors but the vice-versa is not possible.
Subclasses inherit those superclass members declared as public or protected.
Subclasses inherit those superclass members declared as friendly but only when
subclass and superclass should be in the same package.
A superclass can have any number of subclasses but a subclass can directly have
only one superclass
The subclass knows the properties and methods of its superclass but the
superclass doesn’t know about the different properties and methods of
subclasses.
Subclass can’t inherit the constructors from its superclass.
Subclasses don't inherit a superclass 's member if the subclass declares a member
with the same name. In the case of member variables, the member variable
in the subclass hides the one in the superclass. In the case of methods, the
method in the subclass overrides the one in the superclass.
Syntax for creating a subclass
class subclassname extends superclassname
{
body of subclass
}
The is a Relationship
In programming we often create a general model of something (For ex.
Employee) and then create a more specialized version of that general model (For Ex.
Manager). Actually, a manager is an employee with some additional features.
Employee
Manager
name string =
salary double =
city string=
getdetails( ) string
deptname string =
public class Employee
public class Manager extends Employee
{
{
public String name;
public double salary;
public string deptname;
}
public string city;
public string getdetails ( )
{
//body
}
}
The has a Relationship
Objects can contain other objects. This is often called association or the
“has a” relationship. For ex. a manager has a staff of employees. An association is
implemented in java using a data attribute.
Employee
name string =
Manager
Deptname string =
salary double =
city string=
addstaff ( Employee e )
public class Manager extends Employee
getstaff ( i int ) Employee
getdetails( ) string
{
public String deptname;
public Employee[ ] staff = new Employee [20 ];
public int staffsize = 0;
public void addstaff (Employee e)
{
staff [staffsize++] = e ;
}
public Employee getstaff ( int i )
{
return staff [i];
}
…….
}
Example of Inheritance
//create a superclass
class supcls
{
int basic;
public int da;
private int medical;
void netsal( )
{
System.out.println ("net salary of superclass is : "+ (basic + da));
}
}
/* create a subclass of supcls which can access all public or default members of
superclass supcls but cannot access the private members of the superclass */
class subcls extends supcls
{
int hra;
void disphra( )
{
System.out.println ("hra : " + hra);
}
void netsalary( )
{
System.out.println (" net salary of subclass is : "+(basic + da + hra));
}
}
class basic
{
public static void main(String agrs[ ])
{
supcls supob = new supcls( );
subcls subob = new subcls( );
// superclass may be used by itself.
supob.basic=5000;
supob.da=supob.basic*10/100;
supob.netsal( );
// The subclass can access all the public or default members of the
superclass
subob.basic=5000;
subob.da=subob.basic*10/100;
subob.hra=subob.basic*20/100;
//subob.medical=400; it will cause error because medical is
declared as private in superclass.
subob.disphra( ); // this is method of subclass
subob.netsal( );
// this is a method of superclass
subob.netsalary( );
}
}
Output
net salary of superclass is : 5500
hra : 1000
net salary of superclass is : 5500
net salary of subclass is : 6500
More Practical Example of Inheritance
class netsal
{
int basic;
int da;
int hra;
//constructor used when three arguments given
netsal(int b, int d, int h)
{
basic=b;
da=basic*d/100;
hra=basic*h/100;
}
//constructor used when no argument given
netsal( )
{
basic=0;
da=0;
hra=0;
}
//constructor used when one argument given
netsal(int b)
{
basic=b;
da=0;
hra=0;
}
// calculate the salary
int salary( )
{
return basic + da + hra;
}
}
//create a subclass of netsal
class subnetsal extends netsal
{
int medical;
//constructor for subnetsal class
subnetsal(int b, int d, int h,int m)
{
basic=b;
da=basic*d/100;
hra=basic*h/100;
medical=m;
}
}
class basic
{
public static void main(String args[ ])
{
// create object using various constructors
subnetsal n1=new subnetsal(5000,10,20,500);
subnetsal n2=new subnetsal(7000,15,25,750);
int sal;
//calculate salary using n1
sal=n1.salary( );
System.out.println ("net salary of n1 is : "+sal);
System.out.println("net salary of n1 with medical is : " + (sal+n1.medical));
//calculate salary using n2
sal=n2.salary( );
System.out.println ("net salary of n2 is : "+sal);
System.out.println ("net salary of n2 with medical is : " + (sal+n2.medical));
}
}
Output
net salary of n1 is : 6500
net salary of n1 with medical is : 7000
net salary of n2 is : 9800
net salary of n2 with medical is : 10550
A reference variable of a superclass can be assigned a reference to any subclass
derived from that superclass. When you assigned a reference to a subclass object to a
superclass reference variable, then you will have access only to those parts of the object
defined by the superclass. Because it is the type of reference variable not the type of the
object that it refers to, that determines what members can be accessed.
Example of Inheritance
//To write code for class netsal and subnetsal as above
class netsal
{
public static void main(String args[ ])
{
// create object using various constructors
subnetsal n1=new subnetsal(5000,10,20,500);
netsal n2=new netsal(5000);
int sal;
//calculate salary using n1
sal=n1.salary( );
System.out.println ("net salary of n1 is : "+sal);
System.out.println ("net salary of n1 with medical is : " + (sal+n1.medical));
// assign subnetsal reference to netsal reference
n2=n1;
//calculate salary using n2
sal=n2.salary( );
System.out.println ("net salary of n2 is : "+sal);
// The following statement gives error because n2 does not define the
medical member
//System.out.println ("net salary of n2 with medical is : " +sal + n2.medical));
}
}
Output
net salary of n1 is : 6500
net salary of n1 with medical is : 7000
net salary of n2 is : 6500
“super” key-word
In the above examples of inheritances, the constructor for subnetsal also initializes
the basic, da and hra fields of netsal( ). This is inefficient because a subclass must be
granted to access these members. There is a way to avoid the duplication of the code by
using the super keyword.
Subclass can refer to its immediate superclass by using the super.
“super” can call the constructors of the superclass. e.g. super (parameter-list); where
parameter-list specifies the parameters used by the constructor in the superclass.
“super” can also used to access the members of the superclass which are hidden by the
members of the subclass.
super( ) must always be the first statement executed inside a subclass’ constructor
super acts like as a this keyword, but it always refers to superclass of the subclass in
which it is used. super.member where member is a method or a variable of the
superclass.
When a member name of the subclass hides the member name of the superclass means
that the name of member in the subclass and superclass are same, in this situation
we can access member of superclass with using the super.member
Example of Super Class
//create a subclass of netsal
class subnetsal extends netsal
{
int medical;
//constructor for subnetsal class using super( )
subnetsal(int b, int d, int h,int m)
{
super (b,d,h); // call superclass constructor
medical=m;
}
}
Example of Super Class
//complete example of using the super( )
class netsal
{
int basic;
int da;
int hra;
//constructor of an object
netsal(netsal ob)
{
basic=ob.basic;
da=ob.da;
hra=ob.hra;
}
//constructor used when three arguments given
netsal(int b, int d, int h)
{
basic=b;
da=basic*d/100;
hra=basic*h/100;
}
//constructor used when no argument given
netsal( )
{
basic=0;
da=0;
hra=0;
}
//constructor used when one argument given
netsal(int b)
{
basic=b;
da=0;
hra=0;
}
// calculate the salary
int salary( )
{
return basic + da + hra;
}
}
//create a subclass of netsal, which implements all the constructors
class subnetsal extends netsal
{
int medical;
// constroctor of an object
subnetsal (subnetsal ob)
{
super(ob);
medical=ob.medical;
}
//constructor for subnetsal class
subnetsal(int b, int d, int h,int m)
{
super(b,d,h);
medical=m;
}
//default constructor
subnetsal( )
{
super( );
medical=0;
}
//constructor with two arguments
subnetsal(int b, int m)
{
super(b);
medical=m;
}
}
class dispsal
{
public static void main(String args[ ])
{
// create object using various constructors
subnetsal n1=new subnetsal (5000,10,20,500);
subnetsal n2=new subnetsal (7000,15,25,750);
subnetsal n3=new subnetsal ( );
subnetsal n4=new subnetsal (8000,1000);
subnetsal n5=new subnetsal (n2);
int sal;
//calculate salary using n1
sal=n1.salary( );
System.out.println ("net salary of n1 is : "+sal);
System.out.println ("net salary of n1 with medical is : " + (sal+n1.medical));
System.out.println (" ");
//calculate salary using n2
sal=n2.salary( );
System.out.println ("net salary of n2 is : "+sal);
System.out.println ("net salary of n2 with medical is : " + (sal+n2.medical));
System.out.println (" ");
//calculate salary using n3
sal=n3.salary( );
System.out.println ("net salary of n3 is : "+sal);
System.out.println ("net salary of n3 with medical is : " + (sal+n3.medical));
System.out.println (" ");
//calculate salary using n4
sal=n4.salary( );
System.out.println ("net salary of n4 is : "+sal);
System.out.println ("net salary of n4 with medical is : " + (sal+n4.medical));
System.out.println (" ");
//calculate salary using n5
sal=n5.salary( );
System.out.println ("net salary of n5 is : "+sal);
System.out.println ("net salary of n5 with medical is : " +
(sal+n5.medical));
}
}
Output
net salary of n1 is : 6500
net salary of n1 with medical is : 7000
net salary of n2 is : 9800
net salary of n2 with medical is : 10550
net salary of n3 is : 0
net salary of n3 with medical is : 0
net salary of n4 is : 8000
net salary of n4 with medical is : 9000
net salary of n5 is : 9800
net salary of n5 with medical is : 10550
Example of Super Class
class abc
{
int basic;
}
// subclass of abc which hide variable basic.
class bcd extends abc
{
int basic; //this hides basic of class abc
//constructor for bcd
bcd(int a, int b)
{
super.basic=a; // it assign a value to basic of abc.
basic=b; // it assign a value to basic of bcd.
}
void display( )
{
System.out.println ("value of basic in superclass is : " +super.basic);
System.out.println ("value of basic in subclass is : " +basic);
}
}
class dispsal
{
public static void main(String args[ ])
{
bcd subob=new bcd(5000,6000)
subob.display( );
}
}
Output
value of basic in superclass is : 5000
value of basic in subclass is : 6000
Multilevel inheritance
We can also build hierarchies that contains more layers of inheritance means that
a subclass is a superclass of another class. For Ex. there are four classes: abc, bcd, cde and
def where def is a subclass of cde, cde is subclass of bcd and bcd is a subclass of abc. In
this situation, class def inherits all aspects of cde, bcd and abc. The following example
shows you clearly about the multilevel hierarchy.
Example of Multilevel Inheritance
class netsal
{
int basic;
int da;
int hra;
//constructor of an object
netsal(netsal ob)
{
basic=ob.basic;
da=ob.da;
hra=ob.hra;
}
//constructor used when three arguments given
netsal(int b, int d, int h)
{
basic=b;
da=basic*d/100;
hra=basic*h/100;
}
//constructor used when no argument given
netsal( )
{
basic=0;
da=0;
hra=0;
}
//constructor used when one argument given
netsal(int b)
{
basic=b;
da=0;
hra=0;
}
// calculate the salary
int salary( )
{
return basic + da + hra;
}
}
//create a subclass of netsal, which implements all the constructors
class subnetsal extends netsal
{
int medical;
// constroctor of an object
subnetsal (subnetsal ob)
{
super(ob);
medical=ob.medical;
}
//constructor for subnetsal class
subnetsal(int b, int d, int h,int m)
{
super(b,d,h);
medical=m;
}
//default constructor
subnetsal( )
{
super( );
medical=0;
}
//constructor with two arguments
subnetsal(int b,int m)
{
super(b);
medical=m;
}
}
//create a subclass of subnetsal
class subnetsal2 extends subnetsal
{
int pf;
// constroctor of an object
subnetsal2(subnetsal2 ob)
{
super(ob);
pf=ob.pf;
}
//constructor for subnetsal class
subnetsal2(int b, int d, int h, int m, int p)
{
super(b, d, h, m);
pf=p;
}
//default constructor
subnetsal2( )
{
super( );
pf=0;
}
//constructor with three arguments
subnetsal2(int b, int m, int p)
{
super(b, m);
pf=p;
}
}
class dispsal
{
public static void main(String args[ ])
{
// create object using various constructors
subnetsal2 n1=new subnetsal2 (5000,10,20,500,700);
subnetsal2 n2=new subnetsal2 (7000,15,25,750,900);
subnetsal2 n3=new subnetsal2 ( );
subnetsal2 n4=new subnetsal2 (8000,1000,800);
subnetsal n5=new subnetsal (n2);
int sal;
//calculate salary using n1
sal=n1.salary( );
System.out.println ("net salary of n1 is : "+sal);
System.out.println ("net salary(n1) with medical and pf is : " +
(sal+n1.medical-n1.pf));
System.out.println (" ");
//calculate salary using n2
sal=n2.salary( );
System.out.println ("net salary of n2 is : "+sal);
System.out.println ("net salary of n2 with medical ans pf is : " +
(sal+n2.medical-n2.pf));
System.out.println (" ");
//calculate salary using n3
sal=n3.salary( );
System.out.println ("net salary of n3 is : "+sal);
System.out.println ("net salary of n3 with medical and pf is : " +
(sal+n3.medical-n3.pf));
System.out.println (" ");
//calculate salary using n4
sal=n4.salary( );
System.out.println ("net salary of n4 is : "+sal);
System.out.println ("net salary of n4 with medical and pf is : " +
(sal+n4.medical-n4.pf));
System.out.println (" ");
//calculate salary using n5
sal=n5.salary( );
System.out.println ("net salary of n5 is : "+sal);
System.out.println ("net salary of n5 with medical and pf is : " +
(sal+n5.medical-n5.pf));
}
}
Output
net salary of n5 is : 6500
net salary of n5 with medical and pf is : 6300
net salary of n5 is : 9800
net salary of n5 with medical and pf is : 9650
net salary of n5 is : 0
net salary of n5 with medical and pf is : 0
net salary of n5 is : 8000
net salary of n5 with medical and pf is : 8200
net salary of n5 is : 9800
net salary of n5 with medical and pf is : 9650
In a class hierarchy, constructors are called in the sequence from superclass to the
subclass. For Ex. class abc extends bcd, then abc’s constructor called first then the
constructor of the bcd is called. It summaries that constructors are called in the order in
which they are derived, from superclass to subclass. We know that super( ) must be the
first statement executed in the subclass’ constructor, this order is not alter whether or
not super( ) is used. If the super( ) is not used, then the default or parameterless
constructor of each superclass will be executed. The following program clears all the
concepts when constructors are executed.
Example of Constructors
//shows when constructors are called.
class abc
{
abc( )
{
System.out.println (“ main super class abc’s constructor”);
}
}
class bcd extends abc
{
bcd( )
{
System.out.println (“ subclass of main super class, bcd’s constructor”);
}
}
class cde extends bcd
{
cde( )
{
System.out.println (“ subclass of first subclss, cde’s constructor”);
}
}
class callconst
{
public static void main(String args[ ])
{
cde ob = new cde( );
}
}
Output
main super class abc’s constructor
subclass of main super class , bcd’s constructor
subclass of first subclss, cde’s constructor
METHOD OVERRIDING
We had already discussed about the variable overriding in which variable name
used in the subclass and the superclass is same. This situation also sometimes occurs
with the method name. This is called as method overriding. When an overridden method
is called from within a subclass, it will always refers to the version of that method defined
in the subclass and will hide the version of the method defined by the superclass. the
following example shows you a method overriding clearly.
Exmaple of Method Overriding
class netsal
{
int basic, da;
netsal(int b, int d)
{
basic=b;
da=basic*d/100;
}
//calculate and display a salary
void salary( )
{
System.out.println ("net salary from superclass is " + (basic+da));
}
void salary(String m) // overload method salary( )
{
System.out.println (m + (basic+da));
}
}
class subnetsal extends netsal
{
int hra;
subnetsal(int b, int d, int h)
{
super (b, d);
hra=basic*h/100;
}
void salary( ) // this method override the method of superclass
{
super.salary( ); // this calls method in superclass netsal
System.out.println ("net salary from subclass is " + (basic+da+hra));
}
}
class dispsal
{
public static void main(String args[ ])
{
subnetsal subob = new subnetsal(5000,10,20);
subob.salary( ); // this calls method in class subnetsal
subob.salary("this will shows directly the superclass' method ");
}
}
Output
net salary from super class is 5500
net salary from subclass is 6500
this will shows directly the superclass' method 5500
Runtime Polymorphism
Dynamic method dispatch is the mechanism by which a call to an overridden
function is resolved at run time, rather than compile time. It implements runtime
polymorphism. A superclass reference variable can refer to a subclass object. When an
overridden method is called through a superclass reference, java determines which
version of that method to execute based upon the type of the object being referred to at
the time the call occurs at run time. It is the type of the object (not the type of the
reference) being referred to that determines, which version of an overridden method will
be executed.
Therefore, 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. Here is a example which shows a dynamic
method dispatch. With the use of the dynamic method dispatch or runtime
polymorphism, we can reuse the code.
Polymorphism allows a superclass to specify methods that will be common to all of
its subclasses, while allowing subclasses to define the specific implementation of some or
all of those methods. The superclass and subclasses form a hierarchy, which moves from
lesser to greater specialization.
The superclass provides all elements that a subclass can use directly. It also defines
those methods that the derived class must implement on its own. This allows the
subclass the flexibility to define its own methods, yet still enforces a consistent interface.
Thus, by combining inheritance with overridden methods, superclass can define the
general form of the methods that will be used by all of its subclasses.
Example of Runtime Polymorphism
class netsal
{
int basic, da;
netsal(int b, int d)
{
basic=b;
da=basic*d/100;
}
//calculate and display a salary
void salary( )
{
System.out.println ("net salary from superclass is " + (basic+da));
}
}
class subnetsal extends netsal
{
int hra;
subnetsal (int b, int d, int h)
{
super(b, d);
hra=basic*h/100;
}
void salary( )// this method override the method of superclass
{
System.out.println ("net salary from subclass subnetsal is " +
(basic+da+hra));
}
}
class subnetsal2 extends netsal
{
int medical;
subnetsal2(int b, int d, int m)
{
super(b, d);
medical=m;
}
void salary( )// this method override the method of superclass
{
System.out.println ("net salary from subclass subnetsal2 is " +
(basic+da+medical));
}
}
class dispsal
{
public static void main(String args[ ])
{
netsal n1 = new netsal(5000,10); //object of class netsal
subnetsal n2 = new subnetsal(5000,10,20);
subnetsal2 n3 = new subnetsal2(5000,10,700);
netsal r; //create a reference of type netsal (superclass)
r =n1; // r refers to an object netsal
r.salary( );
r =n2; // r refers to an object subnetsal
r.salary( );
r =n3; // r refers to an object subnetsal2
r.salary( );
}
}
Output
net salary from superclass is 5500
net salary from subclass subnetsal is 6500
net salary from subclass subnetsal2 is 6200
Example of Abstract Class
// a program which shows the abstract class and abstract method
abstract class netsal
{
int basic,da;
netsal(int b,int d)
{
basic=b;
da=basic*d/100;
}
//abstract method salary( )
abstract void salary( ); // abstract method does not have body
}
class subnetsal extends netsal
{
int hra;
subnetsal(int b,int d,int h)
{
super(b,d);
hra=basic*h/100;
}
void salary( )// this method override the method of superclass
{
System.out.println ("net salary from subclass subnetsal is " +
(basic+da+hra));
}
}
class subnetsal2 extends netsal
{
int medical;
subnetsal2(int b, int d, int m)
{
super(b, d);
medical=m;
}
void salary( )// this method override the method of superclass
{
System.out.println ("net salary from subclass subnetsal2 is " +
(basic+da+medical));
}
}
class basic
{
public static void main(String args[ ])
{
//netsal n1 = new netsal(5000,10); invalid becuase can't create object of
abstract class
subnetsal n2 = new subnetsal(5000,10,20);
subnetsal2 n3 = new subnetsal2(5000,10,700);
netsal r; //create a reference of type netsal (superclass)
r =n2; // r refers to an object netsal
r.salary( );
r=n3; // r refers to an object subnetsal
r.salary( );
}
}
Output
net salary from subclass subnetsal is 6500
net salary from subclass subnetsal2 is 6200
Example of final
// this program shows a use of final keyword
class netsal
{
int basic, da;
netsal(int b, int d)
{
basic=b;
da=basic*d/100;
}
//final method salary( )
final void salary( ); // final method can't be override
{
System.out.println ("net salary of superclass netsal is "+(basic+da));
}
}
class subnetsal extends netsal
{
int hra;
subnetsal(int b, int d, int h)
{
super(b, d);
hra=basic*h/100;
}
/*
void salary( )
{
System.out.println ("net salary from subclass subnetsal is " +
(basic+da+hra));
}
This method override cause an error because salary( ) method declared as final
in netsal class
*/
}
Example
final class netsal // this class can’t be inherited.
{
//body
}
/*
class subnetsal extends netsal
{
// body
}
this class cause an error because it inherits the class netsal which is declared as final
*/
Exceptions
8
EXCEPTION
EXCEPTION HANDLING
FLOW OF CONTROLS IN EXCEPTION CONDITION
Using try{ } and catch{ }
“throw” statement
“finally” statement
“throws” statement
JAVA’S BUILT-IN EXCEPTION
Checked Exception
Unchecked Exception
CUSTOM EXCEPTIONS
EXCEPTIONS
Sometimes when a program is executing, something occurs that is not quite
normal from the point of view of the goal at hand. For Ex. a user might enter an
invalid file-name, or a file might contain corrupted data, a network-link can fail,
operands being manipulated are out of prescribe ranges etc.
In the solution of these problems, java supports Exceptions. What is an
exception? Any abnormal condition that disturbs the normal program flow while
the program is in execution is an error or an Exception. Exception is an event
during program execution that prevents the program from continuing normally.
The Java programming language supports exceptions with the try, catch, and
throw keywords.
An exception is an abnormal condition that arises in a code sequence at run-time,
means that run-time error.
When an exception is occurred, an object, which represents that exception is
created and passed to the method where the exception has occurred. This
object contains detail information about the exception, which can be
retrieved and processed.
In java the exception class defines mild error conditions that your programs
might encounter.
An exception can also be termed as a special type of error.
Exceptions can be generated by the java run-time system or user code also.
Exceptions are actually objects, and a sub-tree of the class hierarchy is dedicated
to describing them. All exceptions are subclasses of a class called
java.lang.Throwable.
EXCEPTION HANDLING
Java provides an exception-handling model that allows to check for errors
where it is relevant to do so. An exception handler is a block of code that reacts to
a specific type of exception. If the exception is for an error that the program can
recover from, the program can resume executing after the exception handler has
executed.
Exception handling mechanism minimizes the chances of a system crash or
abrupt termination of programs
It implements a catch and throw model similar to the C++.
FLOW OF CONTROLS IN EXCEPTION CONDITION
Using try{ } and catch{ }
try{ } is used to declare a block of statements to be executed in the event that
a Java exception, or run time error, occurs in a preceding "try" block. An
exception causes a jump to the end of the enclosing try{ } block even if the
exception occurs within a method called from the try{} block, in which case the
called method is abandoned. A try statement must be accompanied by at least one
catch block or one finally block.
catch{ } defines a block of statements that may throw a Java language
exception. If an exception is thrown, an optional "catch" block can handle specific
exceptions thrown within the "try" block. An optional "finally" block will also be
executed regardless of whether an exception is thrown or not. If any error found
in try{ } block then control shifts to the appropriate catch{ } block.
Syntax
try
{
//body
}
catch ( Exception e )
{
System.out.println (" display your own error message " );
//body
}
Example of an Exception
public class excp
{
public static void main ( String args [] )
{
int a=5;
int b=0;
try
{
System.out.println ("sum is : "+ (a+b));
System.out.println ("subtraction is : " + (a-b));
System.out.println ("division is : "+(a/b));
System.out.println ("multiplication is : " + (a*b)); //won’t display
}
catch (ArithmeticException ae)
{
System.out.println ("system message :" + ae.getMessage( ));
System.out.println ("user message : divided by zero");
}
}
}
Output
sum is : 5
subtraction is : 5
system message : / by zero
user message : divided by zero.
Multiple catch{ } statements
Example of multiple Catch Statements
public class multicatch
{
public static void main(String args[ ])
{
try
{
int a=1 ;
if(args.length==0)
a=0;
int b=15/a;
int d[ ]={0,1,2,3};
d[22]=56;
}
catch (ArrayIndexOutOfBoundsException ae)
{
System.out.println ("System message :" + ae.getMessage( ));
System.out.println ("user message: array index number is not valid");
}
catch (ArithmeticException ae)
{
System.out.println ("System message :" + ae.getMessage( ));
System.out.println ("user message: divided by zero");
}
}
}
Output
java multicatch
system message : / by zero
user message : divide by zero
java multicatch abc bcd
system message : 22
user message: array index number is not valid
When there are multiple catch{ } after try{}, it is important that exception
subclass must come before any of their superclass. This is because a catch
statement that uses a superclass will catch exceptions of that type plus any of its
subclasses. So, a subclass would never be reached if it came after its superclass.
Example of multiple Catch Statements
public class excp
{
public static void main ( String args [ ])
{
int a=5;
int b=0;
try
{
System.out.println ("sum is : "+ (a+b));
System.out.println ("subtraction is : " + (a-b));
System.out.println ("division is : "+(a/b));
System.out.println ("multiplication is : " + (a*b)); //won’t be displayed
}
catch (Exception ae)
{
System.out.println ("system message from superclass :" +
ae.getMessage());
System.out.println ("user message from superclass : divided by zero");
}
/* This catch never reached because ArithmaticException is a subclass of
Exception */
catch (ArithmeticException ae)
{
System.out.println("system message from subclass :" +
ae.getMessage( ));
System.out.println ("user message from subclass: divided by zero");
}
}
}
at compile time this program gives an error as below :
catch not reached
catch(ArithmeticException ae)
Above program is written as below is valid
public class excp
{
public static void main ( String args [ ])
{
int a=5;
int b=0;
try
{
System.out.println ("sum is : "+ (a+b));
System.out.println ("subtraction is : " + (a-b));
System.out.println ("division is : "+(a/b));
System.out.println ("multiplication is : " + (a*b)); //won't be displayed
}
catch (ArithmeticException ae)
{
System.out.println ("system message from subclass :" + ae.getMessage());
System.out.println ("user message from subclass: divided by zero");
}
catch (Exception ae)
{
System.out.println ("system message from superclass :" +
ae.getMessage());
System.out.println ("user message from superclass : divided by zero");
}
}
}
Output
sum is : 5
subtraction is : 5
system message : / by zero
user message : divided by zero.
Nested try statement
Nested try statement means that try statement within a block of another try.
Each time a try statement is entered, the context of that exception is pushed on to
the stack. If an inner try statement does not have a catch handler for a particular
exception, the stack is unwound and the next try statement’s catch handlers are
inspected for a match. This continues until one of the catch statements succeeds,
and until all of the nested try{ } statements are exhausted. If no catch statement
matches, then the Java run –time system will handle the exception.
Example of Nested try statements
public class nesttry
{
public static void main(String args[ ])
{
try
{
int a=1 ;
if(args.length==0)
a=0;
else
a=args.length+1;
int b=15/a;
try // nested try
{
if(a==2)
{
int d[ ]={0,1,2,3};
d[22]=56;
}
if (a==3)
a=15/(a-a);
}
catch (ArrayIndexOutOfBoundsException ae) // catch of inner try
{
System.out.println ("System message :" + ae.getMessage( ));
System.out.println ("user message: array index number is not valid");
}
}
catch (ArithmeticException ae) //catch of outer try
{
System.out.println ("System message :" + ae.getMessage( ));
System.out.println ("user message: divided by zero");
}
}
}
Output
java nesttry
system message : / by zero
user message : divide by zero
java nesttry abc
system message : 22
user message: array index no is not valid
java nesttry abc bcd // this returns error from inner try but execute catch{ }
of outer try{ }
system message : / by zero
user message : divide by zero
“throw” statement
“ throw “ is a keyword that allows the user to throw an exception or any
class that implements the "throwable” interface. throw is used to indicate that
exception has occurred. The operand of throw is an object of a class, which is
derived from class Throwable.
throw Throwableinstance;
Where, Throwableinstance must be an object of type Throwable or a
subclass of Throwable. You can obtain a Throwable object: using a parameter into
a catch clause, or creating one with the new operator
Example of throw statement
public class exthrow
{
public static void main(String args[ ])
{
try
{
int a=1 ;
if(args.length==0)
a=0;
else
a=args.length+1;
int b=15/a;
try
{
if(a==2)
{
int d[ ]={0,1,2,3};
d[22]=56;
}
if (a==3)
a=15/(a-a);
}
catch (ArrayIndexOutOfBoundsException ae)
{
System.out.println ("System message :" + ae.getMessage( ));
System.out.println ("user message: array index number is not valid");
}
catch (ArithmeticException ae)
{
System.out.println ("System message :" + ae.getMessage( ));
System.out.println ("user message: divided by zero");
throw ae;
}
}
catch (ArithmeticException ae)
{
System.out.println ("System message :" + ae.getMessage( ));
System.out.println ("user message: divided by zero");
}
}
}
Output
java exthrow
system message : / by zero
user message : divide by zero
java exthrow abc
system message : 22
user message: array index no is not valid
java exthrow abc bcd /* this matches exception from inner try but execute
catch { } of both inner and outer try{ }
system message : / by zero
user message : divide by zero
system message : / by zero
user message : divide by zero
if throw ae; statement is not written in the catch{} of inner try {} then output
of java throwex abc bcd will be
system message : / by zero
user message : divide by zero
“finally” statement
“finally” is a keyword that executes a block of statements regardless of
whether a Java Exception, or run time error, occurred in a block defined
previously by the "try" keyword. finally block is the block in which return
resources to the system and other statements for printing any message. These
statements include
closing a file
closing a result set
closing the connection established with the database
This block is optional but when included it is placed after the last catch block of a
try.
The finally block is always executed no matter whether exception is thrown or
not.
Either one of the catch{} or finally{} must be immediate after try{}
Control returns to the finally{}, when break or a return statement is executed in
try{}.
Example of “finally” statement
public class exfinal
{
public static void main(String args[ ])
{
exfinal ob=new exfinal( );
try
{
int b=15/args.length;
}
catch (ArithmeticException ae)
{
ob.disp(ae);
}
finally
{
ob.display( );
}
}
void display( )
{
System.out.println ("this will be always executed");
}
void disp(Exception y)
{
System.out.println ("System message :" + y.getMessage( ));
System.out.println ("User message: divided by zero");
}
}
Output
System message : / by zero
User message : divided by zero
This will be always executed
“throws” statement
“throws” keyword is used in method declarations that specify which
exceptions are not handled within the method but rather passed to the next higher
level of the program. If any method that might throw an exception (which
includes unhandled exception), then possibility must be declared by throws
statement. A throws clause lists the types of exceptions that a method might
throw.
Syntax
method_type method_name( ) throws exception1, exception2, …. exceptionn
{
//body
}
Example of “throws” statement
import java.io.*;
class exthrows
{
public static void main(String args[]) throws IOException
{
char g;
g=(char)System.in.read( );
if(g=='F '|| g=='f')
System.out.println ("Person is Female");
else
System.out.println ("Person is Male");
}
}
Output
F
Person is Female
or
M
Person is Male
JAVA’S BUILT-IN EXCEPTION
Inside the standard package java.lang, Java defines several exception
classes. These all classes are subclasses of Exception class, which extends
Throwable. Java provides two types of exceptions checked exceptions and
unchecked exception.
Checked exceptions
Some exceptions, which are defined by java.lang that must be included in a
method’s throws list if that method can generate one of these exceptions and does
not handle it itself, are called checked exceptions. Following is the list of Checked
Exceptions defined in java.lang package.
Class
Description
ClassNotFoundException
IllegalAccessException
InterruptedException
NoSuchFieldException
NoSuchMethodException
A class cannot be found.
An illegal access to a class was attempted.
A thread has been interrupted
A field could not be found
A method could not be found.
Unchecked Exception
Exceptions, which are not checked exceptions are called unchecked
exceptions. The Runtime Exception class is one of the most important subclass of
Exception. It describes run-time problems that can commonly occur in programs.
Following is the list of unchecked runtime exceptions.
Class
Description
ArithmeticException
ArrayIndexOutOfBoundException
ArrayStoreException
Arithmetic error, such as divided by zero.
Array index is out of bounds
Assignment to an array element of incompatible
type.
Invalid cast
Illegal argument used to invoke a method.
Some type of index is out-of-bounds.
Array created with a negative size.
Invalid use of a null reference.
Invalid conversion of a string to a numeric format.
Attempt to violate security.
ClassCastException
IllegalArgumentException
IndexOutOfBoundsException
NegativeArraySizeException
NullPointerException
NumberFormatException
SecurityException
StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
CUSTOM EXCEPTIONS
Java provides built-in exceptions to handle most common errors. Then also
java provides user to create exceptions, which are called custom exceptions or
user exceptions. User can create their own exception classes so application-specific
problems can be handled. This can be done by creating a subclass of Exception.
Example of Custom Exception
import java.util.*;
class a
{
public static void main(String args[])
{
a( );
}
static void a( )
{
try
{
b( );
}
catch (Exception e)
{
e.printStackTrace( );
}
}
static void b( ) throws exceptiona
{
try
{
c( );
}
catch(Exception e)
{
e.printStackTrace( );
}
}
static void c( ) throws exceptiona, exceptionb
{
Random r =new Random( );
int i=r.nextInt( );
if(i%2==0)
throw new exceptiona("we have a problem");
else
throw new exceptionb("we have a problem");
}
}
class exceptiona extends Exception
{
public exceptiona(String s)
{
super(s);
}
}
class exceptionb extends Exception
{
public exceptionb(String s)
{
super(s);
}
}
Output
exceptionb : we have a problem
at a.c(a.java:41)
at a.b(a.java:26)
at a.a(a.java:41)
at a.c(a.java:14)
at a.main(a.java:7)
Multithreaded
Programming
9
WHAT ARE THREADS?
THREAD CLASS AND ITS METHODS
LIFE CYCLE OF A THREAD
CREATING A NEW THREAD
PUTTING THREADS ON HOLD
MULTITHREADING
TESTING THREADS
SETTING THE PRIORITIES OF THREADS
THREAD SYNCHRONIZATION
THE SYNCHRONIZED KEY-WORD
THREAD INTERACTION
EXAMPLE USING WAIT( ) AND NOTIFY( )
WHAT ARE THREADS?
A simplistic view of computer is that it has a CPU that performs
computations, read-only memory (ROM) which contains the program that the
CPU executes, and random-access memory (RAM) which holds the data on which
the program operates. At this time, only one job being performed. But in modern
computers it is possible to perform more than one job at a time, which is similar to
having more than one computer. A THREAD is considered the encapsulation of a
virtual CPU with its own program code and data.
A thread--sometimes called an execution context or a lightweight process--is
a single sequential flow of control within a program. A thread is a smallest unit of
executable code that performs a particular task. There are three parts of a Thread.
A virtual CPU
The code the CPU is executing
The data on which the code works
CPU
Code
FIGURE 9-1 PARTS OF THREAD
Code :Code can be shared by multiple threads, independent of data. Two
Data
threads shared the same code when they execute code from instances of the same
class.
Data :- Data may or may not be shared by multiple threads, independent of code.
Two threads share the same data when they share access to a common object.
CPU :- In java programming, the virtual CPU is encapsulated in an instance of
thread class. When a thread is constructed, the code and the data are specified by the
object passed to its constructor.
THREAD CLASS AND ITS METHODS
Java’s multithreading system is built upon a Thread class, it’s methods,
and it’s companion interface Runnable. Some methods of the Thread class are as
below.
getName( )
setName( )
run( )
sleep( )
isAlive( )
join( )
getPriority( )
setPriority( )
suspend( )
resume( )
stop( )
Obtain a thread’s name.
Change a name of the thread
Entry point for the thread
Suspend a thread for a period of time
Determine whether thread is running or not
Wait for a thread to terminate
Obtain a thread’s priority
Change a priority of thread
Suspends all processes of Thread.
To resume the execution of suspended thread
Stops all processes in the thread.
TABLE 9-1 METHODS OF THREAD CLASS
The methods Thread.suspend( ), Thread.resume( ), Thread.stop( ) are
Deprecated.
When a java programs starts up, one thread begins running immediately.
This is called the main thread of the program. The main thread is important
because of two reasons
It is thread from which other “child” threads will be spawned.
It must be the last thread to finish execution because when it stops the
program is terminated.
LIFE CYCLE OF A THREAD
A thread object can exist in several different states throughout its lifetime.
Blocked
NEW
resume( )
DEAD
notify( )
sleep( )
suspend( )
wait( )
start( )
stop( )
Runnable
Scheduler
Running
FIGURE 9-2 LIFE CYCLE OF THREAD
A thread that has just created is in a born state. The thread does not
immediately start running after it is created. It waits for a start( ) method to be
called and then it is ready for run state. In runnable state you can temporary stop
the execution of the thread using sleep( ).
CREATING A NEW THREAD
There are two ways of creating a new thread.
Through extending Thread class
Syntax
class class_name extend s Thread
{
//body
public void run( )
{
// implementation
}
}
Through implementing Runnable interface.
Syntax
class class_name implements Runnable
{
// body
public void run( )
{
// implementation
}
}
Example of Thread
class display implements Runnable
{
int i;
public void run( )
{
i=0;
System.out.println ("current thread name : "+Thread.currentThread( ).
getName( ));
String s;
while (true)
{
s="Hello"+ i++;
Thread.currentThread( ).setName(s);
System.out.println ("thread " + i + " : " +Thread.currentThread( ).
getName( ));
if(i==5)
break;
}
}
}
public class ThreadTest
{
public static void main(String args [ ])
{
display d= new display( );
Thread t=new Thread(d);
System.out.println ("main thread name : " + Thread.currentThread( ).
getName( ));
t.start( );
}
}
Output
main thread name : main
current thread name : Thread-0
thread 1 : Hello0
thread 2 : Hello1
thread 3 : Hello2
thread 4 : Hello3
thread 5 : Hello4
PUTTING THREADS ON HOLD
Java provides mechanism that can temporarily stop the execution of the
thread. Thread can be stopped as if nothing happened. The sleep( ) method is
one way to halt a thread for a period of time. Recall that thread does not
necessarily resume its execution at the instant that the sleep period expires. This is
because some other thread could be executing at that instant.
Example of putting threads on hold
class display implements Runnable
{
public void run( )
{
int i=0;
while (true)
{
System.out.println ("Hello : "+ i++);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println ("Thread Interrupted");
}
if(i==5)
break;
}
}
}
public class exthread1
{
public static void main(String args [ ])
{
display d= new display( );
Thread t=new Thread(d);
t.start( );
}
}
Output
Hello
Hello
Hello
Hello
Hello
:
:
:
:
:
0
1
2
3
4
MULTITHREADING
Java supports multithreading programming. Each thread specified a
particular task, which is executed concurrently with the other threads is called
multithreading. Using multithreading you can write efficient programs that
makes the maximum use of CPU in minimum time. Each part of the program,
which is called thread, defines a different path of execution. Thus multithreading
is a specialized form of multitasking. Multithreaded programming provides
facility of
Creating multiple threads from the same Runnable instance
Threads share the same data and code.
Example of Multithreading
class display implements Runnable
{
public void run( )
{
int i=0;
while(i<4)
System.out.println ("Hello : " + i++);
}
}
public class exthread2
{
public static void main(String args [ ])
{
display d= new display( );
Thread t1=new Thread(d);
Thread t2=new Thread(d);
Thread t3=new Thread(d);
t1.start( );
t2.start( );
t3.start( );
}
}
Output
Hello : 0
Hello : 0
Hello : 0
Hello : 1
Hello : 1
Hello : 1
Hello : 2
Hello : 2
Hello : 2
Hello : 3
Hello : 3
Hello : 3
TESTING THREADS
A thread can be in an unknown state. The method isAlive( ) is used to
determine whether a thread is still running or not. It returns a boolean argument
true if thread is running otherwise false.
The join( ) method causes the current thread to wait until the thread on
which the join( ) method is called terminates. You can also call the join method
with a timeout value in milliseconds. For Ex.
void join ( long timeout );
Where the join( ) method either suspends the current thread for timeout
milliseconds or until the thread it calls on terminates.
Example of testing threads
class display implements Runnable
{
public void run( )
{
int i=0;
while(i<4)
System.out.println ("Hello : " + i++);
}
}
public class exthread3
{
public static void main(String args [ ])
{
display d= new display( );
Thread t1=new Thread(d);
Thread t2=new Thread(d);
Thread t3=new Thread(d);
t1.start( );
t2.start( );
t3.start( );
try
{
System.out.println ("Thread t1 is alive :" + t1.isAlive());
System.out.println ("Waiting for finishing thread t1");
t1.join( );
System.out.println ("Thread t1 is alive :" + t1.isAlive());
}
catch ( InterruptedException e )
{
System.out.println ("thread t1 interrupted :");
}
}
}
Output
Thread t1 is alive : true
Hello : 0
Hello : 0
Hello : 0
Waiting for finishing thread t1
Hello : 1
Hello : 1
Hello : 1
Hello : 2
Hello : 2
Hello : 2
Hello : 3
Hello : 3
Hello : 3
Thread t1 is alive : false
SETTING THE PRIORITIES OF THREADS
Every thread in java has it’s own priority. getPriority( ) method is used to
determine the current priority of thread.setPriority(int) method is used to set the
priority of the thread. The priority is an integer value. This priority is in the range
of Thread.MIN_PRIORITY and Thread.MAX_PRIORITY. The Thread class
includes the following constants :
Thread.MIN_PRIORITY : which contains constant value 1
Thread.MAX_PRIORITY : which contains constant value 10.
Thread.NORM_PRIORITY : this default priority contains a constant value 5.
Every new thread that has created, inherits the priority of the thread that
creates it.
The priority of the thread can be set by setPriority(int) method of Thread
class. Int contains a value between 1 and 10. If the value is out of this range than
the method throws an exception called as IllegalArgumentException
Example of thread priority
class display implements Runnable
{
public void run( )
{
int i=0;
while(i<4)
System.out.println ("Hello : " + i++);
}
}
public class exthread4
{
public static void main(String args [ ])
{
display d=new display( );
Thread t1=new Thread(d);
Thread t2=new Thread(d);
Thread t3=new Thread(d);
System.out.println ("current priority of thread t1 is :" + t1.getPriority( ));
t1.setPriority(3);
t1.start( );
t2.start( );
t3.start( );
System.out.println ("new priority of thread t1 is :" + t1.getPriority( ));
}
}
Output
current priority of thread t1 is :5
new priority of thread t1 is :3
Hello : 0
Hello : 0
Hello : 1
Hello : 1
Hello : 2
Hello : 2
Hello : 3
Hello : 3
Hello : 0
Hello : 1
Hello : 2
Hello : 3
THREAD SYNCHRONIZATION
While working with multiple threads, it may be possible that more than one
threads share the same data at a time. For Ex. One thread might try to read the
data when other thread tries to change it. It will create an error and data may be
corrupted. In this case, it is necessary to allow one thread to finish its task
completely and then allow next thread to execute. This can be done with the help
of synchronized( ) method.
Thread Synchronization is a mechanism that allows a programmer to
control threads that are sharing data. When two or more threads when two or
more threads need access to share data, they need some way to ensure that, the
data will be used by only one thread at a time.
Example of thread synchronization
class threadex
{
threadsyn t1,t2,t3;
public threadex( )
{
a ob=new a( );
t1=new threadsyn(ob);
t1.start( );
t2=new threadsyn(ob);
t2.start( );
t3=new threadsyn(ob);
t3.start( );
}
public static void main(String args[])
{
new threadex();
}
}
class threadsyn extends Thread
{
a ob1=new a( );
threadsyn(a ob)
{
ob1=ob;
}
public void run( )
{
int c=0;
while(c<5)
{
try
{
Thread.sleep(100);
}
catch(InterruptedException i)
{
System.out.println (i.getMessage());
}
c=ob1.getCount( );
System.out.println ("Count= "+c);
}
}
}
class exthread5
{
int c=0;
public synchronized int getCount( )
{
for(int i=0;i<3;i++)
{
System.out.println (i);
c+=1;
}
return c;
}
}
Output
0
1
2
count= 3
0
1
2
count= 6
0
1
2
count= 9
0
1
2
count= 12
THE SYNCHRONIZED KEY-WORD
Java programming language provides this with a mechanism that allows a
programmer to control threads that are sharing data.
The easy way of achieving synchronization is to create synchronized method
within a class.
All access to delicate data should be synchronized.
Delicate data protected by synchronized should be private.
A synchronized block ensures that a call to a method that is a member of object
occurs only after the current thread has successfully entered object’s monitor.
Example of “synchronized “ key-word
class b
{
void b(String s)
{
System.out.print("["+s);
try
{
Thread.sleep(1000);
}
catch(InterruptedException i)
{
System.out.println ("Interrupted");
}
System.out.println ("]");
}
}
class c implements Runnable
{
String s;
b bob;
Thread t;
public c(b bob1,String s1)
{
bob=bob1;
s=s1;
t=new Thread(this);
t.start( );
}
public void run( )
{
synchronized(bob)
{
bob.b(s);
}
}
}
class a
{
public static void main(String args[])
{
b bob=new b( );
c cob1=new c(bob,"Welcome");
c cob2=new c(bob,"to");
c cob3=new c(bob,” AYE");
try
{
cob1.t.join( );
cob2.t.join( );
cob3.t.join( );
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
Output
[Welcome]
[to]
[AYE]
THREAD INTERACTION
Different threads are created specifically to perform unrelated tasks.
However, sometimes the jobs they perform are actually related in the same way
and it might be necessary to program some interactions between them. The
java.lang.object class provides two methods for thread communication: wait( )
and notify( ).
wait( ) and notify( ) are called only from within a synchronized block on the
instance on which they are being called.
The wait( ) allows a thread that is executing a synchronized method or statement
block on that object to release the lock and wait for a notification from
another thread.
The notify( ) method allows a thread that is executing a synchronized method or
statement block to notify another thread that is waiting for a lock on this
object.
The notifyAll( ) allows a thread that is executing a synchronized method or
statement block to notify all threads that is waiting for a lock on this object.
Example of thread interaction
class queue
{
int n;
synchronized int output( )
{
System.out.println("output : "+n);
return n;
}
synchronized void input(int n)
{
this.n=n;
System.out.println("input : "+n);
}
}
class producer implements Runnable
{
queue q;
producer(queue q)
{
this.q=q;
new Thread(this, "Producer").start( );
}
public void run( )
{
int i=0;
while(true)
{
q.input(i++);
}
}
}
class consumer implements Runnable
{
queue q;
consumer(queue q)
{
this.q=q;
new Thread(this, “Consumer").start();
}
public void run( )
{
while(true)
{
q.output( );
}
}
}
class thrdinter
{
public static void main(String args[])
{
queue q=new queue( );
new producer(q);
new consumer(q);
System.out.println("Press ctrl+c to stop");
}
}
Output
input : 0
output : 0
input : 1
input : 2
input : 3
output : 3
output : 3
output : 3
EXAMPLE USING WAIT ( ) AND NOTIFY( )
class queue
{
int n;
boolean b=false;
synchronized int output( )
{
if(!b)
try
{
wait( );
}
catch(InterruptedException e)
{
System.out.println ("InterruptedException caught");
}
System.out.println("output : "+n);
b=false;
notify( );
return n;
}
synchronized void input(int n)
{
if(b)
try
{
wait( );
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n=n;
b=true;
System.out.println ("input : "+n);
notify( );
}
}
class producer implements Runnable
{
queue q;
producer(queue q)
{
this.q=q;
new Thread(this, "Producer").start();
}
public void run( )
{
int i=0;
while(true)
{
q.input(i++);
}
}
}
class consumer implements Runnable
{
queue q;
consumer(queue q)
{
this.q=q;
new Thread(this, “Consumer").start();
}
public void run( )
{
while(true)
{
q.output( );
}
}
}
class a
{
public static void main(String args[])
{
queue q=new queue( );
new producer(q);
new consumer(q);
System.out.println("Press ctrl+c to stop");
}
}
Output
input : 0
output : 0
Press ctrl+c to stop
input : 1
output : 1
input : 2
output : 2
input : 3
output : 3
Packages &
Interfaces
PACKAGE
Advantages of Packages
Classpath
INTERFACE
Declaration
Implementation
Interface Inheritance
7
PACKAGE
Reusability of code is one of the most important requirements because it
saves time, effort and also ensures consistency. For Ex. a class once defines and
then used repeatedly will ensure that all applications using the particular class
will have identical behavior. Java provides reusability of existing code or class by
using package. A package allows to create a various class without concern that it
will collide with some other class stored elsewhere. Packages are stored in a
hierarchical manner and are explicitly import into new class definition. A package
is a collection of all reusable code, classes, interfaces and other packages.
Advantages of Packages
Packages allow you to organize your classes into smaller units and make it easy to
locate and use the appropriate class file.
It helps to avoid naming conflicts when you are working with number of classes. It
becomes difficult to decide on names of the classes and methods. At times, you
would to use the same name, which belongs to another class. A package
basically,
hides
the
classes
and
avoids
conflicts
the name.
Packages allow you to protect your classes’ data and methods in a larger way then
on a class-to-class .basis.
A package mechanism is partitioning the classname into more manageable chunks.
Package names can be used to identify your classes.
Syntax
Creating Package
package package_name;
//body
or
package package_name.subpackage_name;
//body
Including Package
import package_name.*;
Including Package Member
import package_name.member_name;
Accessing Java Package Members
package_name.member_name;
or
package_name.subpackage_name.member_name;
A package is a group of classes and interfaces.
Java provides the package mechanism as a way to group related classes.
All members of the package must be defined as public if they need to be accessed
from outside.
Package names must be hierarchical and separated by dot ( . )
If no package is declared in the file then all the classes of that file “belongs” to
the default package ( that is package with no name ).
Import statement tells the compiler where to find classes to use them.
The import statement must precede all class declarations.
Classpath
The compiler and the interpreter search for the classes in the current
directory and the directory, which consists JDK class files. This means that the
JDK class files and the current directory are automatically set in your classpath.
But in some cases you need to set your classpath. A Classpath is a list of
directories, which the compiler and interpreter use to search for the respective
class file. To set the classpath at run-time is preferable as it sets the path for the
current execution.
Javac –d classpath filename
Example of creating Package
package mypack;
public class netsal
{
public int salary(int b)
{
int hra=b*10/100;
int da=b*20/100;
return(b+hra+da);
}
public int pfund(int b)
{
int pf=b*15/100;
return (pf);
}
}
Save this file as “netsal.java” in c: \mypack
Compile this file as
Javac netsal.java
Which creates a class file netsal.class in c: \mypack
Example of importing Package
import mypack.*;
public class pack
{
public static void main ( String args [ ])
{
int sal,netsalary;
netsal nt=new netsal( );
sal=nt.salary(5000);
netsalary=sal- nt.pfund(5000);
System.out.println ("Salary is :" +sal);
System.out.println ("Net Salary is :" +netsalary);
}
}
Save this file as c:\pack.java
Set the classpath as set classpath=%path%;c:\;
Now compile this file as javac pack.java
Run this file as java pack.java
Output
Salary is : 6500
Net Salary is : 5750
INTERFACES
Interface is a keyword used to define a collection of method
definitions and constant values. It can later be implemented by classes that define
this interface with the "implements" keyword. Inheritance is very useful to save a
time and energy of programmers by reusing the existing code. In C++ multiple
inheritance is possible which is used to inherits methods and properties from
several different classes. But Java doesn’t support multiple inheritance but java
introduces the interface.
Interface is a class, which contain methods and variables.
Classes have the ability to define objects, while interfaces define a set of methods
and constants to be implemented by another object.
We can define a set of functionality without any idea as to how this property of
the function will be defined later.
Once interface is defined, any number of classes can implement an interface.
One class can implement more than one interface.
To implement an interface, a class must create the complete set of methods
defined by the interface.
Each class is free to define its own implementation.
With interface, we can fully utilize the polymorphism.
Interfaces support the dynamic method resolution at run time.
Interface method must be declared as public at the time of implementing.
If a class includes an interface but does not fully implement the method defined
by that interface, then that class must be declared as abstract. Any other
class that inherits this abstract class must implement the methods of
interface otherwise it must be declared as abstract.
An interface is a template that other class needs to implement them. This means
that the body of the method is empty and variables are declared as final
means constants in interfaces,
Declaration
Access interface name
{
type method-1( parameter-list);
:
:
type method-n(parameter-list);
final type var-1=value;
:
:
final type var-n=value;
}
Example
public interface netsal
{
final int basic=5000;
void display( int b, int da);
double salary(double b,double d, double h);
}
implementation
access classname [extends otherclassname] [implements interfacename1 ,
interfacename2, ….
{
//body
}
Example of declaring an Interface
// class salary implements netsal
// class salary extends netsal1 implements netset2,netsal3
public interface netsal
{
final int basic=5000;
public void salary(int d, int h);
public void pfund(int d, int h, int p);
}
after creating an interface save it with name netsal.java and compile it with using
javac netsal.java
Example of implementing an Interface
class dispsal implements netsal
{
public void salary(int d, int h)
{
System.out.println ("net salary is " + (basic+basic*(d+h)/100));
}
public void pfund(int d, int h, int p )
{
System.out.println ("net salary after deduction of pf is " +
(basic+basic*(d+h-p)/100));
}
public static void main(String args[ ])
{
dispsal s=new dispsal( );
s.salary(20,10);
s.pfund(20,10,15);
}
}
Output of dispsal.java is
net salary is 6500
net salary after deduction of pf is 5750
Example of declaring an Interface
public interface netsal
{
void netsal(int b);
}
Save and compile this file as netsal.java
Example of implementing an Interface
class netsal1 implements netsal
{
//implement netsal interface's
public void netsal(int b)
{
int da=10*b/100;
int hra=15*b/100;
System.out.println("net salary is : "+(b+da+hra));
}
}
class dispsal
{
public static void main(String args[ ])
{
netsal oa=new netsal1( );
oa.netsal(5000);
}
}
Save and compile this file as dispsal.java
Output
net salary is : 6250
Example of declaring an Interface
public interface netsal
{
void netsal(int b);
}
Save this file as netsal.java
Example of implementing an Interface
class netsal1 implements netsal
{
//implement netsal interface's
public void netsal(int b)
{
int da=10*b/100;
int hra=15*b/100;
System.out.println ("net salary is : "+(b+da+hra));
}
}
class netsal2 implements netsal
{
//implement netsal interface's
public void netsal(int b)
{
int medical=700;
int pf=5*b/100;
int da=10*b/100;
int hra=15*b/100;
System.out.println ("net salary with pf and medical is : "+
(b+da+hra+medical-pf));
}
}
class dispsal
{
public static void main(String args[ ])
{
netsal oa=new netsal1( );
oa.netsal(5000);
netsal ob=new netsal2( );
ob.netsal(5000);
}
}
Output
net salary is : 6250
net salary with pf and medical is : 6700
Example of creating an interface
public interface netsal
{
final int basic=5000;
public void salary(int d, int h);
}
Save and compile this file as netsal.java
Example of creating an interface
public interface netsal1
{
final int medical=500;
public void pfund(int d, int h, int p);
}
Save and compile this file as netsal1.java
Example of implementing more than one interfaces
class dispsal implements netsal,netsal1 // implements netsal and netsal1
{
public void salary(int d, int h)
{
System.out.println ("net salary is " + (basic+medical+basic*(d+h)/100));
}
public void pfund(int d, int h, int p )
{
System.out.println ("net salary after deduction of pf is " +
(basic+medical+basic*(d+h-p)/100));
}
public static void main(String args[ ])
{
dispsal obj=new dispsal( );
obj.salary(20,10);
obj.pfund(20,10,15);
}
}
Save and compile this file as dispsal.java
Output
net salary is 7000
net salary after deduction of pf is 6250
Interface Inheritance
One interface can inherit another by use of extends keyword same as class
inheritance when class implements an interface which inherits another interface, it
must provide implementation for all methods defined within the interface
inheritance chain.
Example of Interface Inheritance
public interface netsal
{
final int basic=5000;
public void salary(int d, int h);
}
Save and compile this file as netsal.java
public interface subnetsal extends netsal // this interface inherits all methods
and variables of netsal
{
final int medical=500;
public void pfund(int d, int h, int p);
}
Save and compile this file as subnetsal.java
class dispsal implements subnetsal // implements netsal and subnetsal
{
public void salary(int d, int h)
{
System.out.println ("net salary is " + (basic+medical+basic*(d+h)/100));
}
public void pfund(int d, int h, int p )
{
System.out.println ("net salary after deduction of pf is " +
(basic+medical+basic*(d+h-p)/100));
}
public static void main(String args[ ])
{
dispsal obj=new dispsal( );
obj.salary(20,10);
obj.pfund(20,10,15);
}
}
Save and compile this file as dispsal.java
Output
net salary is 7000
net salary after deduction of pf is 6250
INPUT &
OUTPUT
I/O FUNDAMENTALS
java.io PACKAGE
The InputStream Class
The OutputStream Class
BYTE ARRAY INPUT AND OUTPUT
The ByteArrayInputStream Class
The ByteArrayOutputStream Class
FILE INPUT AND OUTPUT
The File Class
The FileDescriptor Class
The FileInputStream Class
The FileOutputStream Class
FILTERED INPUT AND OUTPUT
The FilterInputStream Class
The FilterOutputStream Class
BUFFERED INPUT AND OUTPUT
The BufferedInputStream Class
The BufferedOutputStream Class
THE Reader AND Writer CLASS
The Reader Class
The Writer Class
CHARACTER ARRAY AND STRING INPUT AND
12
I/O FUNDAMENTALS
Streams are pipelines for sending and receiving information in java programs.
When a stream of data is being sent or received, it is referred as writing and reading a
stream. A stream is a flow of data from a source to a sink. Here, sources and sinks are
also called as input streams and output streams. User can read from input stream but
can’t write to it. User can write to output stream but can’t read from it.
When a stream is read or written, other threads are blocked. While reading or
writing a stream if an error occurs, an IOException is thrown. So, the stream statement
must consist of a try-catch block.
Java technology supports two types of data in streams: raw bytes or Unicode
characters. Normally, the term “stream” is used to refer to byte streams and the terms
“reader” and “writer” refer to character streams.
Byte Streams
Character Streams
Source Streams
InputStream
Reader
Sink Streams
OutputStream
Writer
TABLE 11-1 FUNDAMENTAL STREAM CLASSES
java.io PACKAGE
Although system streams are very beneficial, they are not powerful enough to use
when dealing with substantial I/O. the java.io package has to be imported for this
purpose. The following classes belong to java.io.
InputStream Class
OutputStream Class
The InputStream Class
The class InputStream class is an abstract class, which defines how data is
received.
The important point is not where the data comes from, but that it is accessible.
InputStream class provides a number of methods for reading and taking streams
of data as input, which help in creating, reading and processing input
streams.
Methods
Syntax
Description
read( )
It reads bytes of data from a stream. If no data is available it
blocks the method. When a method is blocked, the thread
executing waits until the data is available. It throws an
IOException if an error occurs.
available( )
This method returns the number of available bytes that can be
read without blockage.
close( )
This method closes the input stream. It releases the resources
associated with the stream. It throws an IOException if an error
occurs.
mark( )
This method is used to mark the current position in the stream.
markSupported( )
This method returns a boolean value indicating whether the
stream supports mark and reset capabilities. It returns true if the
stream type supports it and otherwise false.
reset( )
This method repositions the stream to the last marked position.
This method throws an IOException if an error occurs.
skip( )
This method skips n bytes of input.
-n is the parameter used which specifies the number of bytes to
be skipped. It throws an IOException if an error occurs.
Following figure shows the hierarchy of InputStream classes in the java.io package.
StringBufferedInputStream
SequenceInputStream
DataInputStream
FileInputStream
PushbackInputStream
InputStream
FilterInputStream
BufferedInputStream
ObjectInputStream
LineNumberInputStream
PipedInputStream
ByteArrayInputStream
Figure – 12-1 Hierarchy of InputStream Class
The OutputStream Class
The OutputStream class is an abstract class.
It defines the way in which outputs are written to streams.
OutputStream class provides a number of methods for writing streams of data as
output, which help in creating, writing and processing output streams.
Methods
Syntax
Description
write( )
This method writes a byte and throws an
IOException if an error occurs. This method
actually blocks until the byte is written. The
thread waits until the write operation is been
completed.
flush( )
This method flushes the stream. The buffered
data is written to the output stream. It throws an
IOException if an error occurs.
close( )
This method closes the stream. It is used to
release any resource associated with the stream.
It throws an IOException if an error occurs.
Following figure shows the hierarchy of OutputStream classes in the java.io
package.
ObjectOutputStream
FileOutputStream
DataOutputStream
OutputStream
FilterOutputStream
BufferedOutputStream
PipedOutputStream
PrintStream
ByteArrayOutputStream
Figure – 12-2 Hierarchy of OutputStream Class
BYTE ARRAY INPUT AND OUTPUT
The classes ByteArrayInputStream and ByteArrayOutputStream make use of
memory buffers. It is not necessary to use them together.
ByteArrayInputStream Class
This class creates an input stream from the memory buffer, which is nothing but an
array of bytes. This class does not support any new methods. It overrides methods of the
class InputStream like read(), available( ), and reset( ).
ByteArrayOutputStream Class
This class creates an output stream on a byte array. It also provides additional
capabilities for the output array to grow so as to accommodate the new data that is
written. It also provides two methods like toByteArray( ) and toString( ). This is to convert
a stream to a byte array or String object.
Example of ByteArray Input and Output Class
import java.lang.System;
import java.io.*;
public class exbyte
{
public static void main(String args[ ]) throws IOException
{
ByteArrayOutputStream bs=new ByteArrayOutputStream ( );
String s="Byte Array Input Output Classes";
for(int i=0; i<s.length( ); i++)
bs.write(s.charAt(i));
System.out.println ("Output stream is : "+bs);
System.out.println ("Size of output stream is : " + bs.size());
ByteArrayInputStream as;
as=new ByteArrayInputStream (bs.toByteArray());
int b=as.available( );
System.out.println ("Input stream has : " + b + " available bytes.");
byte bf[ ]=new byte[b];
int brd=as.read(bf,0,b);
System.out.println ("Number of bytes read are : " + brd);
System.out.println ("These bytes are : " + new String(bf));
}
}
Output
Output stream is : Byte Array Input Output Classes
Size of output stream is : 29
Input stream has : 29 available bytes
Number of bytes read are : 29
These bytes are : Byte Array Input Output Classes
FILE INPUT AND OUTPUT
Java provides a number of methods and classes that allow user to read and write
files. In java, all files are byte-oriented, and Java provides methods to read and write
bytes from and to a file. Java supports file input and output operations with the help of
the following classes:
File
FileDescriptor
FileInputStream
FileOutputStream
The File Class
Most of the classes defined by java.io operate on streams, but File class deals
directly with files and filesystem.
This class is used to access file and directory objects.
A File object is used to obtain and manipulate the information associated with a
disk file, such as permissions, time, date, and directory path.
This class provides constructors for creating files and directories. These
constructors take both absolute and relative file paths and file and directory
names.
All common file and directory operations are performed by the access methods
of File class. They allow creating, deleting and renaming of files.
The FileDescriptor Class
This class provides access to the file descriptors that are maintained by the
Operating System when files and directories are being accessed.
This class does not provide any visibility to specific information maintained by
the operating system.
It provides only one method called valid(), which helps to determine whether a
file descriptor object is currently valid or not.
The FileInputStream Class
This class creates an InputStream that you can use to read bytes from a file.
Objects of this class are created using a filename String, File or FileDescriptor
object as an argument.
This class overrides the methods of InputStream class.
It also provides following two methods
finalize( ) – used to close a stream while being processed by the java
garbage collector.
getFD( ) – returns the file descriptor object that represents the connection
to the actual file in the file system being used by the FileInputStream.
The FileOutputStream Class
This class creates an OutputStream that you can use to write bytes to a file.
Objects of this class are created using a filename String, File or FileDescriptor
object as an argument.
This class overrides the method of OutputStream class.
It also provides two methods finalize( ) and getFD( ).
Example of File Input and Output Class
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.File;
import java.io.IOException;
public class exfileio
{
public static void main(String args[ ]) throws IOException
{
//creating an output file a.txt
FileOutputStream fos=new FileOutputStream("a.txt");
String s="File Input Output Stream";
for(int i=0; i<s.length(); ++i)
fos.write(s.charAt(i));
fos.close( );
FileInputStream fis=new FileInputStream("a.txt");
int b=fis.available( );
System.out.println ("Input Stream has " + b + " available bytes");
byte bf[ ]=new byte[b];
int br=fis.read(bf,0,b);
System.out.println ("Number of Bytes read are : " + br);
System.out.println ("These bytes are : " + new String(bf));
fis.close( );
File f=new File("a.txt");
f.delete( );
}
}
Output
Input Stream has 24 available bytes
Number of Bytes read are : 24
These bytes
are : File Input Output Stream
FILTERED INPUT AND OUTPUT
A Filter is a type of stream that modifies the way an existing stream is handled.
The filtered input and output streams classes provided by java are basically used
to adapt streams to specific program needs.
The filter sits between an input stream and an output stream, which performs
some special processing on the bytes transferred from input and output.
The FilterInputStream Class
This abstract class is the parent of all filtered input stream classes.
This class provides the capability of creating one stream, where one stream can
be read and provided as the output to another stream.
This class is designed in such a way that it allows multiple chained filters to be
created using several layers of nesting.
The FilterOutputStream Class
This class is the parent of all filtered output stream classes.
The data written to this class can be modified as needed to perform filtering
operations, and then forwarded to the OutputStream class.
BUFFERED INPUT AND OUTPUT
A Buffer is a storage place where data is kept. By storing the data in a buffer, we
can get it from the buffer instead of going back to the original source of the
data.
Java uses buffered input and output to temporarily cache data read from or
written to a stream, which helps programs to read or write small amounts
of data without affecting the performance of the system.
The filters operate on the buffer. The buffer is located between the program and
the destination of the buffered stream.
The BufferedInputStream Class
This class allows user to “wrap” any InputStream into a buffered stream and
achieve this performance improvement.
This class supports input buffering by automatically creating and manipulating a
buffer. So, programs can read data from the stream one byte at a time
without affecting the performance of the system.
This class makes use of several variables to implement input buffering. These
variables are declared as protected and hence cannot be accessed directly by
the program
This class defines two constructors, which take an object of the class InputStream
as an argument
This class overrides the access methods provided by the InputStream and does
not introduce any new method.
The BufferedOutputStream Class
This class performs output buffering in a manner corresponding to the class
BufferInputStream.
This class overrides the access methods provided by the OutputStream and does
not introduce any new method.
This class defines two constructors, which allows user to specify the size of the
output buffer in a constructor as well as provide a default buffer size.
Example of Buffered Input and Output Class
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.SequenceInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class exbuff
{
public static void main(String args[ ]) throws IOException
{
SequenceInputStream sq;
FileInputStream fis1,fis2;
fis1=new FileInputStream("exbyte.java");
fis2=new FileInputStream("exfileio.java");
sq=new SequenceInputStream(fis1, fis2);
//create buffered input and output stream
BufferedInputStream bis;
bis=new BufferedInputStream(sq);
BufferedOutputStream bos;
bos=new BufferedOutputStream(System.out);
bis.skip(1000);
boolean b=false;
int cnt=0;
while(!b)
{
int num=bis.read( );
if(num==-1)
b=true;
else
{
bos.write((char) num);
++cnt;
}
}
String s=String.valueOf(cnt);
s+="bytes were read";
bos.write(s.getBytes( ),0,s.length( ));
//close all streams
bis.close( );
bos.close( );
fis1.close( );
fis2.close( );
}
}
Output
THE READER AND WRITER CLASS
This two are abstract classes. They are at the top of the class hierarchy that
supports reading and writing of Unicode character streams.
The Reader Class
This abstract class defines Java’s model of streaming character input.
All of the methods in this class will throw an IOException on error condition. This class
supports following methods:
read( )
reset( )
skip( )
mark( )
markSupported( )
close( )
The Writer Class
This abstract class defines streaming character output. All of the methods in this
class return a void value and throw an IOException on error condition. This class supports
following methods:
write()
flush( )
close( )
CHARACTER ARRAY AND STRING INPUT AND OUTPUT
The classes CharArrayReader and CharArrayWriter are similar to the classes
ByteArrayInputStream and ByteArrayOutputStream in that they support input and output
from memory buffers. The classes CharArrayReader and CharArrayWriter support 8-bit
character input and output.
The CharArrayReader does not in turn, add any new methods to the ones provided
by the class Reader. The class CharArrayWriter adds the following methods to the ones
provided by the class.
reset( )
-
Resets the buffer
size( )
-
Returns the current size of the buffer
toCharArray( ) -
Returns the character array copy of the output buffer.
toString( )
-
Converts the output buffer to a string object.
writeTo( )
-
Writes the buffer to another output stream.
Example of Character Array Classes
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;
public class test1
{
public static void main(String args[ ]) throws IOException
{
CharArrayWriter ca=new CharArrayWriter();
String s="Welcome to Character Array Program";
for(int i=0; i<s.length(); i++)
ca.write(s.charAt(i));
System.out.println ("Output Stream is: "+ca);
System.out.println ("Size is : "+ca.size( ));
CharArrayReader cr;
cr=new CharArrayReader(ca.toCharArray( ));
int a=0;
StringBuffer sb=new StringBuffer(" ");
while((a=cr.read( )) != (-1))
sb.append((char) a);
s=sb.toString( );
System.out.println (s.length( )+" characters were read");
System.out.print ("They are:" +s);
}
}
Output
Output Stream is : Welcome to Character Array Program
Size is : 34
35 characters were read
They are : Welcome to Character Array Program
Example of String Classes
import java.io.StringReader;
import java.io.StringWriter;
import java.io.*;
import java.io.IOException;
public class test1
{
public static void main(String args[ ]) throws IOException
{
StringWriter sw=new StringWriter( );
String s="String Input Output Program";
for(int i=0; i<s.length( ); i++)
sw.write(s.charAt(i));
System.out.println ("Output Stream is: " + sw);
StringReader sr;
sr=new StringReader (sw.toString( ));
int a=0;
StringBuffer sb=new StringBuffer (" ");
while((a=sr.read( )) != -1)
sb.append((char) a);
s=sb.toString( );
System.out.println ("No of characters read : " + s.length());
System.out.println ("They are :" + s);
}
}
Output
Output Stream is : String Input Output Program
No of characters read : 28
They are : String Input Output Program
THE PrinterWriter CLASS
The class PrintStream Implements an output.
This class has additional methods, which helps in printing basic types of data.
This class is a replacement for the class PrintStream. Actually, it improves the
PrintStream by using a platform-dependent line separator to print line
instead of ‘\n’ character.
This class provides better support for Unicode characters as compared to the
PrintStream.
This class provides support for printing primitive data types, character arrays,
strings and objects.
THE RandomAccessFile CLASS
This class provides the capability to perform I/O to specific locations within a
file.
The name RandomAccess is due to the fact that data can be read or written to
random locations within a file instead of a continuous storage of
information.
This class implements both data input and output and also supports basic file
read/write permissions, which allows files to be accessed in read-only or
read-write modes.
This class has following new methods other than those inherited from the classes
DataInput and DataOutput.
seek( ) Sets the file pointer to a specific location within the file
getFilePointer( )
Returns the current location of the file pointer
length( )
Returns the length of the file in bytes.
Example of RandomAccessFile Class
import java.io.RandomAccessFile;
import java.io.IOException;
public class exrand
{
public static void main(String args[ ]) throws IOException
{
RandomAccessFile rf;
rf=new RandomAccessFile("a.txt", "rw");
rf.writeBoolean(true);
rf.writeInt(12345);
rf.writeChars("A");
rf.writeDouble(123.45);
// use of seek( ) to move to a specific file location
rf.seek(1);
System.out.println (rf.readInt( ));
System.out.println (rf.readChar( ));
System.out.println (rf.readDouble( ));
rf.seek(0);
System.out.println (rf.readBoolean());
rf.close( );
}
}
Output
12345
A
123.45
true
Images &
Swings
IMAGES
Creating Images
Loading Images
Displaying Images
INTRODUCTION TO SWINGS
18
IMAGES
Images are off-screen representation of rectangular pixels patterns.
In java images are object of Image class, which is a part of java.awt package.
Image class provides abstract methods to represent common image behavior,
and special methods to load and display images.
Images are manipulated using the classes of java.awt.image package.
There are three things we can do with images
Creating images
Loading images
Displaying images
Creating Images
Image createImage(ImageProducer obj) To create an image produced by obj which
is an object of Image class
Loading Images
Image getImage(URL fileURL) - To take a URL that references the desired
image file.
Image getImage(URL dirURL, String path) To take a URL that references a
directory and the path of the desired image file, relative
to that directory.
Displaying Images
boolean drawImage(Image imgobj, int left, int top, ImageObserver imgobj) To draw image having specified position.
Example of Simple Image in Applet
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=imgdraw height=400 width=500>
</applet>
*/
public class imgdraw extends Applet
{
Image im;
public void init( )
{
im=createImage(200,200);
Graphics img=im.getGraphics( );
img.setColor(Color.blue);
img.fillRect(0,0,200,300);
img.setColor(Color.magenta);
img.fillOval(50,50,100,100);
}
public void paint(Graphics g)
{
g.drawImage(im,25,80,this);
}
}
Output
Example of Image having a jpg file
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=img height=400 width=500>
</applet>
*/
public class img extends Applet
{
Image im;
public void init( )
{
im=getImage(getDocumentBase( ),"nature.jpg");
}
public void paint(Graphics g)
{
g.drawImage(im,25,30,this);
}
}
Output
SWINGS
Swing is a supercharged alternative of the AWT classes, which is designed for
form based application development.
Swings provide a rich set of components and a framework to specify how to
present GUIs that are visually independent of the platform.
Swing provides a full set of GUI components written in the java programming
language for portability.
Swing must be subclass of a JApplet, which is subclass of Applet.
Example of Swing
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.Random;
/*
<applet code=swingex height=300 width=700>
</applet>
*/
public class swingex extends JApplet implements ActionListener
{
JButton jb1;
JLabel jl;
public void init( )
{
Container cp=getContentPane( );
cp.setLayout(new FlowLayout( ));
ImageIcon i=new ImageIcon("f.jpg");
jb1=new JButton(i);
jl=new JLabel("Color is : BLUE");
cp.add(jb1);
cp.add(jl);
jb1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
Random r=new Random( );
if(ae.getSource( )==jb1)
{
int x=r.nextInt(5);
String s="";
if(x==0)
{
jl.setForeground(Color.blue);
s="BLUE";
}
if(x==1)
{
jl.setForeground(Color.black);
s="BLACK";
}
if(x==2)
{
jl.setForeground(Color.green);
s="GREEN";
}
if(x==3)
{
jl.setForeground(Color.red);
s="RED";
}
if(x==4)
{
jl.setForeground(Color.magenta);
s="MAGENTA";
}
if(x==5)
{
jl.setForeground(Color.yellow);
s="YELLOW";
}
jl.setText("Color is : "+s);
}
}
}
Output
INTRODUCTION TO NETWORKING
Networking is the sharing of information and services. Networking is
possible when individual or groups have information or abilities that they wish to
share with other. Computer networking provides the communication tools to
allow computer to share information and abilities.
Sockets
Socket is the name given, in one particular programming model, to the
endpoints of a communication link between processes. Because of the popularity
of that particular programming model, the name socket has been reused in other
programming models, including java technology.
A network socket is a lot like electrical socket. Various plugs around the
network have a standard way of delivering their payload. Anything that
understands the standard protocol can “plug in” to the socket and communicate.
Internet Protocol(IP) is a low-level routing protocol that breaks data into
small packets and sends them to an address across a network. Transmission
Control Protocol (TCP) is a higher-level protocol that manages to robustly string
together these packets, sorting and retransmitting them as necessary, to reliably
transmit your data. Third protocol User Datagram Protocol(UDP), sits next to
TCP and can be used directly to support fast, connectionless, unreliable transport
of packets.
Client/Server
The term Client/Server, is quite simple in the context of networking. A
server is anything that has some resource that can be shared. There are Compute
Servers, which provide computing power. Some are Print Servers, which manage
a collection of printers. Some are Disk Servers, which provide networked disk
space. Some are Web Servers, which store web pages. A client is any other entity
that wants to gain access to a particular server. The interaction between client and
server is just like the interaction between a lamp and electrical socket.
In Berkeley Sockets, the notion of a socket allows a single computer to serve
many different clients at once, as well as serving many different types of
information. This feat is managed by the introduction of a port, which is a
numbered socket on a particular machine. A server is allowed to accept multiple
clients connected to the same port number, although each session is unique. To
manage multiple client connections, a server process must be multithreaded or
have some other means of multiplexing the simultaneous I/O.
Proxy Servers
A Proxy Server speaks the client side of a protocol to another server. This is
often required when clients have certain restrictions on which servers they can
connect to. Thus a client would connect to a proxy server, which did not have
such restrictions, and the proxy server would in turn communicate for the client.
A caching proxy HTTP server can help reduce the bandwidth demands on a
local network’s connection to the Internet. When a popular web site being hit by
hundreds of users, a proxy server can get the contents of the web server’s popular
pages once, saving expensive internet work transfers while providing faster access
to those pages to the clients.
DOMAIN NAMING SERVICE (DNS)
The name of an IP address is called as Domain name, which describes a
machine location in a name space from left to right. A parallel hierarchy of
domain names to go with all IP addresses is called as Domain Naming Services
(DNS). Eg. WWW.HOTMAIL.COM is in the com domain. Here, HOTMAIL is a
company name and WWW is the name of the web server of the HOTMAIL.
WWW is equivalent to the right most number of an IP address.
Event
14
Handling
EVENT
EVENT CLASS
Event class hierarchy
Methods of Event Class
EVENT LISTENER INTERFACE
ADAPTER CLASSES
EVENT HANDLING USING INNER CLASS
EVENT HANDLING USING ANONYMOUS INNER
CLASS
SOURCES OF EVENTS
EVENT
When the user performs an action at the user interface level this causes an
event to be issued. Events are objects that describe what has happened. In java a
number of event classes are available. An event can be generated as a consequence
of a person interacting with the elements in a GUI.
An Event source is an object that generates an event. This occurs when the
internal state of that object changes in some ways. eg. A mouse click on a Button
component generates an ActionEvent where Button is as the source. The
ActionEvent instance is an object that contains the information about the events. A
source must register listeners in order for the listeners to receive notifications
about a specific type of event. Each type of event has it’s own registration method.
Syntax
public
void addTypeListener (TypeListener
java.util.TooManyListenersException
tl)
throws
Eg. A key-board event listener – addKeyListener ( ) , A mouse-motion listener –
addMouseMotionListener ( )
A source must also provide a method that allows a listener to unregister a specific
type of event. Syntax is
public void removeTypeListener (TypeListener tl )
Eg. A key-board event listener – removeKeyListener ( ) ,
listener – removeMouseMotionListener ( )
A mouse-motion
An Event Listener is a method that receives an event object, and processes the
user’s interaction. An event listener is an object that is notified when an event
occurs. An event listener must have been registered with one or more sources to
receive notifications about specific types of events. An event listener must
implement methods to receive and process these notifications.
EVENT CLASS
Java’s event handling mechanism is represented by event classes. At
the root of the java event class hierarchy is EventObject in java.util, which is the
super class for all events. It’s constructor is EventObject(Object ob ), ob is the
object that generates this event. Event object contains two methods:
Object getSource ( ) - returns the source of the event.
ToString ( )
- returns the string equivalent of the event.
A subclass of EventObject AWTEvent class is defined within the java.awt
package, which is a superclass of all AWT-based events. It contains one method
int getID( ) - to determine the type of the event
Event class hierarchy
java.util.EventObject
java.awt.AWTEvent
ActionEvent
AdjustmentEvent ComponentEvent ItemEvent
ContainerEvent
FocusEvent
InputEvent
PointEvent
TextEvent
WindowEvent
KeyEvent
MouseEvent
Category
Event Class
Description
Action
ActionEvent
Generated when a button is pressed, a list item is
double – clicked or a menu item is selected.
Item
ItemEvent
Generated when a check-box or list-item is
clicked. Also occurs when a choice selection is
made or a checkable menu item is selected or
deselected.
Mouse
MouseEvent
Generated when a mouse is dragged, moved,
clicked, pressed or released.
Key
KeyEvent
Generated when input is received from the keyboard
Focus
FocusEvent
Generated when a component gets or loses keyboard focus
Adjustment
AdjustmentEvent
Generated when a scrollbar is manipulated.
Component
ComponentEvent
Generated when a component is hidden, moved,
resized, or becomes visible.
Window
WindowEvent
Container
ContainerEvent
Generated when a window is activated, closed,
deactivated, deiconified, iconified, opened or
quit.
Generated when a component is added to or
removed from a container
Text
TextEvent
Generated when the value of a text area or text
field is changed.
Methods of Event Class
Class
ActionEvent
AdjustmentEve
nt
ComponentEve
nt
Method
String getActionCommand( )
Description
To obtain the command name for
the invoking ActionEvent object
int getModifiers( )
To return a value that indicates
which modifier keys were pressed
adjustable getAdjustable( )
To return the object that generated
the event
int getAdjustmentType( )
To obtain the type of the adjustment
event.
Component getComponent(
)
To return the component that
generated the event.
ContainerEvent
Container getContainer( )
To return a reference to the
container that generated the event.
Component getChild( )
To return a reference to the
component that was added to or
removed from the container.
FocusEvent
boolean isTemporary( )
To indicate if the focus change is
temporary.
InputEvent
boolean isAltDown( )
To identify if the Alt key is pressed
or not at the time of event
generated.
boolean isControlDown( )
To identify if the Ctrl key is pressed
or not at the time of event
generated.
boolean isShiftDown( )
To identify if the Shift key is pressed
or not at the time of event
generated.
object getItem( )
To obtain a reference to the Item
that generated an event.
ItemSelectable
getItemSelectable( )
To obtain a reference to the
ItemSelectable object that generated
an event.
int getStateChange( )
To return the state change(select or
deselect) for the event.
char getKeyChar( )
To return the character that was
entered
int getKeyCode( )
To return the code that was entered
int getX( ) , int getY( )
To obtain X and Y co-ordinates of
the mouse when an event occurred.
Point getPoint( )
To obtain the co-ordinates of the
mouse.
int getClickCount( )
To obtain the number of mouse click
for this event.
ItemEvent
KeyEvent
MouseEvent
WindowEvent
Window getWindow( )
To return the window object that
generated the event.
EVENT LISTENER INTERFACE
Category
Interface Name
Methods
Description
Action
ActionListener
actionPerformed
(ActionEvent ae )
Defines one method
to receive action
events.
Item
ItemListener
itemStateChanged
(ItemEvent )
Mouse
MouseListener
MouseMoti
on
MouseMotionListe
ner
Key
KeyListener
mousePressed
(MouseEvent )
mouseReleased
(MouseEvent )
mouseEntered
(MouseEvent )
mouseExited
(MouseEvent )
mouseClicked
(MouseEvent )
mouseDragged
(MouseEvent )
mouseMoved
(MouseEvent )
keyPressed ( KeyEvent )
keyreleased (KeyEvent )
keyTyped ( KeyEvent )
Defines one method
to recognize when
the state of an item
Changed.
Defines five methods
to recognize when
the mouse is clicked,
enters a component,
exits a component, is
pressed or is
released.
Focus
FocusListener
focusGained (FocusEvent )
focusLosed
(FocusEvent )
Adjustment
AdjustmentListener
adjustmentValueChanged
Defines two methods
to recognize when
the mouse is dragged
or moved
Defines three
methods to recognize
when a key is
pressed, released or
typed
Defines two methods
to recognize when a
component gains or
loses a key-board
focus
Defines one method
( AdjustmentEvent )
to receive adjustment
event.
Component
ComponentListene
r
componentMoved
(ComponentEvent)
componentHidden
(ComponentEvent )
componentResized
(ComponentEvent )
componentShown
(ComponentEvent )
Defines four methods
to recognize when a
component is hidden,
moved, resized or
shown.
Window
WindowListener
windowClosing
(WindowEvent )
windowOpened
(WindowEvent )
windoeIconified
(WindowEvent )
windowDeiconified
(WindowEvent )
windowClosed
(WindowEvent )
windowActivated
(WindowEvent )
windowDeactivated
(WindowEvent )
Defines seven
methods to recognize
when a window is
activated, closed,
deactivated,
deiconified, iconified,
opened or quit.
Container
ContainerListener
componentAdded
(ContainerEvent )
componentRemoved
(ContainerEvent )
Defines two methods
to recognize when a
is added or removed
from a container.
Text
TextListener
textValueChanged (
TextEvent )
Defines one method
to recognize when a
text value is changed.
Example of Mouse Event
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
/*
<applet code=mevent height=300 width=400>
</applet>
*/
public class mevent extends Applet implements MouseListener,
MouseMotionListener
{
String s="";
int mx=0, my=0;
public void init( )
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent m)
{
mx=10;
my=20;
s="Mouse Clicked";
repaint( );
}
public void mouseEntered(MouseEvent m)
{
mx=20;
my=30;
s="mouse entered";
repaint( );
}
public void mouseExited(MouseEvent m)
{
mx=30;
my=40;
s="mouse exited";
repaint( );
}
public void mousePressed(MouseEvent m)
{
mx=m.getX( );
my=m.getY( );
s="mouse down";
repaint( );
}
public void mouseReleased(MouseEvent m)
{
mx=m.getX( );
my=m.getY( );
s="mouse up";
repaint( );
}
public void mouseDragged(MouseEvent m)
{
mx=m.getX( );
my=m.getY( );
showStatus("Mouse dragging at ="+mx+", "+my);
}
public void mouseMoved(MouseEvent m)
{
mx=m.getX( );
my=m.getY( );
showStatus("Mouse moving at ="+mx+", "+my);
}
public void paint(Graphics g)
{
g.drawString(s, mx, my);
}
}
Output
Example of Key Event
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
/*
<applet code=kevent height=300 width=400>
</applet>
*/
public class kevent extends Applet implements KeyListener
{
String s="";
int kx=30, ky=40;
public void init( )
{
addKeyListener(this);
requestFocus( );
}
public void keyReleased(KeyEvent k)
{
showStatus("key up");
}
public void keyTyped(KeyEvent k)
{
s += k.getKeyChar( );
repaint( );
}
public void keyPressed(KeyEvent k)
{
showStatus("key down");
int key=k.getKeyCode();
switch(key)
{
case k.VK_F1:
s+="<F1>";
break;
case k.VK_PAGE_DOWN:
s+="<PageDown>";
break;
case k.VK_PAGE_UP:
s+="<PageUp>";
break;
case k.VK_LEFT:
s+="<Left Arrow>";
break;
}
repaint( );
}
public void paint(Graphics g)
{
g.drawString(s, kx, ky);
}
}
Output
ADAPTER CLASSES
Some of the interfaces have only a single method, while others have
several methods. The largest interface, WindowListener has seven methods. If you
want to use only one method of WindowListener interface, eg.
Example
class windowlis implements WindowListener
{
public void windowActivated (WindowEvent e)
{
//body
}
}
This code will not compile. Because WindowListener interface
includes seven methods and so other six methods of WindowListener interface
must be implemented in this class.
Here typing the other methods and having empty bodies is very
tedious. The java.awt.event package provides seven adapter classes, one for each
listener interface that defines more than just a single method. An adapter is
simply a class that implements an interface by providing do-nothing methods. Eg.
this code will compile successfully,
class windowlis extends WindowAdapter
{
public void windowActivated (WindowEvent e)
{
//body
}
}
List of all adapter classes along with the event-listener interfaces.
Adapter Class
Listener Interface
MouseAdapter
MouseMotionAdapter
KeyAdapter
FocusAdapter
ComponentAdapter
WindowAdapter
ContainerAdapter
MouseListener
MouseMotionListener
KeyListener
FocusListener
ComponentListener
WindowListener
ContainerListener
Example of Mouse Adapter Class
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
/*
<applet code=adptr height=300 width=400>
</applet>
*/
public class adptr extends Applet
{
public void init( )
{
addMouseListener(new b(this));
}
}
class b extends MouseAdapter
{
adptr ob;
public b(adptr ob)
{
this.ob=ob;
}
public void mouseClicked(MouseEvent m)
{
ob.showStatus("Mouse Clicked");
}
}
Output
EVENT HANDLING USING INNER CLASS
Event handler can be implemented in Inner class. Private data of the
outer class can be accessed by this Inner class.
Example of Inner Class
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
/*
<applet code=inner height=300 width=400>
</applet>
*/
public class inner extends Applet
{
public void init( )
{
addMouseListener(new b( ));
}
class b extends MouseAdapter
{
public void mouseClicked(MouseEvent m)
{
showStatus("Mouse Clicked");
}
}
}
Output
Same as previous example
EVENT HANDLING USING ANONYMOUS INNER CLASS
An entire class definition within scope of an expression is called
anonymous class. Anonymous inner classes are generally in conjuction with AWT
event handling. An anonymous inner class is one that is not assigned a name.
Example of Anonymous Inner Class
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
/*
<applet code=anonym height=300 width=400>
</applet>
*/
public class anonym extends Applet
{
public void init( )
{
addMouseListener
(
new MouseAdapter( )
{
public void mouseClicked(MouseEvent m)
{
showStatus("Mouse Clicked");
}
}
);
}
}
Output
Same as previous example
SOURCES OF EVENTS
Figure
Button
Checkbox
Choice
List
clicked
-
Generates action events when the button is pressed
Generates item events when check box is selected or deselected
Generates item events when the choice is changed
Generates action events when an item is double-
Generates item events when an item is selected or
deselected.
Menu Item Generates action events when a menu is selected
Generates item events when a checkable menu item is selected or
deselected.
Scrollbar
Generates adjustment event when the scroll bar is manipulated.
Textcomponents
Generates text events when the user enters a character.
Window
- Generates window events when a window is activated, closed,
deactivated, deiconified, iconified, opened or quit.
AWT
Components - I
AWT
Component
Visual Components
Container Components
Menu Components
VISUAL COMPONENTS
Button
Label
Checkbox
List
Choice
Scroll bars
Canvas
TextField
TextArea
AWT
15
AWT classes are contained in the java.awt package. It is one of the
java’s largest packages. The java.awt package contains classes that generate GUI
components.
Component
Every GUI component that appears on the screen is a subclass of the
abstract class Component or MenuComponent. Component class is at the top of
the AWT hierarchy. So, basic GUI components inherit methods and instance
variables from
the Component class. It defines more than hundred public
methods, which are responsible for handling events, moving and changing the
size of the windows etc. A Component object is responsible for remembering
current foreground and background color and currently selected fonts.
Components can be divided into three categories.
Visual Components
Container Components
Menu Components
VISUAL COMPONENTS
Following figure shows the list of the visual components.
Button
Label
Checkbox
List
Component
Choice
Scrollbar
Canvas
TextField
TextComponent
Button
TextArea
Button is very common component, which provides a basic “push to activate”
user interface component.
It can be constructed with a text label that informs the user of its use.
A push button is an object of type Button, which can generates an event when it
is pressed.
Constructors
Button( )
Button(String str)
-
Creates an empty button
Creates a button that contains str as a label.
Methods
void SetLabel(String str) - To set str as new label, after button has been
created.
String getLabel( )
To retrieve a label of the button.
Object getSource( ) To retrieve the name of the object.
Example using Button
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=exbtn1 height=300 width=700>
</applet>
*/
public class exbtn1 extends Applet implements ActionListener
{
Button b1,b2,b3;
String s = " ", s1 = " ";
public void init( )
{
b1=new Button("YES");
b2=new Button("NO");
b3=new Button("TEST BUTTON");
add(b1);
add(b2);
add(b3);
b3.setEnabled(false);
b1.addActionListener(this);
b2.addActionListener(this);
s1="To enable TEST BUTTON press YES";
repaint( );
}
public void paint(Graphics g)
{
g.drawString(s, 10,50);
g.drawString(s1,10,70);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource( ) = = b1)
{
b3.setEnabled(true);
b3.setLabel("ENABLE");
s="You have pressed "+b1.getLabel( );
s1="To disable ENABLE button press NO";
repaint( );
}
else
{
b3.setEnabled(false);
b3.setLabel("DISABLE");
s="You have pressed "+b2.getLabel( );
s1="To enable DISABLE button press YES";
repaint( );
}
}
}
Output
Example of Button using Random Class
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.util.Random;
/*
<applet code=exbtn2 height=300 width=500>
</applet>
*/
public class exbtn2 extends Applet implements ActionListener
{
Button b1;
public void init( )
{
b1=new Button("Magic Color");
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
Random r=new Random( );
if(ae.getSource( )==b1)
{
int x=r.nextInt(5);
if(x==0)
setBackground(Color.blue);
if(x==1)
setBackground(Color.black);
if(x==2)
setBackground(Color.green);
if(x==3)
setBackground(Color.black);
if(x==4)
setBackground(Color.magenta);
if(x==5)
setBackground(Color.yellow);
}
}
}
Output
Label
A label object displays a single line of text.
The easiest control Label has no borders or other decorations.
A label is an object of type Label.
Labels are passive controls, not generally used to handle events, and support any
interaction with the user.
Constructors
Label( )
To create a blank label
Label(String str)
To create a label having str string.
Label(String str, int align) - To create a label having specified text and specified
alignment. The value of align is one of these
Label.LEFT, Label.RIGHT, Label.CENTER
Methods
void setText(String str)
String getText( )
void setAlignment(int align) -
To set or change the text in label
To retrieve the text of the label
To set the alignment of the String within label
void getAlignment( ) - To retrieve the current alignment of the string within
label.
Example using Label
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=exlabel height=300 width=700>
</applet>
*/
public class exlabel extends Applet
{
Label l1, l2, l3;
public void init( )
{
l1=new Label("Welcome", Label.RIGHT);
l2=new Label("To", Label.CENTER);
l3=new Label("AYE!", Label.LEFT);
add(l1);
add(l2);
add(l3);
repaint( );
}
public void paint(Graphics g)
{
g.drawString("l1 alignment = RIGHT = "+l1.getAlignment( ),10,40);
g.drawString("l2 alignment = CENTER = "+l2.getAlignment( ),10,60);
g.drawString("l3 alignment = LEFT = "+l3.getAlignment( ),10,80);
}
}
Output
Checkbox
The checkbox component provides a simple “on/off” input device with a text
label beside it.
The checkbox is an object of Checkbox class
There is a label associated with each check box that describes what option the
box represents.
Check boxes can be used individually or as part of a group.
Constructors
Checkbox( ) - To create a check box having blank label
Checkbox(String str) - To create a check box having label-str, checkbox status-off,
group-null.
Checkbox(String str, boolean on) - To create a check box having label-str, checkbox
status-on, group-null.
Checkbox(String str, boolean on, CheckboxGroup cb) - To create a check box having
label-str, checkbox status-on, group-cb.
Checkbox(String str, CheckboxGroup cb, boolean on) - To create a check box having
label-str, checkbox status-on, group-cb.
Methods
boolean getState - To retrieve the current state of a checkbox
void setState(boolean on) - To set a state of a check box
String getlabel( ) – To obtain the current label associated with a checkbox
void setLabel(String str) - To set the label of a checkbox
Checkbox getSelectedCheckbox( ) - To obtain currently selected checkbox from a
group
void setSelectedCheckbox(Checkbox chkbx) - To on a status of a specific
checkbox
Example using CheckBox
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=exchkbox1 height=300 width=700>
</applet>
*/
public class exchkbox1 extends Applet implements ItemListener
{
Checkbox c1, c2, c3, c4, c5, c6;
public void init( )
{
c1=new Checkbox("S.S.C.");
c2=new Checkbox("H.S.C.");
c3=new Checkbox("B.Com.");
c4=new Checkbox("L.L.B.");
c5=new Checkbox("B.A.");
c6=new Checkbox("B.Sc.");
add(c1);
add(c2);
add(c3);
add(c4);
add(c5);
add(c6);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
c6.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
g.drawString("Current Status of Check Boxes : ",10,60);
g.drawString("S.S.C. = "+c1.getState( ),10,80);
g.drawString("H.S.C. = "+c2.getState( ),10,100);
g.drawString("B.Com. = "+c3.getState( ),10,120);
g.drawString("L.L.B. = "+c4.getState( ),10,140);
g.drawString("B.A. = "+c5.getState( ),10,160);
g.drawString("B.Sc. = "+c6.getState( ),10,180);
}
}
Output
Example using CheckboxGroup
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=exchkbox2 height=300 width=700>
</applet>
*/
public class exchkbox2 extends Applet implements ItemListener
{
Checkbox c1, c2, c3, c4, c5, c6;
CheckboxGroup cg;
public void init( )
{
cg=new CheckboxGroup( );
c1=new Checkbox("B.Com.", cg, true);
c2=new Checkbox("B.A.", cg, false);
c3=new Checkbox("B.Sc.", cg, false);
c4=new Checkbox("B.E.", false, cg);
add(c1);
add(c2);
add(c3);
add(c4);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
g.drawString("Your qualification is = " + cg.getSelectedCheckbox( ).
getLabel( ),10,70);
}
}
Output
Example using CheckBox Group
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=exchkbox3 height=300 width=700>
</applet>
*/
public class exchkbox3 extends Applet implements ItemListener
{
Label l;
Checkbox c1, c2, c3, c4, c5, c6;
CheckboxGroup cg;
public void init( )
{
l=new Label("Choose any color to change background");
cg=new CheckboxGroup( );
c1=new Checkbox("Blue", cg, true);
c2=new Checkbox("Black", cg, false);
c3=new Checkbox("Magenta", cg, false);
c4=new Checkbox("Green", false, cg);
c5=new Checkbox("Red", false, cg);
add(l);
add(c1);
add(c2);
add(c3);
add(c4);
add(c5);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
if(c1.getState( ))
setBackground(Color.blue);
if(c2.getState( ))
setBackground(Color.black);
if(c3.getState( ))
setBackground(Color.magenta);
if(c4.getState( ))
setBackground(Color.green);
if(c5.getState( ))
setBackground(Color.red);
setForeground(Color.white);
g.drawString("You have selected color = " + cg.getSelectedCheckbox( ).
getLabel( ),10,100);
}
}
Output
List
The List is an object of a List class
A list presents text options that are displayed in a region that allows several
items to be viewed at one time.
The list is scrollable and supports single and multi-selection modes.
Constructors
list( ) - To create a list component that allows only one item to be selected at a
time.
list (int r) -
To create a list, which displays specified no. of rows at a time.
list (int r, boolean multiselect ) - To create a list which displays specified no of
rows at a time and if multiselect is true then multiple rows can be selected
from list.
Methods
void add(String str) - To add string str to the list
void add(String str, int index) - To add string str at the specified index to the list.
String getSelectedItem( )
-
To retrieve a selected string from the list.
int getSelectedIndex( ) - To retrieve an index of selected string from the list.
String[ ] getSelectedItems( ) -
To retrieve a selected strings from the list
int[ ] getSelectedIndexes( ) - To retrieve indexes of selected strings from the list.
int getItemCount( ) - To obtain the number of strings in the list.
void select(int index) -
To select a string at a specified index in the list.
String getItem(int index) - To obtain a string at a specified index from the list.
Example using List
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=exlist height=300 width=700>
</applet>
*/
public class exlist extends Applet implements ItemListener
{
List l1, l2;
public void init( )
{
l1=new List(4);
l2=new List(6,true);
l1.add("B.Com.");
l1.add("B.A.");
l1.add("B.Sc.");
l1.add("B.E.");
l2.add("S.S.C.");
l2.add("H.S.C.");
l2.add("B.Com.");
l2.add("B.A.");
l2.add("B.Sc.");
l2.add("L.L.B.");
l2.select(0);
add(l1);
add(l2);
l1.addItemListener(this);
l2.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
String[] s;
g.drawString("Your qualification is = ",10,170);
g.drawString(l1.getSelectedItem( ),10,180);
g.drawString("Your detailed qualification is = ",10,200);
s=l2.getSelectedItems( );
int y=210;
for(int i=0; i<s.length; i++)
{
g.drawString(s[i],10,y);
y=y+10;
}
}
}
Output
Choice
The Choice is an object of Choice class
Choice provides a simple “select one from the list” type of input.
Constructor
choice( ) -
To create an empty choice list.
Methods
void add(String str) -
To add string str to the choice list
void addItem(String str) - To add string str to the choice list
String getSelectedItem( ) -
To retrieve a selected string from the choice list.
int getSelectedIndex( ) - To retrieve an index of selected string from the choice
list.
int getItemCount( ) -
To obtain the number of strings from the choice list.
void select(int index) - To select a string at a specified index from the choice list.
void select(String str) -
To select a specified string from the choice list.
String getItem(int index) - To obtain a string at a specified index from the choice
list.
Example using Choice
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=exchoice1 height=300 width=700>
</applet>
*/
public class exchoice1 extends Applet implements ItemListener
{
Choice c1;
public void init( )
{
c1=new Choice( );
c1.add("B.Com.");
c1.add("B.A.");
c1.add("B.Sc.");
c1.add("B.E.");
add(c1);
c1.addItemListener (this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
g.drawString("Your qualification is = ",10,100);
g.drawString(c1.getSelectedItem( ),10,120);
}
}
Output
Example using Choice
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=exchoice2 height=300 width=700>
</applet>
*/
public class exchoice2 extends Applet implements ItemListener
{
List l1, l2;
Choice c1;
Font f;
public void init( )
{
l1=new List(2);
l2=new List(3);
c1=new Choice( );
l1.add("SansSerif");
l1.add("TimesRoman");
l2.add("Plain");
l2.add("Bold");
l2.add("Italic");
c1.add("8");
c1.add("10");
c1.add("12");
c1.add("15");
l1.select(0);
add(l1);
l2.select(0);
add(l2);
c1.select(0);
add(c1);
l1.addItemListener(this);
l2.addItemListener(this);
c1.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
int i=Integer.parseInt(c1.getSelectedItem( ));
if(l1.getSelectedIndex( )==0 && l2.getSelectedIndex( )==0)
f=new Font("SansSerif", Font.PLAIN,i);
else if(l1.getSelectedIndex( )==0 && l2.getSelectedIndex( )==1)
f=new Font("SansSerif", Font.BOLD,i);
else if(l1.getSelectedIndex( )==0 && l2.getSelectedIndex( )==2)
f=new Font("SansSerif", Font.ITALIC,i);
else if(l1.getSelectedIndex( )==1 && l2.getSelectedIndex( )==0)
f=new Font("TimesRoman", Font.PLAIN,i);
else if(l1.getSelectedIndex( )==1 && l2.getSelectedIndex( )==1)
f=new Font("TimesRoman", Font.BOLD,i);
else if(l1.getSelectedIndex( )==1 && l2.getSelectedIndex( )==2)
f=new Font("TimesRoman", Font.ITALIC,i);
setFont(f);
repaint( );
}
public void paint(Graphics g)
{
g.drawString("You have selected font = "+l1.getSelectedItem( ) + “style=" +
l2.getSelectedItem( ),10,170);
}
}
Output
Scroll bars
The Scroll bar is an object of Scrollbar class
Scroll bars are used to select continuous values between specified ranges.
Scroll bars can be oriented horizontally or vertically.
The current value of the scroll bar is indicated by the slider box.
Constructors
Scrollbar( ) - To create a vertical scroll bar.
Scrollbar( int style ) - To create a scroll bar having specified style either
Scrollbar.VERTICAL or Scrollbar.HORIZONTAL
Scrollbar( int style, int initvalue, int thumbsize, int min, int max )
To
create a scroll bar having specified style, initial value,
height, and maximum and minimum value.
Methods
void setValues(int, int initvalue, int thumbsize, int min, int max ) - To set
initial value, height, minimum value and maximum
value.
int getValue( ) - To obtain the current value of the scroll bar.
void setValue(int newvalue) - To set the new value in the scrollbar.
int getMinimum( ) - To retrieve the minimum value from the scroll bar.
int getMaximum( ) - To retrieve the maximum value from the scroll bar.
void setUnitIncrement(int newvalue) - To change the default increment 1
in the scroll bar
void setBlockIncrement(int newvalue) - To change the default increment of
page up and page down value 10 in the scrollbar.
Example using ScrollBar
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=exsbar height=200 width=400>
</applet>
*/
public class exsbar extends Applet implements AdjustmentListener,
MouseMotionListener
{
Scrollbar vs, hs;
public void init( )
{
setLayout(null);
int w=Integer.parseInt(getParameter("width"));
int h=Integer.parseInt(getParameter("height"));
vs=new Scrollbar(Scrollbar.VERTICAL,0,1,0,h);
hs=new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,w);
add(vs);
add(hs);
vs.addAdjustmentListener(this);
hs.addAdjustmentListener(this);
addMouseMotionListener(this);
hs.setBounds(1,h-16,w-16,16);
vs.setBounds(w-16,1,16,h-16);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
repaint( );
}
public void mouseDragged(MouseEvent me)
{
int x=me.getX( );
int y=me.getY( );
vs.setValue(y);
hs.setValue(x);
repaint( );
}
public void mouseMoved(MouseEvent me)
{
}
public void paint(Graphics g)
{
g.drawString("Vertical ="+vs.getValue( ),10,60);
g.drawString("Horizontal ="+hs.getValue( ),10,80);
g.drawString("?",hs.getValue( ),vs.getValue( ));
}
}
Output
Canvas
A canvas provides a blank (background colored) space.
Canvas is an object of Canvas class
It’s default size is height=0 and width=0
Canvas encapsulates a blank window upon which user can draw.
Constructor
Canvas( )
-
To create a default canvas.
Method
void setSize( int width, int height )
- To set the specified width and height of
the canvas.
Example using Canvas
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=excanvas height=200 width=400>
</applet>
*/
public class excanvas extends Applet
{
Canvas c;
public void init( )
{
c=new Canvas( );
c.setBackground(Color.black);
c.setSize(50,90);
add(c);
}
}
Output
TextField
The Text field supports single line input, which is also called edit control.
The Text field is an object of TextField class
Text field allows the user to enter string and to edit text using arrow keys, cutpaste keys and mouse selection.
Constructors
TextField( ) To create a default text field.
TextField(int size) - To create a text field having specified size.
TextField(String str)
- To create a text field having initial string str.
TextField(String str, int size) - To create a text field having initial string str
and specified size.
Methods
String getText( ) - To obtain the string of the text field
void setText( String str ) - To set a new string in the text field.
String getSelectedText( ) - To obtain the selected text from the text field
void select( int start, int end ) To select a text from start index to end index
in the text field
boolean isEditable( )
To determine edit ability of the text field.
void setEditable( boolean b) - To set edit ability of the text field.
void setEchoChar( char ch ) - To set the character ch that should be displayed in
the text field instead of actual characters entered.
boolean echoCharIsSet( ) - To check a text field is in setEchoChar mode or not.
char getEchoChar( ) To obtain the echo character set in the text field.
Example using TextField
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=extfield height=200 width=400>
</applet>
*/
public class extfield extends Applet implements ActionListener
{
TextField t1, t2;
Label l1, l2;
public void init( )
{
l1=new Label("Enter User Name ");
l2=new Label("Enter Password ");
t1=new TextField(10);
t2=new TextField(10);
t2.setEchoChar('*');
add(l1);
add(t1);
add(l2);
add(t2);
t1.addActionListener(this);
t2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
repaint( );
}
public void paint(Graphics g)
{
g.drawString("User Name
= "+t1.getText( ),10,50);
g.drawString("Password
= " + t2.getText( ),10,70);
g.drawString("Selected Password = " + t2.getSelectedText( ),10,90);
}
}
Output
TextArea
The Text area supports multiple line input, which is also called multi line edit
control.
The Text area is an object of TextArea class.
Text area allows the user to enter string and to edit text using arrow keys, cutpaste keys and mouse selection.
Constructors
TextArea( )
To create a default text area.
TextArea(int height, int width) - To create a text area having specified height
and width.
TextArea(String str) To create a text area having initial string str.
TextArea(String str, int height, int width) To create a text area having
initial string str and specified height and
width.
TextArea(String str, int height, int width, int sbars) To create a text area
having initial string str and specified height,
width
and scrollbars (sbars can be
SCROLLBARS_BOTH,
SCROLLBARS_NONE,
SCROLLBARS_HORIZONTAL_ONLY,
SCROLLBARS_VERTICAL_ONLY.
Methods
String getText( )
void setText( String str )
-
To obtain the string of the text area.
To set a new string in the text area.
String getSelectedText( ) To obtain the selected text from the text area
void select( int start, int end ) - To select a text from start index to end index in
the text area
boolean isEditable( )
To determine edit ability of the text
area.
void setEditable( boolean b)
To set edit ability of the text area.
void append( String str ) - To append the string str to the end of the current text
in text area..
void insert( String str, int index ) To insert the string str at the specified
index.
void replaceRange( String str, int start, int end ) -To replace the string str from
start index to end index–1.
Example using TextArea
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=extarea height=200 width=400>
</applet>
*/
public class extarea extends Applet
{
TextArea t;
String s="";
public void init( )
{
s+="Welcome to AYE !\n";
s+="AYE is a computer education division of AMEE DOT COM Pvt.
Ltd." ;
t=new TextArea(s,10,30);
add(t);
}
}
Output
AWT
16
Components - II
CONTAINER
Container Components
APPLET
PANEL
WINDOW
FRAME
DIALOG BOXES
FILE DIALOG
MENU COMPONENT
MenuBar
Menu
MenuItem
CheckboxMenuITem
As we have seen before that AWT provides three kinds of
components - Visual Component, Container Component, and Menu Component.
So, following figure shows the container components provided by AWT.
Panel
Component
Applet
Container
Window
Frame
FIGURE 15 - 1 CONTAINER COMPONENTS PROVIDED BY AWT
CONTAINER
The Container, which is subclass of Component can contain other components.
A container is responsible for positioning and resizing any component that it
contains.
Components can be added in container with the use of add( ).
The two main types of containers are window and panel
The Container class is abstract class.
Container Components
Applet
Panel
Frame
Dialog Boxes.
APPLET
Applets are small applications that are accessed on an Internet server, and run as
part of a Web document.
Applets only exist in browsers
The easiest browser for applet is the appletviewer, which allows resizing of
applets.
Every applets created by the user must be a subclass of Applet class.
PANEL
A panel is a container of GUI components that must exist in the context of some
other container, such as a window or applet.
A panel is a window without having title bar, menu bar, or border because it is
not seen when an applet runs inside a browser.
A panel is contained within another container or inside a Web browser’s
window.
Panel identifies rectangular area into which other components can be placed.
Panel must be placed into a window to be displayed.
The other components can be added into panel by add( ). Then they can be
positioned and resized by setLocation( ), setSize( ), or setBounds( ) methods
defined by Component.
Example using Panel
import java.awt.*;
public class expanel
{
private Frame f;
private Panel p;
public expanel(String s)
{
f=new Frame(s);
p=new Panel( );
}
public void framelaunch( )
{
f.setSize(200,200);
f.setBackground(Color.black);
f.setLayout(null);
p.setSize(100,100);
p.setBackground(Color.white);
f.add(p);
f.setVisible(true);
}
public static void main(String args[ ])
{
expanel ob=new expanel("Frame with Panel");
ob.framelaunch( );
}
}
Output
WINDOW
The Window class, which is a subclass of Container creates a top-level window.
A top-level window, which is displayed directly on the desktop is not contained
within any other object.
Generally, window can’t be created directly by user and user will use a subclass
of Window called Frame.
Constructor
Window(Frame f) - To create a new window where f is the owner of the window.
Methods
void pack( ) - To lay out the component in the window and set its initial size.
void show( ) To make the window visible.
void dispose( ) To finish with the window.
Example of Creating a Window
import java.awt.*;
import java.awt.event.*;
public class exwin extends Frame
{
String k="", m="";
int mx=40, my=50;
public exwin( )
{
addKeyListener(new kadapter(this));
addMouseListener(new madapter(this));
addWindowListener(new wadapter( ));
}
public void paint(Graphics g)
{
g.drawString(k, 20, 70);
g.drawString(m, mx, my);
}
public static void main(String args[ ])
{
exwin ob=new exwin( );
ob.setSize(200,300);
ob.setTitle("My First Window");
ob.setVisible(true);
}
}
class kadapter extends KeyAdapter
{
exwin ob;
public kadapter(exwin ob)
{
this.ob=ob;
}
public void keyTyped(KeyEvent ke)
{
ob.k+=ke.getKeyChar( );
ob.repaint( );
}
}
class madapter extends MouseAdapter
{
exwin ob;
public madapter(exwin ob)
{
this.ob=ob;
}
public void mousePressed(MouseEvent me)
{
ob.mx=me.getX( );
ob.my=me.getY( );
ob.m="Mouse pressed at "+ob.mx+", "+ob.my;
ob.repaint( );
}
}
class wadapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
Output
FRAME
Frame, which is a subclass of Window having a title bar, menu bar, borders and
resizing corners.
As Frame inherits from a container, components can be added to a Frame by
using add( ).
Frames are initially invisible. They can be visible by using method
setVisible(true).
Components can be added to a Frame while it is invisible.
When, a Frame window is created by a program rather than an applet, a normal
window is created.
When a Frame is created within an applet it will contain a warning message
”Warning : Applet Window”. This means the window shown on screen, is
started by an applet and not by software running on that computer.
Constructors
Frame( ) Frame(String s) -
To create a frame having no title
To create a frame having title s.
Methods
setSize(int w, int h) - To set the new size having w width and h height for a
frame.
Dimension getSize( ) To obtain the current size of a window.
void setVisible(boolean b) - To make the frame visible if b is true otherwise false.
void setTitle(String s) To set a new title in the window.
Example using Frame
import java.awt.*;
public class exframe
{
private Frame f;
public exframe( )
{
f=new Frame("Welcome to AYE!");
}
public void loadframe( )
{
f.setSize(200,300);
f.setBackground(Color.blue);
f.setVisible(true);
}
public static void main(String args[ ])
{
exframe ob=new exframe( );
ob.loadframe( );
}
}
Output
DIALOG BOXES
A dialog which is associated with a Frame, is free-standing window with some
decoration,
Dialogs are commonly presented in graphic user interfaces to display
information or obtain input.
A dialog is usually not made visible to the user when it is first created. It is
displayed in response to some user interface action.
Dialog is either modeless or model.
A modeless dialog means, interaction with both Frame and the Dialog at the
same time is possible.
A modal Dialog blocks input to the remainder of the application, including the
Frame, until the Dialog box is dismissed.
Constructors
Dialog(Frame f, boolean b) -To create a dialog box where f is owner of the dialog
box. If b is true then dialog box is modal otherwise modeless.
Dialog(Frame f, String s, boolean b) - To create a dialog box having title s and
mode either true or false.
Example of Dialog Box
import java.awt.*;
import java.awt.event.*;
public class exdialog extends Frame implements ActionListener
{
Button b;
public static void main(String args[ ])
{
exdialog ob=new exdialog( );
ob.setVisible(true);
ob.setSize(200,100);
}
exdialog( )
{
super("My First Dialog");
setLayout(new FlowLayout( ));
b=new Button("Dialog");
b.addActionListener(this);
add(b);
//Anonymous inner class
addWindowListener(new WindowAdapter( )
{
public void WindowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent ae)
{
String s="This is my message";
b bob=new b(this, "Dialog", true, s);
bob.show( );
}
}
class b extends Dialog implements ActionListener
{
Button b2;
b(Frame f, String s, boolean b, String s1)
{
super(f, s, b);
Panel p=new Panel( );
Label l=new Label(s1);
p.add(l);
add(p, "Center");
Panel p1=new Panel( );
b2=new Button("OK");
b2.addActionListener(this);
p1.add(b2);
add(p1,"South");
pack( ); // to lay out components and set initial size of dialog box.
addWindowListener(new WindowAdapter( )
{
public void WindowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
}
public Insets getInset( )
{
return new Insets(40,20,20,20);
}
public void actionPerformed(ActionEvent ae)
{
dispose( ); // to finish with the dialog.
}
}
Output
FILE DIALOG
Filedialog is an implementation of a file selection device.
FileDialog, which has its own free standing window, allows the user to browse
the file system and select a particular file for more operation.
To create a file dialog box instantiate an object of FileDialog.
Constructors
FileDialog(Frame f, String s)
- To create a file dialog where f is owner of file
dialog and s is the name displayed in the title bar
FileDialog(Frame f, String s, int i) - To create a file dialog where f is owner of
file dialog, s is the name displayed in the title bar, and i is one
of FileDialog.LOAD or FileDialog.SAVE.
FileDialog(Frame f) To create a dialog box for selecting a file for reading.
Methods
String getDirectory( )
To obtain the directory name and path
selected by the user.
String getFile( ) To obtain the file name and path selected by the user.
Example using File Dialog
import java.awt.*;
import java.awt.event.*;
public class exfdialog extends Frame implements ActionListener,
WindowListener
{
Button b1, b2;
TextField t;
public static void main(String args[ ])
{
exfdialog ob=new exfdialog( );
ob.setVisible(true);
ob.setSize(400,200);
}
exfdialog( )
{
super ("My First File Dialog");
setLayout(new FlowLayout( ));
b1=new Button("Load Me");
b1.addActionListener(this);
add(b1);
b2=new Button("Save");
b2.addActionListener(this);
add(b2);
t=new TextField(20);
add(t);
addWindowListener(this);
}
public void actionPerformed(ActionEvent ae)
{
FileDialog fd;
if(ae.getSource( )==b1)
fd=new FileDialog(this, "File Dialog",FileDialog.LOAD);
else
fd=new FileDialog(this, "File Dialog", FileDialog.SAVE);
fd.show( );
String fn=fd.getFile( );
if(fn!=null)
t.setText(fn);
}
public void windowActivated(WindowEvent we) {
}
public void windowClosed(WindowEvent we) {
}
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
public void windowDeactivated(WindowEvent we) {
}
public void windowIconified(WindowEvent we) {
}
public void windowDeiconified(WindowEvent we) {
}
public void windowOpened(WindowEvent we){
}
}
Output
MENU COMPONENT
A Menu is a component of AWT but it is different from other
components because it can’t be added to ordinary container and laid out by layout
manager. Menu can be added only to a menu container. A top-level window can
have menu bar, which displays a list of top - level menu choices and each choice is
associated with a drop-down menu.
In java there are three classes, which can implement menu concepts.
MenuBar
Menu
MenuItem
CheckboxMenuItem
MenuBar
A MenuBar component is a horizontal menu, which contains one or more Menu
objects.
It can only be added to a Frame object.
It forms the root of all menu trees.
A frame can display only one MenuBar at a time.
The MenuBar does not support any listener.
Constructor
MenuBar( )
-
To create a default menu bar.
Menu
A Menu component provides a basic pull-down menu.
It can be added either to a MenuBar or to another Menu.
Menus are used to display and control menu items.
Constructors
Menu( )
-
To create a default menu.
Menu( String str )
-
str specifies the name of the Menu selection
Menu( String str, boolean flag)
flag represents the pop up menu if set
true It can be removed and allowed to float free,else will
remain attached to the menu bar.
MenuItem
MenuItem component are the text leaf nodes of a menu tree.
MenuItems are added to a Menu.
An ActionListener can be added to a MenuItem object.
Constructors
MenuItem( ) -
To create a default MenuItem.
MenuItem( String str )
-
str is the name shown in the Menu.
MenuItem( String str, MenuShortcut key) - key is the short cut key for that
Menu Item
CheckboxMenuItem
CheckboxMenuItem is checkable menu item, which provides selection (on or off
) listed in menus.
CheckboxMenuItem can be controlled by the ItemListener interface.
The itemStateChanged( ) method is called, when the checkbox state is modified.
Constructor
CheckboxMenuItem( )
-
CheckboxMenuItem( String str )
To create a default CheckBoxMenuItem.
-
CheckboxMenuItem( String str, boolean flag )
str is the name shown in the menu.
-
flag can be set on for the
Item to be checkable.
Methods
Following are some common methods, which are used while creating
a menu.
void setEnabled( boolean flag )
- To enable or disable menu item.
boolean isEnabled( ) - To obtain the status of the menu item.
void setLabel( String str ) - To change the name of the invoking menu item.
String getLabel( ) - To obtain the current name of the menu item.
boolean getState( ) - Returns true if the item is checked otherwise false.
void setState( boolean flag) - To check an item pass true and to clear an
pass false.
Example of Menu
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code=a height=300 width=500>
</applet>
*/
class b extends Frame
{
CheckboxMenuItem c1;
String s, s1;
b(String s)
{
super(s);
MenuBar mbar=new MenuBar();
setMenuBar(mbar);
item
Menu file=new Menu("File");
MenuItem f1, f2, f3;
file.add(f1=new MenuItem("New"));
file.add(f2=new MenuItem("Open"));
file.add(f3=new MenuItem("Close"));
file.add(c1=new CheckboxMenuItem("Save"));
mbar.add(file);
Menu edit=new Menu("Edit");
MenuItem e1, e2, e3;
edit.add(e1=new MenuItem("Cut"));
edit.add(e2=new MenuItem("Copy"));
edit.add(e3=new MenuItem("Paste"));
Menu go=new Menu("Goto");
MenuItem g1, g2, g3, g4;
go.add(g1=new MenuItem("First"));
go.add(g2=new MenuItem("Previous"));
go.add(g3=new MenuItem("Next"));
go.add(g4=new MenuItem("Last"));
edit.add(go);
mbar.add(edit);
menuhandler mh=new menuhandler(this);
f1.addActionListener(mh);
f2.addActionListener(mh);
f3.addActionListener(mh);
g1.addActionListener(mh);
g2.addActionListener(mh);
g3.addActionListener(mh);
g4.addActionListener(mh);
e1.addActionListener(mh);
e2.addActionListener(mh);
e3.addActionListener(mh);
c1.addItemListener(mh);
winadapter wa=new winadapter(this);
addWindowListener(wa);
}
public void paint(Graphics g)
{
g.drawString(s,10,220);
if(c1.getState( ))
g.drawString("Save is on",10,240);
else
g.drawString("Save is off",10,240);
}
}
class winadapter extends WindowAdapter
{
b bob;
public winadapter(b bob)
{
this.bob=bob;
}
public void windowClosing(WindowEvent we)
{
bob.setVisible(false);
}
}
class menuhandler implements ActionListener,ItemListener
{
b bob;
public menuhandler(b bob)
{
this.bob=bob;
}
public void actionPerformed(ActionEvent ae)
{
String s="You selected ";
String s1=(String)ae.getActionCommand();
if(s1.equals("New"))
s+="New";
if(s1.equals("Open"))
s+="Open";
if(s1.equals("Close"))
s+="Close";
if(s1.equals("Save"))
s+="Save";
if(s1.equals("Edit"))
s+="Edit";
if(s1.equals("Cut"))
s+="Cut";
if(s1.equals("Copy"))
s+="Copy";
if(s1.equals("Paste"))
s+="Paste";
if(s1.equals("First"))
s+="First";
if(s1.equals("Previous"))
s+="Previous";
if(s1.equals("Next"))
s+="Next";
if(s1.equals("Last"))
s+="Last";
bob.s=s;
bob.repaint( );
}
public void itemStateChanged(ItemEvent ie)
{
bob.repaint( );
}
}
public class a extends Applet
{
Frame f;
public void init( )
{
f=new b("First Menu");
f.setSize(500,300);
f.setVisible(true);
}
public void start( )
{
f.setVisible(true);
}
public void stop( )
{
f.setVisible(false);
}
}
Output
Layout
17
Managers
LAYOUT MANAGERS
FlowLayout
BorderLayout
GridLayout
CardLayout
GridBagLayout
LAYOUT MANAGERS
Layout manager automatically arranges all the components within a window.
A layout manager is an instance of any class that implements the LayoutManager
interface.
Each container object has a layout manager associated with it.
The layout manager is set by the setLayout( ).
GetPreferredSize( ) and getMinimumSize( ) methods are used to obtain the
preferred and minimum size required to display and manage each
component.
Java has several layout manager class like FlowLayout, BorderLayout,
GridLayout, CardLayout, GridBagLayout
FlowLayout
FlowLayout is a default layout manager of panel and applet, so it is usually the
first layout manager that programmers encounter.
The FlowLayout manager arranges all components in horizontal rows and from
left to right.
By default, FlowLayout manager leaves a gap of five pixels between components
in both the horizontal and vertical directions.
The FlowLayout manager does not constrain the size of the components it
manages, but instead allows them to have their preferred size.
Constructors
FlowLayout( )
- To create a default layout, which centers components.
FlowLayout(int align)
- To create a layout with specified alignment.
Alignment can be on of the FlowLayout.LEFT,
FlowLayout.CENTER, FlowLayout.RIGHT.
FlowLayout( int align, int hspace, int vspace) - To create a layout having
specified alignment and horizontal and vertical space
between components.
Example using FlowLayout
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=flayout height=300 width=700>
</applet>
*/
public class flayout extends Applet implements ItemListener
{
Checkbox c1, c2, c3, c4, c5, c6;
public void init( )
{
setLayout(new FlowLayout(FlowLayout.LEFT));
c1=new Checkbox("S.S.C.");
c2=new Checkbox("H.S.C.");
c3=new Checkbox("B.Com.");
c4=new Checkbox("L.L.B.");
c5=new Checkbox("B.A.");
c6=new Checkbox("B.Sc.");
add(c1);
add(c2);
add(c3);
add(c4);
add(c5);
add(c6);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
c6.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
g.drawString("Current Status of Check Boxes : ",10,80);
g.drawString("S.S.C. = "+c1.getState( ),10,100);
g.drawString("H.S.C. = "+c2.getState( ),10,120);
g.drawString("B.Com. = "+c3.getState( ),10,140);
g.drawString("L.L.B. = "+c4.getState( ),10,160);
g.drawString("B.A. = "+c5.getState( ),10,180);
g.drawString("B.Sc. = "+c6.getState( ),10,200);
}
}
Output
BorderLayout
The BorderLayout manager provides a more complex scheme for placing
components within a container.
The BorderLayout manager is default manager for frames and dialog boxes,
where components are added to specific regions.
The BorderLayout manager divides its territory into five regions : NORTH,
SOUTH, EAST, WEST AND CENTER
NORTH, SOUTH, CENTER regions adjust horizontally and EAST, WEST,
CENTER regions adjust vertically.
Each region may contain a single component but no region is required to contain
a component.
Constructors
BorderLayout( )
To create a default border layout.
BorderLayout (int hspace, int vspace) - To create a border layout having
specified horizontal and vertical space left between components.
Methods
void add( Component obj, Object region ) To add components to border
layout where obj is the component to be added and region may
be one of these : BorderLayout.SOUTH, BorderLayout.NORTH,
BorderLayout.EAST,
BorderLayout.WEST,
BorderLayout.CENTER.
Example using BorderLayout
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=blayout height=300 width=700>
</applet>
*/
public class blayout extends Applet
{
Button bn, bs, be, bw, bc;
public void init( )
{
bn=new Button("NORTH");
bs=new Button("SOUTH");
be=new Button("EAST");
bw=new Button("WEST");
bc=new Button("CENTER");
setLayout(new BorderLayout());
add(bn, BorderLayout.NORTH);
add(bs, BorderLayout.SOUTH);
add(be, BorderLayout.EAST);
add(bw, BorderLayout.WEST);
add(bc, BorderLayout.CENTER);
}
}
Output
Using Insets with BorderLayout
Inset is used to leave a small amount of space between the container and the
window that contains it.
getInsets( ) is used to specify the space between the container and the window.
Example using Insets in BorderLayout
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=blayout height=300 width=700>
</applet>
*/
public class blayout extends Applet
{
Button bn, bs, be, bw, bc;
public void init( )
{
setBackground(Color.blue);
bn=new Button("NORTH");
bs=new Button("SOUTH");
be=new Button("EAST");
bw=new Button("WEST");
bc=new Button("CENTER");
setLayout(new BorderLayout());
add(bn, BorderLayout.NORTH);
add(bs, BorderLayout.SOUTH);
add(be, BorderLayout.EAST);
add(bw, BorderLayout.WEST);
add(bc, BorderLayout.CENTER);
}
public Insets getInsets( )
{
return new Insets(10,10,10,10);
}
}
Output
GridLayout
The GridLayout manager provides flexibility for placing components in number
of rows and columns.
In GridLayout manager components are added left to right and top to bottom.
In GridLayout manager all regions are equally sized
GridLayout manager always ignores a component’s preferred size.
In BorderLayout manager the relative position of components does not change as
the area is resized. Only the size of components changed.
Constructors
GridLayout( )
- To create a single column GridLayout.
GridLayout( int rows, int columns ) - To create a GridLayout with a specified
number of rows and columns.
GridLayout( int rows, int columns, int hspace, int vspace) - To create a
GridLayout having specified number of rows and columns
and horizontal and vertical space between components.
Example using GridLayout
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=glayout height=200 width=400>
</applet>
*/
public class glayout extends Applet
{
TextField t1, t2, t3;
Label l1, l2, l3;
GridLayout g;
public void init( )
{
l1=new Label("Enter User Name ");
l2=new Label("Enter Password ");
l3=new Label("Enter Domain ");
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
g=new GridLayout(3,2);
setLayout(g);
t2.setEchoChar('*');
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
}
}
Output
CardLayout
The CardLayout manager enables to treat the interface as a series of cards, only
one of which can be viewed at any time.
The CardLayout manager lays out its components in time rather in space.
In CardLayout manager all the components are resized to occupy the entire
container.
Constructors
CardLayout( ) - To create a default card layout.
CardLayout( int hspace, int vspace ) To create a card layout having
specified horizontal and vertical space left between
components.
Example using CardLayout
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=clayout height=200 width=400>
</applet>
*/
public class clayout extends Applet implements ActionListener ,
MouseListener
{
Checkbox c1, c2, c3, c4, c5;
Button b1, b2;
Panel p;
CardLayout c;
public void init( )
{
b1=new Button("Qualification");
b2=new Button("Additional Qualification");
add(b1);
add(b2);
c=new CardLayout( );
p=new Panel( );
p.setLayout(c);
c1=new Checkbox("B.Com.");
c2=new Checkbox("B.Sc.");
c3=new Checkbox("B.A.");
c4=new Checkbox("L.L.B.");
c5=new Checkbox("B.E.");
Panel p1=new Panel( );
p1.add(c1);
p1.add(c2);
p1.add(c3);
Panel p2=new Panel( );
p2.add(c4);
p2.add(c5);
p.add(p1,"Qualification");
p.add(p2,"Additional Qualification");
add(p);
b1.addActionListener(this);
b2.addActionListener(this);
addMouseListener(this);
}
public void mousePressed(MouseEvent me)
{
c.next(p);
}
public void mouseClicked(MouseEvent me){
}
public void mouseReleased(MouseEvent me){
}
public void mouseEntered(MouseEvent me){
}
public void mouseExited(MouseEvent me){
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource( )==b1)
c.show(p, "Qualification");
else
c.show(p, "Additional Qualification");
}
}
Output
GridBagLayout
GridBagLayout divides its container into an array of cells, but different rows can
have different heights, and different columns can have different widths.
GridBagLayout can occupy a single cell or it can span a number of cells.
In GridBagLayout, it is not necessary that all rows and columns are equal in size.
The number of rows and columns in GridBagLayout is determined by the
number of cells that are in use.
GridBagLayout can be assigned multiple cells, horizontally, vertically, or both,
and can exist within that region.
A GridBagLayout requires a lot of information to know where to put a
component. So, a helper class called GridBagConstraints is used to hold all
layout position information.
Applets
13
APPLETS
Loading Applets
APPLET CLASS
Methods of Applet class
AWT (ABSTRACT WINDOW TOOLKIT )
THE “APPLETVIEWER”
THE APPLET TAG
SIMPLE METHODS TO DESIGN APPLET
SELECTING A COLOR
SELECTING A FONT
GRAPHICS CLASS
APPLETS
An applet is a small program that is intended not to be run on its own, but
rather to be embedded inside another application. Java applet is a Java class that
you can embed in an HTML page, and is downloaded and executed by a Web
browser. It is a specific type of Java technology container. It differs from an
application in
the way it is executing. An application is started when its main
method is called but lifecycle of applet is very complex.
Java Applets are run within a browsers and so they can use all infrastructures
provided by a browser
Java Applets are included in HTML pages using the special tag <APPLET>
Since the Applet is executed on the computer, the browsers limit the actions that
an Applet can perform.
Applets are not allowed to read or write in files on the local System.
Applets allow neither to execute any application nor to load any DLLs on the
local system.
Applets can communicate only with the server on which they are originally
resident.
Applets do not need a main method.
Applets must be run under an appletviewer or a java compatible browser.
Applets use the interface provided by the AWT
Loading Applets
Like an application, java applets can’t be executed directly because they are
executed through the browsers. For running an applet, HTML file must be created
which tells the browser what to load and how to run it.
Browser loads URL
Browser loads HTML documents
Browser loads applet classes
Browser runs Applet
TABLE 12-1 STEPS FOR RUNNING AN APPLET
APPLET CLASS
The java.applet.Applet class is actually a subclass of java.awt.Panel. The
hierarchy of the applet and AWT classes is as follows
Java.lang.Object
Java.awt.Compone
nt
Java.awt.Containe
r
Java.awt.Windo
w
Java.awt.Panel
Java.awt.Frame
Java.applet.Apple
t
FIGURE 12-1 Applet and AWT Class Hierarchy
Methods of Applet class
The following are some various methods of the Applet class.
init( )
This method is called whenever an applet is created.
This method is called only once during the lifetime of an applet.
In this method variables are initialized.
This method runs to completion before start is called.
start( )
After init( ) is completed, the start( ) is called to start the applet from a stop
state.
The start( ) is called whenever applet’s HTML document is reloaded during
execution time of applet.
This method is used to start threads or an animation or to play sound.
start( ) activates the behavior in an applet.
paint( )
The paint( ) is called whenever the applet output has to be redrawn means
applet window is minimized or maximized or overwritten.
Syntax of paint( )
paint( Graphics objectname )
The paint( ) method has one parameter of type Graphics that describes the
graphics environment in which the applet is running paint( ) is called when
the applet begins execution
repaint( )
The repaint( ) is called whenever applet needs to update the information
displayed in it’s window
The repaint( ) actually causes the AWT thread to call update( ).
update( )
update( ) is a method you can use along with paint to improve drawing
performance.
update( ) clears the current display and calls the paint( )
stop( )
The stop( ) method is called when the applet becomes invisible when user
moves from a page in which the applet is running.
stop( ) deactivates the behavior in an applet.
The stop( ) always called before destroy( )
destroy( )
The destroy( ) is called when the browser on which the applet is running is
closed or when a new site is opened in that browser
T he destroy( ) permanently removes the applet and all the resources used by
the running applet from the memory.
AWT (ABSTRACT WINDOW TOOLKIT )
The most common component of java AWT is an object-oriented GUI
framework. It allows the users to paint the screen according to their wish and
creativity. It provides machine independent interface for applications. AWT
classes are contained in the java.awt package. It is one of the java’s largest
packages. The java.awt package contains classes, which generates GUI
components.
AWT provides graphical user interface (GUI) components that are used in all
java applets and applications
AWT contains classes that can be extended and their properties can be inherited.
AWT classes can also be abstract
Every GUI component must be a subclass of the abstract class Component or
MenuComponent
THE “APPLETVIEWER”
An applet is usually run inside a web browser, which is capable of
running java software programs. The appletviewer is a java application that
enables you to run applets without using a Web browser. The appletviewer reads
the HTML file specified by the URL on the command line. This file must contains
an applet tag of HTML code. You can use appletviewer having following syntax.
appletviewer a.java
Enables you to run applets using a Web browser
Loads the HTML file supplied as an argument
It must needs applet tag of HTML code.
THE APPLET TAG
The applet can be started either from HTML document or from an
applet viewer. The applet tag is used to start an applet. The syntax of applet tag.
<applet
code = appletFile
width=pixels height=pixels
[ codebase = codebaseURL ]
[ alt = atlertnateText ]
[ name = appletInstanceName ]
[ align = alignment ]
[ vspace = pixels ] [ hspace = pixels ]
>
[< param name = AttributeName
[< param name = AttributeName2
…..
[alternateHTML ]
</applet>
value = AttributeValue >]
value = AttributeValue >]
code :This is compulsory required attribute. It gives the name of file that contains
the compiled applet class file. This file can be package.appletFile.class
width – height :This attribute specifies the initial width and height of the applet display
area. It doesn’t include any windows and dialogs that are displayed by an applet.
codebase :This optional attribute specifies the base URL of the applet. URL means the
directory that contains the applet code. If this attribute is not specified then the
document’s URL is used.
alt :This optional attribute specifies which text to display if the browser can read
the applet tag, but can’t run java applets.
name :This optional attribute specifies the name for the applet instance , which
makes it possible for applets on the same page to find and to communicate with
each other.
align :This optional attribute specifies the alignment of the applet.
vspace :This optional attributes vspace specifies the number of pixels above and
below the applet,
hspace :This optional attribute hspace specifies the number of pixels on each side
of the applet.
param name :This optional tag provides an applet with a value specified “from the
outside“ . It is same as command-line arguments in java applications.
SIMPLE METHODS TO DESIGN APPLET
METHOD
void setBackground (Color colorname )
void setForeground (Color colorname )
Color getBackground ( )
Color getForeground ( )
Applet getApplet ( String name )
Void showStatus( String status )
URL getDocumentBase ( )
URL getCodeBase( )
DESCRIPTION
To set the background of an applet
window.
To set the foreground color of an applet
window.
To obtain the current settings for the
background color
To obtain the current settings for the
foreground color
To obtain the applet specified by given
name from the current applet context.
To display the status message in the status
bar of applet window
To obtain the directory of the current
browser page.
To obtain the directory from which the
applet’s class file was loaded
Example of Applet
import java.applet.*;
import java.awt.*;
import java.net.*;
/*
<applet code=exapp height=300 width=400>
<param name=first value="AYE" >
</applet>
*/
public class exapp extends Applet
{
String arg;
public void start( )
{
arg=getParameter("first");
}
public void paint(Graphics g)
{
setBackground(Color.black);
setForeground(Color.white);
URL codenm=getCodeBase( );
URL docnm=getDocumentBase( );
g.drawString("String = Welcome to AYE",30,40);
g.drawString("Parameter Value = "+arg,30,70);
g.drawString("CodeBase = "+codenm.toString( ),30,100);
g.drawString("DocumentBase = "+docnm.toString(),30,130);
}
}
Note
Save this program as “c:\exapp.java”
Compile this program with javac exapp.java
Run this program with appletviewer exapp.java
Output
SELECTING A COLOR
Color control is achieved through three primary colors - red, green, blue.
The color object contains three int or float values for red, green and blue parameters.
The range of int value is 0 – 255 .
The syntax of the constructor to create custom colors.
Color ( int red, int green, int blue);
Color (int rgbValue );
Color (float red, float green, float blue);
For Ex.
new Color (255, 100, 100); // light red
How to call constructor and set the color
Color c=new Color (255, 175, 175 )
g.setColor (c)
Table of RGB values of common colors
Color
White
Black
Yellow
Magenta
Pink
Red
255
0
255
255
255
Green
255
0
255
0
175
Blue
255
0
0
255
175
The pre – defined colors available in java are
Color.red
Color.yellow
Color.blue
Color.green
Color.orange
Color.magenta
Color.cyan
Color.pink Color.lightGray
Color.darkGray
Color.gray
Color.white Color.black
Example of Color Class
import java.applet.*;
import java.awt.*;
/*
<applet code=excolor height=300 width=400>
</applet>
*/
public class excolor extends Applet
{
public void paint(Graphics g)
{
Color c1=new Color(255,0,255);
Color c2=new Color(128,128,128);
g.setColor(c1);
int r=c1.getRed( );
int gr=c1.getGreen( );
int b=c1.getBlue( );
g.drawString("RED = "+r+" GREEN = "+gr+" BLUE = "+b,10,20);
c1=c1.darker( );
g.setColor(c1);
g.drawString("RED = "+r+" GREEN = "+gr+" BLUE = "+b,10,40);
g.setColor(c2);
g.drawString("RED = "+r+" GREEN = "+gr+" BLUE = "+b,10,60);
c2=c2.brighter( );
g.setColor(c2);
g.drawString("RED = "+r+" GREEN = "+gr+" BLUE = "+b,10,80);
}
}
Output
SELECTING A FONT
Font class provided in the java.awt package allows us to use and change fonts to
display and type text.
The syntax of the constructor for the Font class
Font ( String fontname, int style, int size )
The first parameter is the name of the font. Font availability is platform independent.
For Ex.
“Serif” “Times New Roman” “Monospaces”
The second style parameter of the Font constructor should be one of the following
three ints
Font.PLAIN
Font.BOLD
Font.ITALIC
The third parameter size must be in int form
How to call constructor and set fonts
Font f = new Font (“Times New Roman”, Font.BOLD, 15 );
g.setFont( f );
You can get a list of available font names, returned as an array of strings, by calling
the getFontList ( ) (which is the method of abstract Toolkit class) on your toolkit.
Example of Font Class
import java.lang.*;
import java.applet.*;
import java.awt.*;
/*
<applet code=exfont height=300 width=400>
</applet>
*/
public class exfont extends Applet
{
public void paint(Graphics g)
{
String fontlist=" ";
GraphicsEnvironment ge = GraphicsEnvironment .
getLocalGraphicsEnvironment( );
Font f[] =ge.getAllFonts( );
g.drawString("Total font objects available in Environment = " + String .
valueOf(f.length),10,20);
String f1[]=ge.getAvailableFontFamilyNames( );
g.drawString("Total fonts available are " + String.
valueOf(f1.length),10,50);
for(int i=0;i<5;i++)
fontlist+=f1[i]+", ";
g.drawstring (fontlist,10,70);
g.drawstring ("Fonts available in Toolkit ",10,100);
Toolkit t = Toolkit.getDefaultToolkit( );
String s[]=t.getFontList( );
int y=120;
for(int j=0; j<s.length; j++, y+=20)
{
g.drawstring (" * "+s[j],10,y);
}
Font fnt=new Font("SansSerif",Font.BOLD,15);
g.setFont (fnt);
g.drawstring ("font=SansSerif style=Bold size=15",10,240);
Font fnt1=new Font("Arial",Font.ITALIC,17);
g.setFont(fnt1);
g.drawString("font=Arial style=Italic size=17",10,270);
}
}
Output
GRAPHICS CLASS
In applets paint( ) must include the object of Graphics class as a parameter.
Following are some methods of Graphics class.
NAME
Drawstring ( String s, int x, int y )
drawChars ( char c[ ], int start_index,
DESCRIPTION
To output a string to an applet at a
specified position. It is called from within
update( ) or paint( ).
To output a characters of array to an applet
int num_of_char, int x, int y )
at specified location.
drawChars ( byte c[ ], int start_index,
int num_of_char, int x, int y )
To output a characters of byte’s array to an
applet at specified location.
drawLine (int x1, int y1, int x2, int y2);
To draw a line at specific location.
drawOval ( int x, int y, int width, int
height)
setColor ( Color c )
fillOval ( int x, int y, int width, int
height )
drawRect ( int x, int y, int width, int
height )
fillRect ( int x, int y, int width, int
height )
DrawRoundRect (int x, int y, int
width, int height, int arcwidth, int
archeight )
To draw an oval at specified location x,y
having specific height and width
To set the color of the object
To fill color in Oval
fillRoundRect (int x, int y, int width,
int height, int arcwidth, int archeight )
To fill color in rounded corner rectangle
draw3DRect (int x, int y, int width, int
height, boolean b)
drawArc (int x, int y, int width, int
height, int arcwidth, int archeight )
fillArc (int x, int y, int width, int
height, int arcwidth, int archeight )
drawPolyline ( int x[ ], int y[ ], int
no_of_points )
setFont ( )
drawPolygon (int x[ ], int y[ ], int
no_of_points )
fillPolygon (int x[ ], int y[ ], int
no_of_points )
setXORMore ( Color c )
To draw 3D rectangle
To draw a rectangle at specific location
To fill color in rectangle
To draw a rounded corner rectangle at
specific location
To draw an Arc
To fill color in Arc.
To draw a Polyline
To draw a Polygon
To fill color in Polygon
To make old as well as new contents of the
drawing object visible on the screen
Example using Graphics Class
import java.awt.*;
import java.applet.*;
/*
<applet code=exgraphic height=500 width=600>
</applet>
*/
public class exgraphic extends Applet
{
public void paint(Graphics g)
{
int x1[ ]={150,175,200,225,250,325};
int y1[ ]={325,150,275,140,230,150};
int x2[ ]={350,400,375,450,500};
int y2[ ]={180,275,200,125,300};
g.setColor (Color.blue);
g.drawLine (20,10,60,10);
g.drawOval (300,10,60,40);
g.drawRect (40,70,30,50);
g.drawRoundRect (50,170,30,50,20,20);
g.draw3DRect (120,10,50,30,true);
g.drawArc (400,50,100,70,30,80);
g.fillArc (200,80,100,70,80,100);
g.drawPolyline (x1,y1,6);
g.setColor (Color.green);
g.fillPolygon (x2,y2,5);
showStatus ("this applet shows figures");
}
}
Output
The java.util
Package
11
THE java.util PACKAGE
The Date Class
The Hashtable Class
The Random Class
The Vector Class
The Stack Class
INTRODUCTION
The java.util is one of the most widely used packages of the java. It provides some
of the most useful Java classes that user rely on. It contains some non-abstract classes
like:
Date
HashTable
Random
Vector
Stack
The Date Class
The date class stores representation of a date and time and provides methods for
manipulating the date and time components.
Constructors
Date ( )
Create a Date using today’s date
Date (long)
Creates a Date using the specified number of milliseconds since January
1, 1970.
Date (int, int, int)
Creates a Date using the specified year, month, and day.
Date (int, int, int, int, int)
Creates a Date using the specified year, month, day, hours and minutes.
Date (int, int, int, int, int,
int)
Creates a Date using the specified year, month, day, hours, minutes,
and seconds.
Date (String)
Creates a Date using the specified string. Eg.
Date d=new Date (“01 January 2001 13:56:45”)
Methods
after (Date)
Returns true if the Date occurs after the specified date.
before (Date)
Returns true if the Date occurs before the specified date.
equals (object)
Returns true if two Dates are equal.
getDate ( )
Returns the day ( 1- 31) portion of the date.
getDay( )
Returns the day of the week (Sunday is 0) indicated by the Date.
getHours ( )
Returns the hours (0-23) portion of the date.
getMinutes ( )
Returns the minutes (0-59) portion of the date.
getMonth ( )
Returns the month (0-11) portion of the date.
getSeconds ( )
Returns the seconds (0-59) portion of the date.
getTime ( )
Returns the number of milliseconds since midnight on January 1, 1970.
getYear( )
Returns the year after 1970.
hashCode( )
Returns the hash code for the date.
setDate (int)
Sets the day of the month
SetHours (int)
Sets the hours.
setMinutes (int)
Sets the minutes.
setMonth (int)
Sets the month.
setSeconds (int)
Sets the seconds.
setTime ( long)
Sets the time to the specified number of milliseconds since midnight
January 1, 1970.
setYear (int)
Sets the year after 1970
toGMTString ( )
Returns a formatted string of the Date in the GMT time zone.
toLocaleString( )
Returns a formatted string of the Date in the current time zone.
toString( )
Returns a formatted string of the Date including the day of the week.
Example of Date Class
import java.util.*;
public class exdate
{
public static void main(String args[])
{
Date today=new Date( );
System.out.println ("Today is : " + today.toString());
System.out.println ("Local time : " + today.toLocaleString());
System.out.println ("GMT
: " + today.toGMTString());
Date d= new Date(94,04,01);
d.setYear(today.getYear( ));
if(today.after(d))
System.out.println ("You missed this date");
else
System.out.println ("This day is coming");
}
}
Output
Today is : Wed Apr 19 10:42:29 GMT+05:30 1989
Local time : Apr 19, 1989 10:42:29 AM
GMT
: 19 Apr 1989 05:12:29 GMT
This day is coming
The Hashtable Class
The Hashtable class extends the abstract Dictionary class that is also defined in
the java.util package.
The Hashtable is used for mapping keys to values. eg. it could be used to map
names to ages, programmers to projects etc.
Hashtable will expand in size as elements are added to it. But while creating a
new Hashtable, user can specify an initial capacity and a load factor.
Constructors
Hashtable (int)
Constructs a new Hashtable with the specified initial capacity.
Hashtable (int, float)
Constructs a new Hashtable with the specified initial capacity and
load factor.
Hashtable ( )
Constructs a new Hashtable using a default values for initial capacity
and load factor.
Methods
clear ( )
Removes all elements from the Hashtable.
clone ( )
Creates a clone of the Hashtable.
Contains (Object)
Returns true if the Hashtable contains the specified Object
containsKey (Object)
Returns true if the Hashtable contains the specified key.
Elements ( )
Returns an enumeration of the elements in the Hashtable.
get (Object key)
Retrieves the object associated with the specified key.
IsEmpty ( )
Returns true if Hashtable is empty.
Keys( )
Returns an enumeration of the keys in the Hashtable.
put (Object, Object)
Adds a new element to the Hashtable using the specified key and
value.
Rehash ( )
Rehashes the Hashtable into a larger Hashtable.
remove (Object key)
Removes the object given by the specified key.
size ( )
Returns the number of elements in the Hashtable.
ToString( )
Returns a formatted string representing the Hashtable.
Example of Hashtable Class
import java.util.*;
class exhashtable
{
public static void main(String args[])
{
Hashtable h=new Hashtable( );
Enumeration nm;
String s;
h.put("JAVA ",new Integer(1));
h.put("C++ ",new Integer(2));
h.put("VB ",new Integer(3));
h.put("HTML ",new Integer(4));
h.put("JAVA SCRIPT ",new Integer(5));
nm=h.keys( );
while(nm.hasMoreElements( ))
{
s=(String)nm.nextElement( );
System.out.println(s+" : " + h.get(s));
}
System.out.println ("");
if (h.containsKey("JAVA "))
System.out.println ("Java is hot language");
}
}
Output
VB : 3
JAVA SCRIPT : 5
HTML : 4
JAVA : 1
C++ : 2
The Random Class
This class represents a pseudo-random number generator.
It provides two constructors one taking a seed value as a parameter and the other
taking no parameters and using the current time as a seed.
Constructing a random number generator with a seed value is a good idea unless
user wants the random number generator to always generate the same set of
values.
Once the random number generator is created, a value can be retrieved from it
using any method provided by Random class
Methods
Random ( )
Creates a new random number generator.
Random (long)
Creates a new random generator based on the specified seed
value.
nextDouble ( )
Returns the next double value between 0.0D and 1.0D from the
random number generator.
nextFloat ( )
Returns the next float value between 0.0F and 1.0F from the
random number generator.
NextInt ( )
Returns the next integer value from the random number
generator.
nextLong ( )
Returns the next long value from the random number
generator
SetSeed (long)
Sets the seed value for the random number generator.
The Vector Class
The Java Vector class provides a form of resizable array that can grow as more
elements are added to it.
A Vector stores items of type Object so that it can be used to store instances of any
Java class.
A single Vector can store different elements that are instances of different classes.
At any point in time a Vector has the capacity to hold a certain number of
elements. When a Vector reaches its capacity, its capacity is incremented by
an amount specific to the Vector.
Constructors
Vector ( int )
Creates a new Vector with the specified initial capacity
Vector (int, int)
Creates a new Vector with the specified initial capacity and increment
quantity.
Vector( )
Creates a new Vector with default initial capacity and increment
quantity.
Methods
addElement (Object)
Inserts the specified element to Vector class
capacity ( )
Returns the number of elements that will fit into the currently
allocated portion of the Vector.
clone ( )
Clones the Vector, but not its elements
contains (Object)
Returns true if the Vector contains the specified Object.
copyInto (Object[])
Copies the elements of the Vector into the specified array.
elementAt (int)
Retrieves the element located at the specified index.
elements ( )
Returns an enumeration of the elements in the Vector.
EnsureCapacity (int)
Ensures that the Vector can hold at least the specified minimum
capacity.
firstElement ( )
Returns the first element in the Vector.
indexOf (Object)
Searches the Vector and returns the zero-based index of the first
matching Object.
insertElementAt (Object,
int)
Adds the specified Object at the specified index.
isEmpty ( )
Returns true if the Vector has no elements.
LastElement ( )
Returns last element in the Vector.
LastIndexOf (Object)
Searches the Vector and returns the zero-based index of the last
matching Object.
RemoveAllElements ( )
Removes all elements from the Vector.
RemoveElement (Object)
Removes the specified Object from the Vector.
removeElementAt (int)
Removes the Object at the specified index.
setElementAt(Object, int)
Replaces the Object at the specified index with the specified Object.
setSize (int)
Sets the size of the Vector to the specified new size.
size ( )
Returns the number of elements currently in the Vector.
toString ( )
Returns a formatted string representing the contents of the Vector.
trimToSize ( )
Removes any excess capacity in the Vector by resizing it.
Example of Vector Class
import java.util.*;
class exvector
{
public static void main(String args[])
{
Vector v=new Vector( );
v.addElement ("ONE");
v.addElement ("TWO");
v.addElement ("THREE");
v.addElement ("FIVE");
v.insertElementAt ("Numbers In Words : ",0);
v.insertElementAt ("FOUR",4);
System.out.println ("Size : " + v.size());
System.out.println ("Vector");
for(int i=0;i<v.size( );i++)
System.out.print (v.elementAt(i) + " , ");
v.removeElement ("FIVE");
System.out.println ("");
System.out.println ("Size :" + v.size());
System.out.println ("Vector ");
for (int i=0;i<v.size( );i++)
System.out.print (v.elementAt(i) + " , ");
}
}
Output
Size : 6
Vector
Numbers In Words : , ONE , TWO , THREE , FOUR , FIVE ,
Size : 5
Vector
Numbers In Words : , ONE , TWO , THREE , FOUR ,
The Stack Class
The Stack class extends the Vector class and implements a simple last-in-first-out
stack.
An item is stored on a stack by “pushing” it into the stack.
As the class stack extends the vector class, no size is associated with a stack
instance.
Constructor
Stack( )
Creates a new stack.
Methods
Empty ( )
Returns true if the stack is empty
peek ( )
Returns the last object added to the Stack but does
not remove it from the Stack.
pop ( )
Returns the last object added to the Stack and
removes it.
push (Object)
Adds the specified object to the Stack.
Search (Object)
Searches for the specified Object in the Stack.
Example of Stack Class
import java.util.*;
class exstack
{
public static void main(String args[])
{
Stack cap=new Stack( );
cap.push("ONE");
cap.push("TWO");
cap.push("THREE");
System.out.println ("Top cap is [stack] : " + cap.peek( ));
while(!cap.empty( ))
{
System.out.println (cap.pop( ));
}
}
}
Output
Top cap is [stack] : THREE
THREE
TWO
ONE