Java Notes
Java Notes
Java Notes
Java notes
Genesis of JAVA
1. JAVA
2. C, Pascal , Basic, Fortran are the based on either compiler or interpreter. But Java programs
are based on compiler and interpreter both.
Java Java
Source code Compiler Byte Code Interpreter Machine Code
3. Java program is platform independent to achieve the independency the Byte codes area
used.
4. Java Compiler is generally known as JVM(Java Virtual Machine).
One of the java advantages for use over the Internet is that platform independent, meaning that
programs created with the java can run on any machine (computers).Java achieves its
independence by creating programs designed to run on the JVM rather than any specific
computer system.
These java programs once compiled and stored in a compact machine independent format
known as Byte codes. Byte code files area easily transferred across the Internet. The preloaded
interpreter run the byte code in the local machine then plays them.
Java Features
Simple - Java's developers deliberately left out many of the unnecessary features of
other high-level programming languages. For example, Java does not support pointer
math, implicit type casting, structures or unions, operator overloading, templates,
header files, or multiple inheritance.
CompiledbyUmeshSharma
Page-2
Object-oriented. Just like C++, Java uses classes to organize code into logical
modules. At runtime, a program creates objects from the classes. Java classes can
inherit from other classes, but multiple inheritance, wherein a class inherits methods
and fields from more than one class, is not allowed.
Statically typed - All objects used in a program must be declared before they are
used. This enables the Java compiler to locate and report type conflicts.
Compiled - Before you can run a program written in the Java language, the program
must be compiled by the Java compiler. The compilation results in a "byte-code" file
that, while similar to a machine-code file, can be executed under any operating system
that has a Java interpreter. This interpreter reads in the byte-code file and translates the
byte-code commands into machine-language commands that can be directly executed
by the machine that's running the Java program. You could say, then, that Java is both a
compiled and interpreted language.
Garbage collector - Java programs do their own garbage collection, which means
that programs are not required to delete objects that they allocate in memory. This
relieves programmers of virtually all memory-management problems.
Robust - Because the Java interpreter checks all system access performed within a
program, Java programs cannot crash the system. Instead, when a serious error is
discovered, Java programs create an exception. This exception can be captured and
managed by the program without any risk of bringing down the system.
Secure - The Java system not only verifies all memory access but also ensures that no
viruses are hitching a ride with a running applet. Because pointers are not supported by
the Java language, programs cannot gain access to areas of the system for which they
have no authorization.
Extensible - Java programs support native methods, which are functions written in
another language, usually C++. Support for native methods enables programmers to
write functions that may execute faster than the equivalent functions written in Java.
Native methods are dynamically linked to the Java program; that is, they are associated
with the program at runtime. As the Java language is further refined for speed, native
methods will probably be unnecessary.
CompiledbyUmeshSharma
Page-3
Java Applet Another advantage of the java for the internet is its ability to create
applets. Applets are the small programs that area designed to be embedded into a Web
Page. Any java enabled browser can load and run java applets directly form web pages.
Applets provide World Wide Web pages with a level of interactivity never before
possible on the internet.
Encapsulation is the combining of data and the code that manipulates that data into a
single component-that is, an object. Encapsulation also refers to the control of access to the
details of an objects implementation.
//Example of Encapsulation
class data {
int idno, mark;
String name;
data() {
name="raja";
idno=12;
mark=900;
}
void show() {
System.out.println("Name of student is="+name);
System.out.println("id no. of student is="+idno);
System.out.println("mark of student is="+mark);
}
}
class firstdemo {
public static void main(String args[]) {
data obj=new data();
obj.show();
}
}
CompiledbyUmeshSharma
Page-4
Save this program named as firstdemo.java and complied as c:\>javac firstdemo.java and run
above program as c:\>java firstdemo {where object call the data with the help of objects}
What is the Polymorphism?
Polymorphism build in two words =poly+morphism here poly means many and morphism
means shapes. And merely means using the same one name to refer to different methods.
Name Reuse would be better terms to use for polymorphism.
There are two types of polymorphism in java.
//Example of overloading.
class student {
int idno, mark;
String name;
void setData() {
idno=90;mark=89;name="raja";
}
void setData(int id,int m,String n) {
idno=id;mark=m;name=n;
}
void show() {
System.out.println("\n\nStudent RollNo.="+idno);
System.out.println("Student Name.="+name);
System.out.println("Student RollNo.="+mark);
}
}//end of student class
class demoOverload {
public static void main(String args[]){
student obj=new student();
obj.setData();
obj.show();
student obj1=new student();
obj1.setData(1,67,"vinu");
obj1.show();
}
}
CompiledbyUmeshSharma
Page-5
C:\corejava\oops>javac demoOverload.java
C:\corejava\oops>java demoOverload
Student RollNo.=90
Student Name.=raja
Student RollNo.=89
Student RollNo.=1
Student Name.=vinu
Student RollNo.=67
//Example of overloading.
class Room {
int length;
int width;
int area;
void setData(int l,int w) {
length=l;
width=w;
}
void setData(int x) {
length=width=x;}
void show() {
area=length*width;
System.out.println("\n\nArea of rectangle="+area);
}
}//end of Room class
class RoomArea {
public static void main(String args[]) {
Room obj=new Room();
obj.setData(25,15);
obj.show();
Room obj1=new Room();
obj1.setData(20);
obj1.show();
}
}
C:\corejava\oops>javac RoomArea.java
C:\corejava\oops>java RoomArea
Area of rectangle=375
Area of rectangle=400
CompiledbyUmeshSharma
Page-6
There may be occasion where we want an object to respond to the same method but have
different behaviour when that method is called. That means we should override the methods
defined in the superclass. This is possible by defining a method in a subclass that has the same
name, same signature and same return type as methods in the super class.
//Example of overriding
class Super {
int x;
Super(int x) {
this.x=x;
}
void show( ) {
System.out.print(X=+x);
}
} //End of Super class
OUTPUT:-
C:\corejava\oops>javac override.java
C:\corejava\oops>java override
X=100
Y=130
CompiledbyUmeshSharma
Page-7
Abstract class
An abstract class is a class that has at least one abstract method, along with concrete methods.
An abstract method is a method that is declared with only its signature, it has no
implementation. That means method without functionality.
Since abstract class has at least one abstract class has at least one abstract method, an abstract
class cannot be instantiated.
Example # 1
abstract class A {
abstract void callme(); // this is abstract method
void callmetoo() // this is concrete method
{
System.out.println("this is concrete method of abstract class");
}
}
class B extends A {
void callme() {
System.out.println("give the functionality of super class abstract method");
CompiledbyUmeshSharma
Page-8
}
}
class abstractDemo {
public static void main(String args[]) {
B obj=new B();
obj.callme();
obj.callmetoo();
}
}
Example # 2
class abstractDemo2 {
public static void main(String args[]) {
// shape obj=new shape(10,29); it is not possible bez
Rectangle r1=new Rectangle(12,3);
shape s;
s=r1;
System.out.println("Area of Rectangle is="+s.area());
Triangle t1=new Triangle(12,3);
System.out.println("Area of Triangle is="+t1.area());
}
}
Super Keyword:
Whenever a sub class needs to refer to its immediate superclass, we make use of the keyword
super. The subclass constructor uses the keyword super to invoke variable or method of the
super class.
The keyword super is used subject to the following condition :-
super may only be used with in a subclass constructor method.
The call to superclass constructor must appear as the first statement with in the subclass
constructor.
The parameter in the super call must match the order and type of the instance variable
declare in the superclass.all must match the order and type of the instance variable
declare in the superclass.
Example ##1
class S {
int x;
S(int x) {
this.x=x;
}
void show() {
System.out.println("x="+x);
}
} // end of super class
CompiledbyUmeshSharma
Page-10
class override {
public static void main(String args[]) {
Sub obj=new Sub(100,50);
obj.show();
}
}
Example # 2
// this is the prg for invoking superclass variable in subclass by using super keyword.
class A {
int a=100;
void show() {
System.out.println("Method in super class");
System.out.println("value of a in super class="+a);
}
} // end of super class
class B extends A {
int a=200;
void show() {
System.out.println("Method in sub class");
System.out.println("value of a in SUB class="+a);
System.out.println("value of a in super class(invoke by super)="+super.a);
}
}
class SuperDemo {
public static void main(String args[]) {
B obj=new B();
obj.show();
}
}
Example # 3
// this is the prg for invoking superclass constructor in subclass by using super keyword.
class Room {
int length;
int breath;
Room(int x,int y) {
length=x;
breath=y;
}
int area() {
return length*breath;
}
}// end of superclass
class vol extends Room {
int height;
CompiledbyUmeshSharma
Page-11
this keyword:-
All instance methods received an implicit agument called this, which may be used inside any
method to refer to the current object, i.e. the object on which method was called. Inside an
instance of method, any unqualified reference is implicitly associated with the this reference.
Final Keyword
CompiledbyUmeshSharma
Page-12
Example #
class A {
final void show() {
statement 1;
statement 1;
}
}
class B extends A {
void show() {
// Error ! cannot override the super class method bez final keyword.
}
}
final class A {
final void show() {
statement 1;
statement 1;
}
}
class B extends A // it is not possible because Class A is declared as final.
{
void show() {
// Error ! cannot override the super class method bez final keyword.
}
}
CompiledbyUmeshSharma
Page-13
What is an Arrays?
An array is a finite set of elements of homogeneous data types. The elements of array are
accessed by index.
Arrays index starts with 0 in java. In java arrays are treated as objects.
Creating an Array:->
Creation of array involves the three steps.
1. Declare the array.
There are two ways to declare an arrays
<data type>[] arrayvariablename;
example:-int[] a;
<data type> arrayvariablename[];
example:-int a[];
Remember: we do not enter the size of array in the declaration. you cannot assign the values to
the array unless the array is created, because array is an object in java it should be create using
new operator.
The final steps is to put values into the array created. This process in known as
initialization. This is done using the array subscripts as shown below.
Arrayname[subscript]=values;
Example:-- number[0]=67;
number[1]=7;
number[2]=6;
number[3]=37;
Note:-we can also initialize arrays automatically in the same way as the ordinary variables
when they are declare.
Data Type ArrayName[]={list of values};
Example::-int numbers[]={2,4,5,6,7};
CompiledbyUmeshSharma
Page-14
Array length:-
In java all arrays store the allocate size in a variable named length. We can access the size of
array using following syntax.
int variableName=array.length;
example :- int n=number.length;
here n assign value 5;
Example # 1
//EXAMPLE OF SINGLE DIMENSIONAL ARRAY FIND THE AVG OF ARRAY
ELEMENTS.
class Avgarraydemo {
public static void main(String args[]) {
int a[]={12,12,12,12,12};
double avg=0;
int i;
for(i=0;i<a.length;i++) {
avg=avg+a[i];
}
System.out.println(i);
avg=avg/i;
System.out.print("Average="+avg);
}
}
Example # 2
//Example for set elements of array in ascending order and descending order.
class AscDsc {
int i,j,a[]={22,33,21,5,26};
int l;
void a() {
l=a.length;
for(i=0;i<l;i++) {
System.out.println("Before the arrange array is a["+i+"]="+a[i]);
}
System.out.println("After sorting array in Ascending order::");
for(i=0;i<l;i++) {
for(j=0;j<l-1;j++)
CompiledbyUmeshSharma
Page-15
if(a[j]>a[j+1]) {
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
void d() {
//l=a.length;
System.out.println("\nAfter sorting array in Dscending order::");
for(i=0;i<l;i++) {
for(j=0;j<l-1;j++)
if(a[j]<a[j+1]) {
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
void show() {
for(i=0;i<l;i++) {
System.out.print(a[i]+" ");
}
}
CompiledbyUmeshSharma
Page-16
TWO DIMENSIONAL
Example # 3
}
}
Example # 4
//Example of two dimensional array MATRIX ADDITION, when values of matrix are
initialized.
class MatrixM {
public static void main(String args[]) {
int a[][]={{2,2},{2,2}};
int b[][]={{1,1},{1,1}};
int c[][]=new int[2][2];
int n=a.length;
int m=a[0].length;
if(n==m){
try{
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
c[i][j]=a[i][j]+b[i][j];
System.out.print("\t"+c[i][j]);
}
System.out.println();
CompiledbyUmeshSharma
Page-17
}
}
catch(Exception e){System.out.print("Some Error"+e);}
}
else{
System.out.print("\n Addition of matrix is not possible");
}
}
}
//this is the program for matrix addition.
Example # 5
//Example of two dimensional array MATRIX ADDITION When value of matrixs are given by
the user.
import java.io.*;
class M {
int a[][]=new int[3][3];
int b[][]=new int[3][3];
int c[][]=new int[3][3];
int i,j,k;
void getdata() {
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the matrix value of a:");
try{
for(i=0;i<3;i++)
for(j=0;j<3;j++)
a[i][j]=Integer.parseInt(in.readLine());
}
catch(Exception e){}
System.out.println("Enter the matrix value of b:");
try{
for(i=0;i<3;i++)
for(j=0;j<3;j++)
b[i][j]=Integer.parseInt(in.readLine());
}
catch(Exception e){}
}
void cal() {
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
}
void show() {
System.out.println("addition of matrix is::");
CompiledbyUmeshSharma
Page-18
for(i=0;i<3;i++) {
for(j=0;j<3;j++)
System.out.print(" "+c[i][j]);
System.out.println();
}
}
public static void main(String args[]) {
M obj=new M();
obj.getdata();
obj.cal();
obj.show();
}
}
Vector CLASS:-
In C and C++ generic utility function that with variable arguments can be uses to pass
different arguments depending upon the calling situation. Java does not support the concept of
variable arguments to a function. This feature can be achieved in java through the use of the
Vector class. Which one find in the java.util. package.
Vector class can be used to create a generic dynamic array known as vector that can
hold objects of any type and any number.
Constructor
Methods-
1. list.addElement(String item); => adds the item into the list at the end.
2. list.elementAt(int n); => Gives the name of element which hold nth position.
3. list.size(); => Gives the number of objects present in list.
4. list.removeElement(String item); => Remove the specific item in the list.
5. list.removeElementAt(int n); => Remove the item in specific position.
6. list.removeAllElements(); => Remove all elements in the list.
7. list.copyInto(array_variable); => Copies all item of list into array.
8. list.insertElementAt(String item,int n); => insert the item at nth position
9. list.indexOf(String item); => return the index number of the object.
Example # 1
CompiledbyUmeshSharma
Page-19
output
C:\>java vdemo
[One, Two, Four, Three, Five]
[One, Two, Three, Four, Three, Five]
[One, Two, Three, Four, Five]
One
Two
Three
Four
Five
CompiledbyUmeshSharma
Page-20
Example # 2
/*run
c:\corejava\class>java Vectordemo Ada BASIC FORTRAN JAVA C++
OUTPUT
List of languges are::
Ada
BASIC
COBOL
FORTRAN
JAVA
C++
*/
So far we have only been consider the simply types of method where we give some parameter
for the iteration. But here we consider passes objects as parameter to the methods .
CompiledbyUmeshSharma
Page-21
IMP..
// Example checks objects are equals are not true and false value should be return.
class Text {
int a,b;
Text(int x,int y)
{a=x;b=y;}
boolean cal(Text obj) {
if(obj.a==a && obj.b==b)
return true;
else
return false;
}
}//end of class Text
class objMethodDemo {
public static void main(String args[]) {
Text ob1=new Text(100,22);
Text ob2=new Text(11,11);
Text ob3=new Text(100,22);
System.out.println("ob1==ob2 is"+ob1.cal(ob2));
System.out.println("ob1==ob3 is"+ob1.cal(ob3));
}
}//end of class
Wrapper classes
Vector class cannot handle the primitive data types like int, float, long, char and double.
So primitive data types may be converted into objects using the wrapper classes. Wrapper
classes are defined in the java.lang package. Each of Javas eight primitive data types has a
corresponding class called a wrapper class.
CompiledbyUmeshSharma
Page-22
int i = 5;
Integer obj=new Integer(i);
int i=5;
String str =Integer.toString();
( VI ) Converting String to Primitive number by using Parsing() static method
String str=5;
int i=Integer.parseInt(str);
Short obj;
m=obj.shortValue()
m= Short.parseShort(str);
CompiledbyUmeshSharma
Page-23
Example # 1
// this is prg for wrapper class which use the all 6 methods
class wdemo {
public static void main(String args[]) {
short m=12;
//1.Convert number to object
Short obj=new Short(m);
System.out.println("Numerical object="+obj);
Example # 2
result=a+b;
System.out.print(result);
}
}
}
Example # 3
import java.lang.*;
class wrapperclass1 {
public static void main(String args[]) {
int n=59;
System.out.println("convert number to string by toString
method :"+Integer.toString(n));
System.out.println("convert number to binary by toBinaryString
method:"+Integer.toBinaryString(n));
System.out.println("convert number to Octal by toOctalString
method:"+Integer.toOctalString(n));
System.out.println("convert number to hexadecimal by toHexString
method:"+Integer.toHexString(n));
System.out.println("12:"+Integer.toString(n,12));
System.out.println("20:"+Integer.toString(n,20));
n=Integer.parseInt("3b",16);
System.out.println("decimal no of 3b:"+n);
}
}
Example # 4
import java.io.*;
import java.lang.*;
class SimpleIntrest {
public static void main(String args[]) {
int year=0;
float principal=0,rate=0;
try {
DataInputStream in=new DataInputStream(System.in);
System.out.print("Enter the principal");
String strp=in.readLine();
principal=Float.parseFloat(strp);
System.out.println("Enter the rate");
String strr=in.readLine();
rate=Float.parseFloat(strr);
System.out.println("Enter the year");
String stry=in.readLine();
year=Integer.parseInt(stry);
}
CompiledbyUmeshSharma
Page-25
catch(Exception e){}
float value=si(principal,rate,year);
line();
System.out.println("Simple intrest="+value);
line();
}
Example :-
In java, strings are class objects and implemented by using two classes, namely String and
StringBuffer. A java string is an instantiated object of the String Class. Java strings as compare
to C and C++ strings are more reliable. This is basically due to Cs lack of bound checking .
A java string is not a character array and is not terminated by null character. Strings may be
declared and creates as follows.
Syntax:=
String string_variable;
String_variable = new String(String);
Example:==
String firstName;
firstName=new String(Anil);
CompiledbyUmeshSharma
Page-26
It is possible toget the length of string by using the length() method of String class. Java strings
can be concatenated using the + operator.
System.out.println(firstName+Kumar);
String Methods:-
Example # 1
class alpha {
public static void main(String args[]) {
String a="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(a);
System.out.println("This string contains"+a.length()+"characters");
System.out.println("The character in 4 index="+a.charAt(4));
System.out.println("The index no. of z is="+a.indexOf('Z'));
String s=a.toLowerCase();
System.out.println(s);
int i=a.indexOf('S');
System.out.println(i);
System.out.println(a.replace('S','#'));
}
}
CompiledbyUmeshSharma
Page-27
output
C:\>java alpha
ABCDEFGHIJKLMNOPQRSTUVWXYZ
This string contains26characters
The character in 4 index=E
The index no. of z is=25
abcdefghijklmnopqrstuvwxyz
18
ABCDEFGHIJKLMNOPQR#TUVWXYZ
Example # 2
class st {
public static void main(String args[]) {
String s1="DishaCollege";
String s2=s1.toUpperCase();
System.out.println(s1);
System.out.println(s2);
String s3=s1.replace('D','M');
System.out.println(s3);
System.out.println( s1.equals(s2));
System.out.println( s1.equalsIgnoreCase(s2));
int n=s1.length();
System.out.println(n);
char ch=s1.charAt(4);
System.out.println(ch);
System.out.println(s1.compareTo(s2));
System.out.println(s1.concat(s2));
String sub1=s1.substring(4);
String sub2=s1.substring(4,8);
System.out.println(sub1);
System.out.println(sub2);
char c[]=new char[n];
c=s1.toCharArray();
for(int i=0;i<n;i++) {
System.out.println(c[i]);
}
}
}
CompiledbyUmeshSharma
Page-28
Example # 3
// this is prg for check given name is palindrome or not
class prg1 {
public static void main(String args[]) {
String name=args[0];
boolean b=true;
int n=name.length();
char a[]=new char[n];
a=name.toCharArray();
int l=n-1;
for(int i=0;i<n;i++) {
if(a[l]!=a[i]) {
b=false;
break;
}
l--;
}
if(b)
System.out.println("name is palindrome");
else
System.out.println("Name is not palindrome");
}
}
output
C:\>java prg1 malayalam
name is palindrome
Example # 1
// this is prg for arrange the names is alphabetical order.
class prg2 {
public static void main(String args[]) {
String a[]={"Rama","Raju","Ajay","Vijay","Kiran"};
int n=a.length;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(a[i].compareTo(a[j])>0)
{
CompiledbyUmeshSharma
Page-29
String temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int i=0;i<n;i++) {
System.out.println(a[i]);
}
}
}
output
C:\>java prg2
Ajay
Kiran
Raju
Rama
Vijay
SubString
A substring is a string whose characters form a contiguous part of another string. The string
class includes a substring() method for extracting substrings.
Example # 1
class SubString {
public static void main(String args[]) {
String a="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("1."+a);
System.out.println("2. This substring from index 4 to index 8 is:::"+a.substring(4,8));
System.out.println("3. substring from index 4 to index 4 is:::"+a.substring(4,4));
System.out.println("4. substring from index 4 to index 5 is:::"+a.substring(4,5));
System.out.println("5. substring from index 0 to index 8 is:::"+a.substring(0,8));
System.out.println("6. substring from index 8 to end is:::"+a.substring(8)
}
}
CompiledbyUmeshSharma
Page-30
output
C:\>java SubString
1.ABCDEFGHIJKLMNOPQRSTUVWXYZ
2. This substring from index 4 to index 8 is:::EFGH
3. substring from index 4 to index 4 is:::
4. substring from index 4 to index 5 is:::E
5. substring from index 0 to index 8 is:::ABCDEFGH
6. substring from index 8 to end is:::IJKLMNOPQRSTUVWXYZ
StringBuffer Class
An instance of Javas StringBuffer Class represents a string that can be dynamically modified.
StringBuffer is a peer class of String class. While String class creates strings of fixed_ length,
StringBuffer class creates strings with flexible length that can be modified in terms of both
length and context. We can insert characters and substrings in the middle of a string or append
another string to the end.
Methods.
1. s1.setCharAt(n,x);
2. s1.append(s2);
3. s1.insert(n, s2);
4. s1.setLength(n)
5. s1.capacity();
6. s1.insert(int index, String str);
7. s1.insert(int index, char ch);
8. s1.insert(int index, object obj);
Example # 1
CompiledbyUmeshSharma
Page-31
int n=str.indexOf('b');
System.out.println("index position of 'b'="+n);
buf.setCharAt(11,'w');
System.out.println("buf=="+buf);
buf.setCharAt(12,'o');
System.out.println("buf=="+buf);
buf.insert(13,'r');
System.out.println("buf=="+buf);
}
}
output
C:\>java sprg1
buf==It was the best of time
buf.length()=23
buf.capacity()=34
index position of 'b'=11
buf==It was the west of time
buf==It was the wost of time
buf==It was the worst of time
Example # 2
class sprg2 {
public static void main(String args[]) {
StringBuffer buf=new StringBuffer("it was the age of wisdom.");
System.out.println("buf=="+buf);
System.out.println("buf.length()=="+buf.length());
System.out.println("buf.capacity=="+buf.capacity());
String str=buf.toString();
System.out.println("str=="+str);
int n=str.indexOf('f');
System.out.println(n);
buf.append(",, "+str.substring(0,18)+"foolish");
System.out.println("buf=="+buf);
System.out.println("buf.length()=="+buf.length());
System.out.println("buf.capacity=="+buf.capacity());
}
}
Output
C:\>java sprg2
buf==it was the age of wisdom.
buf.length()==25
buf.capacity==41
str==it was the age of wisdom.
16
CompiledbyUmeshSharma
Page-32
Interface
An interface is a way of describing what classes should do, without specifying how they
should do it. A class can implements one or more interfaces. You can then use objects of these
implementing classes anything that conformance to the interface is required.
CAUTION
In the interface declaration the method was not declared public because all methods in an
interface are automatically public. However when implementing the interface, you must
declare the methods as public.
Otherwise the compiler assumes that the method has package visibility the default for a class.
Then the compiler complains that you try to supply a weaker access privilege.
Properties of interface
Interface are not classes. You can never use the new operator to instantiate an interface.
However, you cant construct interface objects, therefore you can still declare interface
variable.
interface inner1 {
void meth1();
}
interface inner2 {
void meth2();
}
class interdemo {
public static void main(String args[]) {
client obj=new client();
obj.a=8;obj.b=4;
obj.meth1();
obj.meth2();
inner1 ref;
ref=obj;
ref.meth1();
ref.meth2();// this method is invalid because interface reference variable invoke
only interface method.
obj.show();
}
}
OUTPUT
C:\>javac interdemo.java
interdemo.java:36: cannot find symbol
symbol : method meth2()
location: interface inner1
ref.meth2();// this method is invalid because interface reference variable invok
e only interface method
.
Inheritance:-
Anonymous classes:-
There are occasion where you need to define a class for which you will only ever want to
define one object in your program and only use for the object is to pass it directly as an
argument to a method. In this case as long as your class extends an exiting class, or implements
an inter face you have the option of defining the class as an anonymous class appear in the next
expression in the statement where you create and use the object of class, so the there is not
necessity to provide a name for the class.
If the anonymous class extends an exiting class the syntax is much the same.
An anonymous class can definition is short and simple you should not use the approach to
define classes of any complexity, as it will make the code very difficult to understand.
Example # 1
import java.awt.*;
import java.awt.event.*;
CompiledbyUmeshSharma
Page-34
Packages
Java provides a powerful means of grouping related classes and interfaces together in
a single unit: packages. Put simply, packages are groups of related classes and interfaces.
Packages provide a convenient mechanism for managing a large group of classes and interfaces
while avoiding potential naming conflicts. The Java API itself is implemented as a group of
packages.
CompiledbyUmeshSharma
Page-35
Exception Handling:-
Programming Errors
Compilation error:- that errors occur during compilation are called compilation errors or
syntax error. These errors are easy to detect because the compiler give the indication where
the errors came from and why they are there. It tells the reasons for them.
Example:-
class showerror {
public static void main(String args[]) {
i=20; //missing the datatype int
System.out.println(a+a);
}
}
Runtime Errors:- The errors that occur during the execution of a program is called Runtime
Errors. These errors cause a program to terminate abnormally.
1) Input Errors:- An input errors occurs when the user enters an unexpected input
value that the program cannot handle.
example:
a) It the program expects to read an integer, but the user enters a string.
b) Typing errors, incorrect non-exiting URLs.
2) System Software and Hardware Errors:- These kind of Errors occur rarely happen.
However unreliable system software and hardware malfunction can cause a program to abort.
System Software Errors are beyond the programmers control, and there is little you can do
when you encounter them.
example:
a) System Hanging
b) Hard Disk crashes.
c) Space not available in main memory.
d) Device Errors.
3) Logical Errors:-Logical Errors cause the program to either generate incorrect
results or terminate abnormally. The errors are called bugs. The process of finding logical
errors is called debugging.
a) if file name and class name are different
CompiledbyUmeshSharma
Page-36
Exception Handling
An exception is a condition that is caused by a runtime error in the program, When the java
interpreter encountered an error. It create an exception object and throws it.
A java Exception is an object that describes an exceptional condition that has occurred in a
piece of code. At some point the exception is caught and processed is called Exception
handling.
Exception can be generated by the JVM or they are manually generated.
Throwable
Exception
IOException
ArithmeticException
ArrayStoreException
ArrayIndexOutOfBoundsException
NullPointerException
RuntimeException
FileNotFoundException
EndOfFileException
Error
CompiledbyUmeshSharma
Page-37
Throwable:-
A java exception is an instance of the class derived from Throwable. This class is contained in
java.lang package and subclasses of Throwable contained in various packages.
Exception Class:- This class describes the errors caused by programs. These errors can be
caught and handled by the program. This is also the class that you will subclass to create our
own custom exception types.
IOException : - This class describes errors related to Input / Output operation such as invalid
input or inability to read from a file.
1. Arithmetic Exception:- Caused by math errors, such as divided by zero.
2. ArrayStroeException:- Caused when a programmer tries to store the wrong data types
in an array.
3. ArrayIndexOutOfBoundsException:- Caused by bad array Indexes.
4. NullPointerException:- Caused by referencing a null object.
RunTimeException :
1. FileNotFoundException: - Caused by an attempt to access a nonexistent file.
2. EndOfFileException:- Caused as inability to read from a file.
Error: It is not in our control. The Error class describe internal system errors, which rarely
occur. Stack overflow is the best example of errors.
2. The try block can have one or more than one statements that could generate an
exception . If any one statement generate an exception, the remaining statement in the block
are skipped and exception jumps to catch block
3. Every try statement should be followed by at least one catch statement /finally
otherwise compilation error will occur.
4. The catch statement is passed a single parameter, which is reference to the exception
object thrown by the try block.
CompiledbyUmeshSharma
Page-38
Try Block
Exception Object Creator
Statement that generate the
Exception
Catch Block
Exception Handler
Statement that handles the
Exception
Example # 1
CompiledbyUmeshSharma
Page-39
Example # 2
class prg2 {
public static void main(String args[]) {
int a[]={5,10};
int n=args.length;
int c;
try {
c=a[1]/n;
System.out.println("Value of c="+c);
c=a[2]+a[0];
System.out.println("Value of c="+c);
}
catch(ArithmeticException e) {
System.out.println("Error="+e);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Error="+e);
}
}
}
Output
C:\>java prg2
Error=java.lang.ArithmeticException: / by zero
C:\>java prg2 1 2
Value of c=5
Error=java.lang.ArrayIndexOutOfBoundsException: 2
finally keyword:
If we want some code to be execute regardless of whether the exception occurs and whether is
caught the code in the finally block is executed under all circumstances.
throw Keyword
You can manually throw an exception with the help of using throw keyword. In the method
that has claimed the exception you can throw an object of the exception if the exception arises.
Syntax:-
throw new MyException();
OR
MyException e=new MyException();
throw e;
CompiledbyUmeshSharma
Page-40
Example # 3
class prg3 {
void compute(int a) throws MyException {
System.out.println("Called compute("+a+")");
if(a>10) {throw new MyException(a);}
System.out.println("Compute again");
}
Output
C:/>java prg3
Called compute(1)
Compute again
Called compute(5)
Compute again
Called compute(20)
caughtMyException[20]
CompiledbyUmeshSharma
Page-41
Example # 4
throws keyword
If method is capable of causing an exception that it does not handle it must specify this
behavior so that caller of the method can guarded themselves against the exception by using
throws keyword.
Syntax:-
Retrun_type method_name(Parameter list) throws exception List {
body of the method.
}
Multithreaded Programming
A typical program is executed sequentially and is single threaded. All modern Operating
System may execute multiple programs simultaneously, even if there is only a single CPU
available to run all the application. Multithreading allows multiple tasks to execute
concurrently within a single program. The main advantage of multiple threads in a program is
that it utilizes system resources(like CPU) better because other threads can grab CPU time
when one line of execution is blocked. By using multithreading, you can create programs
showing animation, play music, display
Document and download files from the network simultaneously.
Java was designed from the start to accommodate multithreading. Synchronized method to
avoid collision in which more than one thread attempt to modify the same object at the same
time.
CompiledbyUmeshSharma
Page-42
Main Thread
Switching
Switching
Thread A Thread B Thread C
What is thread?
Any single path of execution is called thread. The path is defined by elements such as stack
and set of registers to store temporary memory. Every program has at least one thread. Each
thread has its own stack, priority and virtual set of registers. Threads subdivided the runtime
behaviour of a programs into separate, independently running subtasks. Switching between
threads is called out automatically by JVM. Even in a single processor system, thread provides
an illusion of carrying out several tasks simultaneously.
CompiledbyUmeshSharma
Page-43
New Thread
New Born
Start() stop()
Killed Thread
Yield
Suspend() resume()
wait() notify(), notifyAll() stop()
sleep(t)
New Born State:- when we create a thread object, it is said to be in newborn state. At this
stage we can start the thread using start() method or kill it using stop() method.
Runnable State:- The thread in runnable state means that the thread is ready for execution and
is waiting for CPU time.
Running State:- Running state means CPU has given its time to the thread for execution.
Dead State:- A thread can be killed in any state by using the stop() method.
CompiledbyUmeshSharma
Page-44
Example # 1
// this is prg for which using the currentThread() and setName() method
// this prg is used single thread so here not need to extends Thread class or implement
//Runnable
class ThreadName {
public static void main(String args[]) {
Thread t=new Thread();
t=Thread.currentThread();
System.out.println("The current running thread is=::"+t);
t.setName("MyThread");
System.out.println("After changing thread name is=::"+t);
System.out.println("only name of the thread is="+t.getName());
}
}
Example # 2
// Using Thread methods yield(), stop() and sleep().
class A extends Thread {
public void run() {
for(int i=0;i<5;i++) {
if(i==1)
yield();
System.out.println("\t From Thread A :i="+i);
CompiledbyUmeshSharma
Page-45
}
System.out.println("Exit from A");
}
}
Output
C:\>java ThreadMethod
Start of Thread A
CompiledbyUmeshSharma
Page-46
Start of Thread B
Start of Thread C
End of main Thread
From Thread A :i=0
From Thread B :j=0
From Thread B :j=1
From Thread B :j=2
From Thread B :j=3
From Thread C :k=0
From Thread C :k=1
From Thread A :i=1
From Thread A :i=2
From Thread A :i=3
From Thread A :i=4
Exit from A
From Thread C :k=2
From Thread C :k=3
From Thread C :k=4
Exit from C
Example # 3
class newThread implements Runnable {
String name;
Thread t;
newThread(String s) {
name=s;
t=new Thread(this,name);
System.out.println("Thread ::"+t.getName()+"is start.");
t.start();
}
public void run() {
try {
for(int i=0;i<5;i++) {
System.out.println(name+"::"+i);
}
t.sleep(1000);
}
catch(Exception e) {
System.out.println(e);
}
}
}
class AliveJoinThread {
public static void main(String args[]) {
newThread obj1,obj2,obj3;
CompiledbyUmeshSharma
Page-47
obj1=new newThread("one");
obj2=new newThread("two");
obj3=new newThread("three");
System.out.println("Thread one is live="+obj1.t.isAlive());
System.out.println("Thread two is live="+obj2.t.isAlive());
System.out.println("Thread three is live="+obj3.t.isAlive());
try {
System.out.println("Wait for thread for finished");
obj1.t.join();obj2.t.join();obj3.t.join();
}
catch(Exception e){System.out.println(e);}
System.out.println("Thread one is live="+obj1.t.isAlive());
System.out.println("Thread two is live="+obj2.t.isAlive());
System.out.println("Thread three is live="+obj3.t.isAlive());
}
}
output
C:\>java AliveJoinThread
Thread ::oneis start.
Thread ::twois start.
Thread ::threeis start.
Thread one is live=true
Thread two is live=true
one::0
two::0
three::0
one::1
two::1
three::1
one::2
two::2
three::2
one::3
two::3
three::3
one::4
two::4
three::4
Thread three is live=true
Wait for thread for finished
Thread one is live=false
Thread two is live=false
Thread three is live=false
CompiledbyUmeshSharma
Page-48
Creating Threads
Creating a thread extends the thread class
Example # 2
CompiledbyUmeshSharma
Page-49
obj2.start();
obj3.start();
}
}
output
C:\>javac ThreadTest.java
C:\>java ThreadTest
From Thread A :i=0
From Thread A :i=1
From Thread A :i=2
From Thread A :i=3
From Thread A :i=4
Exit from A
From Thread B :j=0
From Thread B :j=1
From Thread B :j=2
From Thread B :j=3
From Thread B :j=4
Exit from B
From Thread C :k=0
From Thread C :k=1
From Thread C :k=2
From Thread C :k=3
From Thread C :k=4
Exit from C
To create a thread, declare a class that implement the runnable interface. To implement
runnable, a class needs to only implements a single method called run(). After you create a
class that implements runnable, you will instantiate an object of types thread using the
constructor of thread class.
Example # 3
class A extends Thread {
public void run() {
for(int i=0;i<5;i++) {
System.out.println("\t From Thread A :i="+i);
}
System.out.println("Exit from A");
}
}
CompiledbyUmeshSharma
Page-50
class RunnableTest {
public static void main(String args[]) {
A obj1=new A();
Thread t=new Thread(obj1);
t.start();
}
}
Output
C:\>javac RunnableTest.java
C:\>java RunnableTest
From Thread A :i=0
From Thread A :i=1
From Thread A :i=2
From Thread A :i=3
From Thread A :i=4
Exit from A
Thread Priorities
In java each thread is assigned a priority. Thread priority are used by the thread scheduler is
decide which and when thread should be allowed to run().
The threads of the same priority are gives equal treatment by the java scheduler and
therefore they share the processor on a first come first serve (Round Robin) basis.
Java permits us to set the priority of a thread by using the setPriority( ) method.
Syntax:-
ThreadName.setPriority(int number);
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Higher priority thread gets more CPU time comparison to lower priority threads.
We can also capable to obtain the current setting of priority of thread by using the following
method of thread class.
int getPriority( );
Example # 4
// this is example of using the thread priority methods.
class A extends Thread {
public void run() {
for(int i=0;i<5;i++) {
System.out.println("\t From Thread A :i="+i);
CompiledbyUmeshSharma
Page-51
}
System.out.println("Exit from A");
}
}
class B extends Thread {
public void run() {
for(int j=0;j<5;j++) {
System.out.println("\t From Thread B :j="+j);
}
System.out.println("Exit from B");
}
}
class C extends Thread {
public void run() {
for(int k=0;k<5;k++) {
System.out.println("\t From Thread C :k="+k);
}
System.out.println("Exit from C");
}
}
class ThreadPriority {
public static void main(String args[]) {
A objA=new A();
B objB=new B();
C objC=new C();
objC.setPriority(Thread.MAX_PRIORITY);
objB.setPriority(objA.getPriority()+1);
objA.setPriority(Thread.MIN_PRIORITY);
System.out.println("Start Thread A");
objA.start();
System.out.println("Start Thread B");
objB.start();
System.out.println("Start Thread C");
objC.start();
System.out.println("End of main Thread");
}
}
output
C:\>java ThreadPriority
Start Thread A
Start Thread B
From Thread B :j=0
From Thread B :j=1
From Thread B :j=2
From Thread B :j=3
CompiledbyUmeshSharma
Page-52
Synchronization
So far we have seen threads that use their own data and methods provided inside their run()
methods. What happens when they try to use data and methods outside themselves? On such
occasions, they may compete for the same resources and may lead to serious problems. For
example one thread may try to read a record from a file while another is still writing to the
same file. Depending on the situation, we may get strange results. Java enables us to overcome
this problem using a technique known as Synchronization.
In case of java the keyword synchronized helps to solve such problems by keeping a watch on
such locations. For example, the method that will read information from a file and the method
that will update the same file may be declared as synchronized.
Syntax:
synchronized void update {
.
//code here is synchronized
..
}
Concept of monitor
When we declare a method synchronized, java creates a monitor and hands it over to the
thread that calls the method first time. As long as the thread holds the monitor, no other thread
can enter the synchronized section of the code. A monitor is like a key and the thread that holds
the key can only open the lock.
Whenever a thread has completed its work of using synchronized method, it will hand
over the monitor to the next thread that is ready to use the same resource.
An interesting situation may occur when two or more threads are waiting to gain
control of a resource. Due to some reasons, the condition on which the waiting threads rely on
the gain control does not happen. This results in what is known as deadlock.
CompiledbyUmeshSharma
Page-53
Example of Synchronization:
class SynchronizedTest {
public static void main(String args[]) {
A objA=new A();
B objB=new B();
C objC=new C();
System.out.println("Start Thread A");
objA.start();
System.out.println("Start Thread B");
objB.start();
System.out.println("Start Thread C");
objC.start();
System.out.println("End of main Thread");
}
}
CompiledbyUmeshSharma
Page-54
Overview of Applets
This lesson discusses the parts of an applet. If you haven't yet compiled an applet and included
it in an HTML page, you might want to do so now. Step by step instructions are in Writing
Applets .
Every applet is implemented by creating a subclass of the Applet class. The following figure
shows the inheritance hierarchy of the Applet class. This hierarchy determines much of what
an applet can do and how, as you'll see on the next few pages.
A Simple Applet
Below is the source code for an applet called Simple. The Simple applet displays a descriptive
string whenever it encounters a major milestone in its life, such as when the user first visits the
page the applet's on. The pages that follow use the Simple applet and build upon it to illustrate
concepts that are common to many applets.
/*
* 1.0 code.
*/
import java.applet.Applet;
import java.awt.Graphics;
StringBuffer buffer;
CompiledbyUmeshSharma
Page-55
You can use the Simple applet to learn about the milestones in every applet's life.
The Applet class provides a framework for applet execution, defining methods that the system
calls when milestones -- major events in an applet's life cycle -- occur. Most applets override
some or all of these methods to respond appropriately to milestones.
Applets inherit the drawing and event handling methods of the AWT Component class. (AWT
stands for Abstract Windowing Toolkit; applets and applications use its classes to produce user
interfaces.) Drawing refers to anything related to representing an applet on-screen -- drawing
images, presenting user interface components such as buttons, or using graphics primitives.
Event handling refers to detecting and processing user input such as mouse clicks and key
presses, as well as more abstract events such as saving files and iconifying windows.
Applets inherit from the AWT Container class. This means that they are designed to hold
Components -- user interface objects such as buttons, labels, pop-up lists, and scrollbars. Like
other Containers, applets use layout managers to control the positioning of Components.
For security reasons, applets that are loaded over the network have several restrictions. One is
that an applet can't ordinarily read or write files on the computer that it's executing on. Another
CompiledbyUmeshSharma
Page-56
is that an applet can't make network connections except to the host that it came from. Despite
these restrictions, applets can do some things that you might not expect. For example, applets
can invoke the public methods of other applets on the same page.
Once you've written an applet, you'll need to add it to an HTML page so that you can try it out.
This section tells you how to use the <APPLET> HTML tag to add an applet to an HTML page.
The Life Cycle of an Applet
Loading the Applet
When the user leaves the page -- for example, to go to another page -- the applet
has the option of stopping itself. When the user returns to the page, the applet
can start itself again. The same sequence occurs when the user iconifies and
then reopens the window that contains the applet. (Other terms used instead of
iconify are minaturize, minimize, and close.)
Some browsers let the user reload applets, which consists of unloading the
applet and then loading it again. Before an applet is unloaded, it's given the
chance to stop itself and then to perform a final cleanup, so that the applet can
release any resources it holds. After that, the applet is unloaded and then loaded
again, as described in Loading the Applet, above.
When the user quits the browser (or whatever application is displaying the
applet), the applet has the chance to stop itself and do final cleanup before the
browser exits.
An applet can react to major events in the following ways:
CompiledbyUmeshSharma
Page-57
Methods
public class Simple extends Applet {
. . .
public void init() { . . . }
public void start() { . . . }
public void stop() { . . . }
public void destroy() { . . . }
. . .
}
The Simple applet, like every other applet, features a subclass of the Applet class. The Simple
class overrides four Applet methods so that it can respond to major events:
init
To initialize the applet each time it's loaded (or reloaded).
start
To start the applet's execution, such as when the applet's loaded or when the user
revisits a page that contains the applet.
stop
To stop the applet's execution, such as when the user leaves the applet's page or quits
the browser.
destroy
To perform a final cleanup in preparation for unloading.
The init method is useful for one-time initialization that doesn't take very long. In general, the
init method should contain the code that you would normally put into a constructor. The
reason applets shouldn't usually have constructors is that an applet isn't guaranteed to have a
full environment until its init method is called. For example, the Applet image loading
methods simply don't work inside of a applet constructor. The init method, on the other hand,
is a great place to call the image loading methods, since the methods return quickly.
CompiledbyUmeshSharma
Page-58
Overview of Swing
What Are the JFC and Swing?
JFC is short for JavaTM Foundation Classes, which encompass a group of features to help people
build graphical user interfaces (GUIs). The JFC was first announced at the 1997 JavaOne
developer conference and is defined as containing the following features:
The Swing Components
Include everything from buttons to split panes to tables.
Top-Level Containers
General-Purpose Containers
Tool bar
CompiledbyUmeshSharma
Page-59
Special-Purpose Containers
Root pane
Basic Controls
CompiledbyUmeshSharma
Page-60
Gives any program that uses Swing components a choice of looks and feels. For example, the
same program can use either the JavaTM look and feel or the Windows look and feel. We expect
many more look-and-feel packages -- including some that use sound instead of a visual "look"
-- to become available from various sources.
Accessibility API
Enables assistive technologies such as screen readers and Braille displays to get information
from the user interface.
CompiledbyUmeshSharma
Page-61
Provides the ability to drag and drop between a Java application and a native application. The
first three JFC features were implemented without any native code, relying only on the API
defined in JDK 1.1. As a result, they could and did become available as an extension to
JDK 1.1. This extension was released as JFC 1.1, which is sometimes called "the Swing
release." The API in JFC 1.1 is often called "the Swing API." This trail concentrates on the
Swing components. We help you choose the appropriate ones for your GUI, tell you how to
use them, and give you the background information you need to use them effectively. We
discuss the Pluggable look and feel and Accessibility support when they affect how you write
programs that use Swing components. This trail does not cover the JFC features that appear
only in the Java 2 Platform. The following snapshots show three views of a GUI that uses
Swing components. Each picture shows the same program, but with a different look and feel.
As a core part of the Java 2 Platform (standard edition of either v 1.2 or v 1.3)
JFC 1.1 (for use with JDK 1.1)
Which release you use depends on whether you need to use JDK 1.1 or the Java 2 Platform,
and on whether you're willing to be a beta tester for SDK v 1.3. It's a bit simpler to use the
Java 2 Platform because the JFC is built into the Java 2 Platform and you don't need to add
libraries to be able to use the Swing API. However, if you need to use JDK 1.1, then adding the
Swing API (using JFC 1.1) isn't difficult. This trail describes the Swing 1.1 API, which is the
version present in the Java 2 Platform v 1.2 and in the release called "JFC 1.1 (with
Swing 1.1)." Except where noted, the code in this trail works unchanged with either release and
subsequent compatible releases, such as SDK v 1.3 and JFC 1.1 (with Swing 1.1.1).
CompiledbyUmeshSharma
Page-62
Sun has released many versions of JFC 1.1, which are identified by the version of Swing API
they contain. One previous version, for example, was called "JFC 1.1 (with Swing 1.0.3)." The
last JFC 1.1 release was Swing version 1.1.1. It had the same API as Swing 1.1, but added
many bug fixes, some performance improvements, and a few new capabilities such as HTML
text in labels that required no API changes. The following table shows some of the important
releases containing Swing API. Bold font indicates the releases typically used in shipping
products.
Corresponding
Swing API Corresponding Java 2 Platform
Comments
Version JFC 1.1 Release Version (Standard
Edition)
JFC 1.1
The release of JFC 1.1 included in
Swing 1.0.3 (with none
Java Plug-inTM 1.1.1.
Swing 1.0.3)
The first releases containing the final
Swing 1.1
Swing 1.1 API supported for use in
JFC 1.1 shipping products. Java Plug-in 1.1.2
Note: This is v 1.2, v 1.2.1
(with Swing 1.1) and Java Plug-in 1.2 provide applet
the API this
support for JDK 1.1 + Swing 1.1 and
trail covers.
Java 2 Platform v 1.2, respectively.
Adds performance enhancements,
JFC 1.1
Swing 1.1.1 many bug fixes, and selected new
(with
functionality (requiring no API
Swing 1.1.1)
Note: This changes) to Swing 1.1. Java Plug-in
v 1.2.2
trail includes 1.1.3 and Java Plug-in 1.2.2 provide
Note: This is the
notes about applet support for JDK 1.1 +
last release that
this API. Swing 1.1.1 and Java 2 Platform
supports JDK 1.1.
v 1.2.2, respectively.
Adds significant performance
enhancements and bug fixes, along
with some new features and API
no separate
additions. For more information, see
"Swing"
none v 1.3 Beta the release documentation ,
version
especially Swing Changes and New
number
Features . Java Plug-in 1.3 Beta
provides applet support for this
release.
CompiledbyUmeshSharma
Page-63
Fortunately, most programs use only a small subset of the API. This trail sorts out the API for
you, giving you examples of common code and pointing you to methods and classes you're
likely to need. Most of the code in this trail uses only one or two Swing packages:
javax.swing
javax.swing.event (not always required)
The AWT components are those provided by the JDK 1.0 and 1.1 platforms. Although the
Java 2 Platform still supports the AWT components, we strongly encourage you to use Swing
components instead. You can identify Swing components because their names start with J. The
AWT button class, for example, is named Button, while the Swing button class is named
JButton. Additionally, the AWT components are in the java.awt package, while the Swing
components are in the javax.swing package.
The biggest difference between the AWT components and Swing components is that the Swing
components are implemented with absolutely no native code. Since Swing components aren't
restricted to the least common denominator -- the features that are present on every platform --
they can have more functionality than AWT components. Because the Swing components have
no native code, they can be be shipped as an add-on to JDK 1.1, in addition to being part of the
Java 2 Platform.
Even the simplest Swing components have capabilities far beyond what the AWT components
offer:
Swing buttons and labels can display images instead of, or in addition to, text.
You can easily add or change the borders drawn around most Swing components. For
example, it's easy to put a box around the outside of a container or label.
You can easily change the behavior or appearance of a Swing component by either
invoking methods on it or creating a subclass of it.
Swing components don't have to be rectangular. Buttons, for example, can be round.
Assistive technologies such as screen readers can easily get information from Swing
components. For example, a tool can easily get the text that's displayed on a button or
label.
Swing lets you specify which look and feel your program's GUI uses. By contrast, AWT
components always have the look and feel of the native platform. Another interesting feature
CompiledbyUmeshSharma
Page-64
is that Swing components with state use models to keep the state. A JSlider, for instance, uses
a BoundedRangeModel object to hold its current value and range of legal values. Models are set
up Automatically, so you don't have to deal with them unless you want to take advantage of the
power they can give you. If you're used to using AWT components, you need to be aware of a
few things when using Swing components:
Bothinstructionstellyouhowtorunasimpleprogram,calledSwingApplication,whoseGUIlookslike
this:
CompiledbyUmeshSharma
Page-65
1. Download the latest release of the Java 2 Platform, if you haven't already done so.
2. Create a program that uses Swing components.
3. Compile the program.
4. Run the program.
Which version you choose depends on the features you need and your (or your company's)
tolerance for not-quite-final software. For information about the differences between 1.2 and
1.3, see the Java 2 SDK v 1.3 documentation .
CompiledbyUmeshSharma
Page-66
Components that you can use to build a GUI app, are instances of classes contained in
the javax.swing package:
JButton
JTextField
JRadioButton
JCheckBox
JComboBox
JLabel etc
Layout Managers
You can use the layout managers to design your GUIs. There are several managers like:
FlowLayout
BorderLayout
GridLayout
CardLayout
GridBagLayout
FlowLayout
It is the Default layout of GUI application. Components laid out from the top-left corner, from
left to right and top to bottom like a text.
CompiledbyUmeshSharma
Page-67
BorderLayout
Places components in up to five areas: top, bottom, left, right, and center. All extra space is
placed in the center area.
GridLayout
Simply makes a bunch of components equal in size and displays them in the requested number
of rows and columns
CardLayout
We can implement an area that contains different components at different times. A CardLayout
is often controlled by a combo box, with the state of the combo box determining which panel
(group of components) the CardLayout displays.
CompiledbyUmeshSharma
Page-68
GridBagLayout
It is a sophisticated, flexible layout manager. It aligns components by placing them within a
grid of cells, allowing some components to span more than one cell.
To use the layout managers in the GUI Application we must use it into code:
Container myCont = getContentPane();
myCont.setLayout(new FlowLayout());
Listeners
Any number of event listener objects can listen for all kinds of events from any number of
event source objects. E.g. a program might create one listener per event source or a program
might have a single listener for all events from all sources. Multiple listeners can register to
be notified of events of a particular type from a particular source. Also, the same listener can
listen to notifications from different objects.
Each type of listeners can be notified only for its corresponding types of events which can be
generated by specific types of sources.
Multiple sources, single listener - Many buttons can register the same listener since all
buttons generate the same type of event. This type of event may be generated by other types of
sources as well.
CompiledbyUmeshSharma
Page-69
Sources-events-listeners
Source Event <state Listener Methods
change> (argument:
corresponding
event)
Mouse MouseEvent MouseListener mouseClicked
<mouse clicked, mousePressed
pressed, dragged, mouseReleased etc
moved/ ntered,
exited a component
etc> MouseMotionListener mouseDragged
MouseWheelEvent mouseMoved
<page-up and down>
MouseWheelListener mouseWheelMoved
Keyboard KeyEvent KeyListener keyPressed
keyReleased
keyTyped
Button ActionEvent ActionListener ActionPerformed
<GUI button
clicked>
CompiledbyUmeshSharma
Page-70
Inner classes
You may create all different classes independently and put them in separate files, or you can
implement your listeners inside the class that extends your JFrame, making it an inner class.
This enables you to put everything in one class (and hence file).
Adapter classes
Adapter classes are fully abstract classes that correspond to listener interfaces. They are
extended (not implemented) and thus you can ignore methods that do not interest you. You can
use them instead of listeners in the case that only some of the methods of the interface are to be
used. You dont use the abstract specifier and of course you cannot use multiple inheritence.
Some adapter classes:
KeyAdapter (instead of KeyListener)
MouseAdapter (MouseListener)
MouseMotionAdapter (MouseMotionListener) etc
Create your window
//Extend a JFrame:
public class MyApp extends JFrame {
//Declare all your components private:
private JButton b1;
//Create your constructor:
Public MyApp(){
super(SwingApplication");
//Inside your constructor:
//Get your container:
Container myCont = getContentPane();
//Inside your constructor, set a layout:
GridBagLayout layout = new GridBagLayout();
myCont.setLayout(layout);
// Inside your constructor, create your element objects:
b1=new JButton(Im a Swing button!); ...
// Inside your constructor, Add them on your content pane:
myCont.add(b1); ...
// Inside your application class, add the main method that is the entry point of
your //program and creates the application object:
}
public static void main(String[] args){
MyApp a =new MyApp();
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
CompiledbyUmeshSharma
Page-71
When an event is generated by a source it is handled by the listener registered by this source.
As shown, the listener is an implemented interface (or an extended adapter) and thus you have
to implement some methods. These methods take the event as an argument and this is where
you put the code to be executed when the event happens. In other words, you define what you
want to happen eg. when a button is pressed, inside the actionPerformed method implemented
inside the listener . To be able to do that efficiently, the event classes define specific methods
to extract information about the events.
EventObject:
// superclass of all events, so the following method is inherited by all event objects
Object getSource()
MouseEvent:
int getX(), int getY()
int getButton()
KeyEvent:
char getKeyChar()
ActionEvent:
String getActionCommand()
long getWhen()
CompiledbyUmeshSharma