You are on page 1of 44

JAVA

 Java was conceived by James Gosling, Patrik Naughton, Chris Warth, Ed Frank and Mike
Sheridan at Sun Micro Systems in 1991
 Initially called “OAK”, it was renamed as Java in 1995
 Java is related to C++ which is a direct descendent of C
 From C, Java derives its syntax. Many of the Java’s Object oriented features were influenced
by C++.
 Object Oriented Programming (OOP) is a programming methodology that helps to organize
programs through the use of Inheritance, Encapsulation and Polymorphism.
 The primary motivation for the development of Java is the need for a platform
independent(architecture neutral) language that could to be used to create software to be
embedded in various consumer electronic devices such as micro ovens and remote control
 As the World Wide Web(WWW) emerged, it demanded a portable programming language,
Java became popular for Internet programming
 Java expands the universe of objects that can move about freely in Cyberspace
 Java is used to create two types of programs: Applications and Applets
o An Application is program that run on computer under the operating system of that
computer. It is of two types: console applications and Window Applications.
 Console applications run from system prompt and run with character mode
interface
 Window applications based on frames are standalone applications and run on
their own. However they too need JVM to be installed on the machine
o An Applet is an application designed to be transmitted over Internet and executed by
Java-compatible web browser
Relationship between C, C++ and Java
The following picture shows relationship between C, C++ and Java

C++ Java
C

 C is a subset of C++
 Java contains syntax of C but doesn’t support pointers etc. of C
 Java’s Object oriented features were influenced by C++ but it doesn’t support a lot of
features of C++ such as Operator Overloading, Default function arguments, Templates,
Friends functions etc.
Java Editions
Java is available in three different editions
J2SE (Java2 Standard Edition)
 This is the core part of the language.
 It supports the development of applets and applications but doesn’t support Web application
and enterprise application development
J2EE (Java2 Enterprise Edition)
 This support Web application and enterprise application development
 Provides specifications for Servlets, JSP, EJB, JMS etc.
J2ME (Java2 Micro Edition
 It is used to develop Java programs for micro devices

1
Java2 SDK, Standard Edition
 It is a software development kit for application development
 It contains command line compiler of Java, Java Virtual Machine, sample programs and few
other tools
 It supports development of application as well as applets
 Some of the available tools are
o javac  the compiler for Java language
o java  the launcher for Java applications
o appletviewer  Run and debug applet without a web browser
o jar  the manage Java archive(JAR) files
o jdb  Java debugger
Features of Java Language
Robust
 Java is strictly typed language
 Doesn’t allow to access elements outside the boundary of an array
 Makes exception handling mandatory
Object Oriented Language
 Java support encapsulation, inheritance and polymorphism
 Though Java was influenced by C and C++, it ignored all ambiguous features of C++
 Java is pure object oriented. Everything in Java is an object except standard data types such
as int and float
Dynamic
 A lot of activity takes at runtime
 Arrays and Objects are dynamic. An array can be resized and reallocated at runtime
 Dynamic memory allocation is done by Java and not by the programmer
 Garbage collector is responsible for realizing unused blocks in memory
Multithreaded
 Java language allows programmer to create multiple threads
 Multiple threads run simultaneously, allowing program to do two or more operation at the
same time
 Java supports synchronization
Distributed
 As a language designed for Internet allows process to be distributed to different machines
 Allows Java objects to run on different machines and yet communicate with each other
Platform Independent
 Once a Java program is written and compiled on a machine, it can be run on any platform
 Write once and run anywhere
Platform Dependent – ‘C” and other languages
The following is the process that takes place when you want to compile and run a program
written in C and other high-level languages
C Source program

Object Code
Linker
Native Code Libraries

Executable Code
2
Native code is the machine code of a particular processor. Native code of one family of
microprocessor doesn’t run on another family as it makes use of instruction set of the
microprocessor. However, it is possible to take source code onto a different machine, compile it on
the new platform and run it on that platform. But for this the compiler of the language must be
available on the target platform.
Compilation of Java program – platform independent

Java Source Code .Java file

Java Compiler

Byte code .class file

Java Virtual Machine (JVM)

Translates Byte code to native code

Native Code/ Machine Code

Steps: The following is the sequence of steps related to compilation and running of Java program
 Java program is compiled by Java compiler (javac) that is available on the current platform
 Java compiler creates bytecode, which is an intermediate code and not object code
 The byte code generated by compiler must be converted to machine code (native code) of the
machine on which the program is to be run. This conversion is done by Java Virtual Machine
which contains JIT(Just-In-Time) compiler
 Once Java program is compiled to byte code, it can run on any platform as long as JVM is
available on the target machine.
 All browsers are equipped with JVM

Java and Internet


The following figure shows the importance of Java. Web server sends an Applet from server
to client. On client browser executes Applet as it contains JVM. We can keep applet on the server
without worrying about client as it is generally responsibility of the client to make sure that it has
JVM to run Java programs.

JVM of Platform1
Web Server
Applet is passed to clients

JVM of Platform2
Hard disk

Java Applet

3
Data Types
The following table shows the data types available in Java, their size in bytes and the range
Data Type Size Range
byte 1 -128 to 127
short 2 -32,768 to 32,767
int 4 -2,147,483,648 to 2,147,483,647
long 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 1.4e-045 to 3.4e+038
double 8 4.9e-324 to 1.8e+308
boolean 1 true or false
char 2 Supports Unicode characters

Arithmetic Operators Relational Operators


Operator Meaning Operator Meaning
+ Addition == Equal to
- Subtraction > Greater than
* Muliplication < Less than
/ Division >= Greater than or equal
% Modulus <= Less than or equal
++ Increment != Not equal
-- Decrement

Logical operators: Combines two conditions and result a Boolean value


Operator Meaning
& AND
| OR
^ XOR( Exclusive OR)
&& Short-circuit And: Doesn’t check second condition if first condition is false
|| Short-circuit OR: Doesn’t check second condition if first condition is true
! Unary NOT

Looping Structures in Java

while
Repeats the statements as long as the condition is true
While (<condition>)
{
Statements;
}
do-while
Executes the body of the loop and then checks condition thus guaranteeing the execution of
the statement at least once.
do
{
Statements;
} while (<condition>);

for
Executes statements as long as condition is true.
4
for(initialization; condition checking; re-evaluation parameters)
{
Body of the loop;
}
First executes the initialization, and then checks the condition. It the condition is true, it then
executes the statements and then re-evaluates the parameters.
Eg: for(int i=0;i<5;i++){ … }
Note: Allows variables to be declared within initialization but they are available only within
loop.
Labeled break:
break statement is having the optional argument which can be used to break out the labeled
loop.
Eg: outerloop:
for(int i=0;i<3;i++)
{
for(int j=0;j<10;j++)
{
if(..)
break outerloop:
}
}
A label is any valid Java identifier followed by a colon (:). When break is used with label
then execution resumes at the end of the labeled block.
Labeled continue:
As break statement, continue statement may also specify a label to tell which loop to
continue.
Arrays
 Array is set of elements that are of same type and commonly referred by a common name
 Arrays in Java work differently from their counterparts in C or C++
 A array in Java is dynamic. Its creation involves two steps- declaring array and allocating
memory using new operator
 Length attribute of the array returns the number of elements in array.
Eg: int ary[] or int[] ary //declaration
ary=new int[10]; // create array of 10 elements
Note: Elements of numeric array are assigned with zero, character array with NULL and boolean
array with false, when created.
Resizing and array
 In Java resizing an array is possible at runtime.
 To do this, just point to new array.
 New array doesn’t contain old data as it is separate memory location. Old block is released by
garbage collector subsequently
For each loop or Enhanced for loop
 Enables to traverse the complete array sequentially without using index variable
for (elementType element:arrayRefVar)
{
//process element
}
Passing arrays to methods
 Java uses pass-by-value to pass primitive datatypes (int, char, float…) as arguments to
methods
5
 Java uses pass-by-sharing i.e., passing reference of an array as an argument to a method. The
array in the method is the same as the array being passed and any changes to the array in the
method will affect the array outside the method
Variable Length Argument List
 Java allows variable length of arguments of same type to a method.
return_type methodName(typeName… parameterName)
 An array is created with the given parameter name and passed arguments are stored.
Two Dimensional Arrays
 Used to represent two-dimensional data such as graphs, matrix, table etc.
data_type[][] arrayRefName;
arrayRefName = new data_type[size1][size2];
 It is possible to create each array in two-dimensional array of different size (ragged arrays)
Eg: int a[][]=new int[3][];
a[0]= new int[3]; a[0]0[] a[0][1] a[0][2]
a[1]= new int[2]; a[1][0] a[1][1]
a[2]= new int[4]; a[2][0] a[2][1] a[2][2] a[2][3]
Scanner class
Scanner is class which creates an object of Scanner type. Java uses System.out to refer to standard
output device and System.in to refer to standard input device. Console input is not directly supported
in Java. Scanner class, found in java.util package, is used to create an object to read input from
System.in.
Methods for Scanner Objects
nextInt() Reads an integer of int type
nextShort() Reads an integer of short type
nextByte() Reads an integer of byte type
nextLong() Reads an integer of long type
nextFloat() Reads an integer of float type
nextDouble() Reads an integer of double type
next() Reads a string that ends with a whitespace character
nextLine() Reads a string that ends with the Enter key pressed.
Math class
Java provides many useful static methods in the Math class for performing common mathematical
functions
Method Description
public static double Generates a value ab
pow(double a,double b)
public static double random() Generates the value between 0.0 and 1.0 such that 0.0<=d<1.0
public static double Returns square root of x
sqrt(double x)
public static double Converts degrees to radians
toRadians(double)
public static double Converts radians to degrees
toDegrees(double)
public static double Returns the trigonometric sine of an angle in radians.
sin(double radians)
public static double Returns the trigonometric cosine of an angle in radians
cos(double radians)
public static double Returns the trigonometric tangent of an angle in radians.
tan(double radians)
public static double Returns the angle in radians for the inverse of sine
6
asin(double radians)
public static double Returns the angle in radians for the inverse of cosine.
acos(double radians)
public static double Returns the angle in radians for the inverse of tangent
atan(double radians)
public static double Return e raised to the power of x
exp(double x)
public static double Return the natural logarithm of x
log(double x)
public static double Return the base 10 logarithm of x
log10(double x)
public static double x is rounded up to its nearest integer. This integer is returned as
ceil(double x) double value
public static double x is rounded down to its nearest integer. This integer is returned as
floor(double x) double value
public static double x is rounded to its nearest integer. If the number is equally close to
rint(double x) two integers, the even one is returned as double
public static int round (float x) Return (int)Math.floor(x+0.5)
public static long Return (long)Math.floor(x+0.5)
round(double x)
public static <num> max(a,b) max() method is overloaded to return the maximum value of two
given numbers a and b. (int,long,float,double)
public static <num> min(a,b) min() method is overloaded to return the minimum value of two
given numbers a and b (int,long,float,double)
public static <num> abs(a) abs() method is overloaded to return the absolute value of a given
number (int,long,float,double)
Note: a) Math.PI Returns PI-vaule of 22/7
b) Math.E E-the base of natural algorithms
c) a+Math.random()*b Returns a random integer between a and a+b excluding a+b
Console Output Formatting
System.out.printf() method is used to format the output
Syntax: System.out.printf(format,item1,item2,...)
where format is a string that may consists of substrings and format specifiers
Format Specifier Output Example
%b a Boolean value true or false
%c a character ‘a’
%d a decimal integer 200
%f a floating-point number 45.460000
%e a number in standard scientific notation 4.556000e+01
%s a string “Java”
Specifying width and precision
Example Output
%5c Output the character and add four spaces before the character item.
%6b Output the Boolean value and add one space before the false and two spaces before
the true value.
%5d Output the integer item with width at least 5. If the number of digits in the item is< 5,
add spaces before the number. If the number of digits in the item is > 5, the width is
automatically increased.
%10.2f Output the floating-point item with width at least 10 including a decimal point and
two digits after the point. Thus, there are 7 digits allocated before the decimal point. If
7
the number of digits before the decimal point in the item is <7, add spaces before the
number. If the number of digits before the decimal point in the item is> 7, the width is
automatically increased.
%10.2e Output the floating-point item with width at least 10 including a decimal point, two
digits after the point and the exponent part. If the displayed number in scientific
notation has width less than 10, add spaces before the number.
%12s Output the string with width at least 12 characters. If the string item has fewer than 12
characters, add spaces before the string. If the string item has more than 12 characters,
the width is automatically increased.
Command line parameters
 Parameters that are passed at the time of invoking a Java program from command line are
