0% found this document useful (0 votes)
319 views167 pages

Java Notes PDF

Java was created in 1991 by James Gosling at Sun Microsystems to be a portable and platform-independent language for embedded systems, and has since evolved to be widely used for both web applications and standalone programs, utilizing bytecode run on the Java Virtual Machine to achieve cross-platform functionality. Java is an object-oriented language influenced by C and C++, and applications are developed using the Java Development Kit before being compiled to bytecode and run on any system with a JVM.

Uploaded by

Praneeth Mutnuru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
319 views167 pages

Java Notes PDF

Java was created in 1991 by James Gosling at Sun Microsystems to be a portable and platform-independent language for embedded systems, and has since evolved to be widely used for both web applications and standalone programs, utilizing bytecode run on the Java Virtual Machine to achieve cross-platform functionality. Java is an object-oriented language influenced by C and C++, and applications are developed using the Java Development Kit before being compiled to bytecode and run on any system with a JVM.

Uploaded by

Praneeth Mutnuru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 167

Java:

Father of JAVA is JAMES GOSLING


Java is an object oriented, event driven, high level programming language.
Java is programming language introduced by Sun Microsystems and is based on
the concepts of C and C++.

Java Origins : Embedded Systems ( 1991 – 1994)


In 1991, at Sun, C++ was found to be Unsuitable for a

project on embedded electronic And a need for a portable and

platform –Independent language. Therefore , James Gosling and others

created a new language, intially called “Oak” And later renamed to

java.

Java : Moved into the Middle – tier (1997 to Present):-

In the late 1990‟s, Sun revised middle-tier capabilities for java to ensure

that it runs on Web/Application Servers. In 1997, Sun defined Servelets

for java to generate dynamic HTML web pages. Sun also defined

Enterprise javaBeans(EJB) so that business logic can be developed in

java. In 1999, Sun offered a middle-tier Solution for java called


Java 2 EnterPrise Edition(J2EE)
So What Exactly Java?
“Java is a programming lanuguage populary used to build

program that can work on the internet. It‟s primary features are that

is object-oriented and a cross platform language .”

By cross platform, it means that the programs can run

across several platforms- such as Microsoft windows , Apple

Machintosh, Linux, and so on. Java is not only used for stand-alone

applications and Internet based programs, but it is also used to create

consumer devices and programs for accessories such as celluar phones,

palm pilots and other gadgets


Java Combination of four Components:
Java Programming Language(Following the OOP)
JVM (Java Virtual Machine)
Byte Code ( Instruction set understood by JVM)
Java + API (Application Programmable Interface)

Java Virtual machine:--


Byte code is known as instruction set for JVM. It has its own
instructionset known as byte code. JVM is platform dependent.

JVM is used in three perspectives:-


 Specifications
o Any JVM irrespective of any language understands only
byte code language.JVM can be designed using only
byte code…

 Implementation
o By using above specifications we can implement

 Runtime Instance
o When JVM is running it is known as runtime instance…

JVM Functionalities:-
 JVM will be loaded into the memory.
 JVM has a class loader which loads the class in memory.
 It searches for the main method.
 JVM has an execution engine and calls the main method().
 JVM is also an instance (i.e. from JVM software).
 We can create any number of JVM instances.
 The life time of the JVM is the life time of the application.
 Java programs never run on the operating system.
 It loads the executable code into the RAM.
 Executes this code through local Operating System.
 Deletes the executable code from RAM.

Java consists of two types of compilations


Compiletime Enviroment
Runtime Environment

Java gets a smaller tight code because of byte code, .class file and increase network
mobility which cut shorts the amount transferred.
Security for java:-
Sandbox model is security for java. Security is implemented at 3 different levels.

 Class loader
 Byte code verifier
 Security manager

1. Different systems have different .class files, class loader will check
whether valid .class or not.
2. After loading it checks whether the byte code is downloaded from
authorized .class file (byte code) or not, by byte code verifier.
3. When it goes to run and execute the program it is again checked by
security manager. This entire model is known as sandbox model…

Java platform is downloaded it from java.sun.com it is available under the


category of JRE (java runtime Environment)

To write a java program we need JDK (java development kit) and we can
download it from java.sun.com

Program Loading:
i. Static Loading
ii. Dynamic Loading

i.Static Loading:
A block of code would be loaded into RAM before it is executed
(i.e. after being loaded into the RAM, it may not execute).

ii.Dynamic Loading:
A block of code loaded into the RAM only when it is required to
be executed.
JVM Follows Dynamic Loading:
 JVM would Convert all the statements of the class files into its
executable code at runtime.
 Once the control comes out from the method, then it is deleted
from the RAM and another method of .exe type will be loaded as
required.
 Once the control comes out from main(), the main method would
also be deleted from the RAM. This is only we are not able to
view the .exe contents of of a .class files.

Java Development Toolkit (JDK):


 There are many visual tools for java development. Example
Symantec Visual Café, IBM‟s Visual Age for java, Borland‟s
Jbuilder so on.
 JDK is the Java Development Toolkit provided by the Sun Micro
Systems that is most popular and widely used by java programmer
around the world.

 The JDK contains the software and tools needed to compile, debug
and execute applets and applications written java language. It is
basically a set of command-line tools.
Utilities Offered by JDK:
i. Javac :
This is compiler which converts java source code into byte
code.
ii. Java :
This is java interpreter is used to execute java byte codes.
(Invoke the jvm)
iii. Appletviewer :
This tool is used to view and test applets
iv. Jdb :
Java debugger, which helps us to find errors in our programs
v. Javadoc :
The documentation generator, which is automatically
generates documentation from source code comments.

vi. Javah :
Produces header files for use with native methods
vii. Javap :
Java disassemble, which enables us to convert byte code files
into a program description.
Java Classifications:
Java has three types of Editions

 J2SE (Standard Edition)


 J2EE (Enterprise Edition)
 J2ME (Micro Edition)
Micro editions are also known as mobile editions, if we want do
mobile applications we have to download mobile editions. Example:
Reliance phone works on java operating systems…

Versions:
 JDK 1.0
 JDK 1.1
 JDK 1.2
 JDK 1.3
 JDK 1.4
 JDK 1.5
 JDK 1.6
 JDK 1.7
 JDK 1.8

Type of Java Programs:


 Applications
o CUI
o GUI
 Applets
Application:
An application is a program that runs inside the computer in the
operating system of the computer. The application can either CUI based
or GUI based.

Applets:
Applets are java programs that are created specially to work on the
internet. It must be contained or embedded within a web page.

Java Features:
1. Simple
2. Strictly Object Oriented
3. Distributed
4. Multi Threaded
5. Robust
6. Self Documented
7. Secure
8. Platform Independent or Architecture Neutral

1. Simple
There are various features that make the java as a simple language. Programs are
easy to write and debug because java does not use the pointers explicitly & is high
level. It has a very few keyword – 49 in number. It also has the automatic memory
allocation and deallocation system.

2. Strictly Object Oriented


Unlike languages like C++, no java program can be constructed without the application
of OOP‟s. This means that java has no standalone variable or functions. And primitive data
typed variables can also converted to objects through Wrapper Classes.
3. Distributed
Java supported distributed programming; Concepts like RMI, EJB are the best
examples.

4. Multi Threaded
Multithreading means a single program having different threads executing
independently at the same time. Multiple threads execute instructions according to the
program code in a process or a program. Every java program is itself a thread in the
JVM.

5. Robust
Java has the strong memory allocation and automatic garbage collection
mechanism. It provides the powerful exception handling and type checking
mechanism as compare to other programming languages. Compiler checks the
program whether there any error and interpreter checks any run time error and makes
the system secure from crash. All of the above features make the java language
robust.

6. Self Documented
Java generates the documentation of its application using the special comments
available with the java source file. This reduces the time and work burden from the
programmers end.

7. Secure
Java does not have support to concepts like pointers or any such memory accessing
concept. This will not allow the programmer to handle memory locations. Moreover,
all java programs are executed on a closed memory location called the sandbox. These
are not allowed to use or access any location outside this sandbox. All this adds to the
security provided by the java programs.

8. Platform Independent or Architecture Neutral


The concept of Write-once-run-anywhere (known as the Platform independent) is
one of the important key feature of java language that makes java as the most
powerful language. Not even a single language is idle to this feature but java is closer
to this feature. The programs written on one platform can run on any platform
provided the platform must have the JVM.
Accepting a value from user into the variable:-
 Command line arguments
 Scanner class
 Input output streams.

A system class represents the system in general. They put in java.lang


packages similar to strings class…
System class is made up of data members and member functions it
comes with 3 built in data members
 In
 Out
 Err
in: - Is an object of another class called input stream. It represents
standard input device like keyboard…
out and err:- Is an object of another class called print stream.
out:- Represents output standard device like console
err:- Represents standard error device like console
Print stream, output stream are defined in a package called java.io
(input, output)
Access the system and catch of standard output device and print is the
meaning of System.out.println

Comment for documentation -> \* ends with */

//
Wrapper class:-
A wrapper class is a special class which wraps around the behavior of a
primitive converting it into an object.
Wrapper class Primitive data types
Byte byte

Short short

Integer int

Long long

Float float

Double double

Character char

Boolean bool
Every wrapper class comes with a number of utility methods which
allows us to convert values from one data type to another data
type.
The parse xxxxx method is used for converting a string into the
corresponding primitive type.
If an invalid string is passed to the parse xxxxx method then it
generates an exception called Number format exception.

Scanner class:
It allows us to scan the values from any input device. It works from
above 1.5 versions.

 Import makes available classes in a package java.util into a current


program.
 We need a value that can scan the objects from standard input
device.
 nextInt() method is used to read the next integer value.
 How many numbers we write that many nextInt() we have to give
it.

Arrays:
 Array creation in java is a two step process. In the first step, we
create an array variable with the below syntax.
o Datatype arrvar[];
 Or
o Datatype[] arrvar;
 Array variables are allocated memory on the stack.
 In the second step we create the memory for the array elements
with the new keyword using the below syntax:
o Arrvar=new datatype[width];
 Ex:- a=new int[10];
o In java, we don‟t have pointers as the memory allocated to
array will not refer to large extent.
 The array elements are themselves allocated memory on the heap.
 Unlike in c++, arrays in java are internally treated as objects.
 Reading past the boundaries of an array generates an exception
called ArrayIndexOutOfBoundsException
 Because arrays are internally treated as objects they have given a
built in property called length which returns the number of
elements in the array
 The array elements are implicitly assigned default values zeroes in
case of numbers, false in case of Booleans, null in case of
characters and other objects.

Types of Arrays:
1. Single Dimensional Array
2. Multi Dimensional Array

1. Single Dimensional Array:-

The elements of a single-dimensional array are stored in a single row in


