[Go to site: main page, start]

0% found this document useful (0 votes)
2 views144 pages

Java Notes

The document provides an introduction to Java programming, covering key concepts such as object-oriented programming (OOP), Java bytecode, and the features of Java including its portability, security, and robustness. It explains the definitions of objects and classes, access specifiers, constructors, and provides examples of Java syntax and code structure. Additionally, it highlights the advantages of Java bytecode in achieving platform independence and the overall design goals of the Java programming language.

Uploaded by

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

Java Notes

The document provides an introduction to Java programming, covering key concepts such as object-oriented programming (OOP), Java bytecode, and the features of Java including its portability, security, and robustness. It explains the definitions of objects and classes, access specifiers, constructors, and provides examples of Java syntax and code structure. Additionally, it highlights the advantages of Java bytecode in achieving platform independence and the overall design goals of the Java programming language.

Uploaded by

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

1

JAVA PROGRAMMING(SCS1209)
UNIT-1
Introduction to Java

OOP concepts – Java Byte code –Features of Java- Objects and Classes –Access specifiers-
Constructors- Constuctor Overloading-Method Overloading- Static and Final keywords-This
keyword-Garbage Collection-Finalize method-Inheritance- Using Super- Method overriding-
Abstract classes-Using final with inheritance.

OOP Concepts:

Object:

Any entity that has state and behavior is known as an object.

Class:

Collection of objects is called class. It is a logical entity.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing.

Encapsulation

Binding (or wrapping) code and data together into a single unit are known as
encapsulation

Inheritance

When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

If one task is performed in different ways, it is known as polymorphism

Java Byte code

Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an assembler
which is an alias representation of a C++ code. As soon as a java program is compiled, java
bytecode is generated. In more apt terms, java bytecode is the machine code in the form of a
.class file. With the help of java bytecode we achieve platform independence in java.

How does it works?

When we write a program in Java, firstly, the compiler compiles that program and a bytecode is
generated for that piece of code. When we wish to run this .class file on any other platform, we
can do so. After the first compilation, the bytecode generated is now run by the Java Virtual
Machine and not the processor in consideration. This essentially means that we only need to
have basic java installation on any platforms that we want to run our code on. Resources
required to run the bytecode are made available by theJava Virtual Machine, which calls the

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


2

processor to allocate the required resources. JVM's are stack-based so they stack
implementation to read the codes.
Source code .java file

Compiler

ByteCode .class file

JVM JVM JVM

(Windows) (Linux) (Mac)

Machine Code Machine Code Machine Code

Advantage of Java Bytecode

Platform independence is one of the soul reasons for which James Gosling started the
formation of java and it is this implementation of bytecode which helps us to achieve this.
Hence bytecode is a very important component of any java [Link] set of instructions for
the JVM may differ from system to system but all can interpret the bytecode. A point to keep in
mind is that bytecodes are non-runnable codes and rely on the availability of an interpreter to
execute and thus the JVM comes into play.

Bytecode is essentially the machine level language which runs on the Java Virtual
Machine. Whenever a class is loaded, it gets a stream of bytecode per method of the class.
Whenever that method is called during the execution of a program, the bytecode for that
method gets [Link] not only compiles the program but also generates the bytecode for
the program. Thus, we have realized that the bytecode implementation makes Java a platform-
independent language. This helps to add portability to Java which is lacking in languages like C
or C++. Portability ensures that Java can be implemented on a wide array of platforms like
desktops, mobile devices, severs and many more. Supporting this, Sun Microsystems captioned
JAVA as "write once, read anywhere" or "WORA" in resonance to the bytecode interpretation.

Features of Java

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


3

The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as java buzzwords.

A list of most important features of Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).

o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.

o There is no need to remove unreferenced objects because there is an Automatic


Garbage Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-


oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software development


and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object

2. Class

3. Inheritance

4. Polymorphism

5. Abstraction

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


4

6. Encapsulation

Platform Independent

Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on the top of other hardware-based platforms. It has two components:

1. Runtime Environment

2. API(Application Programming Interface)

Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS,
etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a
platform-independent code because it can be run on multiple platforms, i.e., Write Once and
Run Anywhere(WORA).

o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE)


which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.

o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.

o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.

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

Robust

Robust simply means strong. Java is robust because:

o It uses strong memory management.

o There is a lack of pointers that avoids security problems.

o There is automatic garbage collection in java which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.

o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Architecture-neutral

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


5

Java is architecture neutral because there are no implementation dependent features,


for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both
32 and 64-bit architectures in Java.

Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.

High-performance

Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C,
C++, etc.

Distributed

Java is distributed because it facilitates users to create distributed applications in Java.


RMI and EJB are used for creating distributed applications. This feature of Java makes us able
to access files by calling the methods from any machine on the internet.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java


programs that deal with many tasks at once by defining multiple threads. The main advantage
of multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.

Dynamic

Java is a dynamic language. It supports dynamic loading of classes. It means classes


are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage collection).

Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:

o No explicit pointer

o Java Programs run inside a virtual machine sandbox

Objects and Classes

Object:

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


6

An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an
intangible object is the banking system.

An object has three characteristics:

o State: represents the data (value) of an object.

o Behavior: represents the behavior (functionality) of an object such as deposit,


withdraw, etc.

o Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is
used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

Object Definitions:

o An object is a real-world entity.

o An object is a runtime entity.

o The object is an entity which has state and behavior.

o The object is an instance of a class.

CLASS

A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields(Variable)
o Methods

Fields :

A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time. It gets memory at
runtime when an object or instance is created. That is why it is known as an instance variable.

Methods:

In Java, a method is like a function which is used to expose the behavior of an object

Syntax of Class:

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


7

class classname
{
Fields;
methods;
}

Example:
class welcome
{
public static void main(String[] args)
{
[Link]("welcome");
}
}

Save: [Link]
Compile: javac [Link]

Interpret: java welcome

Output:

welcome.

Program for fields (variable)


class fields
{
int i;
String name;
public static void main(String[] args)
{
fields f=new fields();
[Link](f.i+"\n"+[Link]);
}
}
save :[Link]
compile:javac [Link]

Interpret:java fields

Output:

null

[Link] Intializtion through object

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


8

class fields1
{
int i;
String name;
public static void main(String[] args)
{
fields f=new fields();
f.i=10;
[Link]="cse";
[Link](f.i+"\n"+[Link]);
}
}

E:\basic pgms>javac [Link]

E:\basic pgms>java fields1

10

cse

[Link] for Variables and Methods

class student
{
int rollno;
String name;
void getdata()
{
rollno=123;
name="cse";
}
void display()
{
[Link]("Rollno:"+rollno+"\n"+"Name:"+name);
}
public static void main(String[] args)
{
student s=new student();
[Link]();
[Link]();
}
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


9

E:\basic pgms>javac [Link]

E:\basic pgms>java student

output:

Rollno:123

Name:cse

[Link] values to the Instance methods

class student1
{
int rollno;
String name;
void getdata(int r,String s)
{
rollno=r;
name=s;
}
void display()
{
[Link]("Rollno:"+rollno+"\n"+"Name:"+name);
}
public static void main(String[] args)
{
student1 s1=new student1();
[Link](111,"cse");
[Link]();
}
}
E:\basic pgms>javac [Link]

E:\basic pgms>java student1

Rollno:111

Name:cse

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


10

Access specifiers:

The access specifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and class
by applying the access modifier on it.

There are four types of Java access specifiers:

1. Private: The access level of a private specifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default specifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected specifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public specifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

Constructors

Java allows objects to initialize themselves when they are created. This automatic
initialization is performed through the use of a constructor.

A constructor initializes an object immediately upon creation. It has the same name
as the class in which it resides and is syntactically similar to a method. Once defined,the
constructor is automatically called immediately after the object is created, before the new
operator completes.

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

Rules for creating Java constructor

There are three rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor
SCS1209 - JAVA PROGRAMMING Prepared by [Link]
11

Syntax:

class rectangle
{
variable declaration;
rectangle()//construtor
{
}
}
Default Constructor
If there is no constructor available in the class It calls a default constructor. In such
case, Java compiler provides a default constructor by default.

class Default
{
int i;
String s;
double d;
boolean b;
Default()
{
}
public static void main(String[] args)
{
Default d1=new Default();
[Link]("Int:"+d1.i);
[Link]("String:"+d1.s);
[Link]("Double:"+d1.d);
[Link]("Boolean:"+d1.b);
}
}
E:\basic pgms>javac [Link]
E:\basic pgms>java Default

Int:0

String:null

Double:0.0

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


12

Boolean:false

Parametarized Constructor:

To add parameters to the constructor is called parametarized constructor.

EX:
class circle
{
double rad,area;
double pi;
circle(double r, double p)
{
rad=r;
pi=p;
}
void calculate()
{
area=rad*rad*pi;
[Link](area);
}
public static void main(String[] args)
{
circle c=new circle(6.2,3.14);
[Link]();
}
}

E:\basic pgms>javac [Link]

E:\basic pgms>java circle

120.70160000000001

Method Overloading

In Java it is possible to define two or more methods within the same class that share
the same name, as long as their parameter declarations are different. When this is the case, the

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


13

methods are said to be overloaded, and the process is referred to as method overloading.
Method overloading is one of the ways that Java implements polymorphism.

Syntax:

class overload
{
void add(int a)
{
}
void add(int a,int b)
{
}
double add(double a,double b)
{
}
}

EX:
class addition
{
int a,b,c;
void add()
{
a=20;b=30;
c=a+b;
[Link]("simple function:"+c);
}
void add(int a, int b)
{
c=a+b;
[Link](" function with argument:"+c);
}
double add(double a,double b)
{
return(a+b);
}

public static void main(String[] args)


{
addition an=new addition();
[Link]();
[Link](25,50);
[Link]("return function:"+[Link](10.5,10.5));
}
}
E:\basic pgms>javac [Link]

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


14

E:\basic pgms>java addition

simple function:50

function with argument:75

return function:21.0

Constructor Overloading

Same constructor name with different argument is called constructor overloading.

EX:

class conaddition
{
int a,b,c;
double d,e;
conaddition()
{
a=20;b=30;
[Link]("simple Construtor:"+ (a+b));
}
conaddition(int a, int b)
{
[Link]("Construtor with argument:"+ (a+b));
}
conaddition(double e,double f)
{
[Link]("double constructor:"+ (e+f));
}
public static void main(String[] args)
{
conaddition an=new conaddition();
conaddition an1=new conaddition(10,20);
conaddition an2=new conaddition(10.5,20.5);
}
}
E:\basic pgms>javac [Link]
E:\basic pgms>java conaddition

simple Construtor:50

Construtor with argument:30

double constructor:31.0

Static and Final keywords

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


15

 To create a member that can be used by itself, without reference to a specific instance.
 To create such a member, precede its declaration with the keyword static.
 When a member is declared static, it can be accessed before any objects of its class
are created, and without reference to any object.
 You can declare both methods and variables to be static

Methods declared as static have several restrictions:

 They can only call other static methods.


