You are on page 1of 67

INDEX

1. Introduction
2. Class and Object
3. Method Oveloading & Method Overriding
4. Inheritance
5. Interfaces
6. this, super and final mechanism in JAVA
7. Abstract Classes
8. Inner Classes & Public Classes
9. Exceptions
10. Threads
11. Packages
12. Applets
13. AWT
14. Swings
15. Java Library
16. Generic Classes
17. Stream Classes (Files)
18. Wrapper Classes

/*Scanner Class:- Scanner class is available in java.util package. It provides the following methods to read values into
variables.
1. next() : To read a string into string type variable.
2. nextInt() : To read an integer into int type variable.
3. nextFloat() : To read a float value into float type variable.
4. nextDouble() : To read a double value into double type variable.
5. next().charAt(0) : To read a character into char type variable.
Example:-
To read information of a student and print it */
import java.util.Scanner;
class JP1
{
public static void main(String args[])
{
char g;
String n;
int rno;
float f;
double k;
Scanner x= new Scanner(System.in);
System.out.print("Enter gender code, name, rno, fee and annual income of a student\n");
g = x.next().charAt(0);
n = x.next();
rno = x.nextInt();
f = x.nextFloat();
k = x.nextDouble();
System.out.println("\nStudent Name : " +n);
System.out.println("\nRoll Number : " +rno);
System.out.println("\nGender Code : " +g);
System.out.println("\nTotal Fee : " +f);
System.out.println("\nAnnual Income : " +k);
}
}
/* A program to find area and circumference of a circle */
import java.util.Scanner;
class JP2
{
public static void main(String args[])
{
float r;
double a, c;
Scanner in = new Scanner(System.in);
System.out.print("Enter Radius of Circle : ");
r = in.nextFloat();
a = 3.142*r*r;
c = 2*3.142*r;
System.out.print("Area of Circle = " +a);
System.out.print("\nCircumference of Circle = " +c);
}
}
/* To check given character is Vowel or not */
import java.util.Scanner;
class JP3
{
public static void main(String args[])
{
char ch;
Scanner in= new Scanner(System.in);
System.out.print("Enter an Alphabet ");
ch = in.next().charAt(0);
if(ch=='a' || ch=='A' || ch=='e' || ch=='E' || ch=='i' || ch=='I' || ch=='o' || ch=='O' || ch=='u' || ch=='U')
{
System.out.print("This is a Vowel");
}
else
{
System.out.print("This is not a Vowel");
}
}
}
/* To check given character is an alphabet or not */
import java.util.Scanner;
class JP4
{
public static void main(String args[])
{
char x;
Scanner in = new Scanner(System.in);
System.out.print("Enter a character ");
x = in.next().charAt(0);

if((x>='a' && x<='z') || (x>='A' && x<='Z'))


{
System.out.print(x + " is an Alphabet");
}
else
{
System.out.print(x + " is not an Alphabet");
}
}
}
/* A program to read an arithmetic operator and two numbers and perform the operation between the given
numbers and print the result */
import java.util.Scanner;
class JP5
{
public static void main(String args[])
{
char op;
int a,b;
Scanner in= new Scanner(System.in);
System.out.print("Enter an arithmetic operator ");
op = in.next().charAt(0);
System.out.print("Enter two numbers\n");
a=in.nextInt();
b=in.nextInt();
switch(op)
{
case '+':
System.out.print("Sum = " + (a+b)); break;
case '-':
System.out.print("Difference = " + (a-b));
break;
case '*':
System.out.print("Product = " + (a*b)); break;
case '/':
System.out.print("Quotient = " + (a/b));
break;
case '%':
System.out.print("Remainder = " + (a%b));
break;
default:
System.out.print("Invalid Operator");
}
}
}
/* A program to find N factorial */
import java.util.Scanner;
class JP6
{
public static void main(String args[])
{
int i, n, f=1;
Scanner in= new Scanner(System.in);
System.out.print("Enter n value ");
n=in.nextInt();
for( i=1 ; i<=n ; i++)
{
f = f * i;
}
System.out.println(n + " factorial = " + f);
}
}
/* A program to find HCF and LCM of two given numbers */
import java.util.Scanner;
class JP7
{
public static void main(String args[])
{
int a, b, x, y, t, hcf, lcm;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Two Numbers\n");
x = scan.nextInt();
y = scan.nextInt();
a = x;
b = y;
while(b != 0)
{
t = b;
b = a%b;
a = t;
}
hcf = a;
lcm = (x*y)/hcf;
System.out.print("HCF = " + hcf);
System.out.print("\nLCM = " + lcm);
}
}
ARRAYS
An array is a set of consecutive memory locations having same name and same type of data. Java provides three
types of arrays as follows.
1. Single Dimensional Arrays:-
An array with only one sub-script is known as a single dimensional array. It is used to represent a list. Syntax:-
data-type array-name[] = new data-type[size];
Example:-
int a[]=new int[10];
This means "a" is a single dimensional array used to store 10 integers.
2. Two Dimensional Arrays (or) Double Dimensional Arrays:- An array with two sub-scripts is known as a double
dimensional array. It is used to represent a table or a matrix.
Syntax:-
data-type array-name[][] = new data-type[rows][columns];
Example:-
int m[][]=new int[4][6];
This means "m" is a double dimensional array used to store 24 integers in 4 rows and 6 columns.
3. Multi Dimensional Array:-
An array with more than two sub-scripts is known as a multi dimensional array.
Syntax:-
data-type array-name[][][]=new data-type[rows][cols][tables];
Example:-
int p[][][]=new int[4][6][3];
This means "p" contains 3 tables each one contains 4 rows and 6 columns.

PROGRAMS
/* A program to read N numbers and print the given numbers */
import java.util.Scanner;
class JP8
{
public static void main(String s[])
{
int a[] = new int[20];
int n, i;
Scanner in = new Scanner(System.in);
System.out.println("How many numbers");
n=in.nextInt();
System.out.println("Enter the numbers");
for(i=0;i<n;i++)
{
a[i]=in.nextInt();
}
System.out.println("\nGiven numbers");
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
/* A program to read nxm matrix and print it */
import java.util.Scanner;
class JP9
{
public static void main(String s[])
{
int a[][] = new int[10][10];
int n, m, i, j;
Scanner in = new Scanner(System.in);
System.out.println("Enter matrix size (nxm) \n");
n=in.nextInt();
m=in.nextInt();
System.out.println("Enter "+ n +"x" + m + "matrix\n");
for(i=0; i<n; i++)
for(j=0; j<m; j++)
{
a[i][j]=in.nextInt();
}
System.out.println("\nGiven Matrix");
for(i=0; i<n; i++)
{
System.out.println("\n");
for(j=0; j<m; j++)
{
System.out.print(a[i][j]+" ");
}
}
}
}
COMMAND LINE ARGUMENTS
/* Ex1: - Write a program to read and print given strings using command line arguments */
class JP10
{
public static void main(String args[])
{
for(int i=0 ; i<args.length ; i++)
{
System.out.println(args[i]);
}
}
}
Compile the programs as follows
c:\> javac JP39.java
Run this program as follows
c:\> java JP39 Rajesh Ramesh Ganesh Suresh Mahesh
Output: - Rajesh Ramesh Ganesh Suresh Mahesh
/* Ex2: - Write a program to find sum of two given numbers using command line arguments */
class JP11
{
public static void main(String args[])
{
int a,b;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
System.out.println("Sum = " + (a+b));
}
}
CLASS AND OBJECT
A class is a user defined data type used to encapsulate the data and code as a whole unit.
Object is nothing but an instance of a class. An object is a basic run time entity used to allocate memory for the class
members and also used to process the members of the class.
Syntax to define a class:-
class class-name
{
fields; (or) data-members;
methods; (or) member-functions;
}
Example:-
class A
{
int x;
float y;
char z;
void readvalues();
void printvalues();
}
Syntax to declare an object:-
class-name object = new class-name();
Example:-
A obj = new A();
Note:- We should use dot membership operator (.) associated with an object to access methods and members of the
class from the main() function.
PROGRAMS
/* Write a program to accept and print the details of an employee using class and object */
import java.util.Scanner;
class Emp
{
int eno;
float sal;
String en;
void read()
{
Scanner in = new Scanner(System.in);
System.out.println("\nEnter Employee Id, Name and Salary");
eno=in.nextInt();
en=in.next();
sal=in.nextFloat();
}
void print()
{
System.out.println("\nEmployee ID : " + eno);
System.out.println("\nEmployee Name : " + en);
System.out.println("\nSalary Rs : " + sal);
}
}
class JP12
{
public static void main(String s[])
{
Emp e1 = new Emp();
Emp e2 = new Emp();
System.out.println("Input about first employee");
e1.read();
System.out.println("Input about second employee");
e2.read();
System.out.println("First employee details: - ");
e1.print();
System.out.println("Second employee details: - ");
e2.print();
}
}
/* Method Overloading in Java:-
If a class has multiple methods with same name but different parameters, it is known as method overloading.
Advantage of method overloading: -
Method overloading increases the readability of the program.
Different ways to overload methods: -
There are three ways to overload a method in java. They are
1) By changing number of arguments
2) By changing the data type of arguments
3) By changing the order of arguments
Note: - Method overloading is not possible by changing the return type of the method because there may occur
ambiguity.
That means compiler doesn't identify the right method to be invoked when it is called.
Example:-
/* Write a program for method overloading in java */
import java.io.*;
class Calculation
{
void sum(int a,int b)
{
System.out.println("Sum = " + (a+b));
}
void sum(int a,int b,int c)
{
System.out.println("Sum = " + (a+b+c));
}
void sum(String a, String b)
{
System.out.println("Full Name = " + (a+b));
}
void output(String a, int b)
{
System.out.println("Candidate Name = " + a);
System.out.println("Age = " + b + " years");
}
void output(int a, String b)
{
System.out.println("Item Name = " + b);
System.out.println("Rate = " + a + " rupees");
}
}
class JP13
{
public static void main(String args[])
{
Calculation x = new Calculation();
x.sum(10,10,10);
x.sum(20,20);
x.sum("Lakshmi","Priya");
x.output("Narayana" , 9000);
x.output(25000, "Laptop");
}
}
/* write a program to print default values of all primitive data types in java */
class DefaultValues
{
boolean t;
char c;
byte b;
short s;
int i;
long l;
float f;
double d;
String st;
void display()
{
System.out.println("Data type Default value");
System.out.println("boolean " + t);
System.out.println("char [" + c + "]");
System.out.println("byte " + b);
System.out.println("short " + s);
System.out.println("int " + i);
System.out.println("long " + l);
System.out.println("float " + f);
System.out.println("double " + d);
System.out.println("String " + st);
}
}
class JP14
{
public static void main(String args[])
{
DefaultValues x = new DefaultValues();
x.display();
}
}
CONSTRUCTOR
A Constructor is a special method whose name is same as its class name and is used to automatically initialize the
members of its class when ever an object is created.
Types of constructors:-
1) Default Constructor: - A constructor with no arguments is known as default constructor. It is used to initialize all
objects with the same set of values. A default constructor never takes arguments nor does it return any value.
/* Write a program using default constructor */
import java.io.*;
class Student
{
String n,c;
int rno,m;
Student()
{
n = "SATYA";
c = "MBBS";
rno = 9;
m = 92;
}
void output()
{
System.out.println("Roll Number : " +rno);
System.out.println("Student : " + n);
System.out.println("Course Title : " + c);
System.out.println("Percentage of Marks : " +m);
}
}
class JP15
{
public static void main(String x[])
{
Student s1 = new Student();
Student s2 = new Student();
System.out.println("Details in object s1:-");
s1.output();
System.out.println("\n\nDetails in object s2:-");
s2.output();
}
}
PERAMETERIZED CONSTRUCTOR
A Constructor with arguments is known as a perameterized constructor. It is used to initialize different objects with
different values.
/* Write a program using Perameterized Constructor */
import java.io.*;
class Student
{
String n,c;
int rno,m;
Student(String p, String q, int r, int s)
{
n = p;
c = q;
rno = r;
m = s;
}
void output()
{
System.out.println("Roll Number : " +rno);
System.out.println("Student : " + n);
System.out.println("Course Title : " + c);
System.out.println("Percentage of Marks : " +m);
}
}
class JP16
{
public static void main(String x[])
{
Student s1 = new Student("Uma","MBA",18,77);
Student s2 = new Student("Satya","MBBS",9,97);
System.out.println("\n\nValues in object s1:-");
s1.output();
System.out.println("\n\nValues in object s2:-");
s2.output();
}
}
COPY CONSTRUCTOR
A copy constructor is a constructor which initialize a new object using an existing object of the same class.
A copy constructor uses object as its argument.

/* Ex: - Program to implement copy constructor */


import java.io.*;
class Student
{
String n,c;
float f;
Student()
{
n = "Devi";
c = "B.Tech";
f = 52000;
}
Student(String p, String q, float r)
{
n = p;
c = q;
f = r;
}
Student(Student k)
{
n = k.n;
c = k.c;
f = k.f;
}
void output()
{
System.out.println("Student Name: " + n);
System.out.println("Course Title: " + c);
System.out.println("Fee: " +f);
}
}
class JP17
{
public static void main(String x[])
{
Student a = new Student();
Student s1 = new Student("Ravi","MBA", 18, 72);
Student c = new Student(b);
System.out.println("\n\nValues in object a:- ");
a.output();
System.out.println("\n\nValues in object b:- ");
b.output();
System.out.println("\n\nValues in object c:- ");
c.output();
}
}
INHERITANCE
The process of making a new class from an existing class is known as inheritance. The existing class is known as super
class and the new class is known as sub class. The following syntax is used to define a new class from an existing
class.
class new-class-name extends existing -class-name
{
data_members;
methods;
}
SINGLE INHERITANCE: - If a super class contains only one sub-class then that type of inheritance is known as single
inheritance. It is shown in the following diagram.

Note: - The sub-class object can access the members and methods of sub-class as well as its super class aslo. But
super-class object can access the members and methods of super-class only. It should not access the members and
methods of its sub-class.
/* Ex: - Program using single inheritance */
import java.util.Scanner;
class College
{
String cn,a;
int ts,sm;
void input()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter college name and address\n");
cn=in.next();
a=in.next();
System.out.println("Also enter number of students and total staff members\n");
ts=in.nextInt();
sm=in.nextInt();
}
void output()
{
System.out.println("\nCollege Name : " + cn);
System.out.println("\nNo. of Students : " + ts);
System.out.println("\nStaff members : " + sm);
System.out.println("\nCollege Address : " + a);
}
}
class Student extends College
{
String sn,c;
int tf,pm;
void read()
{
Scanner in = new Scanner(System.in);
System.out.println("\nEnter student name, course, total fee and percentage of marks\n");
sn=in.next();
c=in.next();
tf=in.nextInt();
pm=in.nextInt();
}
void show()
{
System.out.println("Student Name : " + sn);
System.out.println("Course Title : " + c);
System.out.println("Total Fee : " + tf);
System.out.println("Percentage of Marks : " + pm);
}
}
class JP18
{
public static void main(String s[])
{
Student x = new Student();
x.input();
x.read();
x.output();
x.show();
}
}
MULTI LEVEL INHERITANCE
If a sub-class is derived from another sub-class then the inheritance is known as Multi Level Inheritance. It is shown
in the following diagram.