the allocated memory.

Multi-Dimensional Array:-
Consider a scenario where we need to store the roll numbers
of 50 students and their marks in three exams.
Using a single-dimensional array, we require two separate arrays
for storing roll numbers and marks. However, using a multi-
dimensional array, we just need one array to store both, roll
numbers as well as marks.

A multi-dimensional array allows you to store combination


of values of a single type in two or more dimensions. The
dimensions of the array are represented as rows and columns
similar to the rows and columns of a Microsoft Excel Sheet.

There are two types of multi-dimensional arrays. Those are 1.


Rectangular Arrays and 2. Jagged Arrays.

1. Rectangular Arrays:
A rectangular array is multi-dimensional array where all the specified
dimensions have constant values. A rectangular array will always have
the same number of columns for each row.
Example of Rectangular Array:

class Arr5

{
public static void main(String arg[])
{
int dimension[][]=new int[4][5];
int numone=0;
for(int row=0;row<4;row++)
{
for(int col=0;col<5;col++)
{
dimension[row][col]=numone;
numone ++;
}
}
for(int row=0;row<4;row++)
{
for(int col=0;col<5;col++)
{
System.out.print(dimension[row][col]+"\t");
}
System.out.println();
}
}
}

Jagged Array:
A jagged array is a multidimensional array where one of the
specified dimensions can have varying sizes. Jagged arrays can have
unequal number of columns for each row.
Example of Jagged Array
class Arr6
{
public static void main(String arg[])
{
String[][] companies=new String[3][];
companies[0]=new String[]{"Intel","AMD"};
companies[1]=new String[]{"IBM","Microsoft","Sun"};
companies[2]=new String[]{"HP","Canon","Lexmark","Epson"};
for(int row=0;row<companies.length;row++)
{
System.out.print("List of companies in group "+(row+1) + ":\t");
for(int col=0;col<companies[row].length;col++)
{
System.out.print(companies[row][col] + " ");
}
System.out.println();
}
}
}
OBJECT ORIENTED PROGRAMMING SYSTEM

OOPS:- Object Oriented Programming Language


It is very important concept in JAVA Language. OOPS have
three parts based on their process.
o OOD:-Object Oriented Designing
o OOA:-Object Oriented Approach
o OOP:-Object Oriented Programming

The combination of above three parts is called "OOPS".

Above all process is used to develop any application systematically


by following set of predefined standards. All the standards come under
"Unified Modeling Language"(UML)

Object Oriented Designing(OOD):-


It stands for object oriented design. It determines to develop the
application by phase wise designing of each module and each module
will be designed later by following set of methods, principles and
applications.

Object Oriented Approach(OOA):-


It follows the object oriented designing based on its (OOD) phase.
Object Oriented Programming(OOP):-
It determines the real implementation of program (coding) by
following set of functions libraries, header files and other technical tools
by performing a suitable syntaxes. Any real implementation of the
program in OOP which follows a standard structure of program.

In JAVA we have a standard structure of program. If you write


program we should clear about object.

Standard Structure of Program in OOPS:-


class
Object
objective
1.Data Members
2.Member Functions

Class:-
In a JAVA program the "class" keyword denotes that the JAVA
program follows this standard of class structure.
(or)
Class is nothing but collection of data and functions.
(or)
Collection of data members and member functions.
2.Objective:-
It is a invisible and it is the end result of an application which can
be achieved using data members and member functions. Objective
means end result of the program.
3.Data Members:-
Data members are the elements which can be participated in a prog
to achieve the objective of an application.

4.Member Function:-
It is a process of a technic in a program which can take a parameter
and returns a value. Member function can be called methods in OOPS
Programming.

5.Object:-
It is a instance of a class which can be gives the reference to its.
The data member and the member functions which can be used outside
of the class.
(or)
Object is nothing but instance of a class.

Datatypes:-
Datatypes which are denotes what type of data that your processing
to our program.
Variables:-
It is a location memory where we can store the values into the
memory those values in the memory called "constants".

OOPS:- Object Oriented Programming System


1. Encapsulation
2. Data Abstraction
3. Polymorphism
4. Inheritance

1.Data Encapsulation:-
The union of data and functions into objects is known as Data
Encapsulation.
(or)
Details of what a class contains need not be visible to other classes and
objects that use it. Instead, only specific information can be made
visible and the others can be hidden. This is achieved through
encapsulation, also called data hiding. Both abstraction and
encapsulation are complementary to each other.

2.Data Abstraction:-
We can give restricting the data, to set a number of functions.

(or)

It gives security.
(or)

Abstraction is the feature of extracting only the required information from


objects. For example, consider a television as an object. It has a manual stating
how to use the television. However, this manual does not show all the technical
details of television, thus giving only an abstraction to the user.

3.Polymorphism:-
It is ability to take more than one form.
(or)
Use of something for different purposes.
(or)
Polymorphism is the ability to behave differently in different
situations. It is basically seen in programs where you have multiple
method declared with the same name but with diferent parameters and
different behavior.

4.Inheritance:-
Relation between two classes.
(or)
Object of one class can acquire the properties of object of another
class.
(or)
Inheritance is the process of creating a new class based on the
attributes and methods of an existing class. The existing class is called
the base class whereas the new calss created is called the derived class.
This is very important concept of objet-oriented programming as it helps
to reuse the inherited attributes and methods.

Super Class:-
It is a old class or parent class

Sub Class:-
It is a new class or child class which can acquire the properties
from base class.

Example on Class and Object:

class Demo
{
public void display()
{
System.out.println("This is the First method in Class..");
}
public void disp()
{
System.out.print("This is Second method in Class..");
}
}
class A7
{
public static void main(String args[])
{
Demo d=new Demo();
d.display();
d.disp();
}
}
Constructor:-
Constructors are special member function whose name is same as a class
name constructors are need not require to be called because it is invoked
automatically in the objects are created. Constructor may have an argument or
may not have an argument. Constructors have no return type.

Normal Method:-
A normal method may have any name associated with it. Normal methods
may or may not return values. Normal methods may be invoked any time
anywhere once an object is created.
Method Overloading:-
No class is allowed to contain two methods with the same name and same
signature. However, it is possible for a class to have two methods having the same
name but different signatures. The concept of declaring more than one method
with the same method name but different signatures is called method overloading.

Constructor Overloading:
The concept of declaring more than one constructor in a class is called
constructor overloading. The process of overloading constructor is similar to
overloading methods. Every constructor has a signature similar to that of a
method. You can declare multiple constructors in a class wherein each constructor
will have different signatures. Constructors reduce the task of assigning different
values to member variables each time when needed by different objects of the
class.

this method and this keyword:-


We can have the global and local variables can have the same name. We can
have the same name for formal parameters and instance variables…

i. . Whenever we create an object memory for the instance variables is


allocated on the heap memory however the methods belonging to that object
are loaded only once to the method area.

ii. Whenever we invoke a method on an object the system implicitly passes on


a reference to the current object as an additional parameter which is caught
hold of within the object as this. Keyword.

iii. The „this‟ keyword hence is a representation of the current object.

iv. A formal parameter and an instance variable may have the same name but
in such a case it is the formal parameter that is given precedence over the
instance variable within the method. To differentiate the two, we precede
the instance variable with the this keyword.
v. We can also use keyword this for different names of instance variables and
formal parameters. Example: this.length= l

vi. this method can be used only within a constructor. this can be used in two
ways: 1) Keyword 2)Method

vii. If used as a keyword it represents the current object.

viii. If used as a method it let us execute other overloaded constructors from


within a constructor.

ix. The usage of this method is subject to the following restrictions:

1.It can be used only within constructors.

2.Even within a constructor it has to be the first statement.

Example of this keyword:

class Demo

int x,y;

public void Show(int x,int y)

this.x=x;

this.y=y;

public void Display()

System.out.println("The Sum is "+(x+y));


}

class C14

public static void main(String args[])

Demo d=new Demo();

d.Show(10,20);

d.Display();

Polymorphism:
Polymorphism is derived from two Greek words, namely Poly and Morphos.
Poly means many and Morphos means forms. Polymorphism means existing in
multiple forms. Polymorphism is the ability of an entity to behave differently in
different situations. The two methods in class having the same name but different
signatures performing the same basic operation but in different ways.

Example on Polymorphism:
class demo

public int sum(int x,int y)