 They must only access static data.
 They cannot refer to this or super in any way.

Ex:

class staticex
{
static int a = 3;
static int b;
static void meth(int x) {
[Link]("x = " + x);
[Link]("a = " + a);
[Link]("b = " + b);
}
static {
[Link]("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}

E:\basic pgms>javac [Link]


E:\basic pgms>java staticex

Static block initialized.

x = 42

a=3

b = 12

Final Keyword

 A variable can be declared as final.


 Its prevents its contents from being modified.
 This means that you must initialize a final variable when it is declared.

Syntax:

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


16

final int a;

final void display()


{
}
final class finalex
{
}

Final method and final class used in inheritance.


EX:

class finalex
{
final int a=20;
int b=10,c;
void display()
{
a=a+b;
[Link](" value a is cannot changed"+a);
}
public static void main(String[] args)
{
finalex fe=new finalex();
[Link]();
}
}

E:\basic pgms>javac [Link]


[Link]: error: cannot assign a value to final variable a

a=a+b;

1 error

This keyword:

this is a reference variable that refers to the current object.

Usage of this keyword

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


17

EX:

class thisex
{
int i,fa=1,f;
thisex(int f)
{
this.f=f;
}
int fact()
{
for(i=1;i<=f;i++)
{
fa=fa*i;
}
return fa;
}
public static void main(String[] args)
{
thisex te=new thisex(5);
[Link]("factorial is:"+[Link]());
}
}

E:\basic pgms>javac [Link]


E:\basic pgms>java thisex

factorial is:120

Garbage Collection

 In java, garbage means unreferenced objects.


 Garbage Collection is process of reclaiming the runtime unused memory automatically.
In other words, it is a way to destroy the unused objects.
 To do so, we were using free() function in C language and delete() in C++. But, in java
it is performed automatically. So, java provides better memory management.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


18

Advantage of Garbage Collection

o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.

o It is automatically done by the garbage collector(a part of JVM) so we don't need to


make extra efforts.

How can an object be unreferenced?

There are many ways:

o By nulling the reference

o By assigning a reference to another

o By anonymous object etc.

By nulling a reference:

1. Employee e=new Employee();

2. e=null;

By assigning a reference to another:

1. Employee e1=new Employee();

2. Employee e2=new Employee();

3. e1=e2;

By anonymous object:

1. new Employee();

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object class as:

1. protected void finalize(){}

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.

1. public static void gc(){}

EX:spublic class TestGarbage1{

public void finalize(){[Link]("object is garbage collected");}


public static void main(String args[]){

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


19

TestGarbage1 s1=new TestGarbage1();


TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
[Link]();
} }
E:\basic pgms>javac [Link]
E:\basic pgms>java TestGarbage1

object is garbage collected

Inheritance

 Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
 Inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
 Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.

Uses of inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.

o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.

o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

o Reusability: As the name specifies, reusability is a mechanism which facilitates you to


reuse the fields and methods of the existing class when you create a new class. You can use
the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name

//methods and fields

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


20

Types of Inheritance in Java

[Link] Inheritance:

Class A

Class B

[Link] Inheritance

Class A

Class B

Class C

[Link] Inheritance

Class A

Class B Class C

[Link] Inheritance

Class A Class B

Class c

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


21

[Link] Inheritance

Class A

Class B Class C

Class D

Single Inheritance:

one parent class one child class

Ex:

class add
{
int x,y,result;
public void sum()
{
result=x+y;
}
}
class sub extends add
{
public void minus()
{
result=x-y;
}

}
public class Singleinherit {
public static void main(String[] args) {
sub obj=new sub();
obj.x=10;
obj.y=20;
[Link]();
[Link]([Link]);
[Link]();
[Link]([Link]);
}
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


22

E:\basic pgms>javac [Link]


E:\basic pgms>java Singleinherit

30

-10

Multilevel Inheritance:

When there is a chain of inheritance, it is known as multilevel inheritance.

EX:

class first
{
String name;
first()
{
name ="IstYear";
[Link](name);
}
void dis()
{
[Link]("6subjects+3lab");
}
}
class second extends first
{
second()
{
name="IInd year";
[Link](name);
}
void dis()
{
[Link]("6subjects+2lab");
}
}
public class Multilevel extends second
{
Multilevel()
{
name="Department";
[Link](name);
}
void dis2()
{

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


23

[Link]("HOD");
}

public static void main(String[] args) {


Multilevel obj=new Multilevel();
[Link]();
obj.dis1();
obj.dis2();
}
}

E:\basic pgms>javac [Link]

E:\basic pgms>java Multilevel

IstYear

IInd year

Department

6subjects+3lab

6subjects+2lab

HOD

Hierarchial Inheritance:

Two child class inherits one parent class is called Hierarchial inheritance

Ex:

class first
{
String s="cse";
void dis()
{
[Link]("Name:"+s);
}
}
class second extends first
{
int m[]={90,98,99,100,100,100};
int total;
void dis1()
{
for(int i=0;i<[Link];i++)
{
total=total+m[i];

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


24

}
[Link]("Total:"+total);
}
}

public class hierarchi extends first


{
void dis2()
{
[Link]("IIchild");
}
public static void main(String[] args) {
second si=new second();
[Link]();
si.dis1();
//si.dis2();//error
}
}

E:\basic pgms>javac [Link]


E:\basic pgms>java hierarchi

Name:cse

Total:587

Method overriding:

 Base class and sup class have the same methods, the sub class method only
[Link] is known as Overriding.
 Java has a method provision to executes the same methods of Base and sup class is
called "super ".

Ex:

class student
{
int rno;
String name;
void display(int rno,String name)
{
[Link](rno+"\n"+name);
}
}
class mark extends student
{
int m1,m2,m3,tot,avg;
void display(int m1,int m2,int m3)
{
[Link](1234,"mahi");

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


25

tot=m1+m2+m3;
avg=tot/3;
[Link]("tot:"+tot+"\n"+"avg:"+" "+avg);
}
}

class overriding
{
public static void main(String args[])
{
mark m1=new mark();
[Link](90,92,98);
}
}

E:\javapgms>javac [Link]

E:\javapgms>java overriding

1234

mahi

tot:280

avg: 93

Abstract classes

 Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

There are two ways to achieve abstraction in java

1. Abstract class
2. Interface

Rules:

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the
method.

Ex:

abstract class phone

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


26

{
String s,city,add;
int i;
void f1()
{
s= "cse";
i=12345;
city="chennai";
add="sathaybama";
}
//abstract public void dis1();
abstract public void address();
}

public class Abs1 extends phone {

public void address()


{
[Link](s+"\n"+i+"\n"+city+"\n "+add);
}
public static void main(String[] args) {
Abs1 m1=new Abs1();
m1.f1();
[Link]();
} }

E:\basic pgms>javac [Link]

E:\basic pgms>java Abs1

cse

12345

chennai

sathaybama

Using final with inheritance:

 To disallow a method from being overridden, specify final as a modifier at the start of its
declaration.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


27

 Methods declared as final cannot be overridden.

To implement final in three ways

[Link] Class

[Link] method

[Link] variable

Ex:

final class finalex


{
final int i=10;
}
class inherit extends finalex
{
void display()
{
[Link](i);
}
public static void main(String[] args)
{
inherit fx=new inherit();
[Link]();
}
}

E:\basic pgms>javac [Link]


[Link]: error: cannot inherit from final finalex

class inherit extends finalex

1 error

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


28

Unit -II

Interfaces , Packages & Exception Handling

Interface-Defining an interface-Implementing interfaces-Extending interfaces.

Packages-Defining a package -Importing packages-Access protection.

Exception Handling – Fundamentals-Types- Using Try and Catch- Multiple Catch


clauses-throw-throws-finally.

Interface:

 To acheive the multiple and hybrid inheritance, interfaces are used.


 interface can specify what a class must do, but not how it does it.
 Interfaces are syntactically similar to classes, but they lack instance variables,and their
methods are declared without any body.
 Once it is defined, any number of classes can implement an interface. Also, one class
 can implement any number of interfaces.
 By providing the interface keyword, Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism.

Defining an Interface:

 An interface is defined much like a class.

This is the general form of an interface:

access interface name {

return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

type final-varname1 = value;

type final-varname2 = value;

// ...

return-type method-nameN(parameter-list);

type final-varnameN = value;

Rules for defining an inteface

 Access is public, an interface can be used by any other code.


 The methods which are declared have no bodies(abstract methods)
 Variables can be declared inside of interface declarations.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


29

 They are impicitly final and static means they cannot be changed by the implemented
class.
 They must be initalized with a constant value.

Ex:

interface student

void display();

Implementing interfaces

 Once an interface has been defined, one or more classes can implement that interface.
 To implement an interface, include the implements clause in a class definition, and
then create the methods defined by the interface.

Ex:

interface student
{
int i=10;
public void display(String s);
}
class A implements student
{
public void display(String s)
{
if(i%2==0)
{
[Link]("My first interface"+s);
[Link]("i is even:"+i);
}
}
}
class interfaceex
{
public static void main(String[] args)
{
A a1=new A();
[Link]("student");
}}

E:\basic pgms\unit ii>javac [Link]


E:\basic pgms\unit ii>java interfaceex

My first interfacestudent

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


30

i is even:10

Extending interfaces

One interface can inherit another by use of the keyword extends.

EX:

interface A {
void meth1();
void meth2();
}

interface B extends A {
void meth3();
}

class MyClass implements B {


public void meth1() {
[Link]("Implement meth1().");
}
public void meth2() {
[Link]("Implement meth2().");
}
public void meth3() {
[Link]("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

E:\basic pgms\unit ii>javac [Link]


E:\basic pgms\unit ii>java IFExtend

Implement meth1().

Implement meth2().

Implement meth3().

Imlement Multiple Inheritance through Interface

Ex:

interface area

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


31

{
final static float pi=3.14F;
float compute(float x,float y);
}
class rectangle implements area
{
public float compute(float x,float y)
{
return(x*y);
}
}
class circle implements area
{
public float compute(float x,float y)
{
return(pi*x*x);
}
}
public class Interface1 {
public static void main(String[] args) {
rectangle rect=new rectangle();
circle c=new circle();
area a;
a=rect;
[Link]("area of rectangle"+[Link](10,20));
a=c;
[Link]("area of circle"+[Link](10,0));
}
}

output:
area of rectangle200.0

area of circle314.0

Packages:

 A java package is a group of similar types of classes, interfaces and sub-packages.


 Package in java can be categorized in two form, built-in package and user-defined
package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.

Advantage of Java Package

1. Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2. Java package provides access protection.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


32

3. Java package removes naming collision.

Defining a package:

 To create a package is quite easy.


 simply include a package command as the first as the first statement in a Java source
file.

This is the general form of the package statement:

package pack;
Here, pack is the name of the package.

Conditions for Create a package

 pack must be stored in a directory called pack.


 Remember that case is significant, and the directory name must match the package
name exactly.
 Create a .java file and stored under the pack [Link] can create many different
.java files and stored under the pack directory.

Simple package example

package pack;
public class a
{
public void msg()
{
[Link]("welcome");
}
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


33

Importing packages

 Java includes the import statement to bring certain classes, or entire packages, into
visibility.
 Once imported, a class can be referred to directly, using only its name. The import
statement is a convenience to the programmer and is not technically needed to write a
complete Java program.
 In a Java source file, import statements occur immediately following the package
 statement (if it exists) and before any class definitions.

This is the general form of the import statement:

import packagename.*;
or
import [Link];

Ex:

import pack.*; (or) import pack.a;

Importing the package 'pack'

import pack.*;
public class calculator
{
public static void main(String args[])
{
a a1=new a();
[Link]();

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


34

}}

Condition to save '[Link]' file


 Don't save [Link] under 'pack' folder.
 To store the [Link] in outside of the 'pack' folder.
 Make sure '[Link]' and 'pack' is in the same Drive("E: (or) c: (or) d:")

How to RUN the Package

[Link] need to run the package.

[Link] the .java file which imported the package.

E:\javapgms>javac [Link]

E:\javapgms>java calculator

welcome

Access Two Package in a single class:

[Link] a package 'pack'.

[Link] a file '[Link]' and stored under 'pack'.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


35

package pack;
public class a
{
public void msg()
{
[Link]("welcome");
}
}

[Link] a package 'mypack'


[Link] class 'arith' and stored under 'mypack'

package mypack;
import [Link].*;
public class arith
{
public void cal()
{
int a,b,c;
Scanner sr=new Scanner([Link]);
[Link]("enter the value of a");
a=[Link]();
[Link]("enter the value of b");
b=[Link]();
c=a+b;
[Link]("Addition:"+c);
c=a-b;
[Link]("Subtraction:"+c);
c=a*b;
[Link]("Multipliction:"+c);
c=a/b;
[Link]("Division:"+c);
}
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


36

Create a class'calculator' to access the package 'pack' and 'mypack'

import pack.*;
import mypack.*;
public class calculator
{
public static void main(String args[])
{
a a1=new a();
arith ar=new arith();
[Link]();
[Link]();
}
}

E:\javapgms>javac [Link]
E:\javapgms>java calculator

welcome

enter the value of a

10

enter the value of b

20

Addition:30

Subtraction:-10

Multipliction:200

Division:0

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


37

Access protection

 Classes and packages are both means of encapsulating and containing the name space
and scope of variables and methods.
 Packages act as containers for classes and other subordinate packages
 Classes act as containers for data and code.

In packages, Java addresses four categories of visibility for class members:

 Subclasses in the same package


 Non-subclasses in the same package
 Subclasses in different packages
 Classes that are neither in the same package nor subclasses

The three access specifiers, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories.

Private No modifier Protected Public

Same class Yes Yes Yes Yes

Same package No Yes Yes Yes


Subclass

Same package No Yes Yes Yes


non-subclass

Subclass No No Yes Yes


Different
Package subclass

Different No No No Yes
package
non-subclass

Ex:

Private:

In 'pack' 'class a' and 'void msg' declared as private.

package pack;
class a
{
void msg()
{
[Link]("welcome");

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


38

}
}

E:\javapgms>javac [Link]
[Link]: error: a is not public in pack; cannot be accessed from outside
package

a a1=new a();

[Link]: error: a is not public in pack; cannot be accessed from outside


package

a a1=new a();

2 errors

Protected:

package pack;
protected class a
{
protected void msg()
{
[Link]("welcome");
}
}

E:\javapgms>javac [Link]
.\pack\[Link]: error: modifier protected not allowed here

protected class a

[Link]: error: a is not public in pack; cannot be accessed from outsi

de package

a a1=new a();

[Link]: error: a is not public in pack; cannot be accessed from outsi

de package

a a1=new a();

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


39

3 errors

Exception Handling in java

The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.

Exception

Exception is an abnormal [Link] java, exception is an event that disrupts the


normal flow of the program. It is an object which is thrown at runtime.

Exception handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound,


IO, SQL,Remote etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application.

Exception normally disrupts the normal flow of the application that is why we use exception

handling. Let's take a scenario:

1. statement 1;

2. statement 2;

3. statement 3;

4. statement 4;

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


40

5. statement 5;//exception occurs

6. statement 6;

7. statement 7;

8. statement 8;

9. statement 9;

10. statement 10;

Suppose there is 10 statements in your program and there occurs an exception at

statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we

perform exception handling, rest of the statement will be executed. That is why we use
exception

handling in java.

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types of
exceptions:

1. Checked Exception

2. Unchecked Exception

3. Error

Difference between checked and unchecked exceptions

1) Checked Exception

The classes that extend Throwable class except Runtime Exception and Error are known as

checked exceptions [Link], SQLException etc. Checked exceptions are checked at

compile-time.

2) Unchecked Exception

The classes that extend Runtime Exception are known as unchecked exceptions e.g. Arithmetic

Exception, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions

are not checked at compile-time rather they are checked at runtime.

3) Error

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


41

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, Assertion Error etc.

Common scenarios where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where Arithmetic Exception occurs

If we divide any number by zero, there occurs an Arithmetic Exception.

1. int a=50/0;//Arithmetic Exception

2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs
an NullPointerException.

1. String s=null;

2. [Link]([Link]());//NullPointerException

3) Scenario where NumberFormatException occurs

The wrong formatting of any value may occur NumberFormatException. Suppose I


have a string variable that has characters, converting this variable into digit will occur

NumberFormatException.

1. String s="abc";

2. int i=[Link](s);//NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result

ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];

2. a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

1. try

2. catch

3. finally

4. throw

5. throws

Java try block

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


42

Java try block is used to enclose the code that might throw an exception. It must be
used within the method.

Java try block must be followed by either catch or finally block.

Syntax of java try-catch

try

//code that may throw exception

catch(Exception_class_Name ref)

{}

Syntax of try-finally block

try

//code that may throw exception

finally{}

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block
[Link] can use multiple catch block with a single try.

Problem without exception handling

public class Testtrycatch1


{
public static void main(String args[]
{
int data=50/0;//may throw exception
[Link]("rest of the code...");
}
}

Output:
Exception in thread main [Link]:/ by zero

As displayed in the above example, rest of the code is not executed (in such case, rest of the

code... statement is not printed).

There can be 100 lines of code after exception. So all the code after exception will not be

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


43

executed.

Solution by exception handling

Ex:(with try catch block)

public class Testtrycatch2


{
public static void main(String args[])
{
try
{
int data=50/0;
}
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code...");
}
}

Output:

Exception in thread main [Link]:/ by zero

rest of the code...

Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...

statement is printed.

Java catch multiple exceptions

Java Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use
java multicatch block.

Ex.

public class TestMultipleCatchBlock


{
public static void main(String args[])
{

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


44

try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){[Link]("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("task 2 compltd");
}
catch(Exception e){[Link]("common task completed");}
[Link]("rest of the code...");
}
}

Output:task1 completed
rest of the code...

Rules

 At a time only one Exception is occured and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .

class TestMultipleCatchBlock1
{
public static void main(String args[])
{
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){[Link]("common task completed");}
catch(ArithmeticException e){[Link]("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){[Link]("task 2 completed");}
[Link]("rest of the code...");
}
}

Nested try block


The try block within a try block is known as nested try block in java.

Need of nested try block

 Sometimes a situation may arise where a part of a block may cause one error and the
entire block
 itself may cause another error. In such cases, exception handlers have to be nested.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


45

Syntax:

try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}

Java nested try example


class Excep6
{
public static void main(String args[])
{
Try
{
Try
{
[Link]("going to divide");
int b =39/0;
}catch(ArithmeticException e){[Link](e);
}
Try
{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){[Link](e);}
[Link]("other statement);
}catch(Exception e){[Link]("handeled");}
Syste [Link]("normal flow..");
}
}

finally block

 It is a block that is used to execute important code such as closing connection,stream


etc.
 Java finally block is always executed whether exception is handled or not.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


46

 Java finally block must be followed by try or catch block.


 If you don‟t handle exception before terminating the program, JVM executes finally
block(if
 any)

Need of finally

Finally block in java can be used to put "cleanup" code such as closing a file, closing

connection etc.

Usage of Java finally

Case 1

class TestFinallyBlock
{
public static void main(String args[])
{
Try
{
int data=25/5;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always executed");}
[Link]("rest of the code...");
}
}
Output:5

finally block is always executed

rest of the code...

Case 2

class TestFinallyBlock1
{
public static void main(String args[])
{
Try
{
int data=25/0;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always executed");}
[Link]("rest of the code...");
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


47

Output:finally block is always executed


Exception in thread main [Link]:/ by zero

Case 3

public class TestFinallyBlock2


{
public static void main(String args[])
{
Try
{
int data=25/0;
[Link](data);
}
catch(ArithmeticException e){[Link](e);}
finally{[Link]("finally block is always executed");}
[Link]("rest of the code...");
}
}

Output:Exception in thread main [Link]:/ by zero


finally block is always executed

rest of the code...

For each try block there can be zero or more catch blocks, but only one finally block. The

finally block will not be executed if program exits(either by calling [Link]() or by causing a

fatal error that causes the process to abort).

throw exception

throw keyword

 The Java throw keyword is used to explicitly throw an exception.


 We can throw either checked or uncheked exception in java by throw keyword.
 The throw keyword is mainly used to throw custom exception.

The syntax of java throw keyword is given below.

1. throw exception;

Ex of throw IOException.

1. throw new IOException("sorry device error);

java throw keyword example

In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


48

public class TestThrow1


{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[])
{
validate(13);
[Link]("rest of the code...");
}
}

Output:
Exception in thread main [Link]:not valid

throws keyword

 The Java throws keyword is used to declare an exception.


 It gives an information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that normal flow
can be maintained.
 Exception Handling is mainly used to handle the checked exceptions.
 If there occurs any unchecked exception such as NullPointerException, it is programmers
fault that he is not performing check up before the code being used.

Syntax of throws

return_type method_name() throws exception_class_name

//method code

Which exception should be declared

checked exception only, because:

• unchecked Exception: under your control so correct your code.

• error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of throws keyword

 Now Checked Exception can be propagated (forwarded in call stack).


 It provides information to the caller of the method about the exception.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


49

import [Link];
class Testthrows1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
Try
{
n();
}catch(Exception e){[Link]("exception handled");}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
[Link]("normal flow...");
}
}

There are two cases:

 Case1:You caught the exception i.e. handle the exception using try/catch.
 Case2:You declare the exception i.e. specifying throws with the method.

Case1: You handle the exception

In case you handle the exception, the code will be executed fine whether exception

occurs during the program or not

import [Link].*;
class M
{
void method()throws IOException
{
throw new IOException("device error");
}
}
public class Testthrows2
{

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


50

public static void main(String args[])


{
try
{
M m=new M();
[Link]();
}
catch(Exception e)
{
[Link]("exception handled");
}
[Link]("normal flow...");
}
}

Output:exception handled
normal flow...

Case2: You declare the exception

 In case you declare the exception, if exception does not occur, the code will be
executed fine.
 In case you declare the exception if exception occures, an exception will be thrown at
runtime because throws does not handle the exception.

A)Program if exception does not occur

import [Link].*;
class M
{
void method()throws IOException
{
[Link]("device operation performed");
}
}
class Testthrows3
{
public static void main(String args[])throws IOException
{//declare exception
M m=new M();
[Link]();
[Link]("normal flow...");
}
}

Output:device operation performed


normal flow...

B)Program if exception occurs

import [Link].*;

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


51

class M
{
void method()throws IOException
{
throw new IOException("device error");
}
}
class Testthrows4
{
public static void main(String args[])throws IOException
{//declare exception
M m=new M();
[Link]();
[Link]("normal flow...");
}
}

Output:Runtime Exception
Difference between throw and throws

No. throw throws

1) Java throw keyword is used to explicitly throw an exception.

Java throws keyword is used to declare an exception.

2) Checked exception cannot be propagated using throw only. Checked exception can be
propagated with throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method signature.

5) You cannot throw multiple exceptions. You can declare Multiple

Exceptions

public void method()throws IOException,

Que) Can we rethrow an exception?

Yes, by throwing same exception in catch block.

throw example

void m()

throw new ArithmeticException("sorry");

Java throws example

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


52

void m()throws ArithmeticException

//method code

Java throw and throws example

void m()throws ArithmeticException

throw new ArithmeticException("sorry");

Difference between final, finally and finalize

There are many differences between final, finally and finalize. A list of differences between

final, finally and finalize are given below:

No. Final finally finalize

1) Final is used to apply restrictions on class, method and variable. Final classcan't be inherited,
final method can't be overridden and final variable value can't be changed.

Finally is used to place important code, it will be executed whether exception is handled or

not.

Finalize is used to perform clean up processing just before object is garbage collected.

2) Final is a keyword. Finally is a block. Finalize is a method.

Java final example

class FinalExample
{
public static void main(String[] args)
{
final int x=100;
x=200;//Compile Time Error
}
}

Java finally example

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


53

class FinallyExample
{
public static void main(String[] args)
{
Try
{
int x=300;
}
catch(Exception e){[Link](e);}
finally{[Link]("finally block is executed");}
}
}

Java finalize example

class FinalizeExample
{
public void finalize()
{
[Link]("finalize called");
}
public static void main(String[] args)
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
[Link]();
}
}

ExceptionHandling with MethodOverriding in Java

There are many rules if we talk about methodoverriding with exception handling.

The Rules are as follows:

 If the superclass method does not declare an exception


 If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but it can declare unchecked exception.
 If the superclass method declares an exception
 If the superclass method declares an exception, subclass overridden method can declare
same, subclass exception or no exception but cannot declare parent exception.
 If the superclass method does not declare an exception.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


54

Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception.

import [Link].*;
class Parent
{
void msg(){[Link]("parent");}
}
class TestExceptionChild extends Parent
{
void msg()throws IOException
{
[Link]("TestExceptionChild");
}
public static void main(String args[])
{
Parent p=new TestExceptionChild();
[Link]();
}
}

Output:Compile Time Error

Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.

import [Link].*;
class Parent
{
void msg(){[Link]("parent");}
}
class TestExceptionChild1 extends Parent
{
void msg()throws ArithmeticException
{
[Link]("child");
}
public static void main(String args[])
{
Parent p=new TestExceptionChild1();
[Link]();
}
}

Output:child
If the superclass method declares an exception

Rule: If the superclass method declares an exception, subclass overridden method can declare

same, subclass exception or no exception but cannot declare parent exception.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


55

Example in case subclass overridden method declares parent exception

import [Link].*;
class Parent
{
void msg()throws ArithmeticException{[Link]("parent");}
}
class TestExceptionChild2 extends Parent
{
void msg()throws Exception{[Link]("child");}
public static void main(String args[])
{
Parent p=new TestExceptionChild2();
Try
{
[Link]();
}catch(Exception e){}
}
}

Output:Compile Time Error

Example in case subclass overridden method declares same exception

import [Link].*;
class Parent
{
void msg()throws Exception{[Link]("parent");}
}
class TestExceptionChild3 extends Parent
{
void msg()throws Exception{[Link]("child");}
public static void main(String args[])
{
Parent p=new TestExceptionChild3();
Try
{
[Link]();
}catch(Exception e){}
}
}

Output:child

Example in case subclass overridden method declares subclass exception

import [Link].*;
class Parent
{

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


56

void msg()throws Exception{[Link]("parent");}


}
class TestExceptionChild4 extends Parent
{
void msg()throws ArithmeticException{[Link]("child");}
public static void main(String args[])
{
Parent p=new TestExceptionChild4();
Try
{
[Link]();
}catch(Exception e){}
}
}

Output:child

Example in case subclass overridden method declares no exception

import [Link].*;
class Parent
{
void msg()throws Exception{[Link]("parent");}
}
class TestExceptionChild5 extends Parent
{
void msg(){[Link]("child");}
public static void main(String args[])
{
Parent p=new TestExceptionChild5();
Try
{
[Link]();
}catch(Exception e){}
}
}
Output:child

UNIT 3

Multi Threading & IO Streams

Multi Threading - Introduction – Life Cycle of Thread-Creating and Running Threads-Methods


in Thread Class-Setting the Priority of a Thread-Synchronization.

IO Streams - Introduction – Wrapper Classes- Text and Binary formats of Data – Input Stream
and Output Stream classes- Reader and Writer Classes –Data Output Stream and Data Input
Stream classes.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


57

Multi Threading

Multi threading is a program control. In this the program is divided into two or more
independent subprograms called threads and are processed Parallely. Every program has
atleast one thread.

In single processor system, multiple threads share the cpu time. This is achieved
because a thread does not always need the cpu. That is, it might have to wait for user input or
it might have to display something on the screen. During this time other threads take over the
cpu. The previous thread can resume after the current thread comes out of the cpu.

The O/S is resposible for scheduled and allocating resources for threads.

Advantages of threads

1. it increases the speed of the execution


2. it allows to run more tasks simultaneously
3. it reduces the complexity of the large programs
4. it maximize cpu utilization

LIFE CYCLE OF THREAD

While using thread it enters into the following states.

1. Newborn state

2. Runmode state

3. Running state

4. Blocked state

5. Dead State

I) Newborn State:

At once the thread object is created for the defined thread a new thread is born. This
state of thread is called new born state.

from this state the new born thread can go to any one of the following state

a) Runmode State

b) Dead State.

if start() is called it goes to runmode [Link] stop() is called i goes to dead state.

Multi threading is a program control. In this the program is divided into two or more
independent subprograms called threads and are processed Parallely. Every program has
atleast one thread.

In single processor system, multiple threads share the cpu time. This is achieved
because a thread does not always need the cpu. That is, it might have to wait for user input or

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


58

it might have to display something on the screen. During this time other threads take over the
cpu. The previous thread can resume after the current thread comes out of the cpu.

The O/S is resposible for scheduled and allocating resources for threads.

Advantages of threads

 it increases the speed of the execution


 it allows to run more tasks simultaneously
 it reduces the complexity of the large programs
 it maximize cpu utilization

LIFE CYCLE OF THREAD

While using thread it enters into the following states.

1. Newborn state
2. Runmode state
3. Running state
4. Blocked state
5. Dead State

I) Newborn State:

At once the thread object is created for the defined thread a new thread is born. This
state of thread is called new born state.

From this state the new born thread can go to any one of the following state

Runmode State

Dead State.

if start() is called it goes to runmode [Link] stop() is called i goes to dead state.

New Sleep
done,I/Ocomplete,lock
available,resume,notify
start()

Runnable
SCS1209 - JAVA PROGRAMMING Prepared by [Link]
Non-Runnable
59

Creating a Thread
In the most general sense, you create a thread by instantiating an object of type
Thread.

Java defines two ways in which this can be accomplished:


 You can extend the Thread class, itself.
 You can implement the Runnable interface.

Create a Thread using Thread class


 To create a new class that extends Thread,and then to create an instance of that class.
 The extending class must override the run( ) method, which is the entry point for the