/* Ex: - Write a program using multi level inheritance */


import java.util.Scanner;
class Company
{
String cn, p, a;
void read()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter company name, product and address\n");
cn = in.next();
p = in.next();
a = in.next();
}
void print()
{
System.out.println("Company Name : " + cn);
System.out.println("Product Name : " + p);
System.out.println("Company Address : " + a);
}
}
class Emp extends Company
{
String en, j;
float s;
void input()
{
Scanner in = new Scanner(System.in);
System.out.println("\nEnter employee name, job and monthly salary\n");
en = in.next();
j = in.next();
s = in.nextFloat();
}
void output()
{
System.out.println("Employee Name : " + en);
System.out.println("Job Title : " + j);
System.out.println("Monthly Salary : " + s);
}
}
class Loan extends Emp
{
int amt, flag=0;
String lt,name;
void accept()
{
Scanner in = new Scanner(System.in);
System.out.println("\nEnter employee name to apply for the loan ");
name = in.next();
if(en.compareTo(name)==0)
{
System.out.println("How much loan you want");
amt=in.nextInt();
if(amt<=s*10)
{
System.out.println("\nEnter the loan type ");
lt=in.next();
System.out.println("\nLoan Sanctioned ");
flag=1;
}
else
{
System.out.println("\nToo much amount required, So your request is rejected ");
}
}
else
System.out.println("\nInvalid Employee ");
}
void display()
{
System.out.println("\nLoan Type : " + lt);
System.out.println("\nLoan Amount : " + amt);
}
}
class JP19
{
public static void main(String s[])
{
Loan x = new Loan();
x.read();
x.input();
x.accept();
if(x.flag == 1)
{
x.print();
x.output();
x.display();
}
}
}
HIERARCHICLE INHERITANCE
If a super class has two or more sub classes then the inheritance is known as Hierarchicle Inheritance. . It is shown in
the following diagram.

/* Ex:- Write a program using Hierarchicle inheritance */


import java.util.Scanner;
class Company
{
String cn, a;
void read()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter company name and address\n");
cn = in.next();
a = in.next();
}
void print()
{
System.out.println("Company Name : " + cn);
System.out.println("Company Address : " + a);
}
}
class Emp extends Company
{
String en, j;
int s;
void input()
{
Scanner in = new Scanner(System.in);
System.out.println("\nEnter employee name, job and monthly salary\n");
en = in.next();
j = in.next();
s = in.nextInt();
}
void output()
{
System.out.println("Employee Name : " + en);
System.out.println("Job Title : " + j);
System.out.println("Monthly Salary : " + s);
}
}
class Product extends Company
{
float r;
String pn, mfd;
void accept()
{
Scanner in = new Scanner(System.in);
System.out.println("\nEnter product name , mfd and rate\n");
pn = in.next();
mfd = in.next();
r = in.nextFloat();
}
void display()
{
System.out.println("\nProduct Name : " + pn);
System.out.println("\nM.F.D : " + mfd);
System.out.println("\nUnit Cost : " + r);
}
}
class JP20
{
public static void main(String args[])
{
Emp x = new Emp();
Product y = new Product();
x.read();
x.input();
y.read();
y.accept();
System.out.println("\nDETAILS OF EMPLOYEE:-");
x.output();
x.print();
System.out.println("\nDETAILS OF PRODUCT:-");
y.display();
y.print();
}
}
/* METHOD OVERRIDING IN JAVA
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
In other words, if subclass provides the specific implementation of the method that has been provided by its super
class, it is known as method overriding.
Advantages of Method Overriding: -
1) Method overriding is used to provide specific implementation of a method that is already provided by its super
class.
2) Method overriding is used for runtime polymorphism
Rules for Method Overriding in Java: -
Method must have same name as in the parent class
Method must have same parameter as in the parent class.
Note: - A static method cannot be overridden. Because static method is bound with class whereas instance method
(overridden method) is bound with object. Static belongs to class area and instance belongs to heap area.
/* Ex: - A program to demonstrate method overriding in java */
import java.io.*;
class Bank
{
int getRateOfInterest()
{
return 12;
}
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
class Baroda extends Bank
{
}
class JP21
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
Baroda b = new Baroda();
System.out.println("SBI Rate of Interest = " + s.getRateOfInterest());
System.out.println("ICICI Bank Rate of Interest = " + i.getRateOfInterest());
System.out.println("AXIS Bank Rate of Interest = " + a.getRateOfInterest());
System.out.println("Baroda Bank Rate of Interest = " + b.getRateOfInterest());
}
}
MODIFIERS IN JAVA
The access modifiers in java specify the accessibility (scope) of a data member, method, constructor or class. Java
provides 4 types of java access modifiers. They are
1) private : The private access modifier is accessible only within class.
2) protected : The protected access modifier is accessible within package and outside the package but through
inheritance only
3) public: The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
4) default: If you don't use any modifier, by default it is treated as default. The default modifier is accessible only
within the package.
SUPER KEYWORD IN JAVA
The super keyword in java is a reference variable that is used to refer immediate parent class object.
Usage of java super Keyword
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
/* Write a program to accept super class members using super keyword */
import java.io.*;
class Vehicle
{
int speed=50;
}
class Bike extends Vehicle
{
int speed=100;
void display()
{
System.out.println("Bike Speed = " + speed);
System.out.println("Vehicle Speed = " + super.speed);
}
}
class JP22
{
public static void main(String args[])
{
Bike x = new Bike();
x.display();
}
}
/* Write a program to invoke parent class constructor using super keyword */
import java.io.*;
class Vehicle
{
Vehicle()
{
System.out.println("Vehicle is created");
}
}
class Bike extends Vehicle
{
Bike()
{
super();
System.out.println("Bike is created");
}
}
class JP23
{
public static void main(String args[])
{
Bike b=new Bike();
}
}
this KEYWORD IN JAVA
The keyword this is a reference variable that refers to the current object.
Ex1: - If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of
ambiguity. It is explained in the following example.
/* Write a program using this keyword */
class Student
{
String name;
float fee;
void input(String name, float fee)
{
this.name = name;
this.fee = fee;
}
void output()
{
System.out.println("Name = " + name);
System.out.println("Fee = " + fee);
}
}
class JP24
{
public static void main(String args[])
{
Student x = new Student();
x.input("Satya",75000);
x.output();
}
}
/* Ex2: - this() method call can be used to invoke current class constructor. It is explained in the
following program */
class Student
{
int id;
String name;
Student()
{
System.out.println("Default constructor is invoked");
}
Student(int id,String name)
{
this(); // To invoke default constructor
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id + "\t" + name);
}
}
class JP25
{
public static void main(String args[])
{
Student x = new Student(111,"kiran");
Student y = new Student(222,"Charan");
x.display();
y.display();
}
}
Output: -
Default constructor is invoked
Default constructor is invoked
111 Kiran
222 Charan