{
return x+y;

public String sum(String x,String y)

return x+y;

public double sum(double x,double y)

return x+y;

public int sum(int x,int y,int z)

return x+y+z;

class Poly

public static void main(String a[])

demo d=new demo();

System.out.println("The Sum of integer value is : "+d.sum(10,20));

System.out.println("The String value is : "+d.sum("Aptech Computer


Education "," Dwarakanagar"));
System.out.println("The Sum of double value is : "+d.sum(10.23,20.54));

System.out.println("The Sum of multiple integer value is :"+d.sum(10,20,30));

Compile-time and Run-time Polymorphism:

------------------------------------------------------

Polymorphism can be broadly classified into two categories,

compile-time polymorphism and run-time polymorphism.

Compile-time Polymorphism:-
* It is implemented through method overloading.

* It is executed at hte compile-time since the compiler knows which method


to execute depending on the number f parameters and their data types.

* It is referred to as static polymorphism.

Run-time Polymorphism:
* It is implemented through method overriding.

* It is executed at run-time since the compiler does not know the method to
be executed, whether it is the base class method that will be called or the derived
class method.

* It is referred to as dynamic polymorphism.


The „super‟ can be used in two ways:-

As a keyword:-

If used as a keyword it lets you access the immediate super class members

As a method:-

If used as a method it lets you execute your immediate super class


constructors.

A subclass and a super class may have the variables with the same name.
However, in such a case it becomes mandatory to precede the super classes‟
members with the super keyword.

Class A

int x;

int y;

Class B extends A

int x;

int y;

In class B, we have totally 4 variables, when we are invoking the


variables of A we invoke using super keyword.

Different variable names can also have super keyword.


Example on Super

class base

int a = 100;

class sup1 extends base

int a = 200;

void show()

System.out.println(super.a);

System.out.println(a);

class A18

public static void main(String[] args)

new sup1().show();

//sup1 s=new sup1();

//s.show();

}
Example of Super Method:

class Demo1

public void display()

System.out.println("Method in Super Class");

class Derived extends Demo1

public void display()

super.display();

System.out.println("Method in Sub Class");

class A19

public static void main(String args[]) {

Derived d=new Derived();

d.display();

}
Class variables: -

i. Class variables are variables that belong to the entire class and not to a
specific instance of a class.

ii. Instance variables on the contrary are variables belongs to specific instance
of the class.

iii. Class variables are declared with the static keyword.

iv. Class variables are allocated memory only once which can then be
commonly accessed by all the instances of the class.

v. Static variables are allocated memory on the static pool. They are allocated
memory only once that to when a class is loaded into the memory for the
first time.

vi. Since memory for a class variable is allocated at the time of loading the class
itself. We can access this static variable directly with the class name itself
without having to wait for the instantiation of the class.

vii. Static variables are given default values (zeroes in case of numbers, false
in case of Booleans, null incase of characters and other objects)

Static Block:-
i. A static block is a block of statements preceded by a static keyword.

ii. The main purpose of a static block is to initialize static members to non-zero
values.

iii. We can have any number of static blocks defined in a java program.

iv. If there is more than one static block in a java program, the block are
executed in a top-down approach

v. Static blocks are executed only once, when the class is loaded into memory
for the very first time.
vi. Static blocks have a higher precedence than constructors and even the main
method.

Static blocks are subject to the following restrictions:-

i. They can access other static members only.

ii. They cannot make use of this and super keywords as this and super are used
when an object is created

iii. But in static blocks we won‟t create an object.

Not only variables if required , methods may also be declared as static the
advantage of declaring methods as static is one gets to execute the static methods
directly with the class more itself rather than creating an instance of the class.

Example of Static Variable:

class StaticVar

static int eno=101;

static String ename="Uma";

public static void main(String a[])

System.out.println("Employee ID is "+eno);

System.out.println("Employee Name is " + ename);

}
Example of Static Block:

class A

static

System.out.println("In static of A");

static int x;

static

System.out.println("In the other static of A");

x=20;

class A22

static

System.out.println("In static before main");

public static void main(String args[])

System.out.println("In main");
System.out.println("A.x....."+A.x);

static

System.out.println("In static after main");

Differences between Overloading and overriding


Overloading:
Overloading will take place, either within the same class or in a sub class,
super class hierarchy.
The two overloaded methods may have different number of parameters.
The two overloaded methods may have different data types for the
parameters.
The return types may be different.

Overriding:
Overriding can take place only in a sub class, super class hierarchy.
The two overridden methods must have the same number of parameters.
The two overridden methods must have the same data types for the
parameters.
The return types must be the same…
Dynamic Method Dispatch:-
Dynamic method dispatch is a concept wherein we assign a subclass object
to the super class object reference.
The main advantage of dynamic method dispatch is Run Time
Polymorphism

Example of Dyanamic Method Dispatch:

class vehicle
{
public void brake()
{
System.out.println("Vehicle's brakes applied....");
}
}
class Car extends vehicle
{
public void brake()
{
System.out.println("car's brakes applied....");
}
}
class Bike extends vehicle
{
public void brake()
{
System.out.println("bike's brakes applied....");
}
}
class A20
{
public static void main(String args[])
{
int ch=Integer.parseInt(args[0]);
vehicle V;
if(ch==1)
{
V=new Car();
V.brake();
}
else if(ch==2)
{
V=new vehicle();
V.brake();
}
else if(ch==3)
{
V=new Bike();
V.brake();
}
else
{
System.out.println("Invalid Method..");
}
}
}

Final keyword can be used at 3 different locations:-

i.In front of variables:-

If a variable is declared as final, it is converted to a constant and is prevented


from further modifications.

ii.In front of methods:-

If a method is declared as final, then the method is prevented from being


overridden
iii.In front of classes:-

If a class is declared as final, the class is prevented from being


subclass(inherited).

Example of Final Variable:

class Testfinalvar

static final int max=5;

public static void main(String args[])

max = 10;

for(int i=0;i<=max;i++)

System.out.println("value at i :"+i);

Example of Final Method:

/* finalmemo cannot be overriden*/

class Proposal

public final void finalMemo()


{

System.out.println("This is final memo");

class Finalmethod extends Proposal

/*public void finalMemo()

System.out.println("This is final override method");

*/

public static void main(String args[])

Proposal p=new Proposal();

p.finalMemo();

Example on Final Class:

final class superclass

public void sayHello()

{
System.out.println("Hello World");

class subclass extends superclass

public void sayHelloAgain()

System.out.println("Hello World Again");

class FinalClass

public static void main(String args[])

superclass supobj=new superclass();

subclass subobj=new subclass();

supobj.sayHello();

subobj.sayHello();

subobj.sayHelloAgain();

}
Abstract Classes:
A class that is defined using the abstract keyword and that contains at least
one method which is not implemented in the class itself is referred to as
abstract class. Means the abstract class contains at least one method without
a body, the class cannot be instantiated using the new keyword. While
declaring an abstract class or abstract method the keyword 'abstract' should
be used. The abstract keyword is thus an indicative of incompleteness. As
an abstract class is considered to be an incomplete class the JVM does not
permit the creation of objects of abstract classes. The JVM allows objects for
concrete classes only.

Example of Abstract class:

abstract class shape

abstract public void draw();

public void display()

System.out.println("This is a normal method in Abstract class");

class Circle extends shape

public void draw()

System.out.println("Drawing a circle");
}

class Rectangle extends shape

public void draw()

System.out.println("Drawing a rectangle");

class A26

public static void main(String args[])

//shape s=new Circle();

Circle s=new Circle();

s.draw();

s.display();

Rectangle s1=new Rectangle();

s1.draw();

s1.display();

}
Interfaces:
An interface contains only abstract members. Unlike an abstract class, an interface
cannot implement any method. But similar to an abstract class, an interface cannot
be instantiated. An interface can only be inherited by classes or other interfaces.
An interface is declared using the keyword interface Interfaces does not allow the
normal methods. To inherit the interface “implements “ keyword should be used.

Example of Interface:

interface A

public void aMeth();

interface B

public void bMeth();

class C implements A,B

public void aMeth()

System.out.println("a Method");

public void bMeth()

{
System.out.println("b Method");

class A27

public static void main(String args[])

C ob=new C();

ob.aMeth();

ob.bMeth();

Example of Class and Interface:

class A

public void Method()

System.out.println("Method from Class");

interface B

{
public void Meth();

class C extends A implements B

public void Meth()

System.out.println("Method Definition of Interface");

class A28

public static void main(String args[])

C ob=new C();

ob.Method();

ob.Meth();

Implicit Typecasting:-
Implicit typecasting refers to automatic conversion of datatypes. Implicit
typecasting is done only when the destination and source data types belongs to
same hierarchy. In destination data type must hold a larger range of values than
the source data type. So Implicit typecasting prevents the loss of data. If you have
int type value to, you can assign long type of variable.

int -----> Implicit Typecasting ------>long

Example of Implicit Conversion:

//Implicit Conversion

class A29

public static void main(String args[])

long a = 10, result;

int b = 7;

result = a + b;

System.out.println("a + b = "+ result);

Explicit Typecasting:-
Explicit typecasting refers to changing a data type of higher precision into a data
type of lower precision. For example, using explicit typecasting, you can
manually convert the value of float type into int type. This typecasting might
result in loss of data, the digits after the decimal point are lost.

float----->Explicit Conversion----->int
Example of Explicit Conversion:

//Explicit Conversion

class A30

public static void main(String args[])

int subject = 6;

float avg = 353/(float)6;

System.out.println("average is :"+avg );

Packages:-
1. Packages offer different namespaces allowing two or more programmers to
make use of the same class name but with different implementations without any
problem.

2. Packages effective management of classes. They act as a collection of


interrelated classes and interfaces.

3. Packages are implemented by the JVM using the underlined operating systems
file structure mechanisms.

4. Working with packages is a two step process, in the first step , we intimate the
JVM about the placement of a class in a package by using the package statement.

5. Syntax :

package packagename;
6. The package statement must be the first statement in the program. There is only
one package statement per program.

7. If we din‟t place a class explicitly in a package the program the class will be
placed implicitly in the default package…..

8. Whatever, the JVM understands as a package is understood by the operating


system as a directory i.e. every package in java relates to a directory in the
operating system.

9. The default package relates to the current working directory. When we place a
class in a package we have to ensure that the .class file corresponding to the class
is placed in a directory. Which has the same name as that of a package.

10. This can be done in two ways : Either manually or by using -d option of the
java utility.

11. -d option if used will implicitly ensure that the respective directories structures
are created if requires and ensure that the .class files are placed in them
respectively.

12.Syntax for using javac

Javac –d path to the directory structures program.java

Ex:- javac –d Employee.java

Compiles the employee.java creates directory structures if required (as


indicated by .) and places the .class files in those directories.

13. To execute a class that has been placed in a package we give the following
command from the parent directory containing the package directory.

Java Packagename.classname

14. One must compulsorily declare a class placed in a package public to be able to
create its objects in other classes belonging to other packages.

15. To use a class placed in a package in another class we can follow one of the
below procedures.
16. Use a fully qualified class name as and when required.

Use the import statement to make the classes or interfaces available to the current
program.

17. The import if used can be used in one of the following ways

Import packagename.*

18. Makes all the classes and interfaces placed directly under the package available
to the current program, irrespective of whether they are used or not. This may
increase the compilation time however.

19. Import packagename.classname

Imports only the specified class name into the current program

–usually considered to be more effective of the two

To use a class placed in a package from a directory different from the parent
directory containing the package directory, we have to set the classpath
“environment variable” appropriately.

20. The order in which package , import and class statements have to be used is
1)package,2) import,3) class

Static imports (from 1.5 version)


Sub-Package:-

A package within a package is a sub-package.

1. Sometimes placing classes in a package may not offer us the required


uniqueness in such cases we place classes in the sub-packages.

2. To place a class in a subpackage we use the below syntax:

Java package packagename.subpackagename

3. To run a class placed in a sub-package we use the below

Syntax:

Java packagename.subpackagename.classname

4. Import packagename.* imports only the classes and interface placed directly in
the package. To import classes and interfaces belonging to sub-packages

5.we use the below syntax:

Import packagename.subpackagename.*

Import packagename.subpackagename.classname
How to execute Packages Manully:-

===========================

->First create Pack1 folder in D drive and create file Employee.java.

->Compile (javac Employee.java) it creates a class file.

->In above program our package name is EmpDetails.

->In D:\pack1>md EmpDetails

It creates EmpDetails folder in pack1 folder

->D:\>pack1> move Employee.class EmpDetails

->Now execute the Employee file

D:\pack1>java EmpDetails.Employee

Then the program will be executed successfully.

How to execute Packages Automatically:


->create a folder in pack2 in D drive

->Save Employee.java file in pack2 folder

->Compiling:
D:>pack2>javac -d . Employee.java

Executing:-
->java EmpDetails.Employee
Package Executing From Different Floders:-
->create pack3 folder in D drive

->copy above EmpDetails folder in pack3 folder

->D:>pack3>java EmpDetails.Employee

Package Executing From Different Floders:-


->create pack4 folder in D drive