new thread
Ex:
class firstthread extends Thread
{
public void run()
{
}}
 call start( ) to begin execution of the new thread.

Ex:
class two extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{

[Link](i+"*2="+(i*2));
}
}
}
class three extends Thread
{

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


60

public void run()


{
for(int i=1;i<=5;i++)
{
[Link](i+"*3="+(i*3));

}
}
}
class wel extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link]("welcome");
} }}
public class Thread1 {
public static void main(String[] args) {
two t1=new two();
three f1=new three();
wel w1=new wel();
[Link]();
[Link]();
[Link]();
}}

E:\basic pgms\unit iii>javac [Link]


E:\basic pgms\unit iii>java Thread1
1*2=2
2*2=4
3*2=6
4*2=8
5*2=10
welcome
welcome
welcome
welcome
welcome
1*3=3
2*3=6
3*3=9
4*3=12
5*3=15
Output order is not same. Different compile time you can get different output.
Using Thread Methods Stop() and yield()

Ex:
class maths extends Thread
{

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


61

public void run()


{
for(int i=1;i<6;i++)
{
if(i==2) stop();
{
[Link]("maths score is:"+i);
}
}
}
}
class science extends Thread
{
public void run()
{
for(int i=1;i<6;i++)
{
if(i==3) yield();
{
[Link]("science score is:"+i);
}}}}
class subthread
{
public static void main(String args[])
{
maths ma=new maths();
science sc=new science();
[Link]();
[Link]();
}}

E:\javapgms>javac [Link]
Note: [Link] uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
E:\javapgms>java subthread

science score is:1


science score is:2
science score is:3
maths score is:1
science score is:4
science score is:5

Imlementing Runnable Interface

 To create a new class that implements Runnable,and then to create an instance of that
class.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


62

 The extending class must override the run( ) method, which is the entry point for the
new thread

Ex:
class firstthread implements Runnable
{
public void run()
{
}}
 Use Thread () to create a object for Thread class. In this to pass the object
of each class.
 Use strart() to start execution.
Ex:
class two implements Runnable{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link](i+"*2="+(i*2));
} }}
class three implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link](i+"*3="+(i*3));
} }}
class wel implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link]("welcome");
} }}
public class Runnablethread {
public static void main(String[] args) {
two t1=new two();
Thread t=new Thread(t1);
[Link]();
three f1=new three();
Thread th=new Thread(f1);
[Link]();
wel w1=new wel();
Thread th2=new Thread(w1);
[Link](); }}

E:\basic pgms\unit iii>javac [Link]


E:\basic pgms\unit iii>java Runnablethread

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


63

1*2=2
2*2=4
3*2=6
4*2=8
5*2=10
1*3=3
2*3=6
3*3=9
4*3=12
5*3=15
welcome
welcome
welcome
welcome
welcome

Setting the Priority of a Thread:


 Thread priorities are used by the thread scheduler to decide when each thread should
be allowed to run.
 higher-priority threads get more CPU time than lower priority threads.
 A higher-priority thread can also preempt a lower-priority one.

Metohds:

setPriority( ):

To set a thread‟s priority, use the setPriority( ) method, which is a member


of Thread.

This is its general form:

final void setPriority(int level)

The value of level must be within the range


MIN_PRIORITY
MAX_PRIORITY
These values are 1 and 10, respectively.
To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These
priorities are defined as final variables within Thread.

getPriority( ):
You can obtain the current priority setting by calling the getPriority( ) method of
Thread, shown here:
final int getPriority( )

EX:

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


64

public class Thprioity extends Thread {


public void run()
{
[Link]([Link]().getPriority());
}
public static void main(String[] args) {
Thprioity obj=new Thprioity();
Thprioity obj1=new Thprioity();
Thprioity obj2=new Thprioity();
[Link](Thread.MIN_PRIORITY);
[Link](5);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
[Link]();
} }
E:\basic pgms\unit iii>javac [Link]
E:\basic pgms\unit iii>java Thprioity
1
10
5

Synchronization.

When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization.

Types of Synchronization

There are two types of synchronization


1. Process Synchronization
2. Thread Synchronization

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


65

Ex:
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}}
Output: 5
100
10
200
15
300
20
400
25
500

Java synchronized method

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


66

 If you declare any method as synchronized, it is known as synchronized method.


 Synchronized method is used to lock an object for any shared resource.
 When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.

class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}

}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
}
}

public class TestSynchronization2{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}
Output: 5
10
15
20
25

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


67

100
200
300
400
500

IO Streams
 Console based I/O is easier for simple programs only.
 Console based I/O is not suitable for application oriented programs which uses AWT.
 So, Java does provide the strong ,flexible I/O which is related to file and networks

STREAMS
 Java programs perform I/O through streams.
 A stream is an abstraction that either produces or consumes information.
 A stream is linked to a physical device by the Java I/O system
 Java implements streams within class hierarchies defined in the [Link] package.

Types of Streams

STREAMS

 Java programs perform

Byte Stream I/O through streams. Character Stream

 A stream is an

abstraction that either


Input Stream Output Stream Reader Writer
produces or consumes
Byte Stream information.
 Byte streams are used reading or writing binary data.
 At the lowest level, all I/O isstillA byte-oriented.
stream is linked to a
Character Stream
physical device by the
 Character streams provide a convenient means for handling input and output of
characters.
Java I/O system
 The character-based streams simply provide a convenient and efficient means for
handling characters.
 Java implements streams
 In some cases, character streams are more efficient than byte streams.
within class hierarchies
INPUT STREAM
It is for streaming byte input .
defined in the [Link]

package.
Method Description

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


68

int available( ) Returns the number of bytes of available in


the file for reading.

void close( ) Closes the input source. Further read


attempts will generate an IOException.

void mark(int numBytes) Places a mark at the current point in the input
stream that will remain valid until numBytes
bytes are read.

boolean markSupported( ) Returns true if mark( )/reset( ) are supported


by the invoking stream.

int read( ) Returns an integer representation of the next


available byte of input. –1 is returned when
the end of the file is encountered.
int read(byte buffer[ ]) Attempts to read up to [Link] bytes
into buffer and returns the actual number of
bytes that were successfully read. –1 is
returned when the end of the file is
encountered.
int read(byte buffer[ ], int offset, Attempts to read up to numBytes bytes into
int numBytes) buffer starting at buffer[offset], returning the
number of bytes successfully read. –1 is
returned when the end of the file is
encountered.
void reset( ) Resets the input pointer to the previously
set mark.