called as command line arguments
 These parameters are accessible from main() through args parameter, which is an array of
strings.
 length attribute of args returns the number of parameters passed
Object Oriented Programming
 Allows for the analysis and design of an application in terms of entities or objects so that the
process replicates human thought process as closely as possible
 This means that the application has to implement entities as they are seen in real life and
associate actions and attributes with each.
 In OOP, code and data are merged into single indivisible thing- an object.
Object
 Concept or thing with defined boundaries that is relevant to the problem we are dealing with.
 Represents an entity in real world
 Helps to understand the real world and provide a practical basis for computer application
 Each object has its own properties and actions it can perform
Class
 Grouping of objects that have same properties, common behavior and common relationship.
Property/Attribute
 A characteristic required of an object or an entity when represented in class
Method/Function
 An action required of an object or entity when represented in class
Abstraction
 Process of examining certain aspects of a problem
 In system development, abstraction means focusing on what an object is and does, before
deciding how it should be implemented
Data Abstraction
 Process of examining all the available information about an entity to identify information that
is relevant to the application.
 Process of identifying properties and methods related to a particular entity as relevant to the
application
Features of OOP
Features supported by all OOP languages are Encapsulation, inheritance, Polymorphism. Java
being an OOP language completely supports these features.
Encapsulation
 Binds or encapsulates code and the data that code manipulates
 Doesn’t allows data to be accessed from outside
 Increases control as each object is independent and data of an object is manipulated only by
the code that is part of the object
8
 Allows program to be divided into self contained objects
 A class in Java defines data and code that is to be encapsulated
Inheritance
 Allows a class to be created from another class thereby inheriting all properties of another
class
 Allows reusability of existing classes
 New classes may new members and override existing members of the inherited members
 Overriding is the process where the inheriting(sub class ) is creating a method with the same
signature as inheriting class
 Hierarchies can be built using inheritance
 Multiple inheritance is not permitted in Java
Polymorphism
 Allows multiple methods performing same operation to have the same name
 Compiler invokes one of the multiple methods depending upon the context
 Programmer need not remember multiple names
Terminology of OOP in Java
 Class: Description of collection of similar objects is called as class. Class defines the data
members and methods to be encapsulated. Methods are defined within the class
 Object: It is an instance of a class. Memory is allocated only when an object of the class is
created. Instance variables and methods are accessed using objects
 Method: It is a function defined in the class. It is used to process the data of the class. Only
methods are generally callable from outside
 Instance variables: It is data member in a class. It exists in each instance of the class. The data
is generally hidden and cannot be accessed from outside the class.
Creation of class
The following syntax is used to create a class
access class classname
{
[access] instance variable declaration;]
[[access] instance variable declaration;]]…
type method name(parameterlist)
{
//Body of the method
}
...
}
Access may be public, private, protected or default(no access).
Note: Generally, the name of the class contains capital letters for first letter of each word and small
letters for remaining.
Overloading Methods
 It is possible to define two or more methods with the same name within the class provided the
parameters of the methods are different.
 Overloading methods is one way of implementing polymorphism
 Method can be overloaded based upon the type /number of parameters
 Method cannot be overloaded based on return type
Eg: class demo
{
void m(int n){ }
void m(int, int ){ }
9
void m(String, int){ }
}
Constructor
 A method in the class with the same name as the class name
 Invoked automatically whenever an object of the class is created
 Doesn’t contain any return type
 Used to initialize data members of the class
 A class may contain multiple constructors with different parameters.
 If no constructor is explicitly created then Java creates a constructor that takes no parameters.
But Java doesn’t provide this constructor once a user-defined constructor is created in the
class.
Eg: public class Num
{
int n;
public Num()
{ n=0; }
}
In the above example, Num class has constructor that is used to initialize instance variable
num
Number n= new Number();
Overloading Constructors
It is possible to overload constructors of a class like methods of a class are overloaded.
Note: It is not possible to create an object unless Java can invoke one of the constructors.
Object reference
 It is a reference to an object.
 An object in Java is accessed through object reference, which like a pointer in ‘C’
Eg: Num n; //create object reference of class Num
n= new Num(); //Create an object and make n referencing it.
n - Num Object
Assignment between two object references
It is possible to assign one object reference to another. But what we effectively copy is not
the content of an object to another and instead one object reference to another.

Eg: Num n1,n2


n1= new Num(); n1Num Object
n2=new Num(); n2Num Object
n1=n2;
n1

n2 Num Object


Note: When two object references are compared, only the references are compared and not
the content of the object that they point to.
Array of Objects
 Java Supports array of objects.
 When an array of objects is created only object references are created.
 Each object reference must be made to point to an object explicitly
Eg: Num n[]=new Num[5];

10
n[0]= new Num() n[0] Number Object
n[1]= new Num() n[1] Number Object
empty n[2]

Creating an array of class creates only an array of object references that do not refer any
object. So after the array is created, we have to initialize each element of the array so that it points to
an object.
this reference
 It is a reference to the invoking object
 It is used by the methods to implicitly access member of the calling object.
 this reference is made available to each non-static methods automatically
eg: public class Num
{
int n;
public Num(int n)
{ this.n=n; } }
Static variable
 It is a variable that is associated with class not with the object
 It is also known as class variable
 It is defined using a key-word static
 It exists only for once for entire class
 Can be accessed using class name
 Used as constant with final
Static Methods
 Static methods are same as normal methods except that they can be invoked with class name
and need not be invoked by an object
 Cannot invoke non-static methods and cannot access instance variables
 Do not have this reference
 They are generally used to access and manipulate static variables
Final Members
 Java allows variables, methods and classes to be declared as final using keyword ‘final’
 Final variables must be assigned a value at the time of declaring in the class and value of the
final variable cannot be changed.
 Final methods are the methods that cannot be overridden in the sub class
 Final classes are the classes that cannot be extended(Inherited)
Inheritance
 Allows a new class to be created from an existing class
 Keyword ‘extends’ is used to create a new class that inherits an existing class
 Existing class is called as super class and new class is called as sub class
 In a class hierarchy the constructors are called in the order of derivation
 When a method in the sub class has the same name and signature of a method in the super