->copy above EmpDetails folder in pack4 folder

->D:>pack4>java EmpDetails.Employee

Calling Package in another program using set classpath:


-> First create D:>Pack5 folder.

->copy above Employee.java and EmpDetails folder in pack5 folder

-> First create D:>Pack6 folder.

->copy above Employee.java and EmpDetails folder in pack6 folder

->First create C:>Pack7 folder

->Save EmpDemo.java file in C:>Pack7.

->Compiling Program using classpath

->C:>Pack7>set classpath=.;D:\Pack5;D:\Pack6;

->javac EmpDemo.java

->java EmpDemo
Example on Packages(Employee.java)
package EmpDetails;
public class Employee
{
int Empno;
String Ename;
double sal;
public Employee(int Empno,String Ename,double sal)
{
this.Empno=Empno;
this.Ename=Ename;
this.sal=sal;
}
public void PrintDetails()
{
System.out.println("Empno.."+this.Empno);
System.out.println("Ename.."+this.Ename);
System.out.println("Sal.."+this.sal);
}
public static void main(String args[])
{
Employee emp=new Employee(100,"ABC",20000);
emp.PrintDetails();
}
}

Using Package in another Program(EmpDemo.java):


import EmpDetails.Employee.*;
class EmpDemo
{
public static void main(String args[])
{
EmpDetails.Employeeemp=new EmpDetails.Employee(111,"SSS",34343);
EmpDetails.Employee emp1=newEmpDetails.Employee(222,"DDD",5555);

emp.PrintDetails();
emp1.PrintDetails();
}
}
Exceptional Handling
Exception, that means exceptional errors. Actually exceptions are used for
handling errors in programs that occurs during the program execution. During the
program execution if any error occurs and you want to print your own message or
the system message about the error then you write the part of the program which
generate the error in the try{} block and catch the errors using catch() block.
Exception turns the direction of normal flow of the program control and send to the
related catch() block. Error that occurs during the program execution generate a
specific object which has the information about the errors occurred in the program

An exception is a problem that arises during the execution of a program. An


exception can occur for many different reasons, including the following:

•A user has entered invalid data.

•A file that needs to be opened cannot be found.

•A network connection has been lost in the middle of communications, or the JVM
has run out of memory.

Some of these exceptions are caused by user error, others by programmer error,
and others by physical resources that have failed in some manner.

To understand how exception handling works in Java, you need to understand the
three categories of exceptions:

Checked Exceptions:
A checked exception is an exception that is typically a user error or a
problem that cannot be foreseen by the programmer. For example, if a file is to be
opened, but the file cannot be found, an exception occurs. These exceptions cannot
simply be ignored at the time of compilation.

Runtime exceptions: (Unchecked Exceptions):


A runtime exception is an exception that occurs that probably could have
been avoided by the programmer. As opposed to checked exceptions, runtime
exceptions are ignored at the time of compliation.
Errors:
These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer. Errors are typically ignored in your code because you
can rarely do anything about an error. For example, if a stack overflow occurs, an
error will arise. They are also ignored at the time of compilation.

Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The
exception class is a subclass of the Throwable class. Other than the exception class
there is another subclass called Error which is derived from the Throwable class.

Errors are not normally trapped form the Java programs. These conditions
normally happen in case of severe failures, which are not handled by the java
programs. Errors are generated to indicate errors generated by the runtime
environment. Example : JVM is out of Memory. Normally programs cannot
recover from errors.

Throwable

Error Exception

IO Exception Runtime Exception


Here is a list of most common checked and unchecked Java's Built-in Exceptions.

Exceptions Methods:

Following is the list of important medthods available in the Throwable class.

SN Methods with Description


1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3 public String toString()
Returns the name of the class concatenated with the result of getMessage()
4 public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error
output stream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index
0 represents the top of the call stack, and the last element in the array represents
the method at the bottom of the call stack.
6 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to
any previous information in the stack trace.

The throws/throw Keywords:‎


If a method does not handle a checked exception, the method must declare it
‎using the throws keyword. The throws keyword appears at the end of a ‎method's
signature.‎

You can throw an exception, either a newly instantiated one or an exception


‎that you just caught, by using the throw keyword. Try to understand the ‎different in
throws and throw keywords.‎
The finally Keyword:
The finally keyword is used to create a block of code that follows a try
block. ‎A finally block of code always executes, whether or not an exception has
‎occurred.‎

Using a finally block allows you to run any cleanup-type statements that you
‎ ant to execute, no matter what happens in the protected code‎
w

Example 1:

class A32