long skip(long numBytes Ignores (that is, skips) numBytes bytes of


input,
returning the number of bytes actually
ignored

import [Link].*; [Link](10);


class filedemo for(int i=0;i<10;i++)
{ {
public static void main(String args[]) [Link]((char) [Link]());
{ }
try [Link]();
{ }
int size,n; catch(Exception e)
InputStream is=new {
FileInputStream("e:/javapgms/filein [Link]"); [Link](e);
[Link](" file is available"); }
size=[Link](); }
[Link](size); }

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


69

Input :
[Link] a file “[Link]” with a following content.
[Link] the file in the same directory of program file([Link])

E:\javapgms>javac [Link]

E:\javapgms>java filedemo
file is available
97
h
a
i
.

a
m

Program for int read(byte buffer[ ])

import [Link].*;
class filedemo1
{
public static void main(String args[]) throws Exception
{
SCS1209 - JAVA PROGRAMMING Prepared by [Link]
70

int n,i;
char c;
InputStream in=new FileInputStream("e:/javapgms/[Link]");
n=[Link]();
byte[] buffer=new byte[n];
[Link](buffer);
for(byte b:buffer)
{
c=(char) b;
[Link](c);
}
}
}

Example :
Input File stored as [Link]

E:\javapgms>java filedemo1
hai.
i am maheswari saravanan.
i am working as a assistant professor in Sathyabama university.

Program for int read(byte buffer[ ], int offset,int numBytes)

Offset:starting place of the character to print


Numbytes:how many bytes to print
Ex:
import [Link].*;
class filedemo1
{
public static void main(String args[]) throws Exception
{
int n,i;

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


71

char c;
InputStream in=new FileInputStream("e:/javapgms/[Link]");
n=[Link]();
byte[] buffer=new byte[n];
[Link](buffer,5,n-5);
for(byte b:buffer)
{
c=(char) b;
[Link](c);
}
}
}
Example :
Input File stored as [Link]

E:\javapgms>javac [Link]

E:\javapgms>java filedemo1
hai.
i am maheswari saravanan.
i am working as a assistant professor in Sathyabama univers

OUTPUT STREAM

OutputStream is an abstract class that defines streaming byte output

Method Description

void close( ) Closes the output stream. Further write attempts will generate
an IOException.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


72

void flush( ) Finalizes the output state so that any buffers are cleared. That
is, it flushes the output buffers..

void write(int b) Writes a single byte to an output [Link] that the parameter
is an int, which allows you to call write( ) with
expressionswithout having to cast them back to byte.
void write(byte Writes a complete array of bytes to an output
buffer[ ]) stream.

void write(byte Writes a subrange of numBytes bytes from the array buffer,
buffer[ ], int beginning at buffer[offset].
offset,int
numBytes)

Ex:

import [Link].*;
import [Link].*;
class fileout1
{
public static void main(String args[])throws Exception
{
String st;
byte[] b=new byte[10];
Scanner s=new Scanner([Link]);
[Link]("enter a string");
st=[Link]();
b=[Link]();
[Link]("the lengh of the string is:"+[Link]);
OutputStream im=new FileOutputStream("[Link]");
[Link](b);
[Link]();
}
}

INPUT
1. Open cmd
2. Run the program using javac and java
3. Give the input

E:\javapgms>javac [Link]

E:\javapgms>java fileout1
enter a string
sathyabama
the lengh of the string is:10

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


73

Output:

[Link] the output file '[Link]'

Program for void write(byte buffer[ ])

Ex:
import [Link].*;
import [Link].*;
class fileout
{
public static void main(String args[])throws Exception
{
String[] st=new String[10];
byte[][] b=new byte[20][20];
Scanner s=new Scanner([Link]);
[Link]("enter a string");
for(int i=0;i<[Link];i++)
{
st[i]=[Link]();
}
for(int i=0;i<[Link];i++)
{
b[i]=st[i].getBytes();
}
OutputStream im=new FileOutputStream("[Link]");
for(int i=0;i<[Link];i++)
{
[Link](b[i]);

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


74

[Link]('\t ');
}
[Link]();
}
}

Input:
E:\javapgms>javac [Link]

E:\javapgms>java fileout
enter a string
hai
Siststudents
Staysafe
eatwell
Washhands
keepklean
Maintainsocialdistance
drinkWater
Doyoga
runoutcorona

Output:
[Link] the file '[Link]'

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


75

CHARACTER STREAM
 While the byte stream classes provide sufficient functionality to handle any
type of I/O operation, they cannot work directly with Unicode characters.
 Since one of the main purposes of Java is to support the “write once, run
anywhere” philosophy, it was necessary to include direct I/O support for characters.
Reader
Reader is an abstract class that defines Java‟s model of streaming character input. All of the
methods in this class will throw an IOException on error conditions.

Writer
Writer is an abstract class that defines streaming character output. All of the methods in this
class return a void value and throw an IOException in the case of errors.
FileReader:
The FileReader class creates a Reader that you can use to read the contents of a file.
FileReader fr=new FIleReader(“filepath”);
Method Description

boolean ready( ) Returns true if the next input request will not
wait. Otherwise, it returns false.

void close( ) Closes the input source. Further read attempts will
generate an IOException.

void mark(int numBytes) Places a mark at the current point in the input
stream that will remain valid until numBytes
bytes are read.

boolean markSupported( ) Returns true if mark( )/reset( ) are supported by


the invoking stream.

int read( ) Returns an integer representation of the next available


byte of input. –1 is returned when the end of the file is
encountered.
int read(byte buffer[ ]) Attempts to read up to [Link] bytes into buffer
and returns the actual number of bytes that were
successfully read. –1 is returned
when the end of the file is encountered.
abstract int read(byte buffer[ ], int Attempts to read up to numBytes bytes into buffer
offset,int numBytes) starting at buffer[offset], returning the number of
bytes successfully read. –1 is returned when the end
of the file is encountered.
void reset( ) Resets the input pointer to the previously set mark.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


76

long skip(long numBytes Ignores (that is, skips) numBytes bytes of input,
returning the number of bytes actually ignored

Ex:

import [Link].*;
class FileReaderDemo {
public static void main(String args[]) throws Exception {
int ch;
FileReader fr = new FileReader("[Link]");
while((ch = [Link]()) !=-1)
{
[Link]((char)ch);
}
[Link]();
}
}

Input:

Output:

E:\javapgms>java FileReaderDemo
Sathyabama.
stay safe
i hope all are fine.

FILEWRITER
It is used to write the string or input to the file.
Method Description

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


77

void close( ) Closes the output stream. Further write attempts will generate an
IOException.

void flush( ) Finalizes the output state so that any buffers are cleared. That is, it
flushes the output buffers..

void write(int ch) Writes a single character to the invoking output stream. Note that the
parameter is an int, which allows you to call write with
expressions without having to cast them back to char.

void write(char buffer[ ]) Writes a complete array of characters to the invoking output stream.

abstract void write(char Writes a subrange of numChars characters from the array buffer,
buffer[ ],int offset,int beginning at buffer[offset] to the invoking output stream.
numChars)

void write(String str) Writes str to the invoking output stream.

void write(String str, int Writes a subrange of numChars characters from the array str,
offset, beginning at the specified offset.
int numChars)

Ex:
import [Link].*;
import [Link].*;
class FileWriterDemo {
public static void main(String args[]) throws Exception {
String source ;
Scanner s=new Scanner([Link]);
[Link]("Enter the string");
source=[Link]();
char buffer[] = new char[[Link]()];
[Link](0, [Link](), buffer, 0);
FileWriter f0 = new FileWriter("[Link]");
for (int i=0; i < [Link]; i =i+1) {
[Link](buffer[i]);
}
[Link]();
}

Input:

E:\javapgms>java filewriter
Enter the string
engineers

Output

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


78

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

int read(byte[] b) Reads some number of bytes from the contained


input stream and stores them into the buffer array b.

int read(byte[] b, int off, int Reads up to len bytes of data from the contained input
len) stream into an array of bytes.

readBoolean() Reads one input byte and returns true if that byte is
nonzero, false if that byte is zero.

readChar() Reads two input bytes and returns a char value

readDouble() Reads eight input bytes and returns a double value

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


79

readInt() Reads four input bytes and returns an int value

readLong() Reads 8 input bytes and returns a long value.

readShort() Reads 2 input bytes and returns a short value

Ex:

import [Link].*;
class DataOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
OutputStream os=new FileOutputStream("e:/javapgms/[Link]");
DataOutputStream dout = new DataOutputStream((os)) ;
[Link](10.28);
[Link](5);
[Link]('t');
[Link]('4');
DataInputStream din =
new DataInputStream(new FileInputStream("[Link]")) ;

Double a = [Link]();
int b = [Link]();
char c = [Link]();
char d=[Link]();
[Link]("Values: " + a + " " + b + " " + c+" " + d);
}
}

DATAOUTPUT STREAM
Method Description

writeBoolean(boolean v) Writes a boolean to the underlying output


stream as a 1-byte value.

writeByte(int v) Writes out a byte to the underlying output


stream as a 1-byte value.

writeBytes(String s) Writes out the string to the underlying output


stream as a sequence of bytes.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


80

writeChar(int v) Writes a char to the underlying output stream


as a 2-byte value, high byte first.

writeChars(String s) Writes a string to the underlying output


stream as a sequence of characters.

writeInt(int v) Writes an int to the underlying output stream


as four bytes, high byte first.

Input:

E:\javapgms>javac [Link]
E:\javapgms>java DataOutputStreamDemo
Values: 10.28 5 t 4

Output:

Wrapper class in Java


 Wrapper class in java provides the mechanism to convert primitive into object
and object into primitive.
 A wrapper class wraps (encloses) around a data type and gives it an object
appearance.
 Wherever, the data type is required as an object, this object can be used.
 Wrapper classes include methods to unwrap the object and give back the data
type.
Importance of Wrapper classes

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


81

There are mainly two uses with wrapper classes.


1. To convert simple data types into objects, that is, to give object form to a data type;
here constructors are used.
2. To convert strings into data types (known as parsing operations), here methods of
type parseXXX() are used.
One of the eight classes of [Link] package are known as wrapper class in java. The
list of eight wrapper classes are given below:

PRIMITIVE DATA TYPE WRAPPER CLASS

byte Byte
short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

public class WrappingUnwrapping


{
public static void main(String args[])
{ // data types
byte grade = 2;
int marks = 50;
float price = 8.6f; // observe a suffix of <strong>f</strong> for
float
double rate = 50.5;
// data types to objects
Byte g1 = new Byte(grade); // wrapping
Integer m1 = new Integer(marks);
Float f1 = new Float(price);
Double r1 = new Double(rate);
// let us print the values from objects
[Link]("Values of Wrapper objects (printing as objects)");
[Link]("Byte object g1: " + g1);
[Link]("Integer object m1: " + m1);
[Link]("Float object f1: " + f1);
[Link]("Double object r1: " + r1);
// objects to data types (retrieving data types from objects)
byte bv = [Link](); // unwrapping
int iv = [Link]();

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


82

float fv = [Link]();
double dv = [Link]();
// let us print the values from data types
[Link]("Unwrapped values (printing as data types)");
[Link]("byte value, bv: " + bv);
[Link]("int value, iv: " + iv);
[Link]("float value, fv: " + fv);
[Link]("double value, dv: " + dv);
}

Autoboxing and unboxing


it converts primitive into object and object into primitive automatically. The automatic
conversion of primitive into object is known and autoboxing and vice-versa unboxing.
Autoboxing :
It is a process by which primitive type is automatically encapsulated(boxed) into its
equivalent type wrapper
Auto-Unboxing
It is a process by which the value of object is automatically extracted from a type
wrapper.

Example of Autoboxing and Unboxing


Class test
{
public static void main(String args[])
{
Integer iob=100;
int i=iob;
[Link](i+””+iob);
Character cob=‟a‟;
char ch=cob;
[Link](cob+””+ch);
}
}

Benefits of Autoboxing and Unboxing


1. Autoboxing / Unboxing lets us use primitive types and Wrapper class objects
interchangeably.
2. We don't have to perform Explicit typecasting.
3. It helps prevent errors, but may lead to unexpected results sometimes. Hence must
be used with care.

Wrapper class Example: Primitive to Wrapper


public class WrapperExample1
{
public static void main(String args[])
{
int a=20;
Integer i=[Link](a);
Integer j=a;
[Link](a+" "+i+" "+j);

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


83

}
}
Output:
20 20 20

Wrapper class Example: Wrapper to Primitive


public class WrapperExample2
{
public static void main(String args[])
{
Integer a=new Integer(3);
int i=[Link]();//converting Integer to int
int j=a;//unboxing, now compiler will write [Link]() internally
[Link](a+" "+i+" "+j);
}
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


84

UNIT-IV

Event Handling & Applets

Event Handling – Delegation Event Model-Event Classes-Event Listener Interfaces-Handling


Mouse and Keyboard Events.
The Applet Class – Applet basics – Applet architecture – HTML APPLET tag – Passing
parameters to applets.

The Delegation Event Model

The delegation event model, which defines standard and consistent mechanisms to
generate and process events.

Concept of Delegation Event Model


 a source generates an event and sends it to one or more listeners
 the listener simply waits until it receives an event.
 Once received, the listener processes the event and then returns

EVENTS
 An event is an object that describes a state change in a source.
 It can be generated By the user interacting with the elements in a graphical user
interface.
Ex:
Direct Event: pressing a button, entering a character via the keyboard, selecting an item
in a list, and clicking the mouse

In-Direct Event:event may be generated when a timer expires, a counter exceeds a


value, a software or hardware failure occurs, or an operation is completed.

Event Sources:
 A source is an object that generates an event.
 A source must register listeners in order for the listeners to receive notifications
 about a specific type of event.
 Each type of event has its own registration method.

Here is the general form:

public void addTypeListener(TypeListener el)

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


85

Type - name of the event


el -reference to the event listener

Event Listeners
A listener is an object that is notified when an event occurs.

It has two major requirements.


1. it must have been registered with one or more sources to receive notifications
about specific types of events.
2. it must implement methods to receive and process these notifications.

Event Classes

Eventclass hierarchy

EventObject is the root of all Java event class hierarchy , which is in [Link].
It is the superclass for all events.

EvenObject

AWT Event Class

Subclasses of AWT Event Class

Event Class Description

ActionEvent Generated when a button is pressed, a list item is


double-clicked, or a menu item is selected.
AdjustmentEvent. Generated when a scroll bar is manipulated

ComponentEvent Generated when a component is hidden, moved, resized,


or becomes visible.
ContainerEvent Generated when a component is added to or removed
from a container.
FocusEvent Generated when a component gains or loses
keyboard focus.
InputEvent Abstract super class for all component input event classes.
.
ItemEvent Generated when a check box or list item is clicked; also
occurs when a choice selection is made or a checkable

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


86

menu item is selected or deselected


KeyEvent Generated when input is received from the keyboard.

MouseEvent Generated when the mouse is dragged, moved, clicked,


pressed, or released; also generated when the mouse enters
or exits a component.

MouseWheelEvent Generated when the mouse wheel is moved

TextEvent Generated when the value of a text area or text field is


changed.

WindowEvent Generated when a window is activated, closed, deactivated,


deiconified, iconified, opened, or quit
THE ACTIONEVENT CLASS

An ActionEvent is generated when a button is pressed, a list item is double-clicked,

or a menu item is selected.

Five integer constants of ActionEvent class

ALT_MASK,

CTRL_MASK,

META_MASK,

SHIFT_MASK.

ACTION_PERFORMED

Three constructors:

ActionEvent(Object src, int type, String cmd): src - reference to the object that generated
this event.
type - specify the type of the event
cmd- command string

ActionEvent(Object src, int type, String cmd, modifiers - which modifier keys (ALT, CTRL,
int modifiers) META, and/or SHIFT) were pressed when the
event was generated

ActionEvent(Object src, int type, String cmd, when -yes, when the event occurred.
long when, int modifiers)

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


87

Methods

String getActionCommand( ) when a button is pressed, an action event is generated that has
a command name equal to the label on that button
getModifiers( ) The method returns a value that indicates which modifier keys
(ALT, CTRL, META, and/or SHIFT) were pressed when the event
was generated

THE ADJUSTMENTEVENT CLASS:

An AdjustmentEvent is generated by a scroll bar

ADJUSTMENT EVENTS
BLOCK_DECREMENT The user clicked inside the scroll bar to decrease
its value.

BLOCK_INCREMENT The user clicked inside the scroll bar to increase


its value.

TRACK The slider was dragged.

UNIT_DECREMENT The button at the end of the scroll bar was clicked
to decrease its value
UNIT_INCREMENT The button at the end of the scroll bar was clicked
to increase its value.

Constructor:
AdjustmentEvent(Adjustable src, int id, int src - reference to the object that generated
type, int data) this event.
id -ADJUSTMENT_VALUE_CHANGED.
type - type of event data - data

METHODS

Adjustable getAdjustable( ) returns the object that generated the event

int getAdjustmentType( ) returns type of the adjustment event


int getValue( ) returns amount of the adjustment

THE COMPONENTEVENT CLASS

 A ComponentEvent is generated when the size, position, or visibility of a component


is changed.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


88

 ComponentEvent is the superclass either directly or indirectly of ContainerEvent,


FocusEvent, KeyEvent, MouseEvent, and WindowEvent.

COMPONENT EVENTS
COMPONENT_HIDDEN The component was hidden.

COMPONENT_MOVED The component was moved.

COMPONENT_RESIZED The component was resized.

COMPONENT_SHOWN The component became visible.

Constructor of ComponentEvent:

ComponentEvent(Component src, int type) src - reference to the object that generated
this event.
type - specified the type of event

Method

Component getComponent( ) returns the component that generated the event.

THE CONTAINEREVENT CLASS

It is generated when a component is added to or removed from a container.


ContainerEvent is a subclass of ComponentEvent

CONTAINEREVENT
COMPONENT_ADDED component has been added to the container
COMPONENT_REMOVED component has been removed from the container

Constructor:

ContainerEvent(Component src, int type, src - reference to the container that


Component comp) generated this event.
type - event type
component- added to or removed from the
container is comp.

METHODS

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


89

Container getContainer( ) You can obtain a reference to the container that generated
this event by using the method,
Component getChild( ) returns a reference to the component that was added to or
removed from the container

The FocusEvent Class


A FocusEvent is generated when a component gains or loses input focus.
Integer constants: FOCUS_GAINED and FOCUS_LOST.
FocusEvent is a subclass of ComponentEvent
Constructors:
FocusEvent(Component src, int type) src - reference to the component that
generated this event.
type -type of the event

FocusEvent(Component src, int type, boolean temporaryFlag - true if the focus event is
temporaryFlag) temporary
- False(A temporary focus
event occurs as a result of another user
interface operation)

Methods
Component getOppositeComponent( ) The opposite component is returned.

boolean isTemporary( ) indicates if this focus change is temporary.

THE INPUTEVENT CLASS


The abstract class InputEvent is a subclass of ComponentEvent and is the superclass
for component input events. Its subclasses are KeyEvent and MouseEvent.
Methods
boolean isAltDown( )

boolean isAltGraphDown( )

boolean isControlDown( )

boolean isMetaDown( )

boolean isShiftDown( )

int getModifiers( )

THE ITEMEVENT CLASS


An ItemEvent is generated when a check box or a list item is clicked or when a
checkable menu item is selected or deselected

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


90

ITEM EVENT CLASS


DESELECTED The user deselected an item
SELECTED The user selected an item

Integer Constant:
ITEM_STATE_CHANGED - signifies change of state.
Constructor:
ItemEvent(ItemSelectable src, int type, src - indicates the component that
Object entry, int state) generated this event.
type -specified by type.
entry-The specific item that generated the
item event is passed in entry.
State- The current state of that item.

METHODS
Object getItem( ) used to obtain a reference to the item that
generated an event.
ItemSelectable getItemSelectable( ) used to obtain a reference to the
ItemSelectable
object that generated an event.
int getStateChange( ) method returns the state change (i.e.,
SELECTED or DESELECTED) for the event

THE KEYEVENT CLASS


A KeyEvent is generated when keyboard input occurs.
integer constants:
KEY_PRESSED, key is pressed

KEY_RELEASED, and. key is released


KEY_TYPED occurs only when a character is generated.

VK_0 through VK_9 ASCII equivalents of the


Numbers
VK_A through VK_Z ASCII equivalents of the letters
VK_ENTER
VK_ESCAPE
VK_CANCEL The VK constants specify virtual key codes
VK_UP and are independent of any modifiers, such
as control, shift, or alt.
VK_DOWN
VK_LEFT
VK_CONTROL

VK_RIGHT
VK_PAGE_DOWN

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


91

VK_PAGE_UP
VK_SHIFT
VK_ALT

Constructors:
KeyEvent(Component src, int type, long src -reference to the component that
when, int modifiers, int code) generated the event.
type -specified type the type of the event.
when- specify the time at which the Key
event occurred
modifiers - indicates which modifiers were
pressed when a Key event occurred.
virtual key code - VK_UP, VK_A, and so forth,
is passed in code

KeyEvent(Component src, int type, long Ch- character equivalent (if one exists) is
when, int modifiers, int code, char ch) passed in ch.

Methods
char getKeyChar( ) returns the character that was entered
int getKeyCode( ) returns the key code

THE MOUSEEVENT CLASS


Integer constants
MOUSE_CLICKED The user clicked the mouse.

MOUSE_DRAGGED The user dragged the mouse.

MOUSE_ENTERED The mouse entered a component.

MOUSE_EXITED The mouse exited from a component.

MOUSE_MOVED The mouse moved.

MOUSE_PRESSED The mouse was pressed.

MOUSE_RELEASED The mouse was released.

MOUSE_WHEEL The mouse wheel was moved (Java 2, v1.4).

Constructors.
MouseEvent(Component src, int type, long src -reference to the component that
when, int modifiers, generated the event.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


92

int x, int y, int clicks, boolean triggersPopup) type -specified type the type of the event.
when- specify the time at which the mouse
event occurred
modifiers - indicates which modifiers were
pressed when a mouse
event occurred.
Coordinates- of the mouse are passed in x
and y.
Click- count is passed in clicks.
triggersPopup flag- indicates if this event
causes a pop-up menu to
appear on this platform.

Methods
int getX( ) return the X coordinates of the mouse when
the event occurred
int getY( ) return the Y coordinates of the mouse when
the event occurred
void translatePoint(int x, int y) changes the location of the event

int getClickCount( ) obtains the number of mouse clicks for this


event
boolean isPopupTrigger( ) The method tests if this event causes a pop-
up menu to appear on this platform
int getButton( ) It returns a value that represents the button
that caused the event

THE MOUSEWHEELEVENT CLASS


 The MouseWheelEvent class encapsulates a mouse wheel event.
 It is a subclass of MouseEvent
 If a mouse has a wheel, it is located between the left and right buttons.
 Mouse wheels are used for scrolling.
Integer constants.
WHEEL_BLOCK_SCROLL A page-up or page-down scroll event
occurred.
WHEEL_UNIT_SCROLL A line-up or line-down scroll event occurred.

Constructor
MouseWheelEvent(Component src, int type, src - reference to the object that generated
long when, int modifiers, the event
int x, int y, int clicks, boolean triggersPopup, type - type of the event
int scrollHow, int amount, int count) when - system time at which the mouse event
is occurred
modifiers - argument indicates which
modifiers were pressed when the event
occurred
coordinates-coordinates of the mouse are
passed in x and y

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


93

clicks - wheels rotation passed in the click.


triggersPopup- event
causes a pop-up menu to appear on this
platform
scrollHow- WHEEL_UNIT_SCROLL or
WHEEL_BLOCK_SCROLL
count - number of rotational units that
the wheel moved.

METHODS
int getWheelRotation( ) To obtain the number of rotational units, call
getWheelRotation( ),
int getScrollType( ) It returns either WHEEL_UNIT_SCROLL or
WHEEL_BLOCK_SCROLL.

int getScrollAmount( ) can obtain the number of units


to scroll

THE TEXTEVENT CLASS


 Instances of this class describe text events.
 These are generated by text fields and text areas when characters are entered by a
user or program.
Integerconstant
TEXT_VALUE_CHANGED.
Constructor
TextEvent(Object src, int type) src - reference to the object that generated
this event.
type - specified the event type

THE WINDOWEVENT CLASS


Integer Constants
WINDOW_ACTIVATED The window was activated.

WINDOW_CLOSED The window has been closed


WINDOW_CLOSING The user requested that the window
be closed.

WINDOW_DEACTIVATED The window was deactivated.

WINDOW_DEICONIFIED The window was deiconified.

WINDOW_GAINED_FOCUS The window gained input focus.

WINDOW_ICONIFIED The window was iconified.

WINDOW_LOST_FOCUS The window lost input focus

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


94

WINDOW_OPENED The window was opened.

WINDOW_STATE_CHANGED The state of the window changed.

Constructors.
WindowEvent(Window src, int type) src -reference to the object that generated
this event.
Type- event type.

WindowEvent(Window src, int type, Window Other- specifies the opposite window when a
other) focus event occurs

WindowEvent(Window src, int type, int fromState- specifies the prior state of the
fromState, int toState) window
toState- specifies the new state that the
window will have when a window state
change occurs.

WindowEvent(Window src, int type, Window


other, int fromState, int toState)

Methods
Window getWindow( ) It returns the
Window object that generated the event
int getOldState() returns the old state of the window

int getNewState() returns the new state of the window

EVENT LISTENER INTERFACES


Delegation event model has two parts:
[Link] :
Event Source Description
Button Generates action events when the button is pressed.

Checkbox Generates item events when the check box is selected or deselected.

Choice Generates item events when the choice is changed.

List Generates action events when an item is double-clicked; generates


item events when an item is selected or deselected.
Menu Item Generates action events when a menu item is selected; generates item
events when a checkable menu item is selected or deselected.
Scrollbar. Generates adjustment events when the scroll bar is manipulated.

Text components Generates text events when the user enters a character.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


95

Window Generates window events when a window is activated, closed,


deactivated, deiconified, iconifie d, opened, or quit.

[Link]
 Listeners are created by implementing one or more of the interfaces defined by the
[Link] package.
 When an event occurs, the event source invokes the appropriate method defined by
the listener and provides an event object as its argument.
.
ActionListener Defines one method to receive action events
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is
hidden, moved, resized, or shown.

ContainerListener Defines two methods to recognize when a component is


added to or removed from a container.

FocusListener Defines two methods to recognize when a component gains


or loses keyboard focus
ItemListener Defines one method to recognize when the state of an
item changes.

KeyListener Defines three methods to recognize when a key is pressed,


released, or typed.

MouseListener Defines five methods to recognize when the mouse is clicked,


enters a component, exits a component, is pressed, or is
released.

MouseMotionListener Defines two methods to recognize when the mouse is


dragged or moved
MouseWheelListener Defines one method to recognize when the mouse wheel is
moved.
TextListener Defines one method to recognize when a text value changes.

WindowFocusListener Defines two methods to recognize when a window gains or


loses input focus.
WindowListener Defines seven methods to recognize when a window is
activated, closed, deactivated, deiconified, iconified, opened,
or quit.

THE ACTIONLISTENER INTERFACE


METHODS General form
actionPerformed( ) the method that is void actionPerformed(ActionEvent ae)
invoked when an
action

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


96

event occurs

THE ADJUSTMENTLISTENER INTERFACE


METHODS General form
adjustmentValueChanged( ) is invoked when void adjustmentValueChanged(AdjustmentEvent
an adjustment ae)
event occurs

THE COMPONENTLISTENER INTERFACE


METHODS General form
componentResized invoked when a void componentResized(ComponentEvent ce)
component is resized

componentMoved() invoked when a void componentMoved(ComponentEvent ce)


component is moved
componentShown() invoked when a void componentShown(ComponentEvent ce)
component is shown
componentHidden() invoked when a void componentHidden(ComponentEvent ce)
component is hidden

THE CONTAINERLISTENER INTERFACE


METHODS General form
componentAdded( ) When a component is void componentAdded(ContainerEvent ce)
added to a container,
is invoked.
componentRemoved( ) When a component is void omponentRemoved(ContainerEvent
removed from a container, ce)
is invoked.

THE FOCUSLISTENER INTERFACE


METHODS General form
focusGained( ) When a component obtains void focusGained(FocusEvent fe)
keyboard focus,
is invoked
focusLost( ) When a component loses void focusLost(FocusEvent fe)
keyboard focus, is called.

THE ITEMLISTENER INTERFACE


METHODS General form
itemStateChanged( ) invoked when the state void itemStateChanged(ItemEvent ie)
of an item changes.

THE KEYLISTENER INTERFACE


METHODS General form
keyPressed( ) invoked when a key is pressed void keyPressed(KeyEvent ke)

keyReleased( ) invoked when a key is released void keyReleased(KeyEvent ke)

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


97

keyTyped( ) invoked when a character has void keyTyped(KeyEvent ke)


been entered

THE MOUSELISTENER INTERFACE


METHODS General form
mouseClicked( ). If the mouse is pressed and void mouseClicked(MouseEvent me)
released at the
same point, is invoked
mouseEntered method is called When the void mouseEntered(MouseEvent me)
mouse enters a component
mouseExited( ) (When it leaves the method is void mouseExited(MouseEvent me)
called.
mousePressed( ) invoked when the mouse is void mousePressed(MouseEvent me)
pressed
mouseReleased( ) invoked when the mouse is void mouseReleased(MouseEvent
released me)

THE MOUSEMOTIONLISTENER INTERFACE


METHODS General form
mouseDragged( method is called multiple void mouseDragged(MouseEvent me)
) times as the mouse is dragged.

mouseMoved( ) method is called multiple times void mouseMoved(MouseEvent me)


as the mouse is moved

THE MOUSEWHEELLISTENER INTERFACE


METHODS General form
mouseWheelMoved( ) method that is invoked void
when the mouseWheelMoved(MouseWheelEvent
mouse wheel is moved mwe)

TEXTLISTENER INTERFACE
METHODS General form
textChanged( ) invoked when a change occurs void textChanged(TextEvent te)
in a text area or text field.

THE WINDOWFOCUSLISTENER INTERFACE


METHODS General Form
windowGainedFocus( ) Invoked when a window void windowGainedFocus(WindowEvent
gains or losses input focus. we)

windowLostFocus( ). Invoked when a window void windowLostFocus(WindowEvent we)


losses input focus.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


98

THE WINDOWLISTENER INTERFACE


METHODS General Form
windowActivated( ) Invoked when a window is void windowActivated(WindowEvent we)
activated
windowDeactivated( ) Invoked when a window is void windowClosed(WindowEvent we)
deactivated
windowIconified( ) Invoked when a window is void windowClosing(WindowEvent we)
iconified
windowDeiconified( ) Invoked when a window is void windowDeactivated(WindowEvent we)
deiconified
windowOpened( ) Invoked when a window is void windowDeiconified(WindowEvent we)
opened
windowClosed( ) Invoked when a window is void windowIconified(WindowEvent we)
closed
windowClosing( ) Invoked when a window is void windowOpened(WindowEvent we)
being closed

HANDLING KEYBOARD EVENTS.

KeyListerner
METHODS General form
keyPressed( ) invoked when a key is pressed void keyPressed(KeyEvent ke)

keyReleased( ) invoked when a key is released void keyReleased(KeyEvent ke)

keyTyped( ) invoked when a character has void keyTyped(KeyEvent ke)


been entered

KeyboardEvents
import [Link].*;
import [Link].*;
public class keylistenerx implements KeyListener
{
Frame f;
Label l;
TextArea tf;
TextField td;
String msg="";
keylistenerx()
{
f=new Frame();
l=new Label();
[Link](20,50,100,20);

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


99

tf=new TextArea();
td=new TextField();
[Link](100,100,70,30);
[Link](20,80,300,300);
[Link](this);
[Link](l);
[Link](tf);
[Link](td);
[Link](400,400);
[Link](null);
[Link](true);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}

public void keyPressed(KeyEvent e)


{
[Link]("keyup");
}
public void keyReleased(KeyEvent e)
{
[Link]("keydown");
}
public void keyTyped(KeyEvent e)
{
[Link]("key typed");
}
public static void main(String args[])
{
new keylistenerx();
}
}

D:\>javac [Link]

D:\>java keylistenerx

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


100

Mouse listener

import [Link].*;
import [Link].*;
public class mouselistener extends Frame implements MouseListener
{

Label l;
mouselistener(){

l=new Label();
[Link](20,50,100,20);
addMouseListener(this);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


101

}
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
public static void main(String[] args) {
new mouselistener();
}
}

E:\basic pgms\unit iv>javac [Link]

E:\basic pgms\unit iv>java mouselistener

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


102

The Applet Class – Applet basics – Applet architecture – HTML APPLET tag – Passing

parameters to applets.

APPLET
Applets are small Java applications that can be accessed on an Internet server,
transported over Internet, and can be automatically installed and run as apart of a web
document.
Any applet in Java is a class that extends the [Link] class.

Differences between an applet and Java application


 An applet is a Java class that extends the [Link] class.
 A main() method is not invoked on an applet, and an applet class will not define
main().
 Applets are designed to be embedded within an HTML page.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


103

 When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser.
 The security of an applet is often referred to as sandbox security, comparing the
applet to a child playing in a sandbox with various rules that must be followed.
 Other classes that the applet needs can be downloaded in a single Java Archive
(JAR) file.

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:


 The [Link] class 4 life cycle methods and [Link].
 Component class provides 1 life cycle methods for an applet.

Four life cycle methods of applet.


1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It
is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop
or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
[Link] class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.

Example
import [Link].*;
import [Link].*;
/*
<applet code="simple" width=400 height=400>
</applet>
*/
public class simple extends Applet
{
public void paint(Graphics g)
{
[Link] ("A Simple Applet", 25, 50);
}
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


104

E:\basic pgms\unit iv>javac [Link]


E:\basic pgms\unit iv>appletviewer [Link]

Advantages of Applets
1. Very less response time as it works on the client side.
2. Can be run using any browser, which has JVM running in it.

Example of an Applet Skeleton


import [Link].*;
import [Link].*;
public class AppletTest extends Applet
{
public void init()
{
//initialization
}
public void start ()
{
//start or resume execution
}
public void stop()
{
//suspend execution
}
public void destroy()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}

Example of an Applet
import [Link].*;
import [Link].*;
/*
<applet code="MyApplet" width=400 height=400>

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


105

</applet>
*/
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](100,100,50,50);
}
}
E:\basic pgms\unit iv>javac [Link]

E:\basic pgms\unit iv>appletviewer [Link]

Add two numbers In Applet with HTML


import [Link].*;
import [Link].*;
/*
<applet code="addition" width=400 height=400>
</applet>*/
public class addition extends Applet
{
public void paint(Graphics g)
{
int a=10,b=20,c;
String s="";
c=a+b;

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


106

s="sum"+[Link](c);
[Link](s,100,100);
}
}
E:\basic pgms\unit iv>javac [Link]
E:\basic pgms\unit iv>appletviewer [Link]

How to run an Applet?

There are two ways to run an applet


1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an
html file and place the applet code in html file. Now click the html file.

import [Link];
import [Link];
public class First extends Applet
{
public void paint(Graphics g)
{
[Link]("welcome",150,150);
}
}

[Link]

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


107

<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer [Link]. Now Html file is not
required but it is for testing purpose only.

import [Link];
import [Link];
public class First extends Applet
{
public void paint(Graphics g)
{
[Link]("welcome to applet",150,150);
}
}

Displaying Graphics in Applet


[Link] class provides many methods for graphics programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with
the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to
draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill
oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw
line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used to fill a circular or elliptical arc.
[Link] abstract void setColor(Color c): is used to set the graphics current color
to the specified color.
[Link] abstract void setFont(Font font): is used to set the graphics current font
to the specified font.

Example of Graphics in applet:

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


108

import [Link];
import [Link].*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
[Link]([Link]);
[Link]("Welcome",50, 50);
[Link](20,30,20,300);
[Link](70,100,30,30);
[Link](170,100,30,30);
[Link](70,200,30,30);
[Link]([Link]);
[Link](170,200,30,30);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
E:\basic pgms\unit iv>javac [Link]

E:\basic pgms\unit iv>appletviewer [Link]

Parameter in Applet

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


109

We can get any information from the HTML file as a parameter. For this purpose,
Applet class provides a method named getParameter().

Syntax:
1. public String getParameter(String parameterName)

Example of using parameter in Applet:


import [Link];
import [Link];
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
[Link](str,50, 50);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
<param name="msg" value=" Sathyabama University">
</applet>
</body>
</html>

E:\basic pgms\unit iv>javac [Link]

E:\basic pgms\unit iv>appletviewer [Link]

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


110

Applet architecture

Use Parameters
import [Link].*;
import [Link].*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/
public class ParamDemo extends Applet{
String fontName;
int fontSize;
float leading;
boolean active;
// Initialize the string to be displayed.
public void start() {
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try {
if(param != null) // if not found
fontSize = [Link](param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;
}
param = getParameter("leading");
try {

if(param != null) // if not found


leading = [Link](param).floatValue();
else
leading = 0;
} catch(NumberFormatException e) {
leading = -1;
}
param = getParameter("accountEnabled");
if(param != null)
active = [Link](param).booleanValue();
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


111

// Display parameters.
public void paint(Graphics g) {
[Link]("Font name: " + fontName, 0, 10);
[Link]("Font size: " + fontSize, 0, 26);
[Link]("Leading: " + leading, 0, 42);
[Link]("Account Active: " + active, 0, 58);
}
}

E:\basic pgms\unit iv>javac [Link]

E:\basic pgms\unit iv>appletviewer [Link]

UNIT-V
AWT Controls & Database Connectivity

Control Fundamentals- Labels-Buttons-Checkboxes-Checkboxgroup-Lists-Scroll bars-Textfield-


TextArea-Layout Managers-Flow layout-Card layout-Grid layout-Border layout-Menus
JDBC Connectivity - Introduction –Establishing Connection – Creation of Database Tables –
Entering Data into the Tables- Table Updating .

AWT
 AWT ( „Abstract window Toolkit‟) is an API to develop GUI or window-
based applications in java.
 Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system.
 The [Link] package provides classes for AWT api such as TextField,
Label,TextArea, RadioButton, CheckBox, Choice, List etc.

CONTAINER:
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The containers are Frame, Dialog and Panel.

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


112

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

METHODS OF COMPONENT CLASS


Method Description

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

public void setSize(int width,int sets the size (width and height) of the
height) component.

public void defines the layout manager for the


setLayout(LayoutManager m) component.

public void setVisible(boolean changes the visibility of the component,


status) by default false.

EX:
import [Link].*;
import [Link].*;
class framedemo
{
public static void main(String[] args)
{
Frame f=new Frame("my first frame");
[Link](500,500);
[Link](null);
[Link](true);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}
}
E:\javapgms>javac [Link]

E:\javapgms>java framedemo
Output

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


113

LABEL
 label is an object of type Label, and it contains a string, which it displays.
 Labels are passive controls that do not support any interaction with the user.
Label defines the following constructors:
Label( ):
Ex:

Label(String str)
Ex:

Label(String str, int how)


Ex:

Methods
Void setText(String str);
String getText();
void setAlignment(int how)
int getAlignment( )
It has no Listener Class.

Ex:
import [Link].*;
import [Link].*;
class label
{
public static void main(String[] args)

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


114

{
Frame f=new Frame("first");
Label l1=new Label("Name");
Label l2=new Label("age");
Label l3=new Label("gender");
[Link](100,50,70,30);
[Link](100,100,70,30);
[Link](100,120,70,30);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}});
[Link](l1);
[Link](l2);
[Link](l3);
[Link](300,300);
[Link](true);
[Link](null);
}
}
E:\javapgms>javac [Link]

E:\javapgms>java label

Output

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


115

TEXTFIELD
 The TextField class implements a single-line text-entry area, usually called an
edit control.
 Text fields allow the user to enter strings and to edit the text using the arrow
keys, cut and paste keys, and mouse selections.
 TextField is a subclass of TextComponent.

TextField defines the following constructors:


The first version creates a default text field.
Textfield():
Ex:

TextField(int numchars)

TextField(String str):

TextField(String str, int numChars)

METHODS
String getText();
Void setText(“hello”)
setBackground([Link])
getBackground()
getSelectedText()

EVENT
ActionListener()

METHOD
Void actionPerformed(ActionEvent e)
{
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


116

Ex:
import [Link].*;
import [Link].*;
import [Link].*;
public class textfield implements ActionListener
{
Frame f=new Frame();
Label l1,l2;
TextField t1,t2,t3;
textfield()
{
l1=new Label("Name :",[Link]);
l2=new Label("Password:",[Link]);
t1=new TextField(15);
t2=new TextField(15);
[Link]('?');
t3=new TextField(40);
[Link](100,100,100,20);
[Link](100,200,100,20);
[Link](250,100,150,20);
[Link](250,200,150,20);
[Link](50,300,400,20);
[Link](l1);
[Link](l2);
[Link](t1);
[Link](t2);
[Link](t3);
[Link](this);
[Link](this);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](450,450);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e)
{

[Link]([Link]()+" "+[Link]()+" "+"selected text is"+[Link]());


}
public static void main(String[] arg)
{
new textfield();
}
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


117

BUTTON

 The most widely used control is the push button.


 A push button is a component that contains a label and that generates an event when it
is pressed.
 Push buttons are objects of type Button.

Button defines these two constructors:


Button( ):

It creates an empty button.

Button(String str)

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


118

It creates a button that contains str as a label.

METHODS

setLabel():After a button has been created, you can set its label by calling setLabel( ).

getLabel( ):
You can retrieve its label by calling getLabel( ).

Interface
ActionListener

Method
[Link](this);
Public void actionPerformed(ActionEvent e)
{
}

Ex:

Simple Button

import [Link].*;
import [Link].*;
public class firstbutton
{
public static void main(String[] args)
{
Frame f=new Frame("buttonexample");
final TextField tf=new TextField();
[Link](50,50,150,200);
Button b=new Button("yes");
[Link](50,100,60,30);
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
[Link]("clicked yes");

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


119

}
});
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](b);
[Link](tf);
[Link](400,400);
[Link](null);
[Link](true);
}
}