/* Ex3: - his keyword can also be used to return the same object which invoke the method in which this is used.
It is explained in the following program */
class Student
{
int rno,marks;
String name;
void input(int rno, String name, int marks)
{
this.rno = rno;
this.name = name;
this.marks = marks;
}
void print()
{
System.out.println("Roll Number = " + rno);
System.out.println("Student Name = " + name);
System.out.println("Percentage of Marks = " + marks);
}
Student maxmarks(Student k)
{
if (k.marks > this.marks)
{
return(k);
}
else
{
return(this);
}
}
}
class JP26
{
public static void main(String args[])
{
Student x = new Student();
Student y = new Student();
Student z = new Student();
x.input(111, "kiran", 95);
y.input(222, "Charan", 85);
z=x.maxmarks(y);
System.out.println("Details of the student getting more marks: - ");
z.print();
}
}
JAVA FINAL VARIABLE
If you make any variable as final, you cannot change the value of final variable(It will be constant).
/* Ex: - A program using final member and final argument */
import java.util.Scanner;
class College
{
final String cn="VSMCOE, RCPM";
long p;
float f;
void input(long a, float b)
{
cn="GITE, RJY"; // Error because cn is final variable
p=a;
f=b;
}
void update(long a, final float b)
{
a=a+1000;
b=b+1000; // Error because parameter b is final
p=a;
f=b;
}
void output()
{
System.out.println("College Name : " + cn);
System.out.println("Phone Number : " + p);
System.out.println("College Fee : " + f);
}
}
class JP27
{
public static void main(String args[])
{
College x = new College();
x.input(246400,25000);
System.out.println("Input Data: - ");

x.output();
x.update(246500,35000);
System.out.println("Updated Data: - ");
x.output();
}
}
JAVA FINAL METHOD
A method which is defined using the final keyword is known as a final method. If you make any method as final, you
cannot override it.
/* Ex: - A program to define a final method. */
class Bike
{
final void run()
{
System.out.println("Bike is running safely");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("Honda Bike is running safely ");
}
}
class JP28
{
public static void main(String args[])
{
Honda x = new Honda();
x.run();
}
}
JAVA FINAL CLASS
If you make any class as final, you cannot extend it.
/* Ex: - A program to create a final class */
final class Bike
{
}
class Hero extends Bike
{
void run()
{
System.out.println("Hero bike running safely");
}
}
class JP29
{
public static void main(String args[])
{
Hero x = new Hero();
x.run();
}
}
Output: - Compilation Error
ABSTRACTION IN JAVA
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Different ways to achieve Abstraction: -
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
ABSTRACT CLASS
A class which is declared using the keyword abstract is known as an abstract class. It needs to be extended and its
methods should be implemented. An abstract class can have abstract and non-abstract methods. An abstract class
cannot be instantiated. That means we cannot create an object to an abstract class.
ABSTRACT METHOD
A method that is declared as abstract and does not have implementation is known as abstract method.
/* Ex: - A program to define an abstract class*/
abstract class Bike
{
abstract void run();
}
class Hero extends Bike
{
void run()
{
System.out.println("Hero Pleasure running safely...");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("Honda Activa running safely...");
}
}
class JP30
{
public static void main(String args[])
{
Bike obj1 = new Hero();
Bike obj2 = new Honda();
obj1.run();
obj2.run();
}
}
/* Create an abstract class with abstract and non-abstract methods*/
import java.util.Scanner;
abstract class College
{
String cn,a;
College() // constructor
{
cn="Aditya";
a="Kakinada";
}
void read(String p, String q)
{
cn=p;
a=q;
}
abstract void print();
}
class Student extends College
{
String sn,c;
Student()
{
super();
sn="Padmavathi";
c="B.Sc";
}
void input()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter student name and course");
sn=in.next();
c=in.next();
}
void output()
{
System.out.println("Student Name : " + sn);
System.out.println("Course Title : " + c);
}
void print()
{
System.out.println("College Name : " + cn);
System.out.println("College Address : " + a);
}
}
class JP31
{
public static void main(String args[])
{
Student x = new Student();
System.out.println("Available Data: - ");
x.output();
x.print();
x.input();
x.read("VSMCOE","Ramachandrapuram");
System.out.println("Input Data: - ");
x.output();
x.print();
}
}
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods.
Abstract class and interface both can't be instantiated. Simply, abstract class achieves partial abstraction (0 to 100%)
whereas interface achieves fully abstraction (100%).
INTERFACES IN JAVA
Interfaces are used to define standard behavior that can be implemented by a class or anywhere in the class
hierarchy. An interface contains constant values and abstract methods. The difference between classes and
interfaces is that the methods in an interface are only declared and not implemented, that means the methods do
not have body.
Syntax to declare an interface:-
public interface <interface-name>
{
interface body;
}
Note: - To implement multiple inheritance in java, we should use the concept of interfaces. To define a sub-class to
an interface we should use the keyword "implements" instead of "extends".
MULTIPLE INHERITANCE:-
If a sub-class is derived from two or more super classes then the inheritance is known as multiple inheritance. It is
shown in the following diagram.

/* Ex:- Write a program to implement multiple inheritance using the concept of interfaces. */
import java.util.Scanner;
interface Home
{
String fn="Aditya";
String mn="Swathi";
String a="Kakinada";
public void display();
}
interface College
{
String cn="Modern College";
String pn="Ln.G.V.Rao";
String ca="Ramachandrapuram";
}
class Student implements Home , College
{
String sn,c;
float f;
int pm;
void read()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter student name, course, fee and percentage of marks\n");
sn = in.next();
c = in.next();
f = in.next Float();
pm = in.nextInt();
}
void print()
{
System.out.println("\nStudent Name : " + sn);
System.out.println("\nStudent Course : " + c);
display();
System.out.println("\nCollege Name : " + cn);
System.out.println("\nPrincipal Name : " + pn);
System.out.println("\nCollege Address : " + ca);
System.out.println("\nCourse Fee : " + f);
System.out.println("\n Marks " + pm);
}
public void display()
{
System.out.println("\nFather Name : " + fn);
System.out.println("\nMother Name : " + mn);
System.out.println("\nResidential Address : " + a);
}
}
class P32
{
public static void main(String x[])
{
Student k = new Student();
k.read();
k. print();
}
}
JAVA PACKAGE
A package is a group of similar types of classes, interfaces and sub-packages. Each package defines a number of
classes, interfaces, exceptions, and errors. Package in java can be categorized in two types. They are built-in package
and user-defined package. There are many built-in packages such as lang, awt, javax, swing, net, io, util, sql etc.