public static void main(String args[]) {

int x,y;

x=10;

y=0;

try {

int z=x/y;

System.out.println("The result is"+z);

} catch(Exception e) {

System.out.println("Number cannot be divided by zero..");

}
Example 2:
class DepartmentException extends Exception

DepartmentException()

System.out.println("Department does not exist..!");

class A33

protected A33(){ }

public static void main(final String args[])

int empid,deptid;

String empname;

try {

empid=Integer.parseInt(args[0]);

empname = args[1];

deptid = Integer.parseInt(args[2]);

if(deptid>5){

throw new DepartmentException();

} else {
System.out.println("Employe Id is :"+empid);

System.out.println("Employee name is :"+empname);

System.out.println("Detapartment Id is:"+deptid);

} catch(DepartmentException ed) {

System.out.println("Invalid Data");

} catch(NumberFormatException ne) {

System.out.println("Incorrect Data..");

} catch(ArrayIndexOutOfBoundsException ae) {

System.out.println("Incomplete Data");

/* java EemployeeDetails

Incomplete data

java EmployeeDetails clarke 1 3

incorrect data

java EmployeeDetails 1 clerke 5

Employee id is : 1

Employee name is : clerke


Department id is : 5

java EmployeeDetails 1 clarke 10

Department Does not Exist...!

Invalid Data..!

*/

Example 3:

class NumberException

public void test( String []number)

try

String num = number[0];

int numValue = Integer.parseInt(num);

System.out.println("The square is:"+numValue*numValue);

catch(ArrayIndexOutOfBoundsException ne)

System.out.println("No arguments given!");

catch(NumberFormatException nb)

{
System.out.println("Not a Number!");

class A34

public static void main( String args[])

NumberException obj=new NumberException();

obj.test(args);

/*Output:

java A34

No arguament given!

java A34 dd

Not a Number!

java A34 4

The square is 16

*/
Example 4:

/* Nested try-catch Blocks*/

class NestedException

public void test(String[] argument)

try

System.out.println("The argument passed is : "+argument[0]);

/*nested try block*/

try

/*Typecasting*/

int numValue = Integer.parseInt(argument[0]);

System.out.println("The square of "+argument[0]+" is "+numValue*numValue);

} catch(NumberFormatException nb) {

System.out.println("Inner try block...");

System.out.println("Not a Number!");

}catch(ArrayIndexOutOfBoundsException ne){

System.out.println("outer try block..");

System.out.println("please Enter the Number");

}
}

class A35

public static void main(String args[])

NestedException obj=new NestedException();

obj.test(args);

Example 5:

class A36

public static void main(String args[])

try

int a=10;

int b=0;

int c=a/b;

System.out.println("C..."+c);

}
catch(Exception e)

System.out.println("Some Error..");

finally

System.out.println("Infinally..");

Multithreading:
 Java supports concurrent programming through its built-in support for
thread programming. A thread is defined as sequential path of execution.

 Java threads have been represented through java.lang.thread class.

 The JVM treats a thread as an object of java.lang.thread class whose


behavior is defined in the run method.

 Thus in java a thread is an object of thread class which when started


executes the statements defined in the run method.

 To create thread in java, we can follow one of the below approaches.

 One can implement threads in two ways:

 First, by sub classing the Thread class

 Second, by implementing the Runnable interface


Ready : A thread does not immediately start running after it is created; rather, it
is in a ready to run state. It waits for its start() method to be called.

Running : the thread enters the running state when it start executing. It starts
running as soon as it gets the CPU time

Sleeping : the execution of the thread can be halted temporarily for a period of time
with the help of seep() method. The thread becomes ready after the sleep time
expires. Sleeping thread do not use the processor

Waiting : when two or more thread run concurrently and only one thread takes
hold of the resources all the time it will lead to starvation for the other threads. To
avoid this, a technique is required that will make a thread wait till the other thread
notify it to continue. Java provides a wait-notify mechanism to take care of this
problem. More about this will be learnt in the next session. Thus a thread is in
waiting is in waiting stare if the wait() method has been invoked.

Blocked : The thread enters a blocked stare when it waits for an event such as
input/output operations.

Dead : The thread enters a dead state after the run() method has finished execution.
The thread should end on its own by having a run() method that terminates
naturally.

Example I:

public class Normal

public void create()

for(int i=10;i<=20;i++)

System.out.println("Other Thread : "+i);

public static void main(String a[])

T1 t=new T1();

t.create();

for(int i=1;i<=10;i++)
{

System.out.println("Main Thread: "+i);

Example 2

public class T1 extends Thread

public void create()

Thread thread=new Thread(this);

thread.start();

public void run()

for(int i=10;i<=20;i++)

System.out.println("Other Thread : "+i);

public static void main(String a[])

{
T1 t=new T1();

t.create();

for(int i=1;i<=10;i++)

System.out.println("Main Thread: "+i);

Example 3:

public class T2 implements Runnable

public void create()

Thread thread=new Thread(this);

thread.start();

public void run()

for(int i=10;i<=20;i++)

System.out.println("Other Thread : "+i);

}
}

public static void main(String a[])

T2 t=new T2();

t.create();

for(int i=1;i<=10;i++)

System.out.println("Main Thread: "+i);

Example 4:

class ThreadFirst

public static void main(String args[])

Thread thread = Thread.currentThread();

System.out.println("hai :"+thread);

System.out.println(thread.getName());

thread.setName("Uma");

System.out.println("hai :"+thread);

System.out.println(thread.getName());
System.out.println(thread.getPriority());

thread.setPriority(8);

System.out.println(thread.getPriority());

System.out.println(thread.currentThread());

Example 5

class Test2 extends Thread

public static void main(String args[])

throws Exception

Test2 th=new Test2();

th.create();

for(int ctr=0;ctr<=10;ctr=ctr+2)

sleep(1000);

System.out.println(ctr);

public void create()

{
Thread th=new Thread(this);

th.start();

public void run()

try

for(int i=1;i<=5;i++)

sleep(1000);

System.out.println(i);

catch(InterruptedException e){ }

Example 6

class sleepdemo

public static void main(String args[])

throws Exception

{
for(int i=1;i<=5;i++)

Thread.sleep(1000);

System.out.println(i);

/*for(int i=5;i>=1;i--)

Thread.sleep(1000);

System.out.println(i);

}*/

Example 7

class MyThread2 implements Runnable

public static void main(String args[])

MyThread objx=new MyThread();

objx.create();

System.out.println("This is main Thread");

}
public void create()

Thread objth=new Thread(this);

objth.start();

public void run()

for(int i=0;i<=5;i++)

try

Thread.sleep(500);

System.out.println("This is child Thread");

catch(InterruptedException e){ }

}
Java Foundation Classes: -

AWT(Abstract Window Toolkit)


A Graphical User Interface(GUI) is used to accept input in a user-friendly
manner. A GUI varies from application to application and may consist of
textboxes, labels, listboxes and other such elements. Different programming
languages provide different ways and means to create a GUI application;

VB or .Net provide drag and drop approach for creating GUI, whereas C++
requires a programmer to write the entire code towards building a GUI.

1. Create the element. For instance, checkbox or label or listbox and so on.

2. Determine its initial appearance.

3. Add it to the screen interface.

The Abstract Window Toolkit (AWT) is a set of Java classes that allow the
programmer to create a Graphical User Interface(GUI) and accept user input
through the keyboard and the mouse. It is a part of Java Foundation Classes(JFC).
The Java.awt package contains all classes for creating user interfaces and for
painting graphics and images.

Containers:
A container object is a component that can contain other AWT components.

Components:
A component is an object that has graphical representation and can be
displayed n the screen. It allows user interaction.
Layout Managers:
A Layout manager defines the location and size of the Graphical User
Interface components.

Graphics and drawing capabilities:


The AWT supports a rich assortment of Graphics methods. All graphics are
drawn relative to a window.

Fonts:
To select a new font, a Font object has to be constructed that will describe
the font.

Events:
An event is an object that describes a state change in a source. It can be
generated as a consequence of an action interacting with the elements in a
Graphical User Interface.
The classes which we are about to learn is known as Java Foundation
Classes. It consists of 4 API

AWT
Swing
Graphics 2D API
Accessibility API

Frame can be used in two ways:-


Class Creating Object
Class Creating subclass
Text Areas, Test Fields, Radio buttons, Check Boxes
List Boxes are 3 types:-
Dropdown list box

List box

Combo list box

Window based programming if follows a methodology called Event Driven


Methodology. The even driven that followed in java is delegation Model.

Event:-
Interaction between user and system, even any movement like mouse
movement is mouse event

Button – JVM – class –Object –embeds an information – Response – Action Event

Listeners Component are components that listen for a particular event, and when
the event takes place it generates a response(set of statements means behaviors)
listeners are basically interfaces.

Registration process- Registering Components We have to tell to the JVM about


the components and response then only it transfers control. JVM is delegating the
control to the corresponding registered listeners then it known as Delegation
Model.

Layout:-
Its responsibility is to manage the layout of the container… Every Container
comes with built-in layouts

Frame

Dialog Border Layout


Panel
Flow Layout
Applet

The other Layout managers are


Flow Layout ,Border Layout, Grid layout, Card Layout, GridBag Layout, Box
Layout, spring Layout...

Dialog box:-
It is a special window which is poped – up as a result of user-interaction with
existing component.

 Modal Dialog box


 Modless Dialog box
Modal Dialog:- Turn-off –computer

We will get a dialog box and that dialog box until it is interacted and disposed off
it will not allow any other component to interact…

User Defined Dialogs

Dialog class- Representation of dialog box

We can do it in two ways

Extends(if we use so many times in a pppprogram) and creating object(not having


much code then we use for creating object)

Common Dialog:-all window applications commn menus

Pre Defined Dialog:- in awt we don‟t have it but in swings we have

Panel: - It is a container which holds other container it doesn‟t have independent


existence
Example I:

import java.awt.*;

class A43 extends Frame

public static void main(String args[])

Frame f=new Frame("This is my First AWT Program");

f.setSize(200,200);

f.setVisible(true);

//f.setTitle("Frame Demo ");

System.out.println("press Ctrl+C ");

Example II

import java.awt.*;

class A44 extends Frame

public static void main(String args[])

Frame f=new Frame("This is my First AWT Program");

f.setSize(200,200);
f.setVisible(true);

Button btn=new Button("Show");

f.add(btn);

//TextField txt=new TextField();

//f.add(txt);

System.out.println("press Ctrl+C ");

Example III

import java.awt.*;

class A45

public static void main(String args[])

Frame f=new Frame("FirstFrame");

f.setSize(300,100);

f.setVisible(true);

Panel p=new Panel();

Label l=new Label("Enter Name");

TextField t=new TextField("aptech",10);

t.setEchoChar('@');

//t.setText("aptech");
//System.out.println(t.getText());

//System.out.println(t.getEchoChar());

Button b=new Button("I am Button");

//b.setLabel("Username");

//System.out.println(b.getLabel());

t.setForeground(Color.green);

t.setBackground(Color.red);

f.add(p);

p.add(l);

p.add(t);

p.add(b);

Example IV:

import java.awt.*;

import java.awt.event.*;

class TestFrame extends Frame

TestFrame(String Title)

super(Title);

setBackground(Color.black);
setForeground(new Color(0,255,0));

setFont(new Font("Times New Roman",Font.BOLD+Font.ITALIC,36));

setSize(400,100);

setVisible(true);

public void paint(Graphics g)

g.drawString("APTECH",70,70);

class A46

public static void main(String args[])

new TestFrame("SampleWIndow");

Example V

import java.awt.*;

class A47 extends Frame

public void paint(Graphics g){


Font f=new Font("Helvetica",Font.BOLD,24);

g.setFont(f);

g.drawString("This is my Frame",75,100);

public static void main(String args[])

A47 f=new A47();

f.setSize(300,250);

f.setVisible(true);

Example VI

//ListBox Demo

import java.awt.*;

class A48 extends Frame

A48(String name)

super(name);

Button b=new Button("Click");

List c=new List();

//c.setMultipleSelections(true);
c.add("Item1");

c.add("Item2");

c.add("Item3");

add("North",b);

add("South",c);

setVisible(true);

setSize(200,200);

public static void main(String args[])

A48 ld=new A48("My List");

}
Event Handling in Java

The user performs an action, such as, moving the mouse, pressing a key, releasing
the key and so on. All these operations generate an event.

Some of these events are handled by Abstract Window Toolkit (AWT) by the
environement in which these applications are executed, such as a browser. JDK1.2
followsthe "Delegation Model". This is a process that allows to register handlers
called "listeners", with the objects. These handlers are automatically called when
an even takes place.

An "EventListener" listens to a particular event generated by an object.

This calls the methods that handle the event, called the "event handler". Each
event listener provides methods that handle these events.

 Implement the appropriate listener interface.

Syntax:

public class MyApp extends Applet implements ActionListener

 Identify all components that generate events. The components could be a


button, label, menu etc.

 Identify all events to be handled. The events could be an "ActionEvent" if a


button is clicked or a "mouseEvent" if the mouse is dragged.

eg: btnClose.addActionListener(this);
Events and their Description:
Event Class Description
ActionEvent When a button is pressed, a list item is double clicked or a
menu is selected.

AdjustmentEvent When a scrollbar is used

ComponentEvent When a component is resized, moved, hidden or made


visible

FocusEvent When a component loses or gains keyboard focus.

ItemEvent When a menu item is selected or deselected or when a


checkbox or list item

WindowEvent When a window is activated, closed, opened or quit.

TextEvent When the value of a text field or text area is change

MouseEvent When mouse is moved, clicked, dragged or released.

KeyEvent When input is received from the keyboard.

The interfaces that are implemented to handle each of them are:

 ActionListener

 AdjustmentListener

 ComponentListener

 FocusListener

 ItemListener

 WindowListener
 TextListener

 MouseListener

 MouseMotionListener

 KeyListener
Example VII

import java.awt.*;

import java.awt.event.*;

class TestFrame extends Frame implements ItemListener

TextField UserName,Email;

Checkbox UseEmail;

TextField Password;
TestFrame()

super("Sample Window");

setLayout(new FlowLayout());

UserName = new TextField(20);

Email = new TextField(30);

Email.setEnabled(false);

Email.setBackground(Color.LIGHT_GRAY);

Password = new TextField(30);

Password.setEchoChar('*');

UseEmail = new Checkbox("use Email as UserName");

UseEmail.addItemListener(this);

add(new Label("UserName"));

add(UserName);

add(UseEmail);

add(Email);

add(new Label("Email ID"));

add(new Label("Password"));

add(Password);

setSize(400,100);

setVisible(true);

}
public void itemStateChanged(ItemEvent ie)

if(UseEmail.getState()==true)

UserName.setEnabled(false);

UserName.setBackground(Color.LIGHT_GRAY);

Email.setBackground(Color.WHITE);

Email.setEnabled(true);

Email.requestFocus();

else

UserName.setEnabled(true);

UserName.setBackground(Color.WHITE);

Email.setEnabled(false);

Email.setBackground(Color.LIGHT_GRAY);

UserName.requestFocus();

class A49

{
public static void main(String args[])

new TestFrame();

Example VIII

import java.awt.*;

import java.awt.event.*;

class ButtonEventDemo extends Frame implements ActionListener

ButtonEventDemo()

Frame frm=new Frame("Button Event Frame");

Panel pnl=new Panel();

Button btn=new Button("Click Me");

//Adding Event to the Button

btn.addActionListener(this);

frm.add(pnl);

pnl.add(btn);

frm.setVisible(true);

frm.setSize(300,200);
}

public void actionPerformed(ActionEvent ae)

System.out.println("Welcome to AWT Programming");

class A50

public static void main(String args[])

ButtonEventDemo B=new ButtonEventDemo();

Example IX

import java.awt.*;

import java.awt.event.*;

class TestFrame extends Frame implements ItemListener

TextField UserName,Email;

Checkbox UseEmail;
TextField Password;

TestFrame()

super("Sample Window");

setLayout(new FlowLayout());

UserName = new TextField(20);

Email = new TextField(30);

Email.setEnabled(false);

Email.setBackground(Color.LIGHT_GRAY);

Password = new TextField(30);

Password.setEchoChar('*');

UseEmail = new Checkbox("use Email as UserName");

UseEmail.addItemListener(this);

add(new Label("UserName"));

add(UserName);

add(UseEmail);

add(Email);

add(new Label("Email ID"));

add(new Label("Password"));

add(Password);

setSize(400,200);
setVisible(true);

public void itemStateChanged(ItemEvent ie)

if(UseEmail.getState()==true)

UserName.setEnabled(false);

UserName.setBackground(Color.LIGHT_GRAY);

Email.setBackground(Color.WHITE);

Email.setEnabled(true);

Email.requestFocus();

else

UserName.setEnabled(true);

UserName.setBackground(Color.WHITE);