E:\javapgms>javac [Link]

E:\javapgms>java firstbutton

Button Array
Ex:
import [Link].*;
import [Link].*;
public class buttonlist implements ActionListener
{
String s="";
Button y
public void init()

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


120

{
Button yes=new Button("yes");
Button no=new Button("no");
Button maybe=new Button("decided");
b[0]=(Button) add(yes);
b[1]=(Button) add(no);
b[2]=(Button) add(maybe);
for(int i=0;i<3;i++)
{
b[i].addActionListener(this);
}
}
public void actionPerformed(ActionEvent e)
{
for( int i=0;i<3;i++)
{
if([Link]()==b[i])
{
s="you pressed"+b[i].getLabel();
}
}
repaint();
}
public void paint(Graphics g)
{
[Link](s,6,100);
}
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


121

CHECKBOX

 A check box is a control that is used to turn an option on or off.


 It consists of a small box that can either contain a check mark or not.
 There is a label associated with each check box that describes what option the box
represents.
 You change the state of a check box by clicking on it.
 Check boxes can be used individually or as part of a group.
 Checkboxes are objects of the Checkbox class.

Checkbox supports these constructors:

Checkbox( ):

Checkbox(String str):

Checkbox(String str, boolean on)

METHODS

boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
getSource()

INTERFACE

ItemListener

METHOD

addItemListener(this);

public void itemStateChanged(ItemEvent e)


{
}

Ex:

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


122

import [Link].*;
import [Link].*;
public class checkbox implements ItemListener
{
Frame f;
Checkbox Win98, winNT, solaris, mac;
TextField tf;
checkbox()
{
f=new Frame("checkbox");
tf=new TextField();
[Link](100,300,200,20);
Win98 = new Checkbox("win98");
[Link](100,100,70,30);
winNT = new Checkbox("winNT");
[Link](100,150,70,30);
solaris = new Checkbox("Solaris");
[Link](100,200,70,30);
mac = new Checkbox("Mac");
[Link](100,250,70,30);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](Win98);
[Link](winNT);
[Link](solaris);
[Link](mac);
[Link](tf);
[Link](400,400);
[Link](null);
[Link](true);
}

public void itemStateChanged(ItemEvent e)


{
if([Link]()==Win98)
{
[Link]("you pressed"+" "+[Link]()+" "+[Link]());
}
if([Link]()==winNT)
{

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


123

[Link]([Link]()+" "+[Link]());
}
if([Link]()==solaris)
{
[Link]([Link]()+" "+[Link]());
}
if([Link]()==mac)
{
[Link]([Link]()+" "+[Link]());
}
}
public static void main(String[] args)
{
new checkbox();
}
}