Java provides several pre-defined packages. Built-in packages consists of a large number of classes which are a part
of Java API. Some of the commonly used built-in packages are explained here under.
1. java.lang: - It contains language support classes ( for e.g classes which defines primitive data types, math
operations, etc.) . This package is automatically imported. The classes available in Java.lang package are Boolean,
Character, Class, ClassLoader , Compiler, Loader, Math, Number , Byte, Double, Float, Integer, Lang, Short,
SecurityManager, StrictMath, String, StringBuffer, System, Thread, ThreadGroup, Void,
ThreadLocal, Throwable, etc.
2. java.io: - It contains classes for supporting input / output operations. The classes available in Java.io package are
FilterInputStream, FilterOutputStream, BufferedInputStream, BufferedOutputStream, BufferedReader,
BufferedWriter, ByteArrayInputStream, ByteArrayOutputStream, DataInputStream, etc.
3. java.util: - It contains utility classes which implement data structures like Linked List, Hash Table, Dictionary, etc
and support for Date / Time operations. The classes available in Java.util package are Stack, Scanner, Timer,
Random, Calendar, Currency, Dictionary, EnumMap, HashMap, ArrayList, etc.
4. java.applet: - It provides the classes necessary to create an applet and the classes an applet uses to
communicate with its applet context.
5. java.awt: - It contains classes for implementing the components of graphical user interface like buttons, menus,
etc. The java.awt package provides classes such as TextField, Label, TextArea, RadioButton, CheckBox, Choice,
List, etc.
6. java.net: - It contains classes for supporting networking operations. The classes available in java.net package are
ContentHandler, DatagramPacket, DatagramSocket, DatagramSocketImpl, HttpURLConnection, InetAddress,
MulticastSocket, ServerSocket, Socket, SocketImpl, URL, URLConnection, URLEncoder, URLStreamHandler, etc.
USER DEFINED PACKAGES
We can create user defined packages using the following syntax.
package package-name;
Ex: - package college;
Main Points: -
1) A package name should be starts with a small letter.
2) The above statement should be the first line in the program in which the college package is created.
3) We can create only one class for a package using a program. To create another class for the same package we
need to write separate program.
4) Save the program using class name.
5) The extension of the file is as usually ".java"
6) Generally packages are created in the "bin" directory.
7) A package should contain public classes only.
8) Use the following command to compile the package program.
javac -d . filename.java
9) After compiling the program set class path using the following syntax.
set CLASSPATH = CLASSPATH%;c:\j2sdk1~1.1_0\bin\packagename
10) To import the classes from a user defined package in to any program, the following syntax is used.
import packagename.classname1;
import packagename.classname2;
Example: - Create a user defined package (college) with two classes and an interface.
Step1: - Write the following program and save the file as "Department.java"
package college;
import java.util.Scanner;
public class Department
{
String dn,c,ph;
int ts;
public Department()
{
dn = "Civil";
c = "B.Tech and M.Tech";
ts = 300;
ph = "9440801781";
}
public void input()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter department name, courses, total students and department phone number\n");
dn=in.next();
c=in.next();
ts=in.nextInt();
ph=in.next();
}
public void output()
{
System.out.println("\nDepartment Name : " + dn);
System.out.println("\nTotal Students : " + ts);
System.out.println("\nAvailable Courses : " + c);
System.out.println("\nDepartment Phone : " + ph);
}
}
Step2: - Write the following program and save the file as "Course.java"
package college;
import java.util.Scanner;
public class Course
{
String cn,e;
int d;
float f;
public Course()
{
cn = "B.Tech";
e = "Inter or Diploma";
d = 4;
f = 45000;
}
public void input()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter course name, eligibility, duration and yearly fee\n");
cn=in.next();
e=in.next();
d=in.nextInt();
f=in.nextFloat();
}
public void output()
{
System.out.println("\nCourse Name : " + cn);
System.out.println("\nEligibility : " + e);
System.out.println("\nDuration : " + d + " Years");
System.out.println("\nYearly Fee : " + f);
}
}
Step3: - Write the following program and save the file as "Events.java"
package college;
public interface Events
{
String ad="Sixth November";
String tfd="Fifth December";
String Id="Fifteenth August";
public void impdates();
}
Step4: - Write the following program and save the file as "JPP.java"
import college.Department;
import college.Course;
import college.Events;
class Team implements Events
{
public void impdates()
{
System.out.println("\nIndepence Day On : " + Id);
System.out.println("\nAnnual Day on : " + ad);
System.out.println("\nTech Fest On " + tfd);
}
}
class JP33
{
public static void main(String args[])
{
Course c = new Course();
Department d = new Department();
Team x = new Team();
System.out.println("Course Details: -");
c.output();
System.out.println("\nDepartment Details: -");
d.output();
System.out.println("\nCollege Events Details: -");
x.impdates();
}
}
Notes:-
(i) Save this program as "JPP.java"
(ii) Compile this program with the command,
"javac JPP.java"
(iii) Run this program using the command,
"java JPP"
JAVA INNER CLASS
/* An inner class is a class which is declared inside the class or interface. We use inner classes to logically group
classes and interfaces in one place so that it can be more readable and maintainable. Additionally, it can access all
the members of outer class including private data members and methods.
Syntax of Inner class: -
class Java_Outer_class
{
// Outer_class code
class Java_Inner_class
{
// Inner_class code
}
}
Advantage of java inner classes: -
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members (members and
methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically group classes and
interfaces in one place only.
3) Code Optimization: It requires less code to write.
/* Ex: - Write a program to implement a nested class*/
class OuterClass
{
public void callMe()
{
System.out.println("I am outer class !");
}
public static class InnerClass
{
public void printMe()
{
System.out.println("I am inner class !");
}
}
void callInner()
{
InnerClass ic = new InnerClass();
ic.printMe();
}
}
class JP34
{
public static void main(String x[])
{
OuterClass oc = new OuterClass();
oc.callMe();
oc.callInner();
OuterClass.InnerClass obj = new OuterClass.InnerClass();
obj.printMe() ;
}
}
JAVA PUBLIC CLASS
We can create classes with the modifier "public". Then they are called public classes. We can create one public class
using a program. The class name should be used as its filename. Simply compile the program. Do not run/execute it.
We can directly create objects to public classes in our local programs without importing any packages.
Ex: - Creating and using public class in java
/* Step1: -Write the following program and save the file as "Candidate.java" */
import java.util.Scanner;
public class Candidate
{
private
int rno;
String n;
float f;
public void input(int a, String b, float c)
{
rno = a;
n=b;
f = c;
}
public void read()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter roll number, Name and fee ");
rno = in.nextInt();
n= in.next();
f = in.nextFloat();
}
public void print()
{
System.out.println("Roll Number : " + rno);
System.out.println("Student Name : " + n);
System.out.println("Total Fee : " + f);
}
}
/* Step2: -Write the following program and save the file as "JP.java" */
class JP35
{
public static void main(String x[])
{
Candidate c = new Candidate();
c.input(12,"Siva",75000);
c.print();
c.read();
c.print();
}
}
EXCEPTION HANDLING IN JAVA
This technique is used to stop normal flow of execution of the code when an error occurs and communicate the user
with a proper error message. Generally we have 2 types of errors in Programming. They are syntax errors and
runtime errors. The syntax errors are modified at the time of compilation. But we should suffer with runtime errors.
To solve this problem java provides exception handling technique. In this process, all executable statements were
written in between "try" and "catch" keywords. The keyword "catch" is used to raise the exception when
corresponding error occurs. Java supports two types of exceptions. They are (i) Pre-Defined exceptions,
(ii) User-Defined exceptions. The following are some pre-defined exceptions (Built-in Exceptions).
1. ArithmeticException:- It is caused by a mathematical error such as dividing number by zero
2. ArrayIndexOutofBoundsException:- It is caused by a wrong subscript usage.
3. FileNotFoundException:- It is caused by an attempt to access a non existing file.
4. IOException:- It is caused by general input and output failures.
5. NumberFormatException:- It is caused when conversion between number and string fails.
6. StackOverflowException:- It is caused when the system need memory higher than stack space.
7. Exception:- It is capable to handle all types of normal (primary) errors.
/* Write a program using ArrayIndexOutOfBoundsException */
import java.util.Scanner;
class jp36 extends Exception
{
public static void main(String s[])
{
int a[] = new int[5];
int n,i,j,t;
Scanner in = new Scanner(System.in);
try
{
System.out.println("How many numbers");
n=in.nextInt();
System.out.println("Enter the numbers");
for(i=0; i<n; i++)
{
a[i]=in.nextInt();
}
System.out.println("Given Numbers:-");
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Overflow");
}
}
}
/* Write a program using ArithmeticException */
import java.util.Scanner;
class jp37
{
public static void main(String x[])
{
int a,b,c,d;
Scanner in = new Scanner(System.in);
try
{
System.out.println("Enter values of a, b and c");
a= in.nextInt();
b= in.nextInt();
c= in.nextInt();
d=a/(b-c);
System.out.println("Value of a/(b-c) = " + d);
}
catch(ArithmeticException e1)
{
System.out.println("Dividing a number with zero is illegal");
}
catch(IOException e2)
{
System.out.println(e2.getMessage());
}
}
}
USER DEFINED EXCEPTIONS
We can create our own exception classes by extending the "Exception" class. The extended class contains
constructors, data members and methods like any other classs. The "throws" keyword is used while implementing a
user-defined exception.
/* Example1: - In the following example "IllegalValueException" is raised when student rno is less than zero or
percentage of marks is greater than 100 */
import java.io.*;
class IllegalValueException extends Exception
{
}
class Student
{
int rno , pm;
public Student(int a, int b)
{
rno=a;
pm=b;
}
void show() throws IllegalValueException
{
if ( rno<=0 || pm>100 )
throw new IllegalValueException();
else
{
System.out.println("Roll Number = " + rno);
System.out.println("Percentage of Marks = " + pm);
}
}
}
class JP38
{
public static void main(String x[])
{
Student s = new Student(12,181);
try
{
s.show();
}
catch(IllegalValueException e)
{
System.out.println("Invalid rno or percentage of marks found in student class");
}
}
}
/* Example2: - In the following example " NegativeAgeException " is raised when employee age is less than zero */
import java.util.Scanner;
class NegativeAgeException extends Exception
{
public NegativeAgeException() // constructor
{
System.out.println("Age should not be negative");
}
public void message() // exception method
{
System.out.println("Age limit 20 to 60 years");
}
}
class Employee
{
String en;
int age;
void read()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter employee name & age ");
en=in.next();
age=in.nextInt();
}
void print() throws NegativeAgeException
{
if(age<0)
{
throw new NegativeAgeException();
}
System.out.println("Employee Name: " +en);
System.out.println("Age: " + age + " years");
}
}
class JP39
{
public static void main(String[] args)
{
Employee x = new Employee();
try
{
x.read();
x.print();
}
catch(NegativeAgeException e)
{
e.message();
}
}
}
JAVA INNER CLASS
An inner class is a class which is declared inside the class or interface. We use inner classes to logically group classes
and interfaces in one place so that it can be more readable and maintainable. Additionally, it can access all the
members of outer class including private data members and methods.
Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Advantage of java inner classes
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members (members and
methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically group classes and
interfaces in one place only.
3) Code Optimization: It requires less code to write.
Example: -
/* A program to illustrates the implementation of an inner class and its object */
class OuterClass
{
public void callMe()
{
System.out.println("I am outer class !");
}
public static class InnerClass
{
public void printMe()
{
System.out.println("I am inner class !");
}
}
void callInner()
{
InnerClass ic = new InnerClass();
ic.printMe();
}
}
class JP40
{
public static void main(String args[])
{
OuterClass x = new OuterClass();
x.callMe();
x.callInner();

OuterClass.InnerClass y = new OuterClass.InnerClass();


y.printMe() ;
}
}
JAVA THREADS
What is a Thread in Java?
 A thread is a facility to allow multiple activities within a single process
 A thread is referred as lightweight process
 A thread is a series of executable statements
 A thread is a nested sequence of method calls
 Every java program creates at least one thread which is main() thread. Additional threads are created through
the Thread constructor or by instantiating classes that extend the Thread class.
 A thread is a sequential flow of control within a program. Every program has at least one thread that is called
main thread or primary thread. A thread is also known as a lightweight process or execution context. Threads are
used to perform several tasks concurrently.
Single-Threaded and Multi-Threaded Applications: -
A process that is made up of only one thread is said to be single-threaded. A single-threaded application can perform
only one task at a time. A process having more than one thread is said to be multithreaded. Multiple threads in a
process run at the same time, perform different tasks, and interact with each other. Java has built-in support for
threads. A major portion of the java architecture is multithreaded. In java programs, the most common use of a
thread is to allow an applet to accept input from a user and at the same time, display animated information in
another part of the screen. Any application that requires two things to be done at the same time is probably a great
candidate for multithreading.
Why we use Threads?
 To perform background processing
 To increases the responsiveness of GUI applications
 To take advantage of multiprocessor systems
 To simplify program logic when there are multiple independent entities
How to create thread
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
/* A program to execute two threads simultaneously using multi threading concept */
import java.io.*;
class A extends Thread
{
int i;
public void run()
{
try
{
for (i=1;i<=10;i++)
{
System.out.println("\nClass A : " + i);
}
System.out.println("\nExit from class A");
}
catch(Exception e)
{
}
}
}
class B extends Thread
{
int i;
public void run()
{
try
{
for (i=1;i<=10;i++)
{
System.out.println("\nClass B : " + i);
}
System.out.println("\nExit from class B");
}
catch(Exception e)
{
}
}
}
class JP41
{
public static void main(String x[])
{
A t1=new A();
B t2 = new B();
t1.start();
t2.start();
}
}
/* A program to execute three threads simultaneously using multithreading concept */
import java.io.*;
class A extends Thread
{
int i;
public void run()
{
try
{
for (i=1;i<=10;i++)
{
System.out.println("\nClass A : " + i);
if(i==5)
sleep(10000);
}
System.out.println("\nExit from class A");
}
catch(Exception e)
{
}
}
}
class B extends Thread
{
int i;
public void run()
{
try
{
for (i=1;i<=10;i++)
{
System.out.println("\nClass B : " + i);
if(i==3)
yield();
}
System.out.println("\nExit from class B");
}
catch(Exception e)
{
}
}
}
class C extends Thread
{
int i;
public void run()
{
try
{
for (i=1;i<=10;i++)
{
System.out.println("\nClass C : " + i);
if(i==8)
stop();
}
System.out.println("\nExit from class C");
}
catch(Exception e)
{
}
}
}
class JP42
{
public static void main(String x[])
{
A t1=new A();
B t2 = new B();
C t3 = new C();
t1.start();
t2.start();
t3.start();
}
}