Email.setEnabled(false);

Email.setBackground(Color.LIGHT_GRAY);

UserName.requestFocus();

}
class A51

public static void main(String args[])

new TestFrame();

Example X

import java.awt.*;

import java.awt.event.*;

class TestFrame extends Frame implements ItemListener

TextField UserName,Email;

Checkbox UseEmail;

TextField Password;

TestFrame()

super("Sample Window");

setLayout(new FlowLayout());

UserName = new TextField(20);

Email = new TextField(30);

Email.setEnabled(false);
Email.setBackground(Color.LIGHT_GRAY);

Password = new TextField(30);

Password.setEchoChar('*');

UseEmail = new Checkbox("use Email as UserName");

UseEmail.addItemListener(this);

add(new Label("UserName"));

add(UserName);

add(UseEmail);

add(Email);

add(new Label("Email ID"));

add(new Label("Password"));

add(Password);

setSize(400,200);

setVisible(true);

public void itemStateChanged(ItemEvent ie)

if(UseEmail.getState()==true)

UserName.setEnabled(false);

UserName.setBackground(Color.LIGHT_GRAY);

Email.setBackground(Color.WHITE);
Email.setEnabled(true);

Email.requestFocus();

else

UserName.setEnabled(true);

UserName.setBackground(Color.WHITE);

Email.setEnabled(false);

Email.setBackground(Color.LIGHT_GRAY);

UserName.requestFocus();

class A51

public static void main(String args[])

new TestFrame();

}
Example :

import java.awt.*;

import java.awt.event.*;

class MouseDemo extends Frame implements MouseListener

MouseDemo()

setSize(400,400);

setVisible(true);

setTitle("Example for MouseListener");

addMouseListener(this);

MyAdapter a=new MyAdapter();

addWindowListener(a);

public void mouseClicked(MouseEvent m1)

System.out.println("Mouse clicked");

public void mouseEntered(MouseEvent m2)

System.out.println("Mouse Entered");

}
public void mouseExited(MouseEvent m3)

System.out.println("Mouse Exited");

public void mousePressed(MouseEvent m4)

System.out.println("MousePressed");

public void mouseReleased(MouseEvent m5)

System.out.println("MouseReleased");

class MyAdapter extends WindowAdapter

public void windowClosing(WindowEvent we)

System.exit(0);

class A52

{
public static void main(String args[])

new MouseDemo();

Example XI

import java.awt.*;

import java.awt.event.*;

class MousemotionDemo extends Frame implements MouseMotionListener

MousemotionDemo()

setVisible(true);

setTitle("MousemotionExample");

addMouseMotionListener(this);

setSize(200,200);

public void mouseDragged(MouseEvent me)

System.out.println("Mouse dragged to :"+me.getX()+","+me.getY());

}
public void mouseMoved(MouseEvent me)

System.out.println("Mouse moved to :"+me.getX()+","+me.getY());

class A54

public static void main(String args[])

new MousemotionDemo();

FlowLayout:
import java.awt.*;

public class FlowAp extends Frame

public static void main(String argv[]){

FlowAp fa=new FlowAp();

//Change from BorderLayout default

fa.setLayout(new FlowLayout());

fa.setSize(400,300);
fa.setVisible(true);

FlowAp()

add(new Button("One"));

add(new Button("Two"));

add(new Button("Three"));

add(new Button("Four"));

add(new Button("Five"));

add(new Button("Six"));

add(new Button("Seven"));

add(new Button("Eight"));

add(new Button("Nine"));

add(new Button("Ten"));

}//End of constructor

}//End of Application

Example Using FlowLayout:

import java.awt.*;

public class FlowAp extends Frame

public static void main(String argv[]){

FlowAp fa=new FlowAp();


//Change from BorderLayout default

fa.setLayout(new FlowLayout());

fa.setSize(400,300);

fa.setVisible(true);

FlowAp()

add(new Button("One"));

add(new Button("Two"));

add(new Button("Three"));

add(new Button("Four"));

add(new Button("Five"));

add(new Button("Six"));

add(new Button("Seven"));

add(new Button("Eight"));

add(new Button("Nine"));

add(new Button("Ten"));

}//End of constructor

}//End of Application

Example using GridLayout:

import java.awt.*;

import java.awt.event.*;
class TestFrame extends Frame

Panel DisplayPanel;

Panel ButtonsPanel,MoveButtonsPanel,DMLButtonsPanel;

TextField txtDeptno,txtDname,txtLoc;

Button First,Last,Next,Previous;

Button Insert,Update,Delete,Exit;

TestFrame()

super("A sample Window");

DisplayPanel = new Panel();

DisplayPanel.setLayout(new GridLayout(3,2));

txtDeptno = new TextField(20);

txtDname = new TextField(20);

txtLoc = new TextField(20);

DisplayPanel.add(new Label("DeptNo"));

DisplayPanel.add(txtDeptno);

DisplayPanel.add(new Label("Dname"));

DisplayPanel.add(txtDname);

DisplayPanel.add(new Label("Loc"));

DisplayPanel.add(txtLoc);

ButtonsPanel = new Panel();

ButtonsPanel.setLayout(new GridLayout(2,1));
MoveButtonsPanel = new Panel();

First = new Button("|<");

Previous = new Button("<");

Next = new Button(">");

Last = new Button(">|");

MoveButtonsPanel.add(First);

MoveButtonsPanel.add(Previous);

MoveButtonsPanel.add(Next);

MoveButtonsPanel.add(Last);

DMLButtonsPanel = new Panel();

Insert = new Button("Insert");

Update = new Button("Update");

Delete = new Button("Delete");

Exit = new Button("Exit");

DMLButtonsPanel.add(Insert);

DMLButtonsPanel.add(Update);

DMLButtonsPanel.add(Delete);

DMLButtonsPanel.add(Exit);

ButtonsPanel.add(MoveButtonsPanel);

ButtonsPanel.add(DMLButtonsPanel);

add(DisplayPanel);

add(ButtonsPanel,BorderLayout.SOUTH);
pack();

setVisible(true);

class Demo

public static void main(String args[])

new TestFrame();

Applet:
An applet is a Java program that can be embedded in a HTML page and
executed on Java enabled web browser. An applet is like a small executable code
that needs a full application to contain it or execute it. An applet is created by
subclassing the java.applet.Applet class.

Difference between applets and applications:


An applet must be created by extending the java.applet.Applet class

For an application, there is no such constraint

Applications run using the java interpreter, while applets run on any
browser( which supports java) or used the appletviewer tool, which is
included in the JDK.
Execution of application begins with the main() method, while the execution of an
applet begins with the init() method.

An applet must contain at least one public class, failing which the compiler reports
an error. It is not mandatory to declare a main() method for an applet.

Output to an applet's window is not performed using


System.out.println(), but using different AWT methods, such as
drawString().

Life Cycle of Applets:


An Applet defines its structure from four events that takes place during the
execution. For each event a method is automatically called.

The methods are

init():
The method called during initiasation is known as the init() method.

The initialisation process of an applet includes creation of objects that it needs.


The init() method is used to load graphics, initialise variables and create objects.

start():
Once the initialisation is process is complete, the applet is started. The start()
method is called, when the applet is started. This method is used to restart the
applet after it has stopped.
stop():
The stop() method comes into the picture when the execution of an applet has to be
paused. An applet should be stopped before it is destroyed.

destroy():
An applet is destroyed using the destroy() method. The memory processor time
and swap disk space are returned to the system when the applet is destroyed.

Apart from these fundamental methods, there are methods called paint(), repaint()

paint():
The paint() method is used to display a line, text or an image on the screen. It
takes an argument of the class "Graphics".

Graphics is a part of the java.awt package.

eg: import java.awt.Graphics;

Example I:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=ap1 width=200 height=100 >
</applet>*/
public class ap1 extends Applet implements ActionListener
{
Label lab;
TextField tf1,tf2;
Button btnresult;
public void init()
{
lab=new Label("Enter a number: ");
tf1=new TextField(5);
tf2=new TextField(5);
btnresult=new Button("Double is ");
btnresult.addActionListener(this);
add(lab);
add(tf1);
add(btnresult);
add(tf2);
}
public void actionPerformed(ActionEvent ae)
{
System.out.println("Hai.. ");
}
}
/* Executing: javac ap1.java
appletviewer ap1.java
appletviewer ap1.html */

Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = AddButAppExp width=400 height=300>
</applet>
*/
public class AddButAppExp extends Applet
implements ActionListener
{
Button b1,b2;
String s;
public void init()
{
s = "Click a button";
b1 = new Button("This is the First Button");
b2 = new Button("A Smal Button");
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);
add(b2);
}
public void paint(Graphics g)
{
g.drawString(s,10,50);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == b1)
s = "First Button is clicked";
else
s = "Second small Button is clicked";
repaint();
}
}