E:\javapgms>javac [Link]

E:\javapgms>java checkbox

CHECKBOX GROUP

 It is possible to create a set of mutually exclusive check boxes in which one and only
one
 check box in the group can be checked at any one time

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


124

Ex:

import [Link].*;
import [Link].*;
public class checkboxgroup
{
public static void main(String[] args)
{
Frame f=new Frame("checkbox");
boolean b;
CheckboxGroup gp=new CheckboxGroup();
Checkbox Win98, winNT, solaris, mac;
Win98 = new Checkbox("Windows 98/XP", gp, true);
[Link](100,100,50,50);
winNT = new Checkbox("Windows NT/2000",gp,false);
[Link](100,150,50,50);
solaris = new Checkbox("Solaris",gp,true);
[Link](100,200,50,50);
mac = new Checkbox("MacOS",gp,false);
[Link](100,250,50,50);
/*[Link](new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
b=[Link]();

}
});
[Link](new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
str=[Link]();
[Link](str);
}
});
[Link](new ItemListener()
{

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


125

public void itemStateChanged(ItemEvent e)


{
[Link]([Link]());
}
});
[Link](new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
[Link]([Link]());
}
});*/
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](Win98);
[Link](winNT);
[Link](solaris);
[Link](mac);
[Link](400,400);
[Link](null);
[Link](true);
}
}

E:\javapgms>javac [Link]

E:\javapgms>java checkboxgroup

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


126

LIST

 The List class provides a compact, multiple-choice, scrolling selection list.


 a List object can be constructed to show any number of choices in the visible window.
 It can also be created to allow multiple selections.

List provides these constructors:

List( )
The first version creates a List control that allows only one item to be selected at any one time

List(int numRows)
In the second form, the value of numRows specifies the number of entries in the list that will
always be visible (others can be scrolled into view as needed).

List(int numRows, boolean multipleSelect)

In the third form, if multipleSelect is true, then the user may select two or more items at a
[Link] it is false, then only one item may be selected.

Ex:

import [Link].*;
import [Link].*;
public class list
{
public static void main(String[] args)
{
Frame f=new Frame();

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


127

final Label l=new Label();


[Link]([Link]);
[Link](500,100);
Button b=new Button("show");
[Link](200,150,80,30);
final List os=new List(4,false);
[Link](100,100,70,70);
[Link]("windows");
[Link]("linux");
[Link]("unix");
[Link]("android");
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String data="os selected"+[Link]([Link]());
[Link](data);
}});
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](os);
[Link](l);
[Link](b);
[Link](450,450);
//[Link](null);
[Link](true);
}
}

E:\javapgms>javac [Link]

E:\javapgms>java list

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


128

TEXT AREA

AWT includes a simple multiline editor called TextArea.

Following are the constructors for TextArea:

TextArea( )