JAVA AWT
AWT stands for Abstract Window Toolkit. It is an application to develop Graphical User Interface or window-based
application in java. AWT components are platform-dependent i.e. components are displayed according to the view of
operating system. AWT is heavy weight i.e. its components uses the resources of the system.
The java.awt package has 63 classes and 14 interfaces. These classes and interfaces provide classes that are used for
drawing, painting and other features. Using the classes of java.awt package, we can create push buttons, check
boxes, text boxes, list boxes, menus and other components that we find in a data entry form. This package also
provides classes to create containers, panels, frames, etc.
Frame Class: -
A frame is a powerful feature of AWT. We can create a window for our application using "Frame" class. A frame has a
title bar, an optional menu bar and a resizable border. As it is derived from java.awt.Container, we can add
components to a Frame using add() method. The Border layout is the default layout of a frame. The constructor of
Frame class receives the title of the frame as a parameter. The following syntax is used to define a frame.
Frame object = new Frame("Title of the window");
After the window (Frame) is created it can be displayed by calling "setVisible()" method. The window can be sized by
calling "setSize()" method. The background colour of the frame is specified by calling "setBackground()" method.
/* A program is used to create and display a frame */
import java.awt.Frame;
import java.awt.*;
public class Frame1 extends Frame
{
public static void main(String s[ ])
{
Frame x = new Frame("Java Window");
x.setSize(300,400);
x.setBackground(Color.yellow);
x.setVisible(true);
}
}
Panel Class: - Panels are used for organizing components. Each panel can have a different layout. To create a panel,
use the following syntax.
Panel object=new Panel();
Label Class: - The Label class is used to create titles. Labels do not generate an action event. To create a label the
syntax is as follows.
Label object = new Label("Title", alignment);
The default alignment is Left. We can specify the alignment as Label.RIGHT or Label.CENTER
Ex1:- Label L1= new Label("Student Name");
Ex2:- Label L2= new Label("Course",Label.RIGHT);
/* create a frame with text fields and labels */
import java.awt.Frame;
import java.awt.*;
public class Frame2 extends Frame
{
public static void main(String s[])
{
Frame f = new Frame("Java Window");
Panel p = new Panel();
Label l1 = new Label("Student Name");
Label l2 = new Label("Address");
TextField tf = new TextField(20);
TextArea ta = new TextArea(3,20);
f.setSize(300,400);
f.setVisible(true);
f.setBackground(Color.yellow);
f.add(p); p.add(l1); p.add(tf);
p.add(l2); p.add(ta);
}
}
Button Class: - Buttons are used to trigger events in a GUI environment. The following syntax is used to create a
button.
Button object=new Button("button name");
We can use setLabel() method to change button name. Also getLabel() method is used to retrieve the caption of a
button.
Ex1:-Button b1=new Button("Save");
Ex2:-b1.setLabel("Delete") ;
Now the caption of button b1 becomes "Delete".
Ex3:- String s = b1.getLabel();
Now the value of variable "s" is "Delete".
Choice Class: -
A choice menu is used to display a list of choices for the user to select any one choice from it. The choice menu
control is also knwon as drop down list box. To create a choice menu use the following syntax.
Choice object = new Choice();
We can add items to the choice menu by calling the addItem() method as follows.
choice-object.addItem("First Option");
choice-object.addItem("Second Option");
/* create a frame with choice menus and buttons */
import java.awt.Frame;
import java.awt.*;
public class Frame3 extends Frame
{
public static void main(String s[])
{
Frame f = new Frame("Pace Window");
Panel p = new Panel();
Label l1 = new Label("Qualification");
Label l2 = new Label("Category");
Button b1 = new Button("OK");
Button b2 = new Button("Cancel");
Choice c1 = new Choice();
c1.addItem("DCA");
c1.addItem("DTP");
c1.addItem("PGDCA");
c1.addItem("Multi Media");
Choice c2 = new Choice();
c2.addItem("OC");
c2.addItem("BC");
c2.addItem("SC");
c2.addItem("ST");
f.setSize(300,400);
b1.setLabel("Submit") ;
f.setVisible(true);
f.setBackground(Color.red);
f.add(p); p.add(l1);
p.add(c1); p.add(l2);
p.add(c2); p.add(b1);
p.add(b2);
}
}
/* Create a frame with check boxes */
import java.awt.Frame;
import java.awt.*;
public class Frame4 extends Frame
{
public static void main(String s[])
{
Frame f = new Frame("Pace Window");
Panel p = new Panel();
Label l1 = new Label("Student Name");
Label l2 = new Label("Languages Known");
TextField tf = new TextField(20);
Checkbox cb1=new Checkbox("Telugu" , true);
Checkbox cb2=new Checkbox("English" , false);
Checkbox cb3=new Checkbox("Hindi" , false);
Checkbox cb4=new Checkbox("Other" , false);
f.setSize(300,400);
f.setVisible(true);
f.setBackground(Color.yellow);
f.add(p); p.add(l1);
p.add(tf); p.add(l2);
p.add(cb1); p.add(cb2);
p.add(cb3); p.add(cb4);
}
}
/* A program to create a menubar in a window */
import java.awt.*;
import java.awt.Frame;
public class P57 extends Frame
{
public static void main(String s[ ])
{
Frame f = new Frame("Java Window");
MenuBar mb = new MenuBar();
f.setMenuBar(mb);
Menu mfile, medit, mhelp;
mfile = new Menu("File");
medit = new Menu("Edit");
mhelp = new Menu("Help");
mb.add(mfile);
mb.add(medit);
mb.add(mhelp);
MenuItem New,open,save,close,exit,cut,copy;
MenuItem paste,del,about,topics;
New = new MenuItem("New");
open = new MenuItem("Open");
save = new MenuItem("Save");
close = new MenuItem("Close");
exit = new MenuItem("Exit");
cut = new MenuItem("Cut");
copy = new MenuItem("Copy");
paste = new MenuItem("Paste");
del = new MenuItem("Delete");
about = new MenuItem("About Pace");
topics = new MenuItem("Help Topics");
mfile.add(New);
mfile.add(open);
mfile.add(save);
mfile.add(close);
mfile.add(exit);
medit.add(cut);
medit.add(copy);
medit.add(paste);
medit.add(del);
mhelp.add(about);
mhelp.add(topics);
close.setEnabled(false);
Menu mprint;
mprint = new Menu("Print");
mfile.add(mprint);
mprint.add("Page Setup");
mprint.add("Current Page");
mprint.add("All Pages");
f.setSize(400,400);
f.setVisible(true);
}
}
JAVA APPLET

Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside
the browser and works at client side. An applet can be a fully functional Java application because it has the entire
Java Application Interface at its disposal. Note that Applet class extends Panel. Panel class extends Container which is
the subclass of Component.
Advantage of Applet: -
1. It works at client side so less response time.
2. It is more Secured
3. It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet: -
Plugin is required at client browser to execute applet.
Main Points: -
1) An applet is a Java class that extends the java.applet package.
2) The main() method is not invoked on an applet, and an applet class will not define main().
3) Applets are designed to be embedded within an HTML page.
4) A separate JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate
runtime environment.
5) The JVM on the user's machine creates an instance of the applet class and invokes various methods during the
applet's lifetime.
6) An applet works at client side so it requires less response time and more secured.
7) An applet can be executed by browsers running under many plateforms, including Unix, Linux, Windows, Mac Os
etc.
The APPLET Class: -
The java.applet package is the smallest package in java. it contains the Applet class only. An applet is automatically
loaded and executed when you open a web page that contain the applet. The Applet class has pver 20 methods that
are used to display messages, images, play audio files, etc. Each method responds when you interact with it.
Syntax to embed an applet class in a java program: -