Example:
import java.applet.*;
import java.awt.*;
/*
<applet code=FirstAppExp
width=400 height=400>
</applet>
*/
public class FirstAppExp extends Applet
{
String s;
public void init()
{
s = "Hello! Welcome to Applet Programming";
setBackground(Color.YELLOW);
}
public void paint(Graphics g)
{
g.drawString(s,100,200);
}
}

Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=ButChAppExp
width=500 height=500>
</applet>
*/
public class ButChAppExp extends Applet
implements ActionListener,ItemListener
{
Label lob,lcol;
Choice chob,chcol;
Button b;
int obind;
Color col;
public void init()
{
chob = new Choice();
chcol= new Choice();
b = new Button("All Clear");
lob = new Label("Select Object: ");
lcol = new Label("Select Color: ");
chob.add("Rectangle");
chob.add("RoundedRectangle");
chob.add("Square");
chob.add("Circle");
chob.add("Oval");
chob.add("Arc");
chcol.add("Blue");
chcol.add("Red");
chcol.add("Green");
chcol.add("Gray");
chcol.add("Magenta");
chob.select(1);
// obind = 2;
chcol.select("Green");
col = Color.GREEN;
chob.addItemListener(this);
chcol.addItemListener(this);
b.addActionListener(this);
add(lob);
add(chob);
add(lcol);
add(chcol);
add(b);
}
public void paint(Graphics g)
{
g.setColor(col);
switch(obind)
{
case 0: g.drawRect(5,120,120,50);
g.fillRect(5,180,120,50);
break;
case 1: g.drawRoundRect(5,120,120,50,10,10);
g.fillRoundRect(5,180,120,50,10,10);
break;
case 2: g.drawRect(5,120,50,50);
g.fillRect(5,180,50,50);
break;
case 3: g.drawOval(5,120,50,50);
g.fillOval(5,180,50,50);
break;
case 4: g.drawOval(5,120,120,50);
g.fillOval(5,180,120,50);
break;
case 5: g.drawArc(5,120,50,50,0,180);
g.fillArc(5,180,120,50,0,180);
break;
}
}
public void actionPerformed(ActionEvent ae)
{
obind = -1;
repaint();
}
public void itemStateChanged(ItemEvent ie)
{
if(ie.getSource() == chob)
{
obind = chob.getSelectedIndex();
}
else
{
switch(chcol.getSelectedIndex()) {
case 0: col = Color.BLUE; break;
case 1: col = Color.RED; break;
case 2: col = Color.GREEN; break;
case 3: col = Color.GRAY; break;
case 4: col = Color.MAGENTA; break;
}
}
repaint();
}
}
Example
import java.awt.*;
import java.applet.*;
/*
<applet code = FaceAppExp width=450
height =450>
</applet>
*/
public class FaceAppExp extends Applet
{
public void paint(Graphics g)
{
/*---laugh face stright angle---------*/
g.setColor(Color.GREEN);
g.fillOval(0,0,200,200); //face
g.setColor(Color.BLACK);
g.drawLine(100,60,100,120); //nose
g.setColor(Color.RED);
g.fillOval(40,50,40,40);
g.fillOval(120,50,40,40); //eyes
g.setColor(Color.BLACK);
g.drawArc(35,80,130,80,0,-180); //mouth
/*---laugh face side angle---------*/
g.setColor(Color.GREEN);
g.fillOval(250,0,200,200);
g.setColor(Color.BLACK);
g.drawLine(300,60,280,120);
g.drawLine(280,120,300,120);
g.setColor(Color.RED);
g.fillOval(270,50,40,40);
g.fillOval(290,50,40,40);
g.setColor(Color.BLACK);
g.drawArc(275,80,50,80,0,-180);
/*---cry face stright angle---------*/
g.setColor(Color.GREEN);
g.fillOval(0,250,200,200);
g.setColor(Color.BLACK);
g.drawLine(100,310,100,370);
g.setColor(Color.RED);
g.fillOval(40,300,40,40);
g.fillOval(120,300,40,40);
g.setColor(Color.BLACK);
g.drawArc(35,370,130,80,0,180);
/*---cry face side angle---------*/
g.setColor(Color.GREEN);
g.fillOval(250,250,200,200);
g.setColor(Color.BLACK);
g.drawLine(300,310,280,370);
g.drawLine(280,370,300,370);
g.setColor(Color.RED);
g.fillOval(270,300,40,40);
g.fillOval(290,300,40,40);
g.setColor(Color.BLACK);
g.drawArc(275,370,50,80,0,180);
}
}

Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code =LabelAppExp
width=500 height=300>
</applet>
*/
public class LabelAppExp extends Applet implements ActionListener
{
Label l;
TextField t;
public void init()
{
l = new Label("Hello Friends",Label.CENTER);
t = new TextField("Hello Friends",35);
t.addActionListener(this);
add(l);
add(t);
}
public void actionPerformed(ActionEvent ae)
{
l.setText(t.getText());
}
}

Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet
code=ListFontAppExp
width=600 height=600>
</applet>
*/
public class ListFontAppExp extends Applet
implements ItemListener, AdjustmentListener
{
String fn[];
List lb;
Scrollbar s;
GraphicsEnvironment ge;
String fontname;
int fontsize;
public void init()
{
ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
fn = ge.getAvailableFontFamilyNames();
lb = new List(10);
s = new Scrollbar();
s.setOrientation(Scrollbar.HORIZONTAL);
s.setMaximum(500);
s.setMinimum(5);
s.setValue(20);
fontsize = 20;
for(int i=0;i<fn.length;i++)
lb.add(fn[i]);
lb.select(0);
fontname = fn[0];
s.addAdjustmentListener(this);
lb.addItemListener(this);
add(s);
add(lb);
} public void itemStateChanged(ItemEvent ae){
fontname = lb.getSelectedItem();
repaint();
}
public void adjustmentValueChanged
(AdjustmentEvent ae)
{
fontsize = s.getValue();
repaint();
}
public void paint(Graphics g)
{
g.setFont(new Font
(fontname,Font.PLAIN,fontsize));
g.drawString("Selected Font: "+fontname,5,300);
}
}

Example:
import java.applet.*;
import java.awt.*;
/*
<applet code=SecAppExp width=600 height=600>
</applet>
*/
public class SecAppExp extends Applet
{
String s;
int x,y;
public void init()
{
s = "Graphiscs Methods Demo";
}
public void paint(Graphics g)
{
x=y=10;
g.setColor(Color.RED);
g.drawString(s,x,y); y+=5;
g.drawLine(x,y,x+150,y); y+=5;
g.setColor(Color.GRAY);
g.drawOval(x,y,50,50);
x+=55;
g.drawOval(x,y,150,50);
x=10; y+=55;
g.fillOval(x,y,50,50);
x+=55;
g.fillOval(x,y,150,50);
x=10; y+=55;
g.setColor(Color.MAGENTA);
g.drawRect(x,y,50,50);
x+=55;
g.drawRect(x,y,150,50);
x=10; y+=55;
g.fillRect(x,y,50,50);
x+=55;
g.fillRect(x,y,120,50);
x=10; y+=55;
g.setColor(Color.magenta);
g.drawArc(x,y,50,50,0,180);
x+=55;
g.fillArc(x,y,150,50,0,180);
x=10; y+=55;
g.setColor(Color.GREEN);
g.drawRoundRect(x,y,50,50,15,15);
x+=55;
g.fillRoundRect(x,y,150,50,15,15);
setBackground(Color.cyan);
}
}

Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=TextAreaAppExp
width=360 height=400>
</applet>
*/
public class TextAreaAppExp
extends Applet
implements ActionListener, ItemListener
{
Font f;
TextArea ta;
TextField tf;
Button b;
Checkbox cb,cb1,cb2;
CheckboxGroup cbg;
public void init()
{
ta = new TextArea(10,40);
tf = new TextField(35);
b = new Button("Clear");
cb = new Checkbox("Allow Edit",false);
cbg = new CheckboxGroup();
cb1 = new Checkbox("Bold",true,cbg);
cb2 = new Checkbox("Italic",false,cbg);
tf.addActionListener(this);
b.addActionListener(this);
cb.addItemListener(this);
cb1.addItemListener(this);
cb2.addItemListener(this);
add(tf);
add(b);
add(ta);
add(cb);
add(cb1);
add(cb2);
f = ta.getFont();
ta.setFont(new Font(
f.getName(),
Font.BOLD,
f.getSize()
)
);
ta.setEditable(false);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b)
{
tf.setText("");
ta.setText("");
}
else
{
ta.append(tf.getText()+"\n");
tf.setText("");
}
}
public void itemStateChanged(ItemEvent ie)
{
if(ie.getSource() == cb)
ta.setEditable(cb.getState());
else if(ie.getSource() == cb1)
ta.setFont(
new Font(
f.getName(),
Font.BOLD,
f.getSize()
)
);
else
ta.setFont(
new Font(
f.getName(),
Font.ITALIC,
f.getSize()
)
);

}
}

The Layout Managers


The Layout manager provides the physical layout of GUI elements suchs
buttons, textboxes etc.

Types of Layouts:
1. Flow Layout

2. Border Layout

3. Card Layout

4. Grid Layout

5. GridBag Layout
1.Flow Layout Manager:

The „Flow Layout‟ is the default layout manager for applets and panels. The
components are arranged from the upper left corner to the right bottom
corner. When there are number of components, they are arranged row wise
and left to right.

Example of FlowLayout:

import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

/* <applet code="flow" width=300 height=70>

</applet> */

public class flow extends Applet implements ActionListener

Button b1,b2,b3;

String msg="Layouts";

public void init()

b1=new Button("Left Aligned");

b2=new Button("Right Aligned");

b3=new Button("Center Aligned");


b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

add(b1);

add(b2);

add(b3);

public void actionPerformed(ActionEvent e)

int val;

if(e.getSource() == b1)

val=FlowLayout.LEFT;

msg="Layout - Leftt aligned";

else if(e.getSource() == b2)

val=FlowLayout.RIGHT;

msg="Layout - Right aligned";

else

val=FlowLayout.CENTER;
msg="Layout - Center aligned";

setLayout(new FlowLayout(val));

validate();

repaint();

public void paint(Graphics g)

g.drawString(msg, 100, 50);

2. Border Layout Manager:


The Border Layout is default layout manger for „Window‟, „Frame‟ and „Dialog‟.
This layout arranges up to five components in a container. These components can
be assigned to „North‟, „South‟, „East‟, „West‟, and „Center‟ of the container.

NORTH – corresponds to the top of the container

EAST – corresponds to the right of the container

SOUTH - corresponds to the bottom of the container

WEST – corresponds to the left of the container

CENTER - corresponds to the centre of the container.


Example of Border Layout:

import java.applet.Applet;

import java.awt.*;

public class Border1 extends Applet

public void init()

setLayout (new BorderLayout());

Label l = new Label("This is NORTH", Label.CENTER);

l.setBackground(Color.yellow);

Scrollbar sb1 = new Scrollbar();

Scrollbar sb2 = new Scrollbar();

add(l, BorderLayout.NORTH);

add(sb1, BorderLayout.WEST);

add(sb2, BorderLayout.EAST);

3. Card Layout Manager:


The CardLayout can store a stack of several layouts. Each layout is like a card in
deck. The card is usually a Panel object. The card to be displayed on top is
controlled by a separate component such as button.
Example of CardLayout:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class CardLayoutExample extends Applet

public void init()

MyCardPanel M=new MyCardPanel();

class MyCardPanel extends Frame

private Tab1 p;

private Tab2 p1;

private Tab3 p2;

private Panel cardPanel;

private CardLayout card;

private Color activeColor = new Color(100,200,200);

private Color inactiveColor = new Color(150,150,150);

public MyCardPanel()

p = new Tab1();
p1 = new Tab2();

p2 = new Tab3();

setBackground(activeColor);

setBounds(200,200,300,350);

addWindowListener(new Terminator());

Panel controls = new Panel(new GridLayout(1,3));

controls.add(p);

controls.add(p1);

controls.add(p2);

card = new CardLayout();

cardPanel = new Panel(card);

cardPanel.add("Card1", new FirstCard());

cardPanel.add("Card2", new SecondCard());

cardPanel.add("Card3", new ThirdCard());

Panel border = new Panel(new BorderLayout());

border.add(controls, "North");

border.add(cardPanel, "Center");

add(border);

setVisible(true);

public class Terminator extends WindowAdapter

public void windowClosing(WindowEvent e)