TextArea(int numLines, int numChars)

TextArea(String str)

TextArea(String str, int numLines, int numChars)

TextArea(String str, int numLines, int numChars, int sBars)

METHODS
getText( )
setText( )
getSelectedText( )
select( ),
isEditable( )
setEditable( )

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


129

Ex:

import [Link].*;
import [Link].*;
public class TextAreaDemo {
public static void main(String[] args)
{
Frame f=new Frame();
String val = "There are two ways of constructing " +
"a software design.\n" +
"One way is to make it so simple\n" +
"that there are obviously no deficiencies.\n" +
"And the other way is to make it so complicated\n" +
"that there are no obvious deficiencies.\n\n" +
" -C.A.R. Hoare\n\n" +
"There's an old story about the person who wished\n" +
"his computer were as easy to use as his telephone.\n" +
"That wish has come true,\n" +
"since I no longer know how to use my telephone.\n\n" +
" -Bjarne Stroustrup, AT&T, (inventor of C++)";
TextArea text = new TextArea();
[Link](100,100,200,200);
[Link](val);

[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](text);
[Link](400,400);
[Link](null);
[Link](true);
}
}

E:\javapgms>javac [Link]

E:\javapgms>java TextAreaDemo

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


130

SCROLLBAR

 Scroll bars are used to select continuous values between a specified minimum and
 maximum.
 Scroll bars may be oriented horizontally or vertically.
 A scroll bar is actually a composite of several individual parts.
 Each end has an arrow that you can click to move the current value of the scroll bar
one unit in the direction of the arrow.
 The current value of the scroll bar relative to its minimum and maximum values is
indicated by the slider box (or thumb) for the scroll bar.

Scrollbar defines the following constructors:

Scrollbar( )

It creates a vertical scroll bar.

Scrollbar(int style)

It allows you to specify the orientation of the scroll bar.

Scrollbar(int style, int initialValue, int thumbSize, int min, int max)

If style is [Link], a vertical scroll bar is created. If style is


[Link], the scroll bar is horizontal

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


131

METHODS

int getValue( )
void setValue(int newValue)
int getMinimum( )

int getMaximum( )

void setUnitIncrement(int newIncr)

void setBlockIncrement(int newIncr)

INTERFACE

AdjustmentListener interface

OBJECT

AdjustmentEvent

EVENT METHOD
public void getAdjustmentType( )
{}

The types of adjustment events are as follows:


BLOCK_DECREMENT -A page-down event has been generated.
BLOCK_INCREMENT -A page-up event has been generated.
TRACK -An absolute tracking event has been generated.
UNIT_DECREMENT -The line-down button in a scroll bar has been pressed.
UNIT_INCREMENT -The line-up button in a scroll bar has been pressed.

Ex:

import [Link].*;
import [Link].*;
public class SBDemo implements AdjustmentListener
{
String msg = "";
Frame f;
Scrollbar vertSB, horzSB;
Label l;
SBDemo()
{
f=new Frame();
l=new Label();
l1=new Label();
l2=new Label();
vertSB = new Scrollbar([Link],0, 1, 0, 30);
horzSB = new Scrollbar([Link],0, 1, 0, 30);

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


132

[Link](100,100,50,100);
[Link](200,100,200,50);
[Link](200,200);
[Link](this);
[Link](this);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](vertSB);
[Link](horzSB);
[Link](l);
[Link](450,450);
[Link](true);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
if([Link]()==vertSB)

[Link]("Vertical Scrollbar value is:"+e .getValue());


else
[Link]("Horizontal Scrollbar value is:"+e .getValue());
}

public static void main(String[] args)


{
new SBDemo();
}
}

E:\javapgms>javac [Link]

E:\javapgms>java SBDemo

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


133

LAYOUT MANAGERS

 A layout manager is an instance of any class that implements the LayoutManager


interface.
 The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is
made, then the default layout manager is used. Whenever a container is resized (or
sized for the first time), the layout manager is used to position each of the components
within it.

The setLayout( ) method has the following general form:


void setLayout(LayoutManager layoutObj)

Types
[Link]
[Link]
[Link]

FlowLayout

 FlowLayout is the default layout manager.


 It implements a simple layout style, which is similar to how words flow in a text editor.
Components are laid out from the upper-left corner, left to right and top to bottom.
 When no more components fit on a line, the next one appears on the next line.
 A small space is left between each component, above and below, as well as left and
right.

Constructors for FlowLayout:

FlowLayout( )
The first form creates the default layout, which centers components and leaves five

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


134

pixels of space between each component.


FlowLayout(int how)
The second form lets you specify how each line is aligned. Valid values for how are as
follows:
[Link]
[Link]
[Link]
These values specify left, center, and right alignment, respectively.

FlowLayout(int how, int horz, int vert)


The third form allows you to specify the horizontal and vertical space left between
components in horz and vert, respectively.
Ex:

import [Link].*;
import [Link].*;
import [Link].*;
public class flowlayout implements ActionListener
{
Frame f=new Frame();
Label l1,l2,l3;
TextField t1,t2,t3;
Button Add=new Button("add");
flowlayout()
{
l1=new Label("ist value");
l2=new Label("2nd value");
l3=new Label("result");
t1=new TextField(15);
t2=new TextField(15);
t3=new TextField();
[Link](100,100,70,70);
[Link](100,150,70,70);
[Link](100,200,70,70);
[Link](250,100,70,70);
[Link](250,200,70,70);
[Link](250,300,70,70);
[Link](200,400,70,70);
[Link](new FlowLayout([Link]));
[Link](l1);
[Link](l2);
[Link](l3);
[Link](t1);
[Link](t2);
[Link](t3);
[Link](Add);
[Link](this);
/*[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


135

{
int i=[Link]([Link]());
int j=[Link]([Link]());
int c=0;
if([Link]()==Add)
{
c=i+j;
}
[Link]([Link](c));
}
});*/
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](450,450);
[Link](null);
[Link](true);
}

public void actionPerformed(ActionEvent e)


{
String s1=[Link]();
String s2=[Link]();
int i=[Link](s1);
int j=[Link](s2);
int c=0;
if([Link]()==Add)
{
c=i+j;
}
String re=[Link](c);
[Link](re);
}

public static void main(String[] arg)


{
new flowlayout();
}
}

E:\javapgms>javac [Link]

E:\javapgms>java flowlayout

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


136

BorderLayout

 The BorderLayout class implements a common layout style for top-level windows.
 It has four narrow, fixed-width components at the edges and one large area in the
center.
 The four sides are referred to as north, south, east, and west. The middle area is called
the center.

Constructors for BorderLayout:

BorderLayout( )

It creates a default border layout.

BorderLayout(int horz, int vert)

It allows you to specify the horizontal and vertical space left between components in

horz and verz

BorderLayout defines the following constants that specify the regions:

[Link] [Link]
[Link] [Link]
[Link]

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


137

add():
It is used to add the components which is defined by Container:
void add(Component compObj, Object region);
Here, compObj is the component to be added, and region specifies where the
component will be added.
Ex:

import [Link].*;
import [Link].*;
public class borderlayout {
Frame f;
String msg="";
borderlayout()
{
f=new Frame("BorderLayout");
[Link](new BorderLayout());
Button b1=new Button("north");
Button b2=new Button("south");
Button b3=new Button("east");
Button b4=new Button("west");
[Link](b1,[Link]);
[Link](b2,[Link]);
[Link](b3,[Link]);
[Link](b4,[Link]);
msg = "The reasonable man adapts " +
"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
[Link](new TextArea(msg), [Link]);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](200,200);
[Link](true);
}
public static void main(String[] args)
{
new borderlayout();
}
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


138

GridLayout

 GridLayout lays out components in a two-dimensional grid.

 When you instantiate a GridLayout, you define the number of rows and columns.

Constructors for GridLayout

GridLayout( )

The first form creates a single-column grid layout

GridLayout(int numRows, int numColumns )

The second form creates a grid layout with the specified number of rows and columns.

GridLayout(int numRows, int numColumns, int horz, int vert)

It specify the horizontal and vertical space left between components in horz and vert,

respectively. Either numRows or numColumns can be zero. Specifying numRows as zero

allows for unlimited-length columns. Specifying numColumns as zero allows for

unlimited-length rows.

Ex:

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


139

import [Link].*;
import [Link].*;
public class gridlayout {
Frame f;
final int n = 3;
TextField tf;
gridlayout()
{
f=new Frame("");
[Link](new BorderLayout());
[Link](new GridLayout(n, n));
tf=new TextField();
[Link](new Font("SansSerif", [Link], 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k >=0)
[Link](new Button("" + k));
}
}
[Link](new Button("+"));
[Link](new Button("-"));
[Link](new Button("*"));
[Link](new Button("/"));
[Link](new Button("="));
[Link](tf,[Link]);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](200,300);

[Link](true);
}
public static void main(String[] args)
{
new gridlayout();
}
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


140

MENU BARS AND MENUS

A menu bar displays a list of top-level menu choices. Each choice is associated with a drop-
down menu.

Menu Classes

To create a menu bar, first create an instance of MenuBar. This class only defines the default
constructor. Next, create instances of Menu that will define the selections displayed on the bar.
1. MenuBar
2. Menu
3. MenuItem

Constructors for MenuItem:

MenuItem( )

MenuItem(String itemName)

MenuItem(String itemName, MenuShortcut keyAccel)

Constructors for Menu:


Menu( )
Menu(String optionName)
Menu(String optionName, boolean removable)

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


141

Add Menuitem to Menu

Once you have created a menu item, you must add the item to a Menu object by
using add( ).The general form is

[Link](MenuItemobject)

Here, item is the item being added. Items are added to a menu in the order in which the
calls to add( ) take place. The item is returned.

Add Menu to Menubar


Once you have added all items to a Menu object, you can add that object to the menu
bar by using this version of add( ) defined by MenuBar:

Menubarobject. add(Menuobject)
Here, menu is the menu being added. The menu is returned.

Ex:

import [Link].*;
import [Link].*;
public class menudesign implements ActionListener
{
Frame f;
TextArea te;
MenuBar mb;
MenuItem New,Save,Cut,Copy,Paste,Close;
menudesign()
{
f=new Frame();
te=new TextArea();

New=new MenuItem("New");
Save=new MenuItem("Save");
Cut=new MenuItem("Cut");
Copy=new MenuItem("Copy");
Paste=new MenuItem("Paste");
Close=new MenuItem("Close");

//[Link](this);
//[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);

mb=new MenuBar();

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


142

Menu fi=new Menu("File");


Menu ed=new Menu("Edit");
Menu fo=new Menu("Format");
Menu ex=new Menu("exit");

[Link](New);
[Link](Save);
[Link](Cut);
[Link](Copy);
[Link](Paste);
[Link](Close);

[Link](50,50,100,200);
//[Link]([Link]);

[Link](fi);
[Link](ed);
[Link](fo);
[Link](ex);
[Link](mb);
[Link](te);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](200,300);
[Link](true);
}
public void actionPerformed(ActionEvent e)
{
String s=(String)[Link]();
if([Link]("Cut"))
//[Link]();
[Link](s);
if([Link]("Paste"))
//[Link]();
[Link](s);
if([Link]("Copy"))
//[Link]();
[Link](s);
if([Link]("Close"))
[Link](0);
}
public static void main(String[] args)
{

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


143

new menudesign();
}
}

Database Connectivity

• ODBC driver –
 It require a driver to be loaded at runtime to connect to any data source.
 The driver is implemented as a class that is located and loaded at runtime.
 The ODBC driver for JDBC connections is named [Link].
 It require an ODBC connection string to connect to the data source.
 To connect with an ODBC DSN, we require a connection string "jdbc:odbc:ODBC DSN
String"
 The package containing the database related classes is contained in [Link].
 Dynamically load the class [Link] as
[Link]("[Link]");
 Connection conn = [Link](database, "", "");
 The Statement must be created to execute a SQL query on the opened database.
 Statement s = [Link]();
 To clean up after we are done with the SQL query, • To call [Link]() to dispose the
object Statement.
• To call [Link]() for close the database

Step 1 : Open Microsoft Access and select Student data base option and give the data
base name as File name option as “student”
Step 2 : Create a table and insert your data into the table
Step 3 : Save the table with the desired name; in this article we save the following
records with the table name student.

• ODBC connection string

SCS1209 - JAVA PROGRAMMING Prepared by [Link]


144

• Import the classes to connect to the database


• Load the JDBC:ODBC driver
• Open the MS-Access database file in the application space
• Create a Statement object to execute the SQL query
• Cleanup after finishing the job
• Creating a Database

37120001 Aravind
37120002 Arjun
• Now Creating DSN of your data base –
Step 4 : Open your Control Panel and than select Administrative Tools.
Step 5 : Click on Data Source(ODBC)-->User DSN.
Step 6 : Now click on add option for making a new [Link] Microsoft Access Driver (*.mdb.
*.accdb) and than click on Finish
Step 7 : Make your desired Data Source Name and then click on the Select option.
Step 8 : Now you select your data source file for storing it and then click ok and then click on
Create and Finish

Example

import [Link].*;
class DatabaseDemo
{
public static void main(String ar[])
{
Try
{
String url="jdbc:odbc:veeradsn";
[Link]("[Link]");
Connection c=[Link](url);
Statement st=[Link]();
[Link]("INSERT into std(Reg_no,Name) values("+37120003+",'Avinash'"+")");
ResultSet rs=[Link]("select * from std");
while([Link]())
[Link]([Link](1)+ " "+[Link]("Name"));
}
catch(Exception ee)
{
[Link](ee);
}
}
}

SCS1209 - JAVA PROGRAMMING Prepared by [Link]

You might also like