<APPLET Code="name of the class file that extends from java.applet.Applet" HEIGHT= number WIDTH = number>
Note: -
To compile applet program the syntax is
javac Filename.java
To execute/run applet program the syntax is
AppletViewer Filename.java
Life Cycle of an APPLET: -
We can describe the life cycle of an applet through four methods. They are ...
1. init(): - It is invoked at the first time, the applet is loaded into the memory. We can initialize variables and add
components like buttons, check boxes, etc to the applet in the init() method.
2. start(): - It is called immediately after the init() method.
it is also invoked every time the applet receives the focus.
3. stop(): - The stop( ) method is called every time the applet loses the focus. We can use this method to reset the
variables and also to stop the threads that are currently running.
4. destroy(): - It is invoked by the browser when the user moves to another page. We can use this method to close
the applet file.
The Graphics class: -
The Graphics class is an abstract class that represents the display area of the applet. It is a part of the java.awt
package. The Graphics class provides methods to draw a number of graphical figures including text, lines, circles and
ellipses, rectangles and polygons, images, etc.
A few of the methods are given below
1. public abstract void drawString(String,column,row)
2. public abstract void drawLine(column, row, width, height)
3. public abstract void drawRect(column, row, width, height)
4. public abstract void fillRect(column, row, width, height)
5. public abstract void draw3DRect(column, row, width, height,boolean raised)
6.public abstract void rawRoundRect (column,row,width,height,arcWidth,arcHeight)
7. public abstract void fillRoundRect (column,row,width,height,arcWidth,arcHeight)
8. public abstract void drawOval(column,row,width,height)
9. public abstract void fillOval(column,row,width,height)
We can invoke the above methods using an object of Graphics class.
The Paint( ) Method: -
It is used to draw graphics in the drawing area of an applet. This method is automatically called at the first time the
applet is displayed on the screen and every time the applet receives the focus. The paint method takes an object of
the Graphics class as a parameter.
PROGRAMS
EX1: - A program to display message on an applet
/* <Applet Code="JAP1.class" height=200 width=200> </Applet>*/
import java.applet.*;
import java.awt.*;
public class JAP1 extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello World",20,180);
}
}
To compile the above program command is
javac JAP1.java
To execute/run the above program command is
AppletViewer JAP1.java
Font Class: -
The Font class states fonts, which are used to render text in a visible way. The constructor of Font class creates a new
Font with the specified syle and size. The syntax is as follows
Font(String name, int style, int size)
EX2: -A program to print your name and address on an applet with font styles
/* <Applet Code="JAP2.class" height=200 width=200> </Applet>*/
import java.applet.*;
import java.awt.*;
public class JAP2 extends Applet
{
public void paint(Graphics g)
{
Font k =new Font("Arial", Font.BOLD, 36);
g.setFont(k);
g.drawString("Name : Babuji" , 100, 100);
g.drawString("Job: Faculty" , 100, 150);
g.drawString("Address : RCPM" , 100, 200);
}
}
EX3: -A program to display a message with different colours on an applet
import java.applet.Applet;
import java.awt.*;
/* <Applet Code="JAP3.class" height=200 width=200> </Applet>*/
public class JAP3 extends Applet
{
public void paint(Graphics g)
{
Color c[] = {Color.blue,Color.cyan, Color.darkGray,
Color.gray, Color.green, Color.lightGray,
Color.magenta, Color.orange, Color.pink,
Color.red, Color.yellow, Color.black};
for(int i = 0; i<c.length; i++)
{
Font f = new Font("Ravie",Font.BOLD,26);
g.setFont(f);
g.setColor(c[i]);
g.drawString("Hello World...", 50, 50+(i*30));
}
}
}
EX4: - A program to draw line, rectangle and a circle on an applet
/* <Applet Code="JAP4.class" height=200 width=200> </Applet>*/
import java.applet.*;
import java.awt.*;
public class JAP4 extends Applet
{
public void paint(Graphics g)
{
g.drawLine(50,50,300,50);
g.drawRect(50,100,250,100);
g.fillRect(350,100,250,100);
g.drawOval(50,250,250,250);
g.fillOval(350,250,250,250);
}
}
/* TextField Class: - To accept textual data from a user, AWT provides TextField class. The TextField class handles a
single line of text. To create a textbox use the following syntax.
TextField object = new TextField(width);
TextArea Class: - To accept textual data from a user, we can use an object of TextArea class. The TextArea class
allows to take multiple lines of text. The following syntax is used to create a textbox that takes text in two or more
lines.
TextArea object = new TextArea(rows,columns);
Label Class: - The Label class is used to create titles. Labels do not generate an action event. To create a label the
syntax is as follows.
Label object = new Label("Title", alignment);
The default alignment is Left. We can specify the alignment as Label.RIGHT or Label.CENTER
Ex1:- Label L1= new Label("Student Name");
Ex2:- Label L2= new Label("Course",Label.RIGHT);
getText() method: - It is used to read a line of text from the specified TextField.
Syntax:-
StringVariable = TextFieldObject.getText();
setText() method: - It is used to insert the specified text in a TextField.
Syntax:-
TextFieldObject.setText('Text to be inserted');
EX5: - A program to read and print name and address on an applet
/* <Applet Code="JAP5.class" height=200 width=200> </Applet>*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class JAP5 extends Applet
{
TextField t1,t2;
Label L1,L2;
String x,y;
Font f=new Font("Arial", Font.BOLD, 16);
public void init( )
{
t1 = new TextField(10);
t2 = new TextField(10);
L1 = new Label("Enter Your Name");
L2 = new Label("Enter Your Address");
add(L1); add(t1); add(L2); add(t2);
}
public void paint(Graphics g)
{
g.setFont(f);
x=t1.getText();
y=t2.getText();
g.drawString("INPUT",100,20);
g.drawString("OUTPUT",100,80);
g.drawString("Name : " + x ,100,110);
g.drawString("Address : " + y ,100,140);
}
public boolean action (Event e, Object obj)
{
repaint();
return(true);
}
}
EX6: - A program to select an item from a list box and print the selected item
/* <applet code=" JAP6.class" width=200 height=200> </applet> */
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class JAP6 extends Applet implements ItemListener
{
List x = new List(5, false);
public void init()
{
x.add("One");
x.add("Two");
x.add("Three");
x.add("Four");
x.add("Five");
x.add("Six");
x.add("Seven");
add(x);
x.addItemListener(this);
}
public void paint(Graphics g)
{
String msg = x.getSelectedItem();
g.drawString("Selected Item: "+ msg, 10, 120);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
}
/* Checkbox Class: - The Checkbox class is used to create a labeled check box. A check box has two parts. They are
label and state. The label is a string that represents the caption of the check box. The state is a boolean value that
represents the status of the check box. By default the status is false which represents the check box is unchecked.
Check boxes are used to select one or two or all items in the list.
Button Class: -
Buttons are used to trigger events in a GUI (Graphical User Environment) The following syntax is used to create a
button.
Button object=new Button("button name");
setLabel() method is used to change button name. getLabel() method is used to retrieve the caption of a button.
Ex1:-Button b1=new Button("Save");
Ex2:-b1.setLabel("Delete") ;
Now the caption of button b1 becomes "Delete".
Ex3:- String s = b1.getLabel();
Now the value of String variable "s" is "Delete".
EX7: - Create an applet to read data using buttons and check boxes
/* <applet code="JAP7.class" width=200 height=200> </applet> */
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class JAP7 extends Applet implements ActionListener
{
Checkbox cb1 = null;
Checkbox cb2 = null;
Checkbox cb3 = null;
Button b1;
Button b2;
Graphics g;
String msg;
public void init()
{
b1 = new Button("OUTPUT");
b2 = new Button("CLEAR");
cb1 = new Checkbox("Telugu");
cb2 = new Checkbox("English");
cb3 = new Checkbox("Hindi");
add(cb1); add(cb2); add(cb3);
add(b1); add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void paint(Graphics g)
{
g.drawString(msg,10,50);
}
public void actionPerformed(ActionEvent ae)
{
String a = ae.getActionCommand();
if(a.equals("CLEAR"))
{
msg="";
cb1.setState(false);
cb2.setState(false);
cb3.setState(false);
}
if(a.equals("OUTPUT"))
{
if(cb1.getState()==true &&
cb2.getState()==false &&
cb3.getState()==false)
msg="You know Telugu Only";
else if(cb1.getState()==false &&
cb2.getState()==true &&
cb3.getState()==false)
msg="You know English Only";
else if(cb1.getState()==false &&
cb2.getState()==false &&
cb3.getState()==true)
msg="You know Hindi Only";
else if(cb1.getState()==true &&
cb2.getState()==true &&
cb3.getState()==false)
msg="You know Telugu and English";
else if(cb1.getState()==true &&
cb2.getState()==false &&
cb3.getState()==true)
msg="You know Telugu and Hindi";
else if(cb1.getState()==false &&
cb2.getState()==true &&
cb3.getState()==true)
msg="You know English and Hindi";
else if(cb1.getState()==true &&
cb2.getState()==true &&
cb3.getState()==true)
msg="wow ... you know all the three languages";
else
msg="Ok ... you don't know all the three languages";
}
repaint();
}
}
BUTTON CLASS
Buttons are used to perform trigger events in a GUI environment. The following syntax is used to create a button.
Button object=new Button("button name");
We can use setLabel() method to change button name. Also getLabel() method is used to retrieve the caption of a
button.
Ex1:-Button b1=new Button("Save");
Ex2:-b1.setLabel("Delete") ;
Now the caption of button b1 becomes "Delete".
Ex3:- String s = b1.getLabel();
Now the value of variable "s" is "Delete".
CHOICE CLASS
A choice menu is used to display a list of choices for the user to select any one choice from it. The choice menu
control is also knwon as drop down list box. To create a choice menu use the following syntax.
Choice object = new Choice();
We can add items to the choice menu by calling the addItem() method as follows.
choice-object.addItem("First Option");
choice-object.addItem("Second Option");
Ex8: - A program to read details of an employee using an applet
/* <applet code="JAP8.class" width=200 height=200> </applet> */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JAA8 extends Applet implements ItemListener, ActionListener
{
TextField tf;
Button b1,b2;
Label L1,L2;
Choice q;
public void init( )
{
L1=new Label("Employee Name");
L2=new Label("Qualification");
tf= new TextField(20);
b1 = new Button("OK");
b2 = new Button("CLEAR");
q = new Choice();
q.addItem("SSC");
q.addItem("ITI");
q.addItem("INTER");
q.addItem("DIPLOMA");
q.addItem("DEGREE");
q.addItem("B.TECH");
q.addItem("PG");
add(L1); add(tf);
add(L2); add(q);
add(b1); add(b2);
q.addItemListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String x,y;
if(ae.getSource()==b1)
{
x=tf.getText();
y=q.getSelectedItem();
JOptionPane.showMessageDialog(null,"NAME : "+x+"\nQUALIFICATION : "+y);
}
if(ae.getSource()==b2)
{
tf.setText(" ");
JOptionPane.showMessageDialog(null,"Input Cleared");
}
}
public void itemStateChanged(ItemEvent arg)
{
}
}
EX9: - A program to create calculator using an applet
/* <applet code="JAP9.class" width=200 height=200> </applet> */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class JAP9 extends Applet implements ActionListener
{
TextField t;
Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10;
Button b11,b12,b13,b14,b15,b16;
int x, y, f, i, ch;
float z;
public void init()
{
setLayout(new GridLayout(6,3));
x=0;
y=0;
t = new TextField("0" , 20);
b0 = new Button("0");
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4 = new Button("4");
b5 = new Button("5");
b6 = new Button("6");
b7 = new Button("7");
b8 = new Button("8");
b9 = new Button("9");
b10 = new Button("+");
b11 = new Button("-");
b12 = new Button("*");
b13 = new Button("/");
b14 = new Button("=");
b15 = new Button("C");
b16 = new Button("N!");
add(t); add(b0); add(b1);
add(b2); add(b3); add(b4);
add(b5); add(b6); add(b7);
add(b8); add(b9); add(b10);
add(b11); add(b12); add(b13);
add(b14); add(b15); add(b16);
b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b10.addActionListener(this);
b11.addActionListener(this);
b12.addActionListener(this);
b13.addActionListener(this);
b14.addActionListener(this);
b15.addActionListener(this);
b16.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
int k;
if(ae.getSource()==b0)
{
x=x*10+0;
t.setText(String.valueOf(x));
}
if(ae.getSource()==b1)
{
x=x*10+1;
t.setText(String.valueOf(x));
}
if(ae.getSource()==b2)
{
x=x*10+2;
t.setText(String.valueOf(x));
}
if(ae.getSource()==b3)
{
x=x*10+3;
t.setText(String.valueOf(x));
}
if(ae.getSource()==b4)
{
x=x*10+4;
t.setText(String.valueOf(x));
}
if(ae.getSource()==b5)
{
x=x*10+5;
t.setText(String.valueOf(x));
}
if(ae.getSource()==b6)
{
x=x*10+6;
t.setText(String.valueOf(x));
}
if(ae.getSource()==b7)
{
x=x*10+7;
t.setText(String.valueOf(x));
}
if(ae.getSource()==b8)
{
x=x*10+8;
t.setText(String.valueOf(x));
}
if(ae.getSource()==b9)
{
x=x*10+9;
t.setText(String.valueOf(x));
}
if(ae.getSource()==b10)
{
y=x;
x=0;
ch=1;
t.setText(String.valueOf(y));
}
if(ae.getSource()==b11)
{
y=x;
x=0;
ch=2;
t.setText(String.valueOf(y));
}
if(ae.getSource()==b12)
{
y=x;
x=0;
ch=3;
t.setText(String.valueOf(y));
}
if(ae.getSource()==b13)
{
y=x;
x=0;
ch=4;
t.setText(String.valueOf(y));
}
if(ae.getSource()==b16)
{
y=x;
f=1;
for(i=1; i<=x ; i++)
{
f = f * i;
}
t.setText(String.valueOf(f));
}
if(ae.getSource()==b15)
{
x=0;
y=0;
t.setText("0");
}
if(ae.getSource()==b14)
{
switch(ch)
{
case 1:
t.setText(String.valueOf(y+x));
x=y+x;
break;
case 2:
t.setText(String.valueOf(y-x));
x=y-x;
break;
case 3:
t.setText(String.valueOf(y*x));
x=y*x;
break;
case 4:
try
{
t.setText(String.valueOf(y/x));
x=y/x;
break;
}
catch(ArithmeticException e)
{
x=y=0;
}
break;
}
}
}
}
Ex10: - A program to read and print details of an employee in an applet
/* <applet code="JAP10.class" width=200 height=200> </applet> */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Applet9 extends Applet implements ActionListener
{
TextField t1,t2,t3;
Button b1,b2,b3;
Label L1,L2,L3;
String n, j, s;
public void init( )
{
L1=new Label("Employee Name");
L2=new Label("Job Title");
L3=new Label("Monthly Salary");
t1= new TextField(20);
t2= new TextField(20);
t3= new TextField(20);
b1 = new Button("Insert");
b2 = new Button("Display");
b3 = new Button("Clear");
add(L1); add(t1);
add(L2); add(t2);
add(L3); add(t3);
add(b1); add(b2); add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==b1)
{
n = t1.getText();
j = t2.getText();
s = t3.getText();
}
if (ae.getSource()==b2)
{
t1.setText(n);
t2.setText( j );
t3.setText(s);
}
if (ae.getSource()==b3)
{
t1.setText(" ");
t2.setText(" ");
t3.setText(" ");
}
}
}
EX11: - CREATE AN APPLET TO PROCESS EMPLOYEES RECORDS
/* <applet code="JAP11.class" width=200 height=200> </applet> */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Applet10 extends Applet implements ActionListener
{
TextField t1,t2,t3;
Button b1,b2,b3,b4;
Label L1,L2,L3;
String n[] = new String[10];
String j[] = new String[10];
int s[] = new int[10];
int i,k;
public void init( )
{
setLayout(new GridLayout(5,2));
i=k=0;
L1=new Label("Employee Name");
L2=new Label("Job Title");
L3=new Label("Monthly Salary");
t1= new TextField(20);
t2= new TextField(20);
t3= new TextField(20);
b1 = new Button("Add");
b2 = new Button("First");
b3 = new Button("Next");
b4 = new Button("Clear");
add(L1);add(t1);
add(L2);add(t2);
add(L3);add(t3);
add(b1);add(b2);
add(b3);add(b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==b1)
{
n[i] = t1.getText();
j[i] = t2.getText();
s[i] = Integer.parseInt(t3.getText());
i++;
}
if (ae.getSource()==b2)
{
k=0;
t1.setText(n[k]);
t2.setText( j[k] );
t3.setText(String.valueOf(s[k]));
}
if (ae.getSource()==b3)
{
if(k<i)
k++;
t1.setText(n[k]);
t2.setText( j[k] );
t3.setText(String.valueOf(s[k]));
}
if (ae.getSource()==b4)
{
t1.setText(" ");
t2.setText(" ");
t3.setText(" ");
}
}
}
Ex12: - A program to display digital clock on an applet
/* <applet code=" JAP9.class" height=200
width=200> </applet> */
import java.awt.*;
import java.util.*;
import java.text.*;
import java.applet.*;
public class JAP12 extends Applet implements Runnable
{
Thread t = null;
String timeString = "";
public void init()
{
setBackground( Color.green);
}
public void start()
{
t = new Thread(this);
t.start();
}
public void run()
{
try
{
while(true)
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new
SimpleDateFormat("hh:mm:ss");
Date dt = cal.getTime();
timeString = sdf.format(dt);
repaint();
t.sleep( 1000 );
}
}
catch (Exception e)
{
}
}
public void paint( Graphics g )
{
Font k =new Font("Arial", Font.BOLD, 36);
g.setFont(k);
g.setColor( Color.blue );
g.drawString( timeString, 50, 50 );
}
}
Ex15: - A program to embed an image on an applet
/* <applet code="Imgapt.class" height=200 width=200> </applet> */
import java.awt.*;
import java.applet.*;
public class Imgapt extends Applet
{
Image img;
public void init()
{
img = getImage(getDocumentBase(),"DOG.JPG");
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,this);
}
}
Ex16: - Create an applet to perform mouse dragged event
/* <applet code="Mouseapt.class" width="300" height="300"> </applet> */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Mouseapt extends Applet implements MouseMotionListener
{
public void init()
{
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me)
{
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),3,3);
}
public void mouseMoved(MouseEvent me)
{
}
}
JAVA SWINGS
Swings are more familiar and advanced than the applets. Swings provide latest tools like animated buttons, tabbed
panes, etc. Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java. Unlike AWT,
Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes
for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing: -
1. AWT components are platform-dependent. Java swing components are platform-independent.
2. AWT components are heavyweight. Swing components are lightweight.
3. AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
4. AWT provides less components than Swing. Swing provides more powerful components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.
5. AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation
and controller acts as an interface between model and view. Swing follows MVC
A program to read and print details of an employee on an applet using swings
/* <applet code="Swing1.class" height=200 width=200> </applet> */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Swing1 extends JApplet implements ActionListener
{
JTextField t1,t2,t3;
JButton b1,b2,b3;
JLabel L1,L2,L3;
String n, j, s;
public void init( )
{
L1=new JLabel("Employee Name");
L2=new JLabel("Job Title");
L3=new JLabel("Monthly Salary");
t1= new JTextField(20);
t2= new JTextField(20);
t3= new JTextField(20);
b1 = new JButton("Insert");
b2 = new JButton("Display");
b3 = new JButton("Clear");
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(L1); cp.add(t1);
cp.add(L2); cp.add(t2);
cp.add(L3); cp.add(t3);
cp.add(b1); cp.add(b2); cp.add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==b1)
{
n = t1.getText();
j = t2.getText();
s = t3.getText();
}
if (ae.getSource()==b2)
{
t1.setText(n);
t2.setText( j );
t3.setText(s);
}
if (ae.getSource()==b3)
{
t1.setText(" ");
t2.setText(" ");
t3.setText(" ");
}
}
}
A program using option buttons on a swing
/* <applet code="Swing2.class" height=200 width=200> </applet> */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
public class Swing2 extends JApplet implements ActionListener
{
JLabel jl;
JTextField tf;
JRadioButton b1,b2,b3,b4;
public void init( )
{
tf= new JTextField(20);
jl = new JLabel("Select Your Course");
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(jl);
b1 = new JRadioButton("C");
b1.addActionListener(this);
cp.add(b1);
b2 = new JRadioButton("C++");
b2.addActionListener(this);
cp.add(b2);
b3 = new JRadioButton("JAVA");
b3.addActionListener(this);
cp.add(b3);
b4 = new JRadioButton("Oracle");
b4.addActionListener(this);
cp.add(b4);
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
bg.add(b4);
cp.add(tf);
}
public void actionPerformed(ActionEvent ae)
{
tf.setText("Your course is " +ae.getActionCommand());
}
}
TABBED PANES
A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title. When a user
selects a folder, its contents become visible. Only one of the folders may be selected at a time. Tabbed Panes are
commonly used for setting configuration options. Tabbed panes are encapsulated by the JTabbedPane class, which
extends JComponent.
Ex: - A program to design tabbed panes
/* <applet code="Swing3.class" height=200 width=200> </applet> */
import javax.swing.*;
import java.awt.*;
class CitiesPanel extends JApplet
{
Container cp;
public CitiesPanel()
{
cp = getContentPane();
cp.setLayout(new FlowLayout());
JButton b1 = new JButton("New York");
cp.add(b1);
JButton b2 = new JButton("London");
cp.add(b2);
JButton b3 = new JButton("New Delhi");
cp.add(b3);
JButton b4 = new JButton("Hong Kong");
cp.add(b4);
}
}
class ColoursPanel extends JApplet
{
Container cp;
public ColoursPanel()
{
cp = getContentPane();
cp.setLayout(new FlowLayout());
JCheckBox cb1 = new JCheckBox("Red");
cp.add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
cp.add(cb2);
JCheckBox cb3 = new JCheckBox("Yellow");
cp.add(cb3);
JCheckBox cb4 = new JCheckBox("Whit");
cp.add(cb4);
}
}
class FlavorsPanel extends JApplet
{
Container cp;
public FlavorsPanel()
{
cp = getContentPane();
cp.setLayout(new FlowLayout());
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
jcb.addItem("ButterScotch");
cp.add(jcb);
}
}
public class Swing3 extends JApplet
{
Container cp;
public void init()
{
cp = getContentPane();
cp.setLayout(new FlowLayout());
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities" , new CitiesPanel());
jtp.addTab("Colours" , new ColoursPanel());
jtp.addTab("Flavors" , new FlavorsPanel());
cp.add(jtp);
}
}
/*A program to read input using radio buttons */
import javax.swing.*;
import java.awt.event.*;
class RadioExample extends JFrame implements ActionListener
{
JRadioButton rb1,rb2;
JButton b;
RadioExample()
{
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("Click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(rb1.isSelected())
{
JOptionPane.showMessageDialog(this,"You are male");
}
if(rb2.isSelected())
{
JOptionPane.showMessageDialog(this,"You are female");
}
}
}
class Swing4
{
public static void main(String args[])
{
new RadioExample();
}
}
/* Creating Menus in Java: - There are two different kinds of menus supported by Java. They are regular menus and
pop-up menus. Java provides the following classes for creating and managing menus.
1.JMenuBar: Used to create a menu bar.
2.JMenu: Used to create menus like file, edit, etc.
3.JMenuItem: Used to create menu items like new, open, save, print, exit, etc.
4.JCheckBoxMenuItem : Used to create a checkbox in a menu.
5.JRadioButtonMenuItem : Used to create a radio button in a menu.
Write a program to create menu bar with regular menus using swings */
import javax.swing.*;
public class Swing5
{
public static void main(String args[])
{
JFrame f = new JFrame("Student Details Window");
JMenuBar mb = new JMenuBar( );
f.setJMenuBar(mb);
JMenu fm = new JMenu("File");
JMenu em = new JMenu("Edit");
JMenu hm = new JMenu("Help");
mb.add(fm);
mb.add(em);
mb.add(hm);
JMenuItem mnew,open,save,close,exit,cut,copy,paste, del;
JMenuItem about,topics;
JCheckBoxMenuItem find;
mnew = new JMenuItem("New");
open = new JMenuItem("Open");
save = new JMenuItem("Save");
close = new JMenuItem("Close");
exit = new JMenuItem("Exit");
cut = new JMenuItem("Cut");
copy = new JMenuItem("Copy");
paste = new JMenuItem("Paste");
del = new JMenuItem("Delete");
about = new JMenuItem("About Pace");
topics = new JMenuItem("Help Topics");
find = new JCheckBoxMenuItem("Find");
fm.add(mnew);
fm.add(open);
fm.add(save);
fm.add(close);
close.setEnabled(false);
em.add(cut);
em.add(copy);
em.add(paste);
em.add(del);
em.add(find);
hm.add(about);
hm.add(topics);
JMenu pm = new JMenu("Print");
JMenuItem setup, cp, ap;
setup = new JMenuItem("Page Setup");
cp = new JMenuItem("Current Page");
ap = new JMenuItem("All Pages");
fm.add(pm);
fm.add(exit);
pm.add(setup);
pm.add(cp);
pm.add(ap);
f.setSize(400,400);
f.setVisible(true);
}
}
LIBRAY FUNCTIONS IN JAVA
The java.lang.Math class contains methods for performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions.
1. abs(): - Returns the absolute value of the argument.
2. ceil(): - Returns the smallest integer that is greater than or equal to the argument. Returned as a double.
3. floor(): - Returns the largest integer that is less than or equal to the argument. Returned as a double.
4. round(): - Returns the closest long or int, as indicated by the method's return type to the argument.
5. min(): - Returns the smaller of the two arguments.
6. max(): - Returns the larger of the two arguments.
7. pow(): - Returns the value of the first argument raised to the power of the second argument.
8. sqrt(): - Returns the square root of the argument.
9. sin(): - Returns the sine of the specified double value.
10. cos(): - Returns the cosine of the specified double value.
11. tan(): - Returns the tangent of the specified double value.
12. random(): - Returns a random number.

/*A program using mathematical functions in java */


import java.io.*;
class Funs1
{
public static void main(String args[])
{
System.out.println("Big Number = " + Math.max(12,10));
System.out.println("Small Number = " + Math.min(12,10));
System.out.println("2 power 5 = " + Math.pow(2,5));
System.out.println("Floor value of 12.25 = " + Math.floor(12.25));
System.out.println("Ceil value of 12.25 = " + Math.ceil(12.25));
System.out.println("Square Root of 121 = " + Math.sqrt(121));
System.out.println("A random number = " + Math.random());
}
}
CHARACTER CLASS
The java.lang.Character class includes many useful static methods with which text (or characters) can be
manipulated. The other text manipulating classes are String, StringBuffer, StringTokenizer and StringBuilder.
1. isDigit(char ch): - This method determines if the specified character is a digit.
2. isLetter(char ch): - This method determines if the specified character is a letter.
3. isLetterOrDigit(char ch): - This method determines if the specified character is a letter or digit.
4. isLowerCase(char ch): - This method determines if the specified character is a lowercase character.
5. isUpperCase(char ch): - This method determines if the specified character is an uppercase character.
6. toLowerCase(char ch): - This method converts the character argument to lowercase using case mapping
information from the UnicodeData file.
7. toUpperCase(char ch): - This method converts the character argument to uppercase using case mapping
information from the UnicodeData file.
8. getNumericValue(char ch): - This method returns the int value that the specified Unicode character represents.
9. isSpaceChar(char ch): - This method determines if the specified character is a Unicode space character.
10. isWhitespace(char ch): - This method determines if the specified character is white space according to Java.
/* Write a program using character functions */
import java.io.*;
class Funs2
{
public static void main(String args[])
{
char x='A';
System.out.println("Output: " + Character.isLetter(x));
x='7';
System.out.println("Output: " + Character.isDigit(x));
System.out.println("Output: " + Character.isLetterOrDigit(x));
x='+';
System.out.println("Output: " + Character.isLetterOrDigit(x));
x='T';
System.out.println("Output: " + Character.toLowerCase(x));
x=' ';
System.out.println("Output: " + Character.isSpaceChar(x));
}
}
STRING CLASS
The java.lang.String class provides the following methods to manipulate strings.
1. char charAt(int index): - This method returns the char value at the specified index.
2. int String1.compareTo(String2): - This method compares two strings lexicographically.
3. int String1.compareToIgnoreCase(String2): - This method compares two strings lexicographically, ignoring case
differences.
4. string1.concat(String2): - This method concatenates the specified string to the end of this string.
5. int indexOf(int ch): - This method returns the index within this string of the first occurrence of the specified
character.
6. int indexOf(String str): - This method returns the index within this string of the first occurrence of the specified
substring.
7. int length(): - This method returns the length of this string.
8. String toLowerCase(): - This method converts all of the characters in this String to lower case using the rules of the
default locale.
9. String toUpperCase(): - This method converts all of the characters in this String to upper case using the rules of the
default locale.
10. String trim(): - This method returns a copy of the string, with leading and trailing whitespace omitted.
11. String replace(char oldChar, char newChar): - This method returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.
12. isEmpty(): - This method returns true if, and only if, length() is 0.
/* Write a program using string functions */
import java.io.*;
class Funs3
{
public static void main(String args[])
{
String x="";
System.out.println("Output: " + x.isEmpty());
x="venkatesh";
System.out.println("Output: " + x.length());
System.out.println("Output: " + x.toUpperCase());
x="SATYA";
System.out.println("Output: " + x.toLowerCase());
System.out.println("Output: " + x.charAt(2));
x="simhadri srilakshmi";
System.out.println("Output: " + x.indexOf("sri"));
}
}
GENERIC CLASSES
A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type
parameter section. As with generic methods, the type parameter section of a generic class can have one or more
type parameters separated by commas. These classes are known as parameterized classes or parameterized types
because they accept one or more parameters.
Example: - The following example illustrates how we can define a generic class in java
class Box <T>
{
private T t;
Box(T a)
{
t = a;
}
void change(T a)
{
t = a;
}
public T get()
{
return t;
}
}
class GenericClass
{
public static void main(String[] args)
{
Box<Integer> x = new Box<Integer>(10);
Box<String> y = new Box<String>("Hello World");
SOP("By the constructor: - ");
SOP ("\nInteger Box Value = %d", x.get());
SOP ("\nString Box Value = %s", y.get());
x.change(20);
y.change("Hello Students");
SOP ("\n\n\nBy the change method:- ");
SOP ("\nInteger Box Value = %d", x.get());
SOP ("\nString Box Value = %s", y.get());
}
}
Note: - SOP means System.out.println
Generic Methods: - We can write a single generic method declaration that can be called with arguments of different
types. Based on the types of the arguments passed to the generic method, the compiler handles each method call
appropriately.
Ex:- Write a program to define Generic Method */
public class GenericMethodTest
{
public static < E > void printArray( E[] inputArray )
{
for ( E element : inputArray )
{
System.out.printf( "%s ", element );
}
System.out.println();
}
public static void main( String args[] )
{
Integer[] intArray = { 1, 2, 3, 4, 5, 6, 7 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D' };
System.out.println( "integerArray contains:" );
printArray( intArray );
System.out.println( "\ndoubleArray contains:" );
printArray( doubleArray );
System.out.println( "\ncharacterArray contains:" );
printArray( charArray );
}
}
Generic Arguments Example: -
class GenericArgumentsDemo
{
// determines the largest of 3 Comparable objects
public static <T extends Comparable<T>>
T maximum(T x, T y, T z)
{
T max;
max = x;
if ( y.compareTo( max ) > 0 )
{
max = y;
}
if ( z.compareTo( max ) > 0 )
{
max = z;
}
return max;
}
public static void main( String args[] )
{
System.out.printf("\n\nMax of 3, 4 and 5 is %d " , maximum( 3, 4, 5 ) );

System.out.printf( "\n\nMaxm of 6.6, 8.8 and 7.7 is %.1f ", maximum( 6.6, 8.8, 7.7 ) );

System.out.printf( "\n\nMax of orange, apple and mango is %s " , maximum( "orange", "mango", "apple") );

System.out.printf( "\n\nMax of sai, uma and siva is %s " , maximum( "sai", "uma", "siva") );
}
}
JAVA CONSOLE CLASS
Java Console class is used to get input from console.
It provides methods to read text and password.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally.
The Console class is introduced since 1.5.
Methods of Console class: -
1) public String readLine(): - It is used to read a single line of text from the console.
2) public char[] readPassword(): - It is used to read password that is not being displayed on the console.
Note: -
The System class provides a static method console() that returns the unique instance of Console class.
Syntax: - Console c = System.console();
Ex:- A program to read text using console object
import java.io.*;
class Input1
{
public static void main(String args[])
{
Console c = System.console();
System.out.println("Enter your name ");
String n=c.readLine();
System.out.println("Welcome " + n);
}
}
/* A program to read password using console object */
import java.io.*;
class Input2
{
public static void main(String args[])
{
Console c = System.console();
System.out.println("Enter password: ");
char[] x = c.readPassword();
String pwd = String.valueOf(x);
System.out.println("Password is: " + pwd);
}
}
/* A program to read and print details of a student */
import java.io.*;
public class Input3
{
public static void main(String args[]) throws
IOException
{
int rno;
String n;
float f;
DataInputStream in = new
DataInputStream(System.in);
System.out.println("Enter student name ");
n = in.readLine();
System.out.println("Enter roll number ");
rno = Integer.parseInt(in.readLine());
System.out.println("Enter total fee ");
f = Float.parseFloat(in.readLine());
System.out.println("\nOUTPUT:-");
System.out.println("Roll Number : " + rno);
System.out.println("Student Name : " + n);
System.out.println("Total Fee : " + f);
}
}
/* A program to read and print details of a student */
import java.io.*;
public class Input4
{
public static void main(String args[]) throws IOException
{
int rno;
String n;
float f;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter student name ");
n = br.readLine();
System.out.println("Enter roll number ");
rno = Integer.parseInt(br.readLine());
System.out.println("Enter total fee ");
f = Float.parseFloat(br.readLine());
System.out.println("\nOUTPUT:-");
System.out.println("Roll Number : " + rno);
System.out.println("Student Name : " + n);
System.out.println("Total Fee : " + f);
}
}
/* A program to read character input from user */
import java.io.*;
public class Input5
{
public static void main(String args[]) throws IOException
{
char g;
String n;
System.out.print("Enter gender code ");
g = (char)System.in.read();
if(g=='M' || g=='m')
System.out.println("You are Male");
else if(g=='F' || g=='f')
System.out.println("You are Female");
else
System.out.println("Invalid gender code");
}
}
STREAM CLASSES
FileInputStream AND FileOutputStream Classes:-
These streams are classified as node streams as they read and write data from disk files. The classes associated with
these streams have constructors that allow you to specify the name and path of the file to which they are connected.
The FileInputStream class allow you to read input from a file in the form of stream. The FileOutputStream Class
allows you to write output in a file stream.