{

dispose();

public class FirstCard extends Panel

public FirstCard()

add(new Label("First Card"));

setBackground(activeColor);

public class SecondCard extends Panel

public SecondCard()

add(new Label("Second Card"));

setBackground(activeColor);

public class ThirdCard extends Panel

public ThirdCard()
{

add(new Label("Third Card"));

setBackground(activeColor);

public class Tab1 extends Panel

public Tab1()

addMouseListener(new MouseAdapter()

public void mousePressed(MouseEvent e)

card.show(cardPanel, "Card1");

setBackground(activeColor);

p1.setBackground(inactiveColor);

p2.setBackground(inactiveColor);

});

public void paint(Graphics g)

g.drawString("Tab 1",25,20);
}

public Dimension getPreferredSize()

// only need this for one of the tabs

return new Dimension(100,35);

public class Tab2 extends Panel

public Tab2()

setBackground(inactiveColor);

addMouseListener(new MouseAdapter()

public void mousePressed(MouseEvent e)

card.show(cardPanel, "Card2");

setBackground(activeColor);

p.setBackground(inactiveColor);

p2.setBackground(inactiveColor);

});

}
public void paint(Graphics g)

g.drawString("Tab 2",25,20);

public class Tab3 extends Panel

public Tab3()

setBackground(inactiveColor);

addMouseListener(new MouseAdapter()

public void mousePressed(MouseEvent e)

card.show(cardPanel, "Card3");

setBackground(activeColor);

p.setBackground(inactiveColor);

p1.setBackground(inactiveColor);

});

}
public void paint(Graphics g)

g.drawString("Tab 3",25,20);

/*

<applet code=CardLayoutExample width=300 height=200>

</applet>

*/

4. The Grid Layout Manager:


The GridLayout helps us to divide the container into a grid. The components
placed are in rows and columns. Each grid should contain at least one component.
A grid is used when all the components are of the same size.

Example of GridLayout:

import java.applet.Applet;

import java.awt.*;

public class Grid extends Applet

public void init()

{
setLayout (new GridLayout(5, 3)); // 5 rows, 3 columns, no gaps

for (int row = 0; row < 5; row ++)

add (new Label("Label " + row));

add (new Button("Button " + row));

add (new TextField("TextField " + row));

5. The GridBag Layout Manager:


The GridBag Layout is more flexible than any other layout. The GridBagLayout
manager is most complex layout manager. In this layout the components need not
be of the same size. It is similar to the GriLayout manager since the components
are arranged in grid of rows and columns.

Example I:-

/* <applet code=FirstApp width=200 height=100 >

</applet> */

import java.applet.*;

public class FirstApp extends Applet

{
public void init()

System.out.println("Componenet is initializing..");

public void start()

System.out.println("Started..");

public void stop()

System.out.println("Stopped..");

public void destroy()

System.out.println("Destroyed..");

Example II:-

import java.awt.*;

import java.awt.event.*;

import java.applet.*;
public class ap1 extends Applet implements ActionListener

Label lab;

TextField tf1,tf2,tf3;

Button btnresult;

public void init()

lab=new Label("Enter a number: ");

tf1=new TextField(5);

tf2=new TextField(5);

tf3=new TextField(5);

btnresult=new Button("Double is ");

btnresult.addActionListener(this);

add(lab);

add(tf1);

add(btnresult);

add(tf2);

add(tf3);

public void actionPerformed(ActionEvent ae)

System.out.println("Hai.. ");

int x=Integer.parseInt(tf1.getText());
int y=Integer.parseInt(tf2.getText());

int z=x+y;

tf3.setText( " "+ z);

//tf3.setText(Integer.toString(z));

/* Executing: javac ap1.java

appletviewer ap1.java

appletviewer ap1.html */

Example I

import java.applet.*;

import java.awt.*;

/*<APPLET code = HelloWorld height=200 width=400>

<param name = "Message" value = "Applets are easy">

</APPLET>*/

public class HelloWorld extends Applet

String Msg;

public void init()

setForeground(Color.green);

setBackground(Color.black);
setFont(new Font("Times New Roman",Font.BOLD+Font.ITALIC,36));

Msg= getParameter("Message");

public void paint(Graphics g)

g.drawString("HelloWorld",50,100);

Executing Applet Program:


-> Write the Applet Code in notepad (.html)with class name. eg: HelloWorld

-> javac HelloWord.java

-> AppletViewer HelloWorld.html

->AppletViewer HelloWorld.java

Example II

/* <applet code=DisplayImage width=200 height=200>

</applet>*/

import java.awt.*;

import java.applet.*;

public class DisplayImage extends Applet

{
Image img;

public void init()

img=getImage(getCodeBase(),"2.jpg");

public void paint(Graphics g)

g.drawImage(img, 20,20, this);

Example III

/*

<applet code=CoolApplet width=200 height=200>

</applet>

*/

import java.awt.*;

import java.applet.*;

import java.lang.*;

public class CoolApplet extends Applet

public void paint(Graphics g)

Font courier=new Font("Courier New", Font.BOLD, 18);


g.setFont(courier);

setBackground(Color.blue);

g.setColor(Color.white);

g.drawString("Java is Cool! ",100,100);

String Functions
Java provides a class called String to represent text data.

Example:

String str=new String();

str= “Hello World”;

Example I

import java.util.Scanner;

class A55

public static void main(String args[])

String empName=new String();

String typeofwork=new String();

Scanner input=new Scanner(System.in);

System.out.print("Enter Name: ");


empName = input.nextLine();

System.out.print("Enter Designation: ");

typeofwork=input.nextLine();

System.out.println("Employee name: "+empName);

System.out.println("Type of work : "+typeofwork);

Methods:
The class String includes various methods to compare string, find length of string,
remove white spaces characters of string and much more.

length() charAt()

concat() compareTo()

indexOf() lastIndedOf()

replace() subString()

toString() Trim()

Example I:

class A56

public static void main(String args[]) {

String empname=new String();

empname = "aptech computers";

System.out.println(empname.charAt(10));
}

Example II:

class A57

public static void main(String args[])

String empname=new String();

empname = "Aptech";

System.out.println(empname.concat(" Grafx"));

Example III

class A58

public static void main(String args[])

String empname=new String();

empname = "Aptech";

System.out.println(empname.compareTo("Aptech"));

}
}

Example IV

class A59

public static void main(String args[]) {

StringBuilder str=new StringBuilder("Java ");

str.append(" Programming ");

System.out.println(str);

str.append(5.0);

System.out.println(str);

Example V

class A60

public static void main(String args[])

StringBuilder str=new StringBuilder("Java Programming ");

str.insert(5," 6.0 ");

System.out.println(str);

}
}

Example VI

class A61

public static void main(String args[])

StringBuilder str=new StringBuilder("Java Programming language 6.0");

System.out.println("Before Deletion :"+str);

str.delete(12,16); //deleting “ming"

System.out.println("After Deletion :"+str);

}
STREAMS

A Stream is a continuous flow of data from source to destination.


Any data within a device always flows through either input stream or
through output stream.

Figure 1: Output Stream from source to Application (App)

Figure 2: Input Stream from Application to Source (Hard Disk and other memory
devices)

The data will be passed through streams from one device to another
device. So stream can be a sequence of data.

A program uses input stream to reads the data into a source where as
an output stream writes data from source to the application.
In java, Streams can be observed in the program that can be used to
handle data from a file or other similar sources.

There are various stream handling functions in Java, which are given
in a package called java.IO. But these can be classified into 2 types:

Byte Streams:
These are simple input and output streams which reads 8-bit
characters one at a time.

One of the examples of these byte streams are FileInputStream and


FileOutputStream.

System.out class :
The standard output stream is used to typically display the output on the screen.
System.in class :
The standard input stream usually comes from the keyboard and is used for reading
characters of data.

System.err class :
This is standard error stream.

The java.io Package:


All streams are available in java.io package.

The InputStream Class:


The class „InputStream „ is an abstract class. It defines how data is received.
It defines how data is received. The important point is not where the data comes
from, but that it is accessible. The class InputStream provides a number of
methods fro reading and taking streams of data as input. Eg: read() method

The OutputStream Class:


The class „OutputStream‟ is also abstract. It defines the way in which
outputs are written to streams. This class provides a set of methods that help in
creating, writing and processing output streams. Eg: write() method

The File Class:


The File class is used to access file and directory objects.

Example I
import java.io.*;
class FileDetails
{

public void display()


{
File f=new File("f:/uma/io streams/one.txt");
System.out.println("it is file:"+f.isFile());
System.out.println("File Name:"+f.getName());
System.out.println("File Path:"+f.getPath());
System.out.println("size of file:"+f.length());
System.out.println("parent of file:"+f.getParent());
System.out.println("modify time:"+f.lastModified());
System.out.println("file is hidden:"+f.isHidden());
System.out.println("can write:"+f.canWrite());
}
}
class FileDemo
{
public static void main(String args[])
{
new FileDetails().display();
}
}

Example II
import java.io.*;
class ReadFile
{
public static void main(String args[])throws IOException
{
//It reads the data in binary format(Binary Stream (ASII Codes))
FileInputStream f1 = new FileInputStream("one.txt");
int x = f1.read();
while(x!=-1)
{
System.out.print((char)x);
x=f1.read();
}
f1.close();

}
}

Example III
import java.io.*;
class SequenceDemo
{
public static void main(String args[])throws IOException
{
FileInputStream f1 = new FileInputStream("one.txt");
FileInputStream f2 = new FileInputStream("two.txt");

SequenceInputStream sis = new SequenceInputStream(f1,f2);


int x = sis.read();
while(x!=-1)
{
System.out.print((char)x);
x=sis.read();
}
sis.close();
f1.close();
f2.close();
}
}

Example IV
import java.io.*;
class FileWriterDemo {
public static void main(String args[]) {
try {
// Create a file writer
FileWriter fw = new FileWriter("three.txt");
// Write strings to the file
for(int i = 0; i < 12; i++) {
fw.write("Line " + i + "\n");
}
// Close file writer
fw.close();
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}

Example V
import java.io.*;
class BufferedInputStreamDemo {
public static void main(String args[]) {
try {

// Create a file input stream


FileInputStream fis = new FileInputStream("one.txt");
// Create a buffered input stream
BufferedInputStream bis =new BufferedInputStream(fis);
// Read and display data
int i;
while((i = bis.read()) != -1) {
System.out.print((char)i);
}
// Close file input stream
fis.close();
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}

Example VI
import java.io.*;
class SequenceDemo
{
public static void main(String args[])throws IOException
{
FileInputStream f1 = new FileInputStream("one.txt");
FileInputStream f2 = new FileInputStream("two.txt");
SequenceInputStream sis = new SequenceInputStream(f1,f2);
int x = sis.read();
while(x!=-1)
{
System.out.print((char)x);
x=sis.read();
}
sis.close();
f1.close();
f2.close();
}
}

You might also like