class, the method in the sub class is said to be overriding the method in the super class. When
an object of sub class is used to call a method that is common to super class and sub class
(overriding method) then the method in the sub class is called.
Eg: class A //Super class
{
Int n;
public void print()
11
{
System.out.println(n);
}
class B extends class A //Sub class
{
Int m;
public void print()// method overridden
{
System.out.println(n + “ “ +m);
}
class B inherits class A as the result print{} and instance variable n are inherited into sub
class. class B added an instance variable m and overridden print().
Super Keyword
 Super keyword is used to access the member of super class that is hidden by a member in the
sub class
 Invokes constructor of the super class from the constructor of the sub class.
 Passes the values required by the super class constructor
Note: Super keyword refers to immediate super class in the hierarchy. While calling the
constructor of the super class from subclass’s constructor, the call must be first statement in the
constructor of the sub class
Dynamic Method Dispatch
 It is a process in which a call to a overridden method is resolved at runtime instead of
compile time
 It is based on the concept that an object reference of the super class can refer to object of any
sub class in the hierarchy.
 Occurs when an overridden method is called using object reference of super class.
 It is also called runtime polymorphism and late binding.
 Call to method is resolved depending upon the content of the object reference
 This is one of the most important concepts of Java. Since Java is dynamic language, a lot in
Java depends on this feature
Note: Dynamic method dispatch is applied only to method that is defined in super class and
overridden in sub class and invoked using an object reference of super class.
Abstract keyword
 Abstract keyword is used to create abstract methods and abstract classes.
 Abstract methods has only declaration and no definition
 Abstract methods are used to force sub classes implement the abstract method
 If a class contains at ;east one abstract method then it must be defined as abstract class
Feature of Abstract Methods
 Must be overridden in subclass. Otherwise sub class will become abstract.
 Class must also be defined as abstract
 Mutually exclusive with final method
Features of abstract class
 Contains one or more abstract methods
 Cannot instantiate objects but we can declare object reference
Object class
 Object class is one of the standard classes.
 All other classes in Java are sub classes of the Object class
 Reference of an Object class can refer to object of any class in Java
12
The following methods are defined to Object class and are available to every other classes
Method Purpose
Object clone() Crates the new object that is same as the object being cloned
boolean Compares the content of two objects and return true if contents are same
equals(Object)
void finalize() Called before an unused object is released by the garbage collector
int hashCode() Returns the hash code associated with the invoking object
void notify() Resumes execution of the first thread that is waiting to be notified on
same object
void notifyAll() Resumes execution of all threads that are waiting to be notified on the
same object. The highest priority thread will run first.
String toString() Returns a string that describes the object
void wait() Causes the current thread to wait until the object notifies the thread( It tells
void wait(long the thread to give up the monitor and sleep until some other thread enters
milliseconds) the same monitor to notify
String class
 It is one of the standard classes in Java
 It provides methods required to manipulate a string
Method Purpose
char charAt(int) Returns the character at given position
boolean endsWith(String) Returns true if string ends with the give string
int indexOf(String) Returns the position of the substring in the main string
int indexOf(String,frompos) Same as above, but starts search at the given position
int lastIndexOf(String) Returns the position of the substring from the end of the main
String
int Same as above but search starts at given position
lastIndexOf(String,frompos)
int length() Returns the length of the string
boolean startsWith(String) Starts true if string starts with the given string
String substring(from,to) Returns a substring that starts at from and ends at to in main
string
String toLowerCase() Returns the string after converting it to lowercase
String toUpperCase() Returns the string after converting it to Uppercase
String trim() Trims spaces on both sides of the string
static String valueOf(value) Converts the given value of the string
Interface
 It is a collection of methods that must be implemented but the implementing class
 Only the declaration of methods is given
 Implementing class defines all the methods declared in the interface
 An interface may contain variables. They automatically static and final variables of the
implementing class
 An interface can extend one or more interfaces
 An object references of interface may be used to point to an object of its implementation
class( or any of its subclasses
 A class can implement multiple interfaces. In this case the implementing class must define
the combined methods of all interfaces it implements
Syntax: access interface name {
method declaration;
type finalvariable=value; }
13
Object Reference of interface
 A class that is implementing an interface can be accessed using an object reference of the
interface
 But the object reference of the interface can be used to invoke methods of the interface only
Extending Interfaces
 An interface can extend another interface
 A single interface can extend multiple interface. A class implementing the interface must
define all the methods in the entire inheritance chain
 Eg: interface A { public void m1(); }
interface B { publis void m2(); }
class c1 implements A,B{ // implements both m1 and m2 }
Inner class
 Inner class, added in Java 1.1, is a class defined in another class
 It has access to all of the variables and methods of its outer class and can refer to them
directly
 Mainly designed to help handling events AWT
 An inner class can also be anonymous inner class, where inner class doesn’t contain any
name
Recursion
 Java Supports recursion.
 It is the process of defining something in terms of itself.
 Recursion is the attribute that allows a method to call itself in Java programming.
 A method that calls itself is said to be recursive
Package
 It is a collection of classes and interfaces
 Allows to store classes and interfaces without name collision
 Packages are stored in hierarchical manner
 A package in Java is a folder in the underlying operating system.
Creating a package
 package statement is used to specify the package to which classes and interfaces belong to
 A folder in the file system of OS with the same name as the package is to be created
 The .class file must be stored in the package
 All the classes that not explicitly stored in any package are stored in default package
 Eg: package p1;
public class C1{…}
class C2{ … }
Both classes C1 and C2 belong to package p1. Class C1 can be accessed even outside the
package, but class C2 cannot be accessed outside the package.
Note: Make sure that folder with the name P1 is created and C1.class and C2.class files are
copied into that folder
CLASSPATH variable
 It contains the list of directories where Java will look for classes and packages
 Java compiler and runtime use CLASSPATH variable and get the list of folders and .jar files
that are to be searched for the required classes and packages.
 Tools.jar contains all the standard packages and classes
 By default Java searches for the specified classes in the current directory
 But once that CLASSPATH is set then Java uses only the directories in the CLASSPATH to
search for the classes and doesn’t search in the current directory
14
 Eg: The following sets CLASSPATH to current directory(.),tols.jar and p1 directory
C:\>set classpath = .; c:\Java\lip\tools.jar;c:\Java\p1
import statement
 Used to make the specified classes or packages available
 Looks for the classes or packages in CLASSPATH environment variable
 Use * to import all classes in the given packages. But it doesn’t import nested packages. So
each nested packages is to be explicitly specified.
 Syn:: import pkg1[.pkg2]….{classname|*}
‘ * ’ specifies all classes of the package are to be imported
Access methods
 Specifies from where a member can be accessed. Available access methods in Java are as
follows
o public  allows a member to be accessed from anywhere
o protected  allows a members to be accessed from the class and its subclasses
o private  allows to be accessed only from the class in which it is defined
o default  allows members to be accessed throughout the package to which it belongs
The following example shows how access method influences the access method
Package P1;
public class A
{
private int v1;
protected int v2;
public int v3;
int v4; // default access
}

Package P1;
public class B extends A
{ //v2,v3,v4 are accessible }

class C
{ // v3v4 are accessible }
package P2;
import p1.A
class D extends A
{ //v2,v3 are accessible }
Class E
{ //v3 is accessible; }

The following table summarizes methods and their impact on access


Where private default protected Public
Same class Yes Yes Yes Yes
Sub class in same package No Yes Yes Yes
Non subclass in same package No Yes No Yes
subclass in different package No No Yes Yes
Non subclass in different package No No No Yes
Exception Handling
 An exception is an abnormal condition (runtime error)
 When an exception occurs, Java creates an object of exception type and throws the exception
15
 If the exception is not handled then program is terminated
 Exception can be thrown by Java runtime system or by our code
Keyword and their meaning used in Exception handling

Keyword Meaning
Try Specifies the block in which you want to monitor
Catch Catches an exception and takes necessary action
Finally Contains the code that is to be executed before leaving the method
Throws Specifies exceptions that a method might throw
Throw Throws the given exception
Eg: try{
a=b/c; // throws ArithmeticException if c is 0
}
catch(ArithmeticException e){ //Necessary action }
Handling Multiple Exceptions
It is also possible to handle more than one exception. If the code in the try block more than
one exception the you can handle all those exceptions using multiple catches
Eg try{
a=b/c; // throws ArithmeticException if c is 0
a[i}=100; //throws ArrayindexOutOfBoundExceptin if I is out of range
}
catch(ArithmeticException e){ //Necessary action }
catch(ArrayIndexOutOfBoundException e){ //Necessary action }
finally block
 Used to execute that is to be executed after a try/catch block has completed and before the
code following try/catch is executed
 Can be used to perform any operation that must be done before you leave try/catch block
 finally clause is optional. If it is given, it must be given either after catch block(s) if exists or
after try block. i.e., when try block throws an uncaught exception then also programs goes to
finally block and then get terminated
Types of Exceptions
There are two types of exceptions
 Unchecked or implicit exceptions
 Checked or explicit exceptions
Checked Exceptions
These exceptions must be handled. Methods that throw an explicit exception must be called
before try block that contains catch block to handle that exception. All exceptions other than
RuntimeException class are checked Exception
Unchecked Exceptions
These Exceptions need not be handled. However, they can be handled to avoid abnormal
termination. Exceptions that are derived from RuntimeException class are unchecked exceptions
Throwable

Error Exception

RuntimeException IOException
InterruptedException
16
ArithmeticException EOFException
Valid order of catch blocks
Hierarchy of the catch blocks must be followed while defining multiple exceptions. Most
specific exception is handled and most general is handled last.
Eg: try{ … }
catch(ArithmeticException e){ … }
catch(RuntimeException e){ … }
catch(Exception e){ … }
Note: All exception classes are derived from Exception class
User Defined Exceptions
 It is possible to create user defined exceptions. They can be thrown and caught just like built-
in exceptions. However, until built-in exceptions, which are thrown by Java runtime, user
defined exceptions are to be explicitly thrown by the program.
 To create a user defined exception, create a class that extends Exception class.
 The exception class need not create any methods of its own since it inherits methods of
Exception class( which inherits methods from Throwable class)
Exception class
The following are the methods that are derived from Exception class. In fact, all these methods
are actually derived from Throwable class and Exception class has no methods of its own
Method Meaning
String getMessage() Returns description of the exception
void Displays stack trace
printStackTrace()
String toString() Retruns a String object containing a description of exception. This method is
called by println() when outputting a Throwable object
Multithreading
 When a program contains two are more parts that run concurrently, it is called as
multithreading
 Java’s libraries are designed with multithreading in mind
 Each part of the program is called as thread
 Each thread is also called as lightweight process and the overheads are very low compared
with process
 A thread may exists in any of the states such as running, ready blocked etc., during its life
time
 All the threads of the process run within the same address space
Process 1 Process 2

Address Space Address Space

Thread 1
Inter- process
Inter- thread Thread 1
Communication
Communication

Thread 2

Main thread
 Main thread is the first thread to start in a Java program
 This is the thread from where other threads are created and started
17
 It must be the last thread to terminate. When the main thread terminates then program
terminates
 Main thread can be accessed using Thread class’s currentThread() method. It can also be
controlled using method of Thread class
 New Thread can be created either by extending Thread calls or implementing Runnable
interface
Creating a new thread by extending Thread class
 Create a class that extends Thread class
 Override run() method of Thread class
 Create an object of subclass of Thread class and invoke start method to start running the
thread
Creating a new thread by implementing Runnable interface
 Create a class that implement Runnable interface
 Implement run() method of the interface
 Create an object of Thread class and send an object of implementing class as a parameter to
constructor of Thread class
 Call start() method of Thread class
Thread class
It is used to create new Thread. The following are fields and methods of Thread class
Static int MAX_PRIORITY The maximum priority that a thread can have
Static int MIN_PRIORITY The minimum priority that a thread can have
Static int NORM_PRIORITY The default priority that is assigned to a thread
Constructors of Thread class
Thread()
Thread(Runnable target)
Thread(Runnable target,String name)
Thread(String name)
Target is the class that has implemented Runnable interface. Name is the name of the thread
Methods of Thread class
Various methods and meaning of the methods in Thread class
Method Meaning
static Thread Returns a reference of currently executing thread object
currentThread()
void destroy() Destroys this thread, without any cleanup
String getName() Returns this thread’s name
int getpriority() Returns this thread’s priority
void interrupt() Interrupts this thread
Static Boolean Tests whether the current thread has been interrupted
interrupted()
boolean isAlive() Tests if this thread is alive
boolean isDaemon() Tests if this thread is a daemon thread
boolean isInterrupted() Tests whether this thread has been interrupted
void join() Waits for this thread to die
void join(long millis) Wait at most millis milliseconds for this thread to die
void run() Specifies the code to be executed. It is overridden by subclass of Thread
class
void setName(String Changes the name of this thread to be equal to argument ‘name’
name)
void setPriority(int prty) Changes the priority of this thread
18
static void sleep(long Causes the currently executing thread to sleep for specified number of
millis) milliseconds
void start() Causes this thread to begin execution. The JVM call the run method of
this thread
String toString() Returns a string representation of this thread, including the thread’s
name, priority, and thread group.
Thread life cycle
The following are the valid states in the life cycle of the thread
State Meaning
New A new thread is crated and not yet run
Ready Thread is ready to run, but control is not given, if the control is given then it starts running
Running Thread is running
Sleep Sleep() method is invoked and thread is sleeping for the given number of milliseconds
Blocked Thread has initiated some IO operation and waiting for completion of operation
Dead Thread is terminated

New 1

Ready 7
5 Blocked
Sleep 2 3
6
4
Running

Dead 8

1. Thread started and ready to run


2. Thread has got control and started running
3. Time slice is over and thread relinquishes control
4. Sleep method is executed and thread will be in sleep state
5. Sleep time elapsed and thread enters into ready state
6. IO operation is initiated
7. IO operation is completed and thread enters into ready state
8. Thread is completed and terminated
Thread priority
 Each thread is associated with a priority
 Priority is used by the thread scheduler to decide which of the available threads should be
given control
 Priority is relative and not absolute. That means the priority of other thread will decide
whether current thread gets control or not
 Use setPriority(int) and getPriority() to set and get the priority of the thread
 Thread class has three static members(MIN_PRIORITY, NOR_PRIORITY,
MAX_PRIORITY), which can be used to set priority of the thread
Synchronization
 This is process by which Java ensures that a shared resource is accessed only by one thread at
a time

19
 Java provides synchronization as part of language using synchronized methods and
synchronized statements
 A monitor is an object that is used as mutually exclusive lock or mutex. Only one can thread
can own a monitor at a given time. When a thread acquires a lock, it is said to have entered a
monitor.
 When a thread synchronized method, it locks the object(enter the monitor) preventing other
threads from invoking any synchronized methods of the object
Synchronized statement
It allows to implement synchronization even when methods cannot by synchronized
Syntax: synchronized (object)
{ // invoke methods to be synchronized }
The ‘object’ is the object being synchronized. Synchronized block ensures that a call to a
method that is member of object occurs only after the current thread as successfully entered object’s
monitor
IO Streams
 IO streams is linked to physical device by Java
 All streams behave in the same manner even if the actual physical devices are different
 All classes and interfaces related to IO stream are in Java.io.package
 Java defines byte streams and character streams
Byte Streams
 Threats the stream as a collection of bytes
 Used when dealing with input and output of bytes
 Initial versions of Java used only byte streams
 All byte streams are derived from two abstracts classes – InputStream and OutStream
Character Streams
 Threats the stream as a collection characters
 They use Unicode and therefore, can be internationalized
 At the top of the hierarchy they are two abstract classes –Reader and Writer

Byte streams

Input Stream

Output stream

Character streams

Reader

Writer
Predefined streams
 System class of Java.lang package contains three predefined stream variables- in, out and
err.
 These three variables defined public and static in System class
 System.out refers to standard output stream, which is console by default
 System.in refers to standard input stream, which is keyboard by default
 System.err refers to standard error, which is console by default

20
 System.in is of typr InputStream and System.out and System.err are objects of type
PrintStream
Reader class
Abstract class of reading character streams
Method Meaning
int read() Returns a character. Returns -1 on EOF
int read(char buf[]) Read characters into the array. Returns the number of bytes read
long skip(long n) Skip the specified number of bytes
void close() Closes the stream
boolean Returns true if the stream support mark operation
markSupported()
void mark(int Mark the present position in the stream. readAheadLimit specifies the
readAheadLimit) number of characters that may be read while still preserving the mark
void reset() If the stream has marked, then attempt to reposition it at the mark
Writer class
Abstract class for writing to character streams
Method Meaning
void close() Closes the stream, flushing it first
void flush() Flushes the stream. Writes pending data to stream
void write(int c) Writes a single character
Void write(String str) Writes a string
Void write(String, offset, length) Write a portion of a String
FileReader & FileWriter classes
 Used to read and write characters streams that are connected to files
 FileReader is derived from InputStreamReader which is derived from Reader
 FileWriter is derived from OutputStreamWriter which is derived from Writer
Constructors
FileReader(File file)
FileReader(String fileName)

FileWriter(File file)
FileWriter (String fileName)
FileWriter (String filename, boolean append)
If append is to true, then output is appended to the end of file
BufferedReader class
 It improves performance by buffering characters so as to provide for the efficient reading of
characters, arrays and lines
 It is derived from Reader class
 Buffer size may be specifies or default size may be used
Constructors
BufferedReader(Reader in)
Create a buffering character-input stream that uses a default-sized input buffer
BufferedReader(Reader in, int sz)
Create a buffering character-input stream that uses an input buffer of the specified size
Method
readLine(): reads a line of text. A line considered to be terminated by linefeed or carriage return or
both
21
PrintWriter class
 Prints the given data after formatting it to a test-output stream. This class implements all of
the print methods found in PrintStream.
 Methods in this class never throw I/O excpetions. The client may inquire as to whether any
errors have occurred by invoking checkError()
 Derived from Writer class
Constructors
PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoFlush)
autoflush parameters specifies whether output is to automatically flushed everytime a
newline(\n) character in output
File class
 Represents file and directory pathnames
 Provides methods get information about the absolute pathname
Constructors
File(File parent, String Creates a new File instance from a parent abstract pathname and child
child) pathname string
File(String pathname) Creates a new File instance by converting the given pathname string
into an abstract pathname
File(String parent, String Creates a new File instance from a parent pathname string and child
child) pathname string
File(URI uri) Creates a new File instance by converting the given file: URI into an
abstract pathname
Methods
Method Meaning
boolean canRead() Tests whether the application can read the file
boolean canWrite() Tests whether the application can modify to the file
boolean Automatically creates a new, empty file named by this abstract pathname
createNewFile() if and only if a file with this name does not yet exist
boolean delete(0 Deletes the file or directory denoted by this abstract pathname
void deleteOnExit() Request that the file or directory denoted by this abstract pathnamebe
deleted when the virtual machine terminates
boolean equals(Object Tests this abstract pathname for equality wit the given object
obj)
boolean exists() Testes whether the file denoted by this abstractpathname exists
String Returns the absolute pathname
getAbsolutePath()
String getName() Returns the name of the file or directory
String getParent() Returns the pathname string of this abstract pathname’s parent. Or null if
this pathname does not name a parent directory
File getParentFile() Returns the abstract pathname of this abstract pathname’s parent, or null
if this pathname does not name a parent directory
String getPath() Converts this abstract pathname into a pathname string
boolean isAbsolute() Tests whether this abstract path name is absolute
boolean isDirectory() Tests whether the pathname is a directory
boolean isFile() Tests whether this abstract pathname is normal file

22
boolean isHidden() Tests whether the file is a hidden file
long lastModified() returns the time that the file was last modified
long length() Returns the length of file denoted by pathname
String[] list{} Returns an array of strings naming the files and directories in the
directory denoted by pathname
File[] listFiles() Returns an array of pathnames denoting the files in the directory denoted
by pathname
boolean mkdir(0 Creates the directory named by the pathname
boolean renameTo(File Renames the File denoted by this abstract pathname
Dest)
RandomAccessFile class
 Represents random access file
 Implements DataInput and DataOutput interfaces
 Allows to read and write from any position from the stream
Constructors
RandomAccessFile(String name, String mode)
RandomAccessFile(File obj, String mode)
Mode may be “r”- reading or “rw” – read and write
Method Meaning
void length() Returns the length of this file
Type read<type>() Reads the specified value
Void seek(long pos) Sets the file-pointer to the specified location. The pos is the number of
bytes from the beginning of the file
void Writes the specified value
write<type>(value)
Java Networking
 Java provides classes which to program internet or/and TCP/IP network
 All classes are made available through Java.net package
Socket programming
 Sockets enable communication between two machines
 Sockets are endpoints of communication
 Client socket establishes connection to server socket and send request to server socket. In
turn server socket sends response to client socket
 Each server socket is associated with a number called port number. In order to access a server
socket, client socket has to provide the name of the machine on which server runs and port
number at which server socket listens

Port=3400 Host=”server” port=3400

SERVER CLIENT
CONNECTION
SOCKET SOCKET
Some common Internet applications and their port numbers are as follows

Port Application/ Protocol


21 File Transfer protocol(FTP)
23 Telnet Protocol

23
25 Simple mail Transfer Portocol(SMTP)
80 Hypertext Transfer Protocol(HTTP)
ServerSocket class
 Creates a server socket
 A server socket waits for request to come from clients and process the requests
Constructors
ServerSocket(int port) throws IOException
ServerSocket(int port, int queuelength) throws IOException
Port specifies the port number at which server socket listens
Queuelength specifies maximum queue length
Method Meaning
Socket accept() Waits for request and returns client socket
void close() Closes this socket
inetAddress getInetAddress() Returns the local server of the server socket
int getLocalPort() Returns the post on which this socket is listening
Socket class
 Creates a client socket
 Connect to server socket by specifying the name of the machines and port number of server
socket
Constructors
Socket(String host, int port) throws UnknownHostException, IOException
Socket(InetAddress address, int port) throws IOException
Method Meaning
void close() Closes this socket
InetAddress getInetAddress() Returns the address of the machine to which the socket is
connected
InputStream getInputStream() Returns an input stream for this socket
OutputStream Returns an output stream for this socket
getOutputStream()
Int getPort() Returns the remote port to which this socket is connected
InetAddress class
 This class represents an IP address and domain name that address
 Has no constructor
 Contains factory methods(static methods that return instance of the class) which return an
object of InetAddress for the given name
Method Meaning
static InetAddress[] getAllByName(String Determines all the IP address of the given host’s
host) name
static InetAddress[] getByName(String host) Determines the IP address of the given host’s name
String getHostAddress() Returns the IP address string “%d.%d.%d.%d”
String getHostName() Returns the hostname for this address
Static InetAddress getLoaclHost() Returns the local host
URL class
 Represents a Uniform Resource Locator
 URL is used to uniquely identifying a resource in Internet

24
Constructors
URL(String spec)
URL(String protocol, String host, String file)
URL(String protocol, String host, int port, String file)
Method Meaning
boolean equals(Object obj) Compares two URLs
String getFile() Returns the file name of this URL
String getHost() Returns the host name of this URL, if applicable
int getPort() Returns the port number of this URL
String getProtocol() Returns the protocol name of this URL
URLConnection Returns a URLConnection object that represents a connection to the
openConnection() remote object referred to by the URL
InputStream openStream() Opens a connection to this URL and returns an InputStream
UDP (User Data protocol)
 Provides fast, connectionless and unreliable transport of packets
 Datagram is chunk of data that is passed between machines
 Once a Datagram is sent, there is no assurance that it will arrive or even the destination is
existing
 There is no guarantee that the datagram has not been damaged in transit
DatagramSocket class
 This class represents a socket for sending and receiving datagram packets
 A datagram socket is the sending or receiving point for a packet delivery service. Each
packet sent or received on a datagram socket is individually addressed and routed
Constructors
DatagramSocket(int port) throws SocketException
Creates a datagram socket and binds it to specified proton the local host machine
DatagramSocket(int port,InetAddress addr) throws SocketException
Creates a datagram socket and bounds to specified local address
Method Meaning
void close() Closes this datagram socket
void connect(InetAddress addr,int port) Connect the socket for the remote address for this socket
void connect(SocketAddress addr) Connect this socket to remote socket address
(IP address+port number )
void disconnect() Disconnects the socket
InetAddress getInetAddress() Returns the socket to which this socket is connected
int getPort() Returns the port number of this socket
void receive(DatagramPacket p) Receives a datagram packet from this socket
void send(DatagramPacket p) Sends a datagram packet from this socket
void bind(SocketAddress addr) Binds Datagram Socket to specific address and port
java.lang package
 java.lang package is automatically imported into all programs
 It contains classes and interfaces that are fundamental to virtually all of java programs
 The data type’s int, char, etc are not the part of object hierarchy. They are passed by-value to
methods and cannot be directly passed by reference
 Enumeration classes only deal with objects and therefore java provides classes that
correspond to each simple type so as to wrap them within a class. So they are referred as
wrapper classes

25
Wrapper classes
 The following are the simple data types and their corresponding wrapper class types
Simple Types Wrapper Class Constructors
boolean Boolean Boolean(boolean), Boolean(String)
char Character Character(char),
double Double Double(double),Double(String) throws NumberFormatException
float Float Float(float), Float(String) throws NumberFormatException
int Integer Integer(int), Integer (String) throws NumberFormatException
long Long Long(long), Long(String) throws NumberFormatException
byte Byte Byte(byte), Byte(String) throws NumberFormatException
short Short Short(short), Short(String) throws NumberFormatException
 The wrapper classes have a number of unique methods for handling primitive data types and
objects.
 Classes Double, Float, Byte, Integer, Long, Short classes extends abstract class Number
which has abstract methods that return the value of the object in each of the different formats.
byte byteValue(), short shortValue(), int intValue(), long longValue(), float floatValue(),
double doubleValue()
 Char charValue() and boolean booleanvalue() returns the respective type values
Converting primitive numbers into objects
 Integer intval = new Integer(i); Primitive integer to Integer Object
 Float floatval = new Float(f); Primitive double to Float Object
 Double doubleval = new Double(d); Primitive double to Double object
 Long longval = new Long(l); Primitive long to Long object
Note: i,f,d and l are primitive data values denoting int , float , double and long data types. They may
be constant or variables.
Converting objet numbers into primitive
 int i = Intval.intValue(); Object to Primitive integer
 float f =Floatval.floatValue(); Object to Primitive float
 long l = Longvol.longValue(); Object to Primitive long
 double d =Doublevol.doubleValue(); Object to Primitive double.
Eg: class wrap
{
public static void main(String abc[])
{
Integer obj = new Integer(100);
System.out.println(obj);
int i = obj.intvalue();
System.out.println(“i=” +i);
}}
Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its
equivalent type wrapper whenever an object of that type is needed.
Auto- unboxing is the process by which the value of a boxed object is automatically extracted
(unboxed) from a type wrapper when its value is needed.
There is no need to call a method such as intValue() or doubleValue()
Eg: class autobox {
public static void main(String args[])
{ Integer iob = 100; // auto an int;
int i = iob; // auto- unbox;
System.out.println(i +” “+iob);
}}
26
Collection Framework
 A Collection is group of objects
 java.util package contains Collections which is one of the java’s most powerful subsystems
 It reduces the programming effort by providing useful data structures and algorithms so that
you need not code them by yourself
 Its increases performance by providing high-performance implementations of useful data
structures and algorithms
 It reduces the effort required to learn APIs by eliminating to learn multiple ad hoc collection
APIs
 It reduces the effort required to design and implement APIs by eliminating the need to
produce ad hoc collection APIs
 It promotes software reuse by providing a standard interface for collections and algorithms
to manipulate them
 Collection frameworks standardizes the way in which group of objects are handled by java
programs
 Collection frameworks are designed to meet several goals which includes high performance,
allowing different types of collections to work in similar manner and with a high degree of
inter adoptability and extendibility
The collection frame work consists of
 Collection Interfaces: Represent different types of collections such as sets, lists and maps.
These interfaces form the basis of the frame work
 General-purpose Implementations: Primary implementations of the collections interfaces
 Legacy Implementations: The collection classes from earlier releases, Vector and
Hashtable have been retrofitted to implement the collection interfaces
 Wrapper Implementations: Add functionality, such as synchronization, to other
implementations
 Abstract Implementations: Partial implementation of collection interfaces to facilitate
custom implementations
 Algorithms: Static functions that perform useful functions on collections, such as sorting a
list
Collection interface
 This is the most basic interface
syn:: interface Collection<E> E specifies the type of objects the collection will hold
 Provides the methods that all collection will have
Method Meaning
boolean add(Object obj) Adds an object to collection
boolean addALL(Collection col) Adds all elements of collection
boolean contains(Object obj) Returns true if the given object is found in the collection
boolean isEmpty() Returns true if the collection is empty
void clear() Clears all elements in the collection
Iterator iterator() Returns an iterator
boolean remove(Object obj) Removes an object from the collection
boolean removeAll() Removes all elements
int size() Returns no. of elements
Object[] toArray() Returns an array containing all elements of the collection
List interface
 Extends Collection interface
 An ordered collection(also known as sequence)
 Allows elements to be accessed by their position(index)
27
Method Meaning
void add(int index, Object element) Inserts the element in the specified position
Object get(int index) Return the element at the specified position in the list
int indexOf(Object obj) Returns the first occurrence of the element in the list
ListIterator listIterator() Returns the list iterator of the elements in the list
Object set(int index, Object element) Replaces the element at the specified position
Set Interface
 Represents a collection that contains no duplicate elements
 Extends Collection interface
Set Interface
 Extends Set interface
 It declares the behavior of the set sorted in ascending order
Method Meaning
Object first() Return the first element in the invoking sorted set
Object last() Return the last element in the invoking sorted set
SortedSet subset(Object Returns a SortedSet that includes those elements between start and end-
start, Object end) 1. Elements in the returned collection are also referenced by the
invoking object
Collection classes
ArrayList class
 Implements the list interface Syn:: class ArrayList<E>
 This class is roughly equivalent to vector except that it is unsynchronized
 Each ArrayList instance has a capacity. The capacity is the size of the array used to store the
elements in the list. It is always as large as list size. As elements are added to an ArrayList, its
capacity grows automatically
Constructors:
ArrayList()  Constructs an empty List
ArrayList(Collection c) Constructs a list containing the elements of the specified collection, in the
order they are returned by the collection’s iterator
ArrayList(int initialCapacity)  constructs an empty list with the specified initial capacity
LinkedList class
 It is a double linked list implementation of List interface
 It can be used as stack, queue or double-ended queue(deque)
Constructors Syn:: class LinkedList<E>
LinkedList()  Constructs an empty List
LinkedList(Collection c)  Constructs a list containing the elements of the specified collection
Method Meaning
void addFirst(Object o) Insert the element at the beginning of the list
void addLast(Object o) Insert the element at the end of the list
Object getFirst() Returns the first element of the list
Object getLast() Returns the last element of the list
ListIterator listIterator(int Returns the list-iterator of the elements that begins at the specified
index) index
Object removeFirst() Removes and returns the first element from the list
Object removeLast() Removes and returns the last element from the list
HashSet class
 Implements the Set interface Syn:: class HashSet<E>
 It makes no guarantees as to the iteration order of the set; i.e., it doesn’t guarantee that the
order will remain constant over time
28
 The class permit the null element
Constructor
HastSet()  Constructs a new, empty set
HashSet(Collection)  constructs a new set containing the elements in the specified collection
Iterator interface
 Allows to cycle through the elements in the collection
 Allows the caller to remove elements from the underlying collection
Method Meaning
boolean hasNext() Returns true if the iteration has more elements
Object next() Returns the next available element
void remove() Removes from the last element returned by the iterator
ListIterator interface
 Allows the programmer to traverse the list in either direction
 Allows modification to the list during iteration
 Extends Iterator interface
Method Meaning
boolean hasPrevious() Returns true if the iteration has elements before the current one
int nextIndex() Returns the index of the next element
Object previous() Returns the previous element in the list
int previousIndex() Returns the index of the previous element
void remove() Removes from the list the last element that was returned
void set(Object o) Replaces the last element returned
Map Interface
 An object that maps keys to values
 A map cannot contain duplicate keys. Each key can map at most one value
 Contains an inner class Map.Entry that describes a n element (a key/value pair) in a map.
Method Meaning
void clear() Clears the map
boolean containskey(Object key) Returns true if specified key Exist
Object get(Object key) Returns the value of the key
boolean isEmpty() Returns true if this map is empty
Set keySet() Returns the set view of the keys contains in this map
Object put(Object key, Object value) Places the key and the value
Object remove(Object key) Removes mapping for this key from this map if present
int size() Returns the number of keys
Collection values() Returns a collection view of values contained in this map
Note: SortedMap interface extends Map in which keys are maintained in ascending order
HashMap class
 Implements Map and extends AbstractMap. It does have any methods of its own
 Uses hash table to implement the Map interface
 Allows execution time of basic operations such as get() and put() to remain constant even for
large sets
Constructors
HashMap()
HashMap(Map m)
HashMap(int capacity)
TreeMap class
 It implements Map interface
 Provides efficient means of storing key/value pairs in sorted order
29
Constructors
TreeMap()
TreeMap(Map m)
Vector class
 It is one of the legacy classes which implements List interface
 It is synchronized
Constructors: Vector()
Vector(Object[])
Vector(Collection)
Method Meaning
void addElement(Object obj) Add the component at the end of the vector
Object elementAt(int index) Returns element at given index
void removeElementAt(int Deletes the component at the specified index
index)
void Inserts the specified object as the components in the vector at the
insertElementAt(Object,int) specified index
void setElementAt(Object,int) Sets the component at the specified index to the specified index
Enumeration elements() Returns an enumeration of the elements of the vector
Enumeration interface
 Allows to access elements of a vector
 New implementations should consider using Iterator in preference to Enumeration
Method Meaning
boolean hasMoreElements() Returns true if it contains more elements
Object nextElement() Returns the next element of this enumeration
Stack class
 Returns a last-in-first-out(LIFO) stack of objects
 Extends vector class and provides standard push and pop operations
Method Meaning
boolean empty() Tests if this stack is empty
Object peek() Returns the object at the top of this stack without removing it
Object pop() Removes the object at the top of this stack and returns that object
Object push(Object item) Pushes an item onto the top of this stack
int search(Object o) Returns offset from the top of the stack is returned, otherwise -1
Comparator interface
 Defines how two objects are defined
 Elements in the collections and maps are sorted as defined
Method Meaning
int compare(Object o1, Object Returns 0 if objects are equal, returns +ve values if o1 is greater
o2) than 2 otherwise
boolean equals(Object obj) Returns true if obj and invoking object are equal
Collections algorithms
 It defines several algorithms that can be applied to collections and maps
 Methods are static.
Method Meaning
static int binarySearch(List list, Searches for value in sorted list. Returns the position of value
Object value) in list or -1 if value is not found
static Object max(Collection c) Returns the maximum element in c as determined by natural
ordering
static Object min(Collection c) Returns the maximum element in c as determined by natural
30
ordering
static void reverse(List list) Reverses the sequence in list
static void sort(List list, Sorts the elements of list as determined by comp
Comparator comp)
static void sort(List list) Sorts the elements of list as determined by the natural ordering
Date class: Encapsulates the current date and time
Constructors
Date()
Date(long millisec)
Method Meaning
boolean after(Date Returns true if the invoking Date object contains a date that is later than the
date) one specified by date. Otherwise it returns false
boolean Returns true if the invoking Date object contains a date that is earlier than the
before(Date date) one specified by date. Otherwise it returns false
long getTime() Returns the number of milliseconds that have elapsed since January 1, 1970
String toString() Converts the invoking Date object into a string and returns the result
Random
 Generates pseudorandom numbers
 Generated numbers are pseudorandom numbers because they are simply uniformly
distributed sequences
Constructors
Random() Uses the current time as the starting or seed value
Random(long seed) Seed value is specified manually
Method Meaning
boolean nextFloat() Returns the next float random number
boolean nextDouble() Returns the next double random number
boolean nextInt() Returns the next int random number
boolean nextLong() Returns the next long random number
Applet
 Applet is a java program that is to be embedded into a web page
 Applet class is super class of any applet
Applet Tag
It is used to insert an applet into an html page
<APPLET
[CODEBASE=codebaseUrl]
CODE= appletfile
[NAME=AppletInstanceName]
WIDTH= pixels HEIGHT=pixels [ALIGN=alignment]>
[PARAM NAME=name VALUE=value>…]
</APPLET>
CODEBASE Base URL of the Applet code
CODE Name of .class file
NAME The name that other applets in same page can use to find this applet
WIDTH Width of the applet in pixels
HEIGHT Height of the applet in pixels
ALIGN Alignment of the applet
PARAM Used to pass arguments to applet
Life Cycle of an Applet
The following methods of Applet class are different stages of applet’s life cycle
31
Method Time of call
init() Called only once during the runtime of the applet
start() Called after init(). Also called after restart of an applet it has been stopped
paint(Graphics g) Called each time your applets output to be redrawn
stop() It is called when browser goes to another web page
destroy() Called when applet is removed completely
Methods of Applet class
Method Meaning
String getParameter(String Returns the value of the given parameter
name)
AppletContext Returns an object of AppletContext which can be used to access
getAppletContext() other applets in the same page
URL getDocumentBase() Returns the URL of the HTML page in which applet is placed
URL getCodeBase() Returns the URL of applet class
Void showStatus(String msg) Display the given message in the status window

/examples/first.html

Web page
Document Base
/applets/sample.class

Code Base
APPLET

AppletContext interface
 Provides the information applet and other applets in the same document
 The methods in this interface can be used by an applet to obtain information about its
environment
 It is used for Applet-to-Applet communication and invoking an Applet from another Applet
Method Meaning
Applet getApplet(String name) Finds and returns the applet in the document represented by
this applet context with the given name
Enumeration getApplets() Finds all the applets in the document represented by this applet
context
void showDocument(URL url) Replaces the webpage currently being viewed with the given
URL
void showDocument(URL url, Requests that the browser or applet viewer show the webpage
String target)) indicated by the url document
void showStatus(String status) Requests that the argument string being displayed in the “status
window”
Layout manager
 Layout manager is used to arrange components using an algorithm
 Each container has an associated layout manager
 setLayout() method is used to change the layout manager
FlowLayout It is the default layout manager. Components are arranged from upper left corner,
left to right to top to bottom
GridLayout Lays out components in two dimensional grid
GridBagLayout Divides the area into cells where width and height and other attributes of each cell
32
can be specified.
BorderLayout The entire area is divided into 5 zones- east, west, north, south and center. While
adding components to this layout manager, we have to specify to which zone the
component is to be added
CardLayout Allows a set of cards to be displayed and one of the cards to be activated at a time.
Each card displays a panel
Displaying an image
 getImage(URL) and getImage(Url, filename) method are used to load image into memory
 Following methods of Graphics object are used to display an image
drawImage (Image, x, y, ImageObserver)
drawImage (Image, x, y, width, height, ImageObserver)

ImageObserver interface is used to receive notification as an image is being drawn


Eg: Image img;
public void init()
{ img=getImage(getDocumentBase(), “a.gif”); }
public void paint(graphics g)
{ g.drawImage(img,0,0,this);
Delegation Event Model
 An event is generated at a component. This component is called as Source
 Other component that is interested in the event must register itself as the listener of the event
 Whenever an event occurs in the source component a method in listener is invoked
Handling Action Event
 Listener must implement ActionListener interface
 ActionListener interface contains actionPerformed(ActionEvent evt) method. So it must
define it.
 Listener must register itself as the listener of the source for ActionEvent using
addActionListener(ActionListener) methodof the source
WindowListener interface
 Contains methods that are invoked by window events
 Events are generated by Frame
 addWindowListener(WindowListener) method is used to register a listener
Methods
 windowClosed(WindowEvent evt)
 windowClosing(WindowEvent evt)
 windowActivated(WindowEvent evt)
 windowDeactivated(WindowEvent evt)
 windowDeiconified(WindowEvent evt) (window restored)
 windowIconified(WindowEvent evt)  (Window minimized)
 windowOpened(WindowEvent evt)
MouseListener interface
 Contains methods to be implemented to handle mouse events
 Parameter MouseEvent object provides information regarding mouse pointer position etc.
 addMouseListener(MouseListener) method is used to register a listener
Method Meaning
void Invoked when the mouse button has been clicked(pressed and
mouseClicked(MouseEvent) released) on a component
void Invoked when mouse enters a component
mouseEntered(MouseEvent)
33
void mouseExited(MouseEvent) Invoked when mouse exits a component
void Invoked when a mouse button has been pressed on a component
mousePressed(MouseEvent)
void Invoked when a mouse button has been released on a component
mouseReleased(MouseEvent)

Methods of MouseEvent class


Method Meaning
int getClickCount() Returns the no. of mouse clicks
Point getPoint() Returns the x, y position of the mouse pointer
int getX() Returns the X position of the event relative to the source component
int getY() Returns the Y position of the event relative to the source component
boolean Returns true if mouse event is associated with the popup-menu trigger
isPopupTrigger() event for the platform

MouseMotionListener interface
Contains methods to handle events that occur while mouse is in motion
Method Meaning
void mouseDragged(MouseEvent evt) Invoked when a mouse button is dragged
void mouseMOved(MouseEvent evt) Invoked when the mouse pointer has been moved

Keyboard events
 Use KeyListener interface to handle keyboard events
 addKeyListener(KeyListener) method is used to register a listener
 Key typed event is higher-level and generally generated when a Unicode character is entered,
and is the preferred way to find out about character input. No key typed events are generated
for keys that don’t generate Unicode characters (eg., action keys, modifier keys etc)
 Key pressed and key released events are lower-level and depend on the platform and
keyboard layout. The key being pressed or released is indicated by the getKeyCode() method,
which returns a virtual key code
 Virtual key codes are used to report which keyboard key has been pressed
Method Meaning
void keyPressed(keyEvent e) Invoked when a key has been pressed
void keyReleased(keyEvent e) Invoked when a key has been released
void keyTyped(keyEvent e) Invoked when a key has been typed

KeyEvent class
Provides information about the character press by the user
Method Meaning
char getKeyChar() Returns the character associated with the key
int getKeyCode() Returns the integer key-code associated with the key
static String getKeyText(int Returns the string describing the keyCode such as “HOME”,
keyCode) “F1” or “A”

Graphics class
 The Graphics class is the abstract base class for all graphics contexts that allow an application
to draw onto component
 All drawing or writing is done in the current color, using the current paint mode and in the
current font
34
Method Meaning
void clearRect(int x, int y, int width, int Clears the specified rectangle by filling it with the
height) background color of the current drawing surface
void drawRect(int x, int y, int w, int h) Draws the outline of the specified rectangle
void draw3Drect(int x, int y, int w, int h, Draws a 3-d highlighted outline of the specified
boolean raised) rectangle
void drawArc(int x, int y, int w, int h, int Draws the outline of the circular or elliptical arc
startAngle, int arcAngle) covering the specified rectangle
boolean drawImage(Image img, int x, int Draws as much of the specified image as is currently
y, ImageObserver observer) available
void drawLine(int x1, int y1, int x2, int y2) Draws the line using current color from points (x1,y1)
to (x2,y2)
void drawOval((int x, int y, int w, int h) Draws the outline of the oval
void drawPolygon(int[] xpoints, int[] Draws closed polygon defined by arrays of x and y
ypoints, int npoints) coordinates
void drawPolygon(Polygon p) Draws the outline of a polygon defined by specified
Polygon object
void drawstring(String str,int x, int y) Draws the text given by the specified string current
using this graphics context’s current font and color
objects
void fillPolygon(Polygon p) Fills the polygon defined by the specified polygon’s
object with the graphics context’s current color
Color getColor() Gets this graphics context’s current color
Font getFont() Gets the current Font
void setColor(Color c) Sets this graphics context’s current color to specified
color
void setFont(Font f) Sets this graphics context’s current font to specified
font

Component class
 A component is an object having graphical representation that can be displayed on the screen
and that can interact with the user
 Examples of components are buttons, checkboxes and scrollbars of typical user interface
Method Meaning
void add(PopupMenu Add the specified popup menu to the component
popup)
float getAlignmentX() Returns the alignment along the x-axis
float getAlignmentY() Returns the alignment along the y-axis
Color getBackground() Gets the background color of this component
Font getFont() Get the font of this component
Color getForeground() Get the foreground color of this component
Graphics getGraphics() Creates the Graphics context of this component
int getHeight() Return the current height of the component
String getName() Get the name of the component
Container getParent() Get the parent of the component
int getWidth() Returns the current width of this component
int getX() Returns the current x-coordinate of the components origin
int getX() Returns the current y-coordinate of the components origin
35
boolean hasFocus() Returns true if the component has keyboard focus
boolean isEnabled() Returns true if the component is enabled
boolean isShowing() Returns true if the component is showing on the screen
void paint(Graphics g) Paints this component
void repaint() Repaints the component
void requestFocus() Requests that this component get the input focus
void setBackground(Color) Sets the background color of this component
void setEnabled(boolean b) Enables or disables the component depending on the value of the
parameter b
void setFont(Font f) Sets the font of this component
void setForeground(Color) Sets the foreground color of this component
void setLocation(int , int ) Moves the component to new location
void setName(String ) Sets the name of the component to the specified String
void setSize(Dimension d) Resizes the component so that it has width d.width and height
d.height
void setSize(int w, int h) Resizes the component so that it has given width and height
void setVisible(boolean) Shows or hides the component depending on the value of parameter b
void update(Graphics g) Updates the component

Font class
 The Font class represents fonts
 The Font class represents an instance of font face from the collection of font faces that are
present in the system resources of the host system. Eg. Arial, Courier Bold Italic etc., are font
faces
 Constructor: Font(String name, int style, int size)
static int BOLD The bold style constant
static int ITALIC The italicized style constant
Sring name The logical name of this font
staic int PLAIN The plain style constant
int size The point size of the font rounded to integer
int style The style of this font as passed to the constructor

Method Meaning
String getFamily() Returns the family name of this font
String getFontName() Returns the font face name of this font
String getName() Returns the logical name of this font
int getSize() Returns the point size of this font
int getStyle() Returns the style of this font
boolean isBold() Indicates whether or not this Font object’s style is BOLD
boolean isItalic() Indicates whether or not this Font object’s style is ITALIC
boolean isPlain() Indicates whether or not this Font object’s style is PLAIN

Color class
 Encapsulates color
 Static variables of Color type defined Color class are black, blue, cyan, darkGray, gray,
green, lightGray, magenta, orange, pink, red, white, yellow
 Constructor: Color(int red, int green, int blue)
o Creates an opaque RGB color with the specified red, green and blue values in the
range 0-255
36
Method Meaning
int getRed() Retruns the red component
int getGreen() Retruns the green component
int getBlue() Retruns the blue component

Adapter classes
 An adapter class provides an empty implementation of all methods in an event listener
interface
 Adapter classes are useful when you want to receive and process some of the events that are
handled by particular event listener interface
 You can also define new class to act as event listener by extending one of the adapter classes
and implementing only those events in which you are interested.

Adapter classes and their Listener interfaces


Class Interface
ComponentAdapter ComponentListener
ConatinerAdapter ContainerListener
KeyAdapter KeyListener
FocusAdapter FocusListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener

AWT Controls

Label: Displays the string on the container


Label()
Label(String)

Method Meaning
void setText(String) Sets given text to label
String getText() Returns the text of the label
int getAlignment() Returns the current alignment
void setAlignemnt(int) Sets alignment to one of the three- CENTER, LEFT and RIGHT

Button: Create a push button


Button()
Button(String)

void setLabel(String): Sets the label of the control


String getLabel(): Gets the label of the control

Checkbox: Represents a check box or radio button


Checkbox ()
Checkbox(String)
Checkbox(String,boolean)
Checkbox(String,CheckboxGroup,boolean)Used to create radio buttons

37
Method Meaning
boolean getState() Returns the current state of the control. True indicates checkbox is checked
void setState(boolean) Sets the checkbox to checked or unchecked status
String getLabel() Returns label of the control
void setLabel(String) Sets label of the control

ItemListener interface
 Contains itemStateChanged() method which is invoked when the state of an item changes
 itemStateChanged() method has ItemEvent as parameter

ItemEvent class
 Generated by an object (such as a List)when an item is selected or deselected by the user
 Contains the fields ‘DESELECTED’ when user deselects an item and ‘SELECED’ when user
selects an item
Method Meaning
Object getItem() Returns the item affected by the event
int getStateChange() Returns the type of state changed(Selected or deselected)

Checkbox group: Used to create a set of mutually exclusive check boxes


Checkbox getSelectedCheckbox()
void setSelectedCheckbox()

Choice: Used to create pop-up list from which user can select any single item
Method Meaning
void addItem(String) Adds an item to the list
String getSelectedItem() Returns the selected item
int getSelectedIndex() Returns the selected index()
int getItemCount() Returns number of items in the list
void select(int) Selects the item specified by the index
void select(String) Selects item specified by text
String getItem(int) Returns the item at the given position
List: It is used to create list box which allows to display multiple items and multi selection
List()
List(int noofrows)
List(int noofrows, boolean multiselect)

Method Meaning
void add(String) Adds an item to the list
void add(String item, int index) Adds an item at the specified index
String getSelectedItem() Returns the selected item
int getSelectedIndex() Returns the selected index()
void getItemCount() Returns number of items in the list
String[] getSelectedItems() Returns an array of selected items in a multi-select list box
int[] getSelectedIndexes() Returns the indexes of selected items
String getItem(int) Returns the item at the given position
void remove(int) Removes an item at given index
void remove(String) Removes the item from the list
void removeAll() Removes all items in the list
38
Scrollbar class: Allows a value to be selected between a specified minimum and maximum values
Scrollbar()
Scrollbar(int style,int value,int thumbsize,int min, int max)

Method Meaning
int setValues(int intvalue, int thumbsize, int Sets values to different properties of Scrollbar
min, int max)
int getValue() Returns the value represented by scrollbar
void setValue(int newvalue) Sets the value of scrollbar
int getMinimum() Returns the minimum value represented by
Scrollbar
int getMaximum() Returns the maximum value represented by
Scrollbar
void setUnitIncrement(int) Sets the value by which scroll moves when user
clicks the arrows

Events related to Scrollbar can be handled by the methods in AdjustmentListener interface, which
contains method adjustmentvalueChanged(AdjustmentEvent)

int getAdjustmentType(): Returns the type of adjustment which caused the value changed event.

TextField class
 Creates a single lien text box
 It is sub class of TextComponent class
TextField()
TextFieldString(String)
TextField(String str,int numChars)

Method Meaning
String getText() Returns the text of the control
void setText(String) Sets the text to the control
String Returns the selected (highlighted) text
getSelectedText()
void select(int start, int Specifies the text to be selected using start and end positions in the control
end)
boolean isEditable() Returns true if control is editable
void Specifies whether control is editable or not
setEditable(boolean)
void Specifies the character to be displayed when user enters character. By
setEchoChar(char) default the same character is displayed. However, it must be changed for
entering passwords ect.

TextArea
 Creates a text area where we can enter multiple lines
 It is a sub class of TextComponent
TextArea()
TextArea(String str, int nolines, int nochars)
TextArea(String,int nolines,int nochars,int sbars)

39
Sbars may be SCROLLBARS_BOTH, SCROLLBARS_NONE,
SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_VERTICAL_ONLY

Method Meaning
void append(String) Appends text to the text of the TextArea
void insert(String text, int pos) Inserts the given text at the given position
void replacerange(String text, int start, int end) Replaces text between start and with the given text

Swing components
Features
 Swing components are built as the part of java foundation classes
 It is built on the top of AWT
 Awt is a Java interface to native system GUI code present in your OS. It will not work the
same on every system, although it tries.
 Swing is a more-or-less pure-Java GUI. Using awt it creates an operating system window,
and then it paints pictures of buttons, labels, text, checkboxes, etc., into that window and
responds to all of your mouse-clicks, key entries, etc., deciding for itself what to do instead of
letting the operating system handle it
 It is 100% pure implementation of Java-light weight components
 It is consistent across all platforms- same look and feel
 Pluggable Look and Feel(PL&F), wither Swing can use Operating system look and fell or use
mental look and feel
 Introduced new components
 Package is javax.swing

JApplet class
 Used to create an applet in swing
 Extends Applet class
 Its client area can be accessed using getContentPane() method, which returns an object of the
Container
 Use add() of Container class to add components to applet
 They life cycle etc. are same as AWT applet

JComponent class
 This is the parent class of all swing components
 It is derived from Container class of AWT

ImageIcon class: Icons are represented by this class


ImageIcon(String)
ImageIcon(URL)

JLabel class: Represents a label


JLabel(Icon)
JLabel(String)

String getText()
void setText()

40
JTextField class: It extends a JTextComponent. It represents a text box
JTextField(int cols)
JTextField(String s)
JTextField(String s, int cols)

JPasswordField class: It is used to hide characters entered by the user. It extends JTextField
JPasswordField()
JPasswordField(width)
JPasswordField(String, width)

JButton class
 Provides functionality of push button
 Allows an icon or a string or both to be associated with the button
 It extends AbstractButton class
JButton(Icon)
JButton(String)
JButton(String,Icon)

String getText()
void setText()
void addActionListener(ActionListener)
void removeActionListener(ActionListener)

JCheckBox class
 It provides functionality of check box.
 It extends AbstractButton class.
 Generates ItemEvent when user turns on/off checkbox. ItemListener interface contains
ItemStateChanged(ItemEvent e) method

JCheckBox(Icon)
JCheckBox(String)
JCheckBox(String,boolean state)

Void setSelected(Boolean state)


Generates ItemEvent when user turns on/off checkbox. ItemListener interface contains
ItemStateChanged(ItemEvent e)method.

JRadioButton class: It represents radio buttons. It extends AbstractButton


JRadioButton(String s)
JRadioButton(String, boolean)
JRadioBUtton(Icon i)
JRadioButton(Icon I,boolean)
JButtonGroup class is used to group radio buttons so that only one button in the group can be
selected. It makes radio buttons mutually exclusive. Method add() is used to add objects of
JRadioButton to group

JComboBox class: It provides drop-down list cum a text box


JComboBox()
JComboBox(Vector v)
41
Method Meaning
void addItem(Object) Adds an item to ComboBox
Object getItemAt(int) Returns an item at given position
int getItemCount() Returns the number of items
int getSelectedIndex() Returns index of selected item
Object getSelectedItem() Retruns selected item
Boolean isEditable(0 Returns true, if ComboBox is editable
void removeAllItems() Remove all items from ComboBox
void removeItem(Object) Removes the specified item
void removeItemAt(int) Removes item at the given position
void setEditable(boolean) Specifies whether ComboBox is editable
void setSelectedIndex(int) Selects the item with the given index
void setSelectedItem(Object) Selects the specified item

JList class
 It represents a list box
 It takes data from a Vector or an array of objects
 It allows single or multiple selection
JList()
JList(Vector)
JList(Objeect)

Method Meaning
int getSelectedIndex() Returns index of the selected item
void clearSelection() Unselects all selected items
int[] getSelectedIndeces() Returns indexes of all selected items
Object getSelectedValue(0 Returns selected value
Objects[] getSelectedValues() Returns all selected values
boolean isSelected(int) Returns true if item with the given index is selected
void setSelectedIndex(int) Selects item with the given index
void setSelectedValue(Object, Selects the specified value. Shouldscroll specifies whether list
shouldscroll) should scroll to show the selected item
void setListData(Vector) Sets the data of the list box
void setListData(Object[]) Sets the data of the list box

JMenuBar class: Used to create a menu bar which has a collection of menus
JMenubar()
Use add() method of the Container to which menu bar is added
JMenu class: Represents a single menu. A menu contains a collection of options
JMenu()
JMenu(String)
Use add(JMenuItem) to add menu items to menu.

JMenuItem class: Represents a single menu item in a menu


JMenuItem()
JMenuItem(Icon)
JMenuItem(String)
JMenuItem(String,char)
JMenuItem(String,Icon)
42
addActionListener(ActionListener) method od ActionListener interface is used to handle the menu
items

JCheckBoxMenuItem class: Creates a menu item that works like check box.
JCheckBoxMenuItem(String, boolean)

JRadioButtonMenuItem class: Creates a menu item that is either selected or in a group of menu
items

JRadioButtonMenuItem(String)
JRadioButtonMenuItem(String,boolean)

JPopupMenu class
 It is used to create popup menu
 Popup menu is typically displayed when user clicks on right button on a component

JPopupMenu()
JPopupMenu(String)

show(Component,x,y)

JToolBar class: It represents a toolbar in Swing. By default tools bar in Swing is floatable
JToolBar()

Add(Action)
isFloatable()
setFloatable(boolean)

JDialog class: It is used to create a dialog box


JDialog()
JDialog(Frame, String title)
JDialog(Frame, String title, boolean modal)

JOptionPane class
 It contain a set of standard dialog boxes
 It provides static methods that are used to invoke dialog boxes
void showMessageDialog(Component parent, Object message, String title, int MessageType)

MessageType may be one of the following constants on JOptionPane class


ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE,
QUESTION_MESSAGE, PLAIN_MESSAGE

int showConfirmDialog(Component parent,Object message, String title,int OptionType, int


MessgeType)

Option type may be any of the following


YES_NO_OPTION, YES_NO_CANCEL_OPTION

Return values are YES_OPTION, NO_OPTION and CANCEL_OPTION


43
String showInputDialog(Component parent,Object message, String title, int MessgeType)

Timer class: Periodically triggers events of type ActionEvent


Timer(int delay, actionListener listner)

Method Meaning
void start() Starts firing event at the given interval
void stop(0 Stops firing events
void restart() Restarts firing events
void setDelay(int) Changes the interval

JSlider class: Creates a slider that can be used to select a number in the given range
JSlider()
JSlider(int orientation, int minimum, int maximum, int value)
Orientation specifies whether slider vertical or horizontal. Orientation may be
JSlider.HORIZONTAL or JSlider.VERTICAL

Method Meaning
int getValue() Returns the value of slider
void Sets the space for major ticks on the slider
setMajorTickSpacing(int)
void Sets the space for minor ticks, which are ticks between major ticks
setMinorTickSpacing(int) (in between two major tick)
void setPaintTicks(boolean) Determines whether ticks are to be displayed
void setValue(int) Sets the value of the slider

ChangeListener interface contains stateChanged() method that has a parameter of type


ChangeEvent

JScrollPane class: represents scroll pane in Swing. Provides optional horizontal and vertical
scrollsbars
JScrollPane(Component, vspolicy, hspolicy)

Vspolicy may be any of the following:


JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS

Hspolicy may be any of the following:


JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS

JTabbedPane class: Represents tabbed panes. Contains a collection of tabs where only one tab is
displayed at a time. Each tab contains a collection of child components.
JTabbedPane()
void addTab(String title, Component tab)
int getTabCount()
void removeTabAt(index)
44

You might also like