FileOutputStream:- By using an object of FileOutputStream class, we can open a text file to write some data.
Syntax:-
FileOutputStream object = new FileOutputStream("Filename.Txt");

write() method:- The write() method of FileOutputStream class is used to put a character in the text file which is
connected by an object of FileOutputStream class. The syntax is as follows.
FileOutputStream object.write(String.charAt(position));
/* A program to create a text file */
import java.io.*;
import java.util.Scanner;
class File1
{
public static void main(String args[]) throws
IOException
{
String s,fn;
int i;
Scanner in = new Scanner(System.in);
System.out.println("Enter file name that you want
to create ");
fn=in.next();
FileOutputStream fos = new FileOutputStream(fn);
System.out.println("Enter contents of the file, use
END to close the file:-");
s=in.nextLine();
while(s.compareTo("END")!=0)
{
for(i=0 ; i<s.length() ; i++)
fos.write(s.charAt(i));
fos.write('\n');
s=in.nextLine();
}
fos.close();
System.out.println("One file created");
}
}
/* Write a program to display the contents of an existing text file */
import java.io.*;
import java.util.Scanner;
class File2
{
public static void main(String x[]) throws IOException
{
String fn;
Scanner in = new Scanner(System.in);
System.out.println("Enter file name to display the
contents ");
fn=in.next();
FileInputStream fis = new FileInputStream(fn);
int size=fis.available();
byte text[] = new byte[size];
int readbyte = fis.read(text,0,size);
System.out.println("Contents of "+ fn +" file:-");
System.out.println(new String(text));
fis.close();
}
}
FileReader class is used to open a text file to read its contents.
/* A program to display the contents of the specified text file */
import java.io.*;
import java.util.Scanner;
public class File3
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String fn;
try
{
System.out.println("Enter file name ");
fn=in.next();
FileReader x = new FileReader(fn);
int ch;
while ((ch = x.read()) != -1)
{
System.out.print((char) ch);
}
x.close();
}
catch (IOException e)
{
System.out.print("Wrong Input");
}
}
}
The object of BufferedReader class is used to read contents of a file line by line. For this, it invokes readLine()
method. It is explained in the following example.
/* A program to read and print the contents of an existing text file */
import java.io.*;
import java.util.Scanner;
class File4
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String fn,str;
try
{
System.out.println("Enter file name to open the file");
fn=in.next();
File obj = new File(fn);
BufferedReader br = new BufferedReader(new FileReader(obj)) ;
while ((str=br.readLine())!= null)
{
System.out.println(str);
}
}
catch (IOException e)
{
System.out.println("Wrong Input");
}
}
}
/* A program to check the given file exists or not */
import java.io.File;
import java.util.Scanner;
public class File5
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String fn;
try
{
System.out.println("Enter file name ");
fn=in.next();
File f = new File(fn);
if(f.exists())
System.out.println("File already exists");
else
System.out.print("File not found");
}
catch(Exception e)
{
System.out.print("Wrong Input");
}
}
}
/* A program to copy contents of one text file into another text file.*/
import java.io.*;
import java.lang.*;
class File6
{
public static void main(String args[]) throws
IOException
{
DataInputStream k = new
DataInputStream(System.in);
String s,sf,df;
System.out.println("Enter existing file name ");
sf=k.readLine();
System.out.println("Enter new file name ");
df=k.readLine();
FileInputStream x = new FileInputStream(sf);
FileOutputStream y = new FileOutputStream(df);
int size=x.available();
byte text[] = new byte[size];
int readbyte = x.read(text,0,size);
s = new String(text);
for(int i=0 ; i<s.length() ; i++)
y.write(s.charAt(i));
x.close();
y.close();
System.out.println("The contents of " + sf + " is
coppied into " +df);
}
}
/* A program to accept file name and check whether the file exists or not */
import java.io.*;
public class File7
{
public static void main(String s[]) throws
IOException
{
DataInputStream in = new
DataInputStream(System.in);
String fn;
System.out.println("Enter file name ");
fn=in.readLine();
File x = new File(fn);
if(x.exists())
System.out.println("The file already exists");
else
System.out.println("File not found");
}
}
/* A program to change the name of a file */
import java.io.File;
import java.util.Scanner;
public class File8
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String on,nn;

System.out.println("Enter old name");


on=in.next();

System.out.println("Enter new name");


nn=in.next();

File x = new File(on);


File y = new File(nn);

if(x.renameTo(y))
System.out.println("Renamed Successfully");
else
System.out.println("Error while renaming a file");
}
}
/* The java.io.File.deleteOnExit() method deletes the file or directory defined by the abstract path name when the
virtual machine terminates. Files or directories are deleted in the reverse order as they are registered.
Ex: - A program to delete the specified text file */
import java.io.*;
import java.util.Scanner;
public class File9
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String fn;
try
{
System.out.println("Enter file name ");
fn=in.next();
File f = new File(fn);
if(f.exists())
{
f.deleteOnExit();
if(f.delete())
{
System.out.println("File has been deleted");
}
}
else
System.out.println("Invalid File Name");
}
catch(Exception e)
{
System.out.println("Wrong Input");
}
}
}

You might also like