Java Notes
Java Notes
JAVA PROGRAMMING(SCS1209)
UNIT-1
Introduction to Java
OOP concepts – Java Byte code –Features of Java- Objects and Classes –Access specifiers-
Constructors- Constuctor Overloading-Method Overloading- Static and Final keywords-This
keyword-Garbage Collection-Finalize method-Inheritance- Using Super- Method overriding-
Abstract classes-Using final with inheritance.
OOP Concepts:
Object:
Class:
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an assembler
which is an alias representation of a C++ code. As soon as a java program is compiled, java
bytecode is generated. In more apt terms, java bytecode is the machine code in the form of a
.class file. With the help of java bytecode we achieve platform independence in java.
When we write a program in Java, firstly, the compiler compiles that program and a bytecode is
generated for that piece of code. When we wish to run this .class file on any other platform, we
can do so. After the first compilation, the bytecode generated is now run by the Java Virtual
Machine and not the processor in consideration. This essentially means that we only need to
have basic java installation on any platforms that we want to run our code on. Resources
required to run the bytecode are made available by theJava Virtual Machine, which calls the
processor to allocate the required resources. JVM's are stack-based so they stack
implementation to read the codes.
Source code .java file
Compiler
Platform independence is one of the soul reasons for which James Gosling started the
formation of java and it is this implementation of bytecode which helps us to achieve this.
Hence bytecode is a very important component of any java [Link] set of instructions for
the JVM may differ from system to system but all can interpret the bytecode. A point to keep in
mind is that bytecodes are non-runnable codes and rely on the availability of an interpreter to
execute and thus the JVM comes into play.
Bytecode is essentially the machine level language which runs on the Java Virtual
Machine. Whenever a class is loaded, it gets a stream of bytecode per method of the class.
Whenever that method is called during the execution of a program, the bytecode for that
method gets [Link] not only compiles the program but also generates the bytecode for
the program. Thus, we have realized that the bytecode implementation makes Java a platform-
independent language. This helps to add portability to Java which is lacking in languages like C
or C++. Portability ensures that Java can be implemented on a wide array of platforms like
desktops, mobile devices, severs and many more. Supporting this, Sun Microsystems captioned
JAVA as "write once, read anywhere" or "WORA" in resonance to the bytecode interpretation.
Features of Java
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as java buzzwords.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS,
etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a
platform-independent code because it can be run on multiple platforms, i.e., Write Once and
Run Anywhere(WORA).
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
o There is automatic garbage collection in java which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
Architecture-neutral
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both
32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C,
C++, etc.
Distributed
Multi-threaded
Dynamic
Java supports dynamic compilation and automatic memory management (garbage collection).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:
o No explicit pointer
Object:
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an
intangible object is the banking system.
o Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is
used to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
Object Definitions:
CLASS
o Fields(Variable)
o Methods
Fields :
A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time. It gets memory at
runtime when an object or instance is created. That is why it is known as an instance variable.
Methods:
In Java, a method is like a function which is used to expose the behavior of an object
Syntax of Class:
class classname
{
Fields;
methods;
}
Example:
class welcome
{
public static void main(String[] args)
{
[Link]("welcome");
}
}
Save: [Link]
Compile: javac [Link]
Output:
welcome.
Interpret:java fields
Output:
null
class fields1
{
int i;
String name;
public static void main(String[] args)
{
fields f=new fields();
f.i=10;
[Link]="cse";
[Link](f.i+"\n"+[Link]);
}
}
10
cse
class student
{
int rollno;
String name;
void getdata()
{
rollno=123;
name="cse";
}
void display()
{
[Link]("Rollno:"+rollno+"\n"+"Name:"+name);
}
public static void main(String[] args)
{
student s=new student();
[Link]();
[Link]();
}
}
output:
Rollno:123
Name:cse
class student1
{
int rollno;
String name;
void getdata(int r,String s)
{
rollno=r;
name=s;
}
void display()
{
[Link]("Rollno:"+rollno+"\n"+"Name:"+name);
}
public static void main(String[] args)
{
student1 s1=new student1();
[Link](111,"cse");
[Link]();
}
}
E:\basic pgms>javac [Link]
Rollno:111
Name:cse
Access specifiers:
The access specifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and class
by applying the access modifier on it.
1. Private: The access level of a private specifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default specifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected specifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public specifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Constructors
Java allows objects to initialize themselves when they are created. This automatic
initialization is performed through the use of a constructor.
A constructor initializes an object immediately upon creation. It has the same name
as the class in which it resides and is syntactically similar to a method. Once defined,the
constructor is automatically called immediately after the object is created, before the new
operator completes.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Syntax:
class rectangle
{
variable declaration;
rectangle()//construtor
{
}
}
Default Constructor
If there is no constructor available in the class It calls a default constructor. In such
case, Java compiler provides a default constructor by default.
class Default
{
int i;
String s;
double d;
boolean b;
Default()
{
}
public static void main(String[] args)
{
Default d1=new Default();
[Link]("Int:"+d1.i);
[Link]("String:"+d1.s);
[Link]("Double:"+d1.d);
[Link]("Boolean:"+d1.b);
}
}
E:\basic pgms>javac [Link]
E:\basic pgms>java Default
Int:0
String:null
Double:0.0
Boolean:false
Parametarized Constructor:
EX:
class circle
{
double rad,area;
double pi;
circle(double r, double p)
{
rad=r;
pi=p;
}
void calculate()
{
area=rad*rad*pi;
[Link](area);
}
public static void main(String[] args)
{
circle c=new circle(6.2,3.14);
[Link]();
}
}
120.70160000000001
Method Overloading
In Java it is possible to define two or more methods within the same class that share
the same name, as long as their parameter declarations are different. When this is the case, the
methods are said to be overloaded, and the process is referred to as method overloading.
Method overloading is one of the ways that Java implements polymorphism.
Syntax:
class overload
{
void add(int a)
{
}
void add(int a,int b)
{
}
double add(double a,double b)
{
}
}
EX:
class addition
{
int a,b,c;
void add()
{
a=20;b=30;
c=a+b;
[Link]("simple function:"+c);
}
void add(int a, int b)
{
c=a+b;
[Link](" function with argument:"+c);
}
double add(double a,double b)
{
return(a+b);
}
simple function:50
return function:21.0
Constructor Overloading
EX:
class conaddition
{
int a,b,c;
double d,e;
conaddition()
{
a=20;b=30;
[Link]("simple Construtor:"+ (a+b));
}
conaddition(int a, int b)
{
[Link]("Construtor with argument:"+ (a+b));
}
conaddition(double e,double f)
{
[Link]("double constructor:"+ (e+f));
}
public static void main(String[] args)
{
conaddition an=new conaddition();
conaddition an1=new conaddition(10,20);
conaddition an2=new conaddition(10.5,20.5);
}
}
E:\basic pgms>javac [Link]
E:\basic pgms>java conaddition
simple Construtor:50
double constructor:31.0
To create a member that can be used by itself, without reference to a specific instance.
To create such a member, precede its declaration with the keyword static.
When a member is declared static, it can be accessed before any objects of its class
are created, and without reference to any object.
You can declare both methods and variables to be static
Ex:
class staticex
{
static int a = 3;
static int b;
static void meth(int x) {
[Link]("x = " + x);
[Link]("a = " + a);
[Link]("b = " + b);
}
static {
[Link]("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
x = 42
a=3
b = 12
Final Keyword
Syntax:
final int a;
class finalex
{
final int a=20;
int b=10,c;
void display()
{
a=a+b;
[Link](" value a is cannot changed"+a);
}
public static void main(String[] args)
{
finalex fe=new finalex();
[Link]();
}
}
a=a+b;
1 error
This keyword:
EX:
class thisex
{
int i,fa=1,f;
thisex(int f)
{
this.f=f;
}
int fact()
{
for(i=1;i<=f;i++)
{
fa=fa*i;
}
return fa;
}
public static void main(String[] args)
{
thisex te=new thisex(5);
[Link]("factorial is:"+[Link]());
}
}
factorial is:120
Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
By nulling a reference:
2. e=null;
3. e1=e2;
By anonymous object:
1. new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object class as:
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
Inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
[Link] Inheritance:
Class A
Class B
[Link] Inheritance
Class A
Class B
Class C
[Link] Inheritance
Class A
Class B Class C
[Link] Inheritance
Class A Class B
Class c
[Link] Inheritance
Class A
Class B Class C
Class D
Single Inheritance:
Ex:
class add
{
int x,y,result;
public void sum()
{
result=x+y;
}
}
class sub extends add
{
public void minus()
{
result=x-y;
}
}
public class Singleinherit {
public static void main(String[] args) {
sub obj=new sub();
obj.x=10;
obj.y=20;
[Link]();
[Link]([Link]);
[Link]();
[Link]([Link]);
}
}
30
-10
Multilevel Inheritance:
EX:
class first
{
String name;
first()
{
name ="IstYear";
[Link](name);
}
void dis()
{
[Link]("6subjects+3lab");
}
}
class second extends first
{
second()
{
name="IInd year";
[Link](name);
}
void dis()
{
[Link]("6subjects+2lab");
}
}
public class Multilevel extends second
{
Multilevel()
{
name="Department";
[Link](name);
}
void dis2()
{
[Link]("HOD");
}
IstYear
IInd year
Department
6subjects+3lab
6subjects+2lab
HOD
Hierarchial Inheritance:
Two child class inherits one parent class is called Hierarchial inheritance
Ex:
class first
{
String s="cse";
void dis()
{
[Link]("Name:"+s);
}
}
class second extends first
{
int m[]={90,98,99,100,100,100};
int total;
void dis1()
{
for(int i=0;i<[Link];i++)
{
total=total+m[i];
}
[Link]("Total:"+total);
}
}
Name:cse
Total:587
Method overriding:
Base class and sup class have the same methods, the sub class method only
[Link] is known as Overriding.
Java has a method provision to executes the same methods of Base and sup class is
called "super ".
Ex:
class student
{
int rno;
String name;
void display(int rno,String name)
{
[Link](rno+"\n"+name);
}
}
class mark extends student
{
int m1,m2,m3,tot,avg;
void display(int m1,int m2,int m3)
{
[Link](1234,"mahi");
tot=m1+m2+m3;
avg=tot/3;
[Link]("tot:"+tot+"\n"+"avg:"+" "+avg);
}
}
class overriding
{
public static void main(String args[])
{
mark m1=new mark();
[Link](90,92,98);
}
}
E:\javapgms>javac [Link]
E:\javapgms>java overriding
1234
mahi
tot:280
avg: 93
Abstract classes
1. Abstract class
2. Interface
Rules:
Ex:
{
String s,city,add;
int i;
void f1()
{
s= "cse";
i=12345;
city="chennai";
add="sathaybama";
}
//abstract public void dis1();
abstract public void address();
}
cse
12345
chennai
sathaybama
To disallow a method from being overridden, specify final as a modifier at the start of its
declaration.
[Link] Class
[Link] method
[Link] variable
Ex:
1 error
Unit -II
Interface:
Defining an Interface:
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
// ...
return-type method-nameN(parameter-list);
They are impicitly final and static means they cannot be changed by the implemented
class.
They must be initalized with a constant value.
Ex:
interface student
void display();
Implementing interfaces
Once an interface has been defined, one or more classes can implement that interface.
To implement an interface, include the implements clause in a class definition, and
then create the methods defined by the interface.
Ex:
interface student
{
int i=10;
public void display(String s);
}
class A implements student
{
public void display(String s)
{
if(i%2==0)
{
[Link]("My first interface"+s);
[Link]("i is even:"+i);
}
}
}
class interfaceex
{
public static void main(String[] args)
{
A a1=new A();
[Link]("student");
}}
My first interfacestudent
i is even:10
Extending interfaces
EX:
interface A {
void meth1();
void meth2();
}
interface B extends A {
void meth3();
}
Implement meth1().
Implement meth2().
Implement meth3().
Ex:
interface area
{
final static float pi=3.14F;
float compute(float x,float y);
}
class rectangle implements area
{
public float compute(float x,float y)
{
return(x*y);
}
}
class circle implements area
{
public float compute(float x,float y)
{
return(pi*x*x);
}
}
public class Interface1 {
public static void main(String[] args) {
rectangle rect=new rectangle();
circle c=new circle();
area a;
a=rect;
[Link]("area of rectangle"+[Link](10,20));
a=c;
[Link]("area of circle"+[Link](10,0));
}
}
output:
area of rectangle200.0
area of circle314.0
Packages:
1. Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2. Java package provides access protection.
Defining a package:
package pack;
Here, pack is the name of the package.
package pack;
public class a
{
public void msg()
{
[Link]("welcome");
}
}
Importing packages
Java includes the import statement to bring certain classes, or entire packages, into
visibility.
Once imported, a class can be referred to directly, using only its name. The import
statement is a convenience to the programmer and is not technically needed to write a
complete Java program.
In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions.
import packagename.*;
or
import [Link];
Ex:
import pack.*;
public class calculator
{
public static void main(String args[])
{
a a1=new a();
[Link]();
}}
E:\javapgms>javac [Link]
E:\javapgms>java calculator
welcome
package pack;
public class a
{
public void msg()
{
[Link]("welcome");
}
}
package mypack;
import [Link].*;
public class arith
{
public void cal()
{
int a,b,c;
Scanner sr=new Scanner([Link]);
[Link]("enter the value of a");
a=[Link]();
[Link]("enter the value of b");
b=[Link]();
c=a+b;
[Link]("Addition:"+c);
c=a-b;
[Link]("Subtraction:"+c);
c=a*b;
[Link]("Multipliction:"+c);
c=a/b;
[Link]("Division:"+c);
}
}
import pack.*;
import mypack.*;
public class calculator
{
public static void main(String args[])
{
a a1=new a();
arith ar=new arith();
[Link]();
[Link]();
}
}
E:\javapgms>javac [Link]
E:\javapgms>java calculator
welcome
10
20
Addition:30
Subtraction:-10
Multipliction:200
Division:0
Access protection
Classes and packages are both means of encapsulating and containing the name space
and scope of variables and methods.
Packages act as containers for classes and other subordinate packages
Classes act as containers for data and code.
The three access specifiers, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories.
Different No No No Yes
package
non-subclass
Ex:
Private:
package pack;
class a
{
void msg()
{
[Link]("welcome");
}
}
E:\javapgms>javac [Link]
[Link]: error: a is not public in pack; cannot be accessed from outside
package
a a1=new a();
a a1=new a();
2 errors
Protected:
package pack;
protected class a
{
protected void msg()
{
[Link]("welcome");
}
}
E:\javapgms>javac [Link]
.\pack\[Link]: error: modifier protected not allowed here
protected class a
de package
a a1=new a();
de package
a a1=new a();
3 errors
The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
Exception
Exception handling
The core advantage of exception handling is to maintain the normal flow of the
application.
Exception normally disrupts the normal flow of the application that is why we use exception
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we
perform exception handling, rest of the statement will be executed. That is why we use
exception
handling in java.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes that extend Throwable class except Runtime Exception and Error are known as
compile-time.
2) Unchecked Exception
The classes that extend Runtime Exception are known as unchecked exceptions e.g. Arithmetic
3) Error
There are given some scenarios where unchecked exceptions can occur. They are as follows:
If we have null value in any variable, performing any operation by the variable occurs
an NullPointerException.
1. String s=null;
2. [Link]([Link]());//NullPointerException
NumberFormatException.
1. String s="abc";
2. int i=[Link](s);//NumberFormatException
If you are inserting any value in the wrong index, it would result
2. a[10]=50; //ArrayIndexOutOfBoundsException
1. try
2. catch
3. finally
4. throw
5. throws
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.
try
catch(Exception_class_Name ref)
{}
try
finally{}
Java catch block is used to handle the Exception. It must be used after the try block
[Link] can use multiple catch block with a single try.
Output:
Exception in thread main [Link]:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, rest of the
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Output:
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
If you have to perform different tasks at the occurrence of different Exceptions, use
java multicatch block.
Ex.
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){[Link]("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("task 2 compltd");
}
catch(Exception e){[Link]("common task completed");}
[Link]("rest of the code...");
}
}
Output:task1 completed
rest of the code...
Rules
At a time only one Exception is occured and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .
class TestMultipleCatchBlock1
{
public static void main(String args[])
{
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){[Link]("common task completed");}
catch(ArithmeticException e){[Link]("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){[Link]("task 2 completed");}
[Link]("rest of the code...");
}
}
Sometimes a situation may arise where a part of a block may cause one error and the
entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
finally block
Need of finally
Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Case 1
class TestFinallyBlock
{
public static void main(String args[])
{
Try
{
int data=25/5;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always executed");}
[Link]("rest of the code...");
}
}
Output:5
Case 2
class TestFinallyBlock1
{
public static void main(String args[])
{
Try
{
int data=25/0;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always executed");}
[Link]("rest of the code...");
}
Case 3
For each try block there can be zero or more catch blocks, but only one finally block. The
finally block will not be executed if program exits(either by calling [Link]() or by causing a
throw exception
throw keyword
1. throw exception;
Ex of throw IOException.
In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
Output:
Exception in thread main [Link]:not valid
throws keyword
Syntax of throws
//method code
• error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
import [Link];
class Testthrows1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
Try
{
n();
}catch(Exception e){[Link]("exception handled");}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
[Link]("normal flow...");
}
}
Case1:You caught the exception i.e. handle the exception using try/catch.
Case2:You declare the exception i.e. specifying throws with the method.
In case you handle the exception, the code will be executed fine whether exception
import [Link].*;
class M
{
void method()throws IOException
{
throw new IOException("device error");
}
}
public class Testthrows2
{
Output:exception handled
normal flow...
In case you declare the exception, if exception does not occur, the code will be
executed fine.
In case you declare the exception if exception occures, an exception will be thrown at
runtime because throws does not handle the exception.
import [Link].*;
class M
{
void method()throws IOException
{
[Link]("device operation performed");
}
}
class Testthrows3
{
public static void main(String args[])throws IOException
{//declare exception
M m=new M();
[Link]();
[Link]("normal flow...");
}
}
import [Link].*;
class M
{
void method()throws IOException
{
throw new IOException("device error");
}
}
class Testthrows4
{
public static void main(String args[])throws IOException
{//declare exception
M m=new M();
[Link]();
[Link]("normal flow...");
}
}
Output:Runtime Exception
Difference between throw and throws
2) Checked exception cannot be propagated using throw only. Checked exception can be
propagated with throws.
4) Throw is used within the method. Throws is used with the method signature.
Exceptions
throw example
void m()
//method code
There are many differences between final, finally and finalize. A list of differences between
1) Final is used to apply restrictions on class, method and variable. Final classcan't be inherited,
final method can't be overridden and final variable value can't be changed.
Finally is used to place important code, it will be executed whether exception is handled or
not.
Finalize is used to perform clean up processing just before object is garbage collected.
class FinalExample
{
public static void main(String[] args)
{
final int x=100;
x=200;//Compile Time Error
}
}
class FinallyExample
{
public static void main(String[] args)
{
Try
{
int x=300;
}
catch(Exception e){[Link](e);}
finally{[Link]("finally block is executed");}
}
}
class FinalizeExample
{
public void finalize()
{
[Link]("finalize called");
}
public static void main(String[] args)
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
[Link]();
}
}
There are many rules if we talk about methodoverriding with exception handling.
Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception.
import [Link].*;
class Parent
{
void msg(){[Link]("parent");}
}
class TestExceptionChild extends Parent
{
void msg()throws IOException
{
[Link]("TestExceptionChild");
}
public static void main(String args[])
{
Parent p=new TestExceptionChild();
[Link]();
}
}
Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.
import [Link].*;
class Parent
{
void msg(){[Link]("parent");}
}
class TestExceptionChild1 extends Parent
{
void msg()throws ArithmeticException
{
[Link]("child");
}
public static void main(String args[])
{
Parent p=new TestExceptionChild1();
[Link]();
}
}
Output:child
If the superclass method declares an exception
Rule: If the superclass method declares an exception, subclass overridden method can declare
import [Link].*;
class Parent
{
void msg()throws ArithmeticException{[Link]("parent");}
}
class TestExceptionChild2 extends Parent
{
void msg()throws Exception{[Link]("child");}
public static void main(String args[])
{
Parent p=new TestExceptionChild2();
Try
{
[Link]();
}catch(Exception e){}
}
}
import [Link].*;
class Parent
{
void msg()throws Exception{[Link]("parent");}
}
class TestExceptionChild3 extends Parent
{
void msg()throws Exception{[Link]("child");}
public static void main(String args[])
{
Parent p=new TestExceptionChild3();
Try
{
[Link]();
}catch(Exception e){}
}
}
Output:child
import [Link].*;
class Parent
{
Output:child
import [Link].*;
class Parent
{
void msg()throws Exception{[Link]("parent");}
}
class TestExceptionChild5 extends Parent
{
void msg(){[Link]("child");}
public static void main(String args[])
{
Parent p=new TestExceptionChild5();
Try
{
[Link]();
}catch(Exception e){}
}
}
Output:child
UNIT 3
IO Streams - Introduction – Wrapper Classes- Text and Binary formats of Data – Input Stream
and Output Stream classes- Reader and Writer Classes –Data Output Stream and Data Input
Stream classes.
Multi Threading
Multi threading is a program control. In this the program is divided into two or more
independent subprograms called threads and are processed Parallely. Every program has
atleast one thread.
In single processor system, multiple threads share the cpu time. This is achieved
because a thread does not always need the cpu. That is, it might have to wait for user input or
it might have to display something on the screen. During this time other threads take over the
cpu. The previous thread can resume after the current thread comes out of the cpu.
The O/S is resposible for scheduled and allocating resources for threads.
Advantages of threads
1. Newborn state
2. Runmode state
3. Running state
4. Blocked state
5. Dead State
I) Newborn State:
At once the thread object is created for the defined thread a new thread is born. This
state of thread is called new born state.
from this state the new born thread can go to any one of the following state
a) Runmode State
b) Dead State.
if start() is called it goes to runmode [Link] stop() is called i goes to dead state.
Multi threading is a program control. In this the program is divided into two or more
independent subprograms called threads and are processed Parallely. Every program has
atleast one thread.
In single processor system, multiple threads share the cpu time. This is achieved
because a thread does not always need the cpu. That is, it might have to wait for user input or
it might have to display something on the screen. During this time other threads take over the
cpu. The previous thread can resume after the current thread comes out of the cpu.
The O/S is resposible for scheduled and allocating resources for threads.
Advantages of threads
1. Newborn state
2. Runmode state
3. Running state
4. Blocked state
5. Dead State
I) Newborn State:
At once the thread object is created for the defined thread a new thread is born. This
state of thread is called new born state.
From this state the new born thread can go to any one of the following state
Runmode State
Dead State.
if start() is called it goes to runmode [Link] stop() is called i goes to dead state.
New Sleep
done,I/Ocomplete,lock
available,resume,notify
start()
Runnable
SCS1209 - JAVA PROGRAMMING Prepared by [Link]
Non-Runnable
59
Creating a Thread
In the most general sense, you create a thread by instantiating an object of type
Thread.
Ex:
class two extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link](i+"*2="+(i*2));
}
}
}
class three extends Thread
{
}
}
}
class wel extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link]("welcome");
} }}
public class Thread1 {
public static void main(String[] args) {
two t1=new two();
three f1=new three();
wel w1=new wel();
[Link]();
[Link]();
[Link]();
}}
Ex:
class maths extends Thread
{
E:\javapgms>javac [Link]
Note: [Link] uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
E:\javapgms>java subthread
To create a new class that implements Runnable,and then to create an instance of that
class.
The extending class must override the run( ) method, which is the entry point for the
new thread
Ex:
class firstthread implements Runnable
{
public void run()
{
}}
Use Thread () to create a object for Thread class. In this to pass the object
of each class.
Use strart() to start execution.
Ex:
class two implements Runnable{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link](i+"*2="+(i*2));
} }}
class three implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link](i+"*3="+(i*3));
} }}
class wel implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link]("welcome");
} }}
public class Runnablethread {
public static void main(String[] args) {
two t1=new two();
Thread t=new Thread(t1);
[Link]();
three f1=new three();
Thread th=new Thread(f1);
[Link]();
wel w1=new wel();
Thread th2=new Thread(w1);
[Link](); }}
1*2=2
2*2=4
3*2=6
4*2=8
5*2=10
1*3=3
2*3=6
3*3=9
4*3=12
5*3=15
welcome
welcome
welcome
welcome
welcome
Metohds:
setPriority( ):
getPriority( ):
You can obtain the current priority setting by calling the getPriority( ) method of
Thread, shown here:
final int getPriority( )
EX:
Synchronization.
When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization.
Types of Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Ex:
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}}
Output: 5
100
10
200
15
300
20
400
25
500
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}
}
}
100
200
300
400
500
IO Streams
Console based I/O is easier for simple programs only.
Console based I/O is not suitable for application oriented programs which uses AWT.
So, Java does provide the strong ,flexible I/O which is related to file and networks
STREAMS
Java programs perform I/O through streams.
A stream is an abstraction that either produces or consumes information.
A stream is linked to a physical device by the Java I/O system
Java implements streams within class hierarchies defined in the [Link] package.
Types of Streams
STREAMS
A stream is an
package.
Method Description
void mark(int numBytes) Places a mark at the current point in the input
stream that will remain valid until numBytes
bytes are read.
Input :
[Link] a file “[Link]” with a following content.
[Link] the file in the same directory of program file([Link])
E:\javapgms>javac [Link]
E:\javapgms>java filedemo
file is available
97
h
a
i
.
a
m
import [Link].*;
class filedemo1
{
public static void main(String args[]) throws Exception
{
SCS1209 - JAVA PROGRAMMING Prepared by [Link]
70
int n,i;
char c;
InputStream in=new FileInputStream("e:/javapgms/[Link]");
n=[Link]();
byte[] buffer=new byte[n];
[Link](buffer);
for(byte b:buffer)
{
c=(char) b;
[Link](c);
}
}
}
Example :
Input File stored as [Link]
E:\javapgms>java filedemo1
hai.
i am maheswari saravanan.
i am working as a assistant professor in Sathyabama university.
char c;
InputStream in=new FileInputStream("e:/javapgms/[Link]");
n=[Link]();
byte[] buffer=new byte[n];
[Link](buffer,5,n-5);
for(byte b:buffer)
{
c=(char) b;
[Link](c);
}
}
}
Example :
Input File stored as [Link]
E:\javapgms>javac [Link]
E:\javapgms>java filedemo1
hai.
i am maheswari saravanan.
i am working as a assistant professor in Sathyabama univers
OUTPUT STREAM
Method Description
void close( ) Closes the output stream. Further write attempts will generate
an IOException.
void flush( ) Finalizes the output state so that any buffers are cleared. That
is, it flushes the output buffers..
void write(int b) Writes a single byte to an output [Link] that the parameter
is an int, which allows you to call write( ) with
expressionswithout having to cast them back to byte.
void write(byte Writes a complete array of bytes to an output
buffer[ ]) stream.
void write(byte Writes a subrange of numBytes bytes from the array buffer,
buffer[ ], int beginning at buffer[offset].
offset,int
numBytes)
Ex:
import [Link].*;
import [Link].*;
class fileout1
{
public static void main(String args[])throws Exception
{
String st;
byte[] b=new byte[10];
Scanner s=new Scanner([Link]);
[Link]("enter a string");
st=[Link]();
b=[Link]();
[Link]("the lengh of the string is:"+[Link]);
OutputStream im=new FileOutputStream("[Link]");
[Link](b);
[Link]();
}
}
INPUT
1. Open cmd
2. Run the program using javac and java
3. Give the input
E:\javapgms>javac [Link]
E:\javapgms>java fileout1
enter a string
sathyabama
the lengh of the string is:10
Output:
Ex:
import [Link].*;
import [Link].*;
class fileout
{
public static void main(String args[])throws Exception
{
String[] st=new String[10];
byte[][] b=new byte[20][20];
Scanner s=new Scanner([Link]);
[Link]("enter a string");
for(int i=0;i<[Link];i++)
{
st[i]=[Link]();
}
for(int i=0;i<[Link];i++)
{
b[i]=st[i].getBytes();
}
OutputStream im=new FileOutputStream("[Link]");
for(int i=0;i<[Link];i++)
{
[Link](b[i]);
[Link]('\t ');
}
[Link]();
}
}
Input:
E:\javapgms>javac [Link]
E:\javapgms>java fileout
enter a string
hai
Siststudents
Staysafe
eatwell
Washhands
keepklean
Maintainsocialdistance
drinkWater
Doyoga
runoutcorona
Output:
[Link] the file '[Link]'
CHARACTER STREAM
While the byte stream classes provide sufficient functionality to handle any
type of I/O operation, they cannot work directly with Unicode characters.
Since one of the main purposes of Java is to support the “write once, run
anywhere” philosophy, it was necessary to include direct I/O support for characters.
Reader
Reader is an abstract class that defines Java‟s model of streaming character input. All of the
methods in this class will throw an IOException on error conditions.
Writer
Writer is an abstract class that defines streaming character output. All of the methods in this
class return a void value and throw an IOException in the case of errors.
FileReader:
The FileReader class creates a Reader that you can use to read the contents of a file.
FileReader fr=new FIleReader(“filepath”);
Method Description
boolean ready( ) Returns true if the next input request will not
wait. Otherwise, it returns false.
void close( ) Closes the input source. Further read attempts will
generate an IOException.
void mark(int numBytes) Places a mark at the current point in the input
stream that will remain valid until numBytes
bytes are read.
long skip(long numBytes Ignores (that is, skips) numBytes bytes of input,
returning the number of bytes actually ignored
Ex:
import [Link].*;
class FileReaderDemo {
public static void main(String args[]) throws Exception {
int ch;
FileReader fr = new FileReader("[Link]");
while((ch = [Link]()) !=-1)
{
[Link]((char)ch);
}
[Link]();
}
}
Input:
Output:
E:\javapgms>java FileReaderDemo
Sathyabama.
stay safe
i hope all are fine.
FILEWRITER
It is used to write the string or input to the file.
Method Description
void close( ) Closes the output stream. Further write attempts will generate an
IOException.
void flush( ) Finalizes the output state so that any buffers are cleared. That is, it
flushes the output buffers..
void write(int ch) Writes a single character to the invoking output stream. Note that the
parameter is an int, which allows you to call write with
expressions without having to cast them back to char.
void write(char buffer[ ]) Writes a complete array of characters to the invoking output stream.
abstract void write(char Writes a subrange of numChars characters from the array buffer,
buffer[ ],int offset,int beginning at buffer[offset] to the invoking output stream.
numChars)
void write(String str, int Writes a subrange of numChars characters from the array str,
offset, beginning at the specified offset.
int numChars)
Ex:
import [Link].*;
import [Link].*;
class FileWriterDemo {
public static void main(String args[]) throws Exception {
String source ;
Scanner s=new Scanner([Link]);
[Link]("Enter the string");
source=[Link]();
char buffer[] = new char[[Link]()];
[Link](0, [Link](), buffer, 0);
FileWriter f0 = new FileWriter("[Link]");
for (int i=0; i < [Link]; i =i+1) {
[Link](buffer[i]);
}
[Link]();
}
Input:
E:\javapgms>java filewriter
Enter the string
engineers
Output
DataInputStream
A data input stream enable an application read primitive Java data types from
an underlying input stream in a machine-independent way(instead of raw bytes). That is
why it is called DataInputStream – because it reads data (numbers) instead of just
bytes.
Method Description
int read(byte[] b, int off, int Reads up to len bytes of data from the contained input
len) stream into an array of bytes.
readBoolean() Reads one input byte and returns true if that byte is
nonzero, false if that byte is zero.
Ex:
import [Link].*;
class DataOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
OutputStream os=new FileOutputStream("e:/javapgms/[Link]");
DataOutputStream dout = new DataOutputStream((os)) ;
[Link](10.28);
[Link](5);
[Link]('t');
[Link]('4');
DataInputStream din =
new DataInputStream(new FileInputStream("[Link]")) ;
Double a = [Link]();
int b = [Link]();
char c = [Link]();
char d=[Link]();
[Link]("Values: " + a + " " + b + " " + c+" " + d);
}
}
DATAOUTPUT STREAM
Method Description
Input:
E:\javapgms>javac [Link]
E:\javapgms>java DataOutputStreamDemo
Values: 10.28 5 t 4
Output:
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
float fv = [Link]();
double dv = [Link]();
// let us print the values from data types
[Link]("Unwrapped values (printing as data types)");
[Link]("byte value, bv: " + bv);
[Link]("int value, iv: " + iv);
[Link]("float value, fv: " + fv);
[Link]("double value, dv: " + dv);
}
}
}
Output:
20 20 20
UNIT-IV
The delegation event model, which defines standard and consistent mechanisms to
generate and process events.
EVENTS
An event is an object that describes a state change in a source.
It can be generated By the user interacting with the elements in a graphical user
interface.
Ex:
Direct Event: pressing a button, entering a character via the keyboard, selecting an item
in a list, and clicking the mouse
Event Sources:
A source is an object that generates an event.
A source must register listeners in order for the listeners to receive notifications
about a specific type of event.
Each type of event has its own registration method.
Event Listeners
A listener is an object that is notified when an event occurs.
Event Classes
Eventclass hierarchy
EventObject is the root of all Java event class hierarchy , which is in [Link].
It is the superclass for all events.
EvenObject
ALT_MASK,
CTRL_MASK,
META_MASK,
SHIFT_MASK.
ACTION_PERFORMED
Three constructors:
ActionEvent(Object src, int type, String cmd): src - reference to the object that generated
this event.
type - specify the type of the event
cmd- command string
ActionEvent(Object src, int type, String cmd, modifiers - which modifier keys (ALT, CTRL,
int modifiers) META, and/or SHIFT) were pressed when the
event was generated
ActionEvent(Object src, int type, String cmd, when -yes, when the event occurred.
long when, int modifiers)
Methods
String getActionCommand( ) when a button is pressed, an action event is generated that has
a command name equal to the label on that button
getModifiers( ) The method returns a value that indicates which modifier keys
(ALT, CTRL, META, and/or SHIFT) were pressed when the event
was generated
ADJUSTMENT EVENTS
BLOCK_DECREMENT The user clicked inside the scroll bar to decrease
its value.
UNIT_DECREMENT The button at the end of the scroll bar was clicked
to decrease its value
UNIT_INCREMENT The button at the end of the scroll bar was clicked
to increase its value.
Constructor:
AdjustmentEvent(Adjustable src, int id, int src - reference to the object that generated
type, int data) this event.
id -ADJUSTMENT_VALUE_CHANGED.
type - type of event data - data
METHODS
COMPONENT EVENTS
COMPONENT_HIDDEN The component was hidden.
Constructor of ComponentEvent:
ComponentEvent(Component src, int type) src - reference to the object that generated
this event.
type - specified the type of event
Method
CONTAINEREVENT
COMPONENT_ADDED component has been added to the container
COMPONENT_REMOVED component has been removed from the container
Constructor:
METHODS
Container getContainer( ) You can obtain a reference to the container that generated
this event by using the method,
Component getChild( ) returns a reference to the component that was added to or
removed from the container
FocusEvent(Component src, int type, boolean temporaryFlag - true if the focus event is
temporaryFlag) temporary
- False(A temporary focus
event occurs as a result of another user
interface operation)
Methods
Component getOppositeComponent( ) The opposite component is returned.
boolean isAltGraphDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )
int getModifiers( )
Integer Constant:
ITEM_STATE_CHANGED - signifies change of state.
Constructor:
ItemEvent(ItemSelectable src, int type, src - indicates the component that
Object entry, int state) generated this event.
type -specified by type.
entry-The specific item that generated the
item event is passed in entry.
State- The current state of that item.
METHODS
Object getItem( ) used to obtain a reference to the item that
generated an event.
ItemSelectable getItemSelectable( ) used to obtain a reference to the
ItemSelectable
object that generated an event.
int getStateChange( ) method returns the state change (i.e.,
SELECTED or DESELECTED) for the event
VK_RIGHT
VK_PAGE_DOWN
VK_PAGE_UP
VK_SHIFT
VK_ALT
Constructors:
KeyEvent(Component src, int type, long src -reference to the component that
when, int modifiers, int code) generated the event.
type -specified type the type of the event.
when- specify the time at which the Key
event occurred
modifiers - indicates which modifiers were
pressed when a Key event occurred.
virtual key code - VK_UP, VK_A, and so forth,
is passed in code
KeyEvent(Component src, int type, long Ch- character equivalent (if one exists) is
when, int modifiers, int code, char ch) passed in ch.
Methods
char getKeyChar( ) returns the character that was entered
int getKeyCode( ) returns the key code
Constructors.
MouseEvent(Component src, int type, long src -reference to the component that
when, int modifiers, generated the event.
int x, int y, int clicks, boolean triggersPopup) type -specified type the type of the event.
when- specify the time at which the mouse
event occurred
modifiers - indicates which modifiers were
pressed when a mouse
event occurred.
Coordinates- of the mouse are passed in x
and y.
Click- count is passed in clicks.
triggersPopup flag- indicates if this event
causes a pop-up menu to
appear on this platform.
Methods
int getX( ) return the X coordinates of the mouse when
the event occurred
int getY( ) return the Y coordinates of the mouse when
the event occurred
void translatePoint(int x, int y) changes the location of the event
Constructor
MouseWheelEvent(Component src, int type, src - reference to the object that generated
long when, int modifiers, the event
int x, int y, int clicks, boolean triggersPopup, type - type of the event
int scrollHow, int amount, int count) when - system time at which the mouse event
is occurred
modifiers - argument indicates which
modifiers were pressed when the event
occurred
coordinates-coordinates of the mouse are
passed in x and y
METHODS
int getWheelRotation( ) To obtain the number of rotational units, call
getWheelRotation( ),
int getScrollType( ) It returns either WHEEL_UNIT_SCROLL or
WHEEL_BLOCK_SCROLL.
Constructors.
WindowEvent(Window src, int type) src -reference to the object that generated
this event.
Type- event type.
WindowEvent(Window src, int type, Window Other- specifies the opposite window when a
other) focus event occurs
WindowEvent(Window src, int type, int fromState- specifies the prior state of the
fromState, int toState) window
toState- specifies the new state that the
window will have when a window state
change occurs.
Methods
Window getWindow( ) It returns the
Window object that generated the event
int getOldState() returns the old state of the window
Checkbox Generates item events when the check box is selected or deselected.
Text components Generates text events when the user enters a character.
[Link]
Listeners are created by implementing one or more of the interfaces defined by the
[Link] package.
When an event occurs, the event source invokes the appropriate method defined by
the listener and provides an event object as its argument.
.
ActionListener Defines one method to receive action events
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is
hidden, moved, resized, or shown.
event occurs
TEXTLISTENER INTERFACE
METHODS General form
textChanged( ) invoked when a change occurs void textChanged(TextEvent te)
in a text area or text field.
KeyListerner
METHODS General form
keyPressed( ) invoked when a key is pressed void keyPressed(KeyEvent ke)
KeyboardEvents
import [Link].*;
import [Link].*;
public class keylistenerx implements KeyListener
{
Frame f;
Label l;
TextArea tf;
TextField td;
String msg="";
keylistenerx()
{
f=new Frame();
l=new Label();
[Link](20,50,100,20);
tf=new TextArea();
td=new TextField();
[Link](100,100,70,30);
[Link](20,80,300,300);
[Link](this);
[Link](l);
[Link](tf);
[Link](td);
[Link](400,400);
[Link](null);
[Link](true);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}
D:\>javac [Link]
D:\>java keylistenerx
Mouse listener
import [Link].*;
import [Link].*;
public class mouselistener extends Frame implements MouseListener
{
Label l;
mouselistener(){
l=new Label();
[Link](20,50,100,20);
addMouseListener(this);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
public static void main(String[] args) {
new mouselistener();
}
}
The Applet Class – Applet basics – Applet architecture – HTML APPLET tag – Passing
parameters to applets.
APPLET
Applets are small Java applications that can be accessed on an Internet server,
transported over Internet, and can be automatically installed and run as apart of a web
document.
Any applet in Java is a class that extends the [Link] class.
When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser.
The security of an applet is often referred to as sandbox security, comparing the
applet to a child playing in a sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive
(JAR) file.
Example
import [Link].*;
import [Link].*;
/*
<applet code="simple" width=400 height=400>
</applet>
*/
public class simple extends Applet
{
public void paint(Graphics g)
{
[Link] ("A Simple Applet", 25, 50);
}
}
Advantages of Applets
1. Very less response time as it works on the client side.
2. Can be run using any browser, which has JVM running in it.
Example of an Applet
import [Link].*;
import [Link].*;
/*
<applet code="MyApplet" width=400 height=400>
</applet>
*/
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](100,100,50,50);
}
}
E:\basic pgms\unit iv>javac [Link]
s="sum"+[Link](c);
[Link](s,100,100);
}
}
E:\basic pgms\unit iv>javac [Link]
E:\basic pgms\unit iv>appletviewer [Link]
import [Link];
import [Link];
public class First extends Applet
{
public void paint(Graphics g)
{
[Link]("welcome",150,150);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
import [Link];
import [Link];
public class First extends Applet
{
public void paint(Graphics g)
{
[Link]("welcome to applet",150,150);
}
}
import [Link];
import [Link].*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
[Link]([Link]);
[Link]("Welcome",50, 50);
[Link](20,30,20,300);
[Link](70,100,30,30);
[Link](170,100,30,30);
[Link](70,200,30,30);
[Link]([Link]);
[Link](170,200,30,30);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
E:\basic pgms\unit iv>javac [Link]
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose,
Applet class provides a method named getParameter().
Syntax:
1. public String getParameter(String parameterName)
Applet architecture
Use Parameters
import [Link].*;
import [Link].*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/
public class ParamDemo extends Applet{
String fontName;
int fontSize;
float leading;
boolean active;
// Initialize the string to be displayed.
public void start() {
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try {
if(param != null) // if not found
fontSize = [Link](param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;
}
param = getParameter("leading");
try {
// Display parameters.
public void paint(Graphics g) {
[Link]("Font name: " + fontName, 0, 10);
[Link]("Font size: " + fontSize, 0, 26);
[Link]("Leading: " + leading, 0, 42);
[Link]("Account Active: " + active, 0, 58);
}
}
UNIT-V
AWT Controls & Database Connectivity
AWT
AWT ( „Abstract window Toolkit‟) is an API to develop GUI or window-
based applications in java.
Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system.
The [Link] package provides classes for AWT api such as TextField,
Label,TextArea, RadioButton, CheckBox, Choice, List etc.
CONTAINER:
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The containers are Frame, Dialog and Panel.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
public void setSize(int width,int sets the size (width and height) of the
height) component.
EX:
import [Link].*;
import [Link].*;
class framedemo
{
public static void main(String[] args)
{
Frame f=new Frame("my first frame");
[Link](500,500);
[Link](null);
[Link](true);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}
}
E:\javapgms>javac [Link]
E:\javapgms>java framedemo
Output
LABEL
label is an object of type Label, and it contains a string, which it displays.
Labels are passive controls that do not support any interaction with the user.
Label defines the following constructors:
Label( ):
Ex:
Label(String str)
Ex:
Methods
Void setText(String str);
String getText();
void setAlignment(int how)
int getAlignment( )
It has no Listener Class.
Ex:
import [Link].*;
import [Link].*;
class label
{
public static void main(String[] args)
{
Frame f=new Frame("first");
Label l1=new Label("Name");
Label l2=new Label("age");
Label l3=new Label("gender");
[Link](100,50,70,30);
[Link](100,100,70,30);
[Link](100,120,70,30);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}});
[Link](l1);
[Link](l2);
[Link](l3);
[Link](300,300);
[Link](true);
[Link](null);
}
}
E:\javapgms>javac [Link]
E:\javapgms>java label
Output
TEXTFIELD
The TextField class implements a single-line text-entry area, usually called an
edit control.
Text fields allow the user to enter strings and to edit the text using the arrow
keys, cut and paste keys, and mouse selections.
TextField is a subclass of TextComponent.
TextField(int numchars)
TextField(String str):
METHODS
String getText();
Void setText(“hello”)
setBackground([Link])
getBackground()
getSelectedText()
EVENT
ActionListener()
METHOD
Void actionPerformed(ActionEvent e)
{
}
Ex:
import [Link].*;
import [Link].*;
import [Link].*;
public class textfield implements ActionListener
{
Frame f=new Frame();
Label l1,l2;
TextField t1,t2,t3;
textfield()
{
l1=new Label("Name :",[Link]);
l2=new Label("Password:",[Link]);
t1=new TextField(15);
t2=new TextField(15);
[Link]('?');
t3=new TextField(40);
[Link](100,100,100,20);
[Link](100,200,100,20);
[Link](250,100,150,20);
[Link](250,200,150,20);
[Link](50,300,400,20);
[Link](l1);
[Link](l2);
[Link](t1);
[Link](t2);
[Link](t3);
[Link](this);
[Link](this);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](450,450);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e)
{
BUTTON
Button(String str)
METHODS
setLabel():After a button has been created, you can set its label by calling setLabel( ).
getLabel( ):
You can retrieve its label by calling getLabel( ).
Interface
ActionListener
Method
[Link](this);
Public void actionPerformed(ActionEvent e)
{
}
Ex:
Simple Button
import [Link].*;
import [Link].*;
public class firstbutton
{
public static void main(String[] args)
{
Frame f=new Frame("buttonexample");
final TextField tf=new TextField();
[Link](50,50,150,200);
Button b=new Button("yes");
[Link](50,100,60,30);
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
[Link]("clicked yes");
}
});
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](b);
[Link](tf);
[Link](400,400);
[Link](null);
[Link](true);
}
}
E:\javapgms>javac [Link]
E:\javapgms>java firstbutton
Button Array
Ex:
import [Link].*;
import [Link].*;
public class buttonlist implements ActionListener
{
String s="";
Button y
public void init()
{
Button yes=new Button("yes");
Button no=new Button("no");
Button maybe=new Button("decided");
b[0]=(Button) add(yes);
b[1]=(Button) add(no);
b[2]=(Button) add(maybe);
for(int i=0;i<3;i++)
{
b[i].addActionListener(this);
}
}
public void actionPerformed(ActionEvent e)
{
for( int i=0;i<3;i++)
{
if([Link]()==b[i])
{
s="you pressed"+b[i].getLabel();
}
}
repaint();
}
public void paint(Graphics g)
{
[Link](s,6,100);
}
}
CHECKBOX
Checkbox( ):
Checkbox(String str):
METHODS
boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
getSource()
INTERFACE
ItemListener
METHOD
addItemListener(this);
Ex:
import [Link].*;
import [Link].*;
public class checkbox implements ItemListener
{
Frame f;
Checkbox Win98, winNT, solaris, mac;
TextField tf;
checkbox()
{
f=new Frame("checkbox");
tf=new TextField();
[Link](100,300,200,20);
Win98 = new Checkbox("win98");
[Link](100,100,70,30);
winNT = new Checkbox("winNT");
[Link](100,150,70,30);
solaris = new Checkbox("Solaris");
[Link](100,200,70,30);
mac = new Checkbox("Mac");
[Link](100,250,70,30);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](Win98);
[Link](winNT);
[Link](solaris);
[Link](mac);
[Link](tf);
[Link](400,400);
[Link](null);
[Link](true);
}
[Link]([Link]()+" "+[Link]());
}
if([Link]()==solaris)
{
[Link]([Link]()+" "+[Link]());
}
if([Link]()==mac)
{
[Link]([Link]()+" "+[Link]());
}
}
public static void main(String[] args)
{
new checkbox();
}
}
E:\javapgms>javac [Link]
E:\javapgms>java checkbox
CHECKBOX GROUP
It is possible to create a set of mutually exclusive check boxes in which one and only
one
check box in the group can be checked at any one time
Ex:
import [Link].*;
import [Link].*;
public class checkboxgroup
{
public static void main(String[] args)
{
Frame f=new Frame("checkbox");
boolean b;
CheckboxGroup gp=new CheckboxGroup();
Checkbox Win98, winNT, solaris, mac;
Win98 = new Checkbox("Windows 98/XP", gp, true);
[Link](100,100,50,50);
winNT = new Checkbox("Windows NT/2000",gp,false);
[Link](100,150,50,50);
solaris = new Checkbox("Solaris",gp,true);
[Link](100,200,50,50);
mac = new Checkbox("MacOS",gp,false);
[Link](100,250,50,50);
/*[Link](new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
b=[Link]();
}
});
[Link](new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
str=[Link]();
[Link](str);
}
});
[Link](new ItemListener()
{
E:\javapgms>javac [Link]
E:\javapgms>java checkboxgroup
LIST
List( )
The first version creates a List control that allows only one item to be selected at any one time
List(int numRows)
In the second form, the value of numRows specifies the number of entries in the list that will
always be visible (others can be scrolled into view as needed).
In the third form, if multipleSelect is true, then the user may select two or more items at a
[Link] it is false, then only one item may be selected.
Ex:
import [Link].*;
import [Link].*;
public class list
{
public static void main(String[] args)
{
Frame f=new Frame();
E:\javapgms>javac [Link]
E:\javapgms>java list
TEXT AREA
TextArea( )
TextArea(String str)
METHODS
getText( )
setText( )
getSelectedText( )
select( ),
isEditable( )
setEditable( )
Ex:
import [Link].*;
import [Link].*;
public class TextAreaDemo {
public static void main(String[] args)
{
Frame f=new Frame();
String val = "There are two ways of constructing " +
"a software design.\n" +
"One way is to make it so simple\n" +
"that there are obviously no deficiencies.\n" +
"And the other way is to make it so complicated\n" +
"that there are no obvious deficiencies.\n\n" +
" -C.A.R. Hoare\n\n" +
"There's an old story about the person who wished\n" +
"his computer were as easy to use as his telephone.\n" +
"That wish has come true,\n" +
"since I no longer know how to use my telephone.\n\n" +
" -Bjarne Stroustrup, AT&T, (inventor of C++)";
TextArea text = new TextArea();
[Link](100,100,200,200);
[Link](val);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](text);
[Link](400,400);
[Link](null);
[Link](true);
}
}
E:\javapgms>javac [Link]
E:\javapgms>java TextAreaDemo
SCROLLBAR
Scroll bars are used to select continuous values between a specified minimum and
maximum.
Scroll bars may be oriented horizontally or vertically.
A scroll bar is actually a composite of several individual parts.
Each end has an arrow that you can click to move the current value of the scroll bar
one unit in the direction of the arrow.
The current value of the scroll bar relative to its minimum and maximum values is
indicated by the slider box (or thumb) for the scroll bar.
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
METHODS
int getValue( )
void setValue(int newValue)
int getMinimum( )
int getMaximum( )
INTERFACE
AdjustmentListener interface
OBJECT
AdjustmentEvent
EVENT METHOD
public void getAdjustmentType( )
{}
Ex:
import [Link].*;
import [Link].*;
public class SBDemo implements AdjustmentListener
{
String msg = "";
Frame f;
Scrollbar vertSB, horzSB;
Label l;
SBDemo()
{
f=new Frame();
l=new Label();
l1=new Label();
l2=new Label();
vertSB = new Scrollbar([Link],0, 1, 0, 30);
horzSB = new Scrollbar([Link],0, 1, 0, 30);
[Link](100,100,50,100);
[Link](200,100,200,50);
[Link](200,200);
[Link](this);
[Link](this);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](vertSB);
[Link](horzSB);
[Link](l);
[Link](450,450);
[Link](true);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
if([Link]()==vertSB)
E:\javapgms>javac [Link]
E:\javapgms>java SBDemo
LAYOUT MANAGERS
Types
[Link]
[Link]
[Link]
FlowLayout
FlowLayout( )
The first form creates the default layout, which centers components and leaves five
import [Link].*;
import [Link].*;
import [Link].*;
public class flowlayout implements ActionListener
{
Frame f=new Frame();
Label l1,l2,l3;
TextField t1,t2,t3;
Button Add=new Button("add");
flowlayout()
{
l1=new Label("ist value");
l2=new Label("2nd value");
l3=new Label("result");
t1=new TextField(15);
t2=new TextField(15);
t3=new TextField();
[Link](100,100,70,70);
[Link](100,150,70,70);
[Link](100,200,70,70);
[Link](250,100,70,70);
[Link](250,200,70,70);
[Link](250,300,70,70);
[Link](200,400,70,70);
[Link](new FlowLayout([Link]));
[Link](l1);
[Link](l2);
[Link](l3);
[Link](t1);
[Link](t2);
[Link](t3);
[Link](Add);
[Link](this);
/*[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int i=[Link]([Link]());
int j=[Link]([Link]());
int c=0;
if([Link]()==Add)
{
c=i+j;
}
[Link]([Link](c));
}
});*/
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](450,450);
[Link](null);
[Link](true);
}
E:\javapgms>javac [Link]
E:\javapgms>java flowlayout
BorderLayout
The BorderLayout class implements a common layout style for top-level windows.
It has four narrow, fixed-width components at the edges and one large area in the
center.
The four sides are referred to as north, south, east, and west. The middle area is called
the center.
BorderLayout( )
It allows you to specify the horizontal and vertical space left between components in
[Link] [Link]
[Link] [Link]
[Link]
add():
It is used to add the components which is defined by Container:
void add(Component compObj, Object region);
Here, compObj is the component to be added, and region specifies where the
component will be added.
Ex:
import [Link].*;
import [Link].*;
public class borderlayout {
Frame f;
String msg="";
borderlayout()
{
f=new Frame("BorderLayout");
[Link](new BorderLayout());
Button b1=new Button("north");
Button b2=new Button("south");
Button b3=new Button("east");
Button b4=new Button("west");
[Link](b1,[Link]);
[Link](b2,[Link]);
[Link](b3,[Link]);
[Link](b4,[Link]);
msg = "The reasonable man adapts " +
"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
[Link](new TextArea(msg), [Link]);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](200,200);
[Link](true);
}
public static void main(String[] args)
{
new borderlayout();
}
}
GridLayout
When you instantiate a GridLayout, you define the number of rows and columns.
GridLayout( )
The second form creates a grid layout with the specified number of rows and columns.
It specify the horizontal and vertical space left between components in horz and vert,
unlimited-length rows.
Ex:
import [Link].*;
import [Link].*;
public class gridlayout {
Frame f;
final int n = 3;
TextField tf;
gridlayout()
{
f=new Frame("");
[Link](new BorderLayout());
[Link](new GridLayout(n, n));
tf=new TextField();
[Link](new Font("SansSerif", [Link], 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k >=0)
[Link](new Button("" + k));
}
}
[Link](new Button("+"));
[Link](new Button("-"));
[Link](new Button("*"));
[Link](new Button("/"));
[Link](new Button("="));
[Link](tf,[Link]);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](200,300);
[Link](true);
}
public static void main(String[] args)
{
new gridlayout();
}
}
A menu bar displays a list of top-level menu choices. Each choice is associated with a drop-
down menu.
Menu Classes
To create a menu bar, first create an instance of MenuBar. This class only defines the default
constructor. Next, create instances of Menu that will define the selections displayed on the bar.
1. MenuBar
2. Menu
3. MenuItem
MenuItem( )
MenuItem(String itemName)
Once you have created a menu item, you must add the item to a Menu object by
using add( ).The general form is
[Link](MenuItemobject)
Here, item is the item being added. Items are added to a menu in the order in which the
calls to add( ) take place. The item is returned.
Menubarobject. add(Menuobject)
Here, menu is the menu being added. The menu is returned.
Ex:
import [Link].*;
import [Link].*;
public class menudesign implements ActionListener
{
Frame f;
TextArea te;
MenuBar mb;
MenuItem New,Save,Cut,Copy,Paste,Close;
menudesign()
{
f=new Frame();
te=new TextArea();
New=new MenuItem("New");
Save=new MenuItem("Save");
Cut=new MenuItem("Cut");
Copy=new MenuItem("Copy");
Paste=new MenuItem("Paste");
Close=new MenuItem("Close");
//[Link](this);
//[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
mb=new MenuBar();
[Link](New);
[Link](Save);
[Link](Cut);
[Link](Copy);
[Link](Paste);
[Link](Close);
[Link](50,50,100,200);
//[Link]([Link]);
[Link](fi);
[Link](ed);
[Link](fo);
[Link](ex);
[Link](mb);
[Link](te);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
[Link](200,300);
[Link](true);
}
public void actionPerformed(ActionEvent e)
{
String s=(String)[Link]();
if([Link]("Cut"))
//[Link]();
[Link](s);
if([Link]("Paste"))
//[Link]();
[Link](s);
if([Link]("Copy"))
//[Link]();
[Link](s);
if([Link]("Close"))
[Link](0);
}
public static void main(String[] args)
{
new menudesign();
}
}
Database Connectivity
• ODBC driver –
It require a driver to be loaded at runtime to connect to any data source.
The driver is implemented as a class that is located and loaded at runtime.
The ODBC driver for JDBC connections is named [Link].
It require an ODBC connection string to connect to the data source.
To connect with an ODBC DSN, we require a connection string "jdbc:odbc:ODBC DSN
String"
The package containing the database related classes is contained in [Link].
Dynamically load the class [Link] as
[Link]("[Link]");
Connection conn = [Link](database, "", "");
The Statement must be created to execute a SQL query on the opened database.
Statement s = [Link]();
To clean up after we are done with the SQL query, • To call [Link]() to dispose the
object Statement.
• To call [Link]() for close the database
Step 1 : Open Microsoft Access and select Student data base option and give the data
base name as File name option as “student”
Step 2 : Create a table and insert your data into the table
Step 3 : Save the table with the desired name; in this article we save the following
records with the table name student.
37120001 Aravind
37120002 Arjun
• Now Creating DSN of your data base –
Step 4 : Open your Control Panel and than select Administrative Tools.
Step 5 : Click on Data Source(ODBC)-->User DSN.
Step 6 : Now click on add option for making a new [Link] Microsoft Access Driver (*.mdb.
*.accdb) and than click on Finish
Step 7 : Make your desired Data Source Name and then click on the Select option.
Step 8 : Now you select your data source file for storing it and then click ok and then click on
Create and Finish
Example
import [Link].*;
class DatabaseDemo
{
public static void main(String ar[])
{
Try
{
String url="jdbc:odbc:veeradsn";
[Link]("[Link]");
Connection c=[Link](url);
Statement st=[Link]();
[Link]("INSERT into std(Reg_no,Name) values("+37120003+",'Avinash'"+")");
ResultSet rs=[Link]("select * from std");
while([Link]())
[Link]([Link](1)+ " "+[Link]("Name"));
}
catch(Exception ee)
{
[Link](ee);
}
}
}