Java Lab Manual 4th Sem
Java Lab Manual 4th Sem
EXP-1
AIM:- Write a program in Java to read from console employee details of 5 employees
with following details: Name of employee, Department, Age, Salary. Print the details of
every employee.
CODE:-
import [Link];
public class EmployeeDetails
{
public static void main(String[] args) {
Employee e[] = new Employee[20];
for(int i=1; i<=5; i++) {
[Link]("\nEnter the details of "+i+"st employee\n");
e[i] = new Employee();
e[i].getInput();
} [Link]("Details......\n");
for(int i=1; i<=5; i++) {
e[i].getOutput();
[Link]("\n");
}
}
}
class Employee{
String name;
String department;
int age;
int salary;
void getInput() {
Page 1 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Page 3 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Page 4 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Exp-2
Aim:- Write a program to show the use 'this' keyword to call the default and
parameterized constructors.
Code:-
class Student{
int rollno;
String name;
Student(int rollno,String name){ //paraterized constructor
[Link]=rollno;
[Link]=name;
}
void display() //default constructor
{
[Link](rollno+" "+name);
}
}
public class TestThis{
public static void main(String args[]){
Student s1=new Student(52,"Tushar");
Student s2=new Student(50,"Yogesh");
[Link]();
[Link]();
}
}
Output:-
52 Tushar
Page 5 of 52
Chhatrapti Shivaji Institute of Technology, Durg
50 Ashu
Exp-3
Aim:- Write a program in Java to display the count of number of objects
created and finalized. Provide unique IDs to every object while creation and
display the same ID during finalization.
Code:- public class CountObject{
static int count=0;
CountObject(){
count+=1;
[Link]("object created"+this);
try{
finalize();
}
catch(Throwable e){
[Link]();
}
}
public static void main(String[] args){
CountObject cn= new CountObject();
CountObject cm= new CountObject();
CountObject ce= new CountObject();
[Link]("Number of objects created"+count);
}
protected void finalize() throws Throwable
{
Page 6 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Output:-
object createdCountObject@30f39991object garabage collected:
CountObject@30f39991object createdCountObject@452b3a41object garabage
collected: CountObject@452b3a41object
createdCountObject@4a574795object garabage collected:
CountObject@4a574795 Number of objects created: 3
Page 7 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Exp-4
Aim:- Create a Shape Interface which has a member method area(). Derive two
subclasses Circle and Triangle from it. Using reference of Shape class fill the
required members in Circle and Triangle also display the area of Circle and
Triangle. Take input from user while filling data members.
Code:-
import [Link];
interface Shape{
public double area();
}
height = b;
}
public double area(){
return (base * height)/2;
}
}
class ShapeInterface{
public static void main(String args[]){
Scanner scanner = new Scanner([Link]);
[Link]("==========Area of Circle===================\n");
[Link]("Enter the radius of the circle:");
double radius = [Link]();
Circle c = new Circle(radius);
[Link]("Area of circle: " + [Link]()+”\n”);
[Link]("==========Area of Triangle===================\
n");
[Link]("Enter the width of the Triangle:");
double base = [Link]();
Output:-
==========Area of Circle===================
==========Area of Triangle===================
Page 10 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Exp-5
Aim:- Write a program to demonstrate the effect of access modifiers
(default, protected, public and private) on members with and without
inheritance within a package and outside a package.
Exp-6
Aim:- Write a program to show inbuilt and user defined: checked and
unchecked exceptions.
Code:-
import [Link].*;
import [Link];
class CAUC {
public static void main(String args[]) throws NegativeNumException{
int num=[Link]();
if (num < 0) {
Page 11 of 52
Chhatrapti Shivaji Institute of Technology, Durg
[Link]("numerator: ");
double numerator=[Link]();
[Link]("denominator: ");
double denominator=[Link]();
@Override
Output:-
Enter a whole number
4
You passed the first test. Yayy!!
numerator: 30
denominator: 2
result of division: 15.0
Your basics of meth are on point
The specified file is not present at the given path
Exception in thread "main" [Link]: Cannot invoke
"[Link]()" because "<local9>" is null
Page 13 of 52
Chhatrapti Shivaji Institute of Technology, Durg
at [Link]([Link])
Page 14 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Exp-7
Aim:- Write a program to show the use of various member methods of String
class
Code:-
public class StringMethods
{
public static void main(String[] args)
{
[Link]("String methods.............\n");
[Link]("methods-equality.............\n");
boolean a,b,c;
a="Raiders".equals("Raiders");
b="Raiders".equals("raiders");
c="Raiders".equalsIgnoreCase("raiders");
[Link](a+" "+b+" "+c+"\n");
[Link]("methods-Comparisons.............\n");
int diff="chicken".compareTo("egg");
if("chicken".compareTo("egg")<0){
[Link]("egg comes after chicken\n");
}
[Link](diff+"\n");
[Link]("methods-replace.............\n");
String word1="rare";
String word2="rare".replace('r','d');
[Link]("word1= "+word1+" after replacing r to d: "+word2+"\n");
[Link]("methods-changing case.............\n");
Page 15 of 52
Chhatrapti Shivaji Institute of Technology, Durg
String x="Tushar";
[Link]("TO upercase: "+[Link]()+" to Lower case: "+[Link]()+"\
n");
[Link]("methods-String concatenation.............\n");
String longstr="This coould have been" + "a very long line that would have" + "wrapped
around. But String Concatenation";
[Link](longstr+"\n");
[Link]("methods number to string..........\n");
int i=1223;
double d=3.14;
[Link]("integer to string: "+[Link](i)+"\n Double to string:
"+[Link](d)+"\n");
[Link]("methods-character extraction.............\n");
String w="R Tushar";
[Link]("extract character of 0,2 element-"+[Link](0)+" "+[Link](2)+"\n");
[Link]("methods-get char.............\n");
String o="this is a demo of the get char method";
int start=10;
int end=14;
char buf[]= new char[end-start];
[Link](start,end,buf,0);
[Link](buf);
[Link]("methods-starts() and endswith()............\n");
String l="foobar";
[Link]([Link]("bar")+" "+[Link]("foo")+"\n");
[Link]("methods-region match............\n");
String str1 = new String("Hello, How are you");
Page 16 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Output:-
String methods.............
methods-equality.............
true false true
methods-Comparisons.............
egg comes after chicken
-2
methods-replace.............
word1= rare after replacing r to d: dade
methods-changing case.............
TO upercase: TUSHAR to Lower case: tushar
methods-String concatenation.............
This coould have beena very long line that would havewrapped around. But String
Concatenation
methods number to string..........
integer to string: 1223
Double to string: 3.14
methods-character extraction.............
extract character of 0,2 element-R T
methods-get char.............
demomethods-starts() and endswith()............
true true
Page 17 of 52
Chhatrapti Shivaji Institute of Technology, Durg
methods-region match............
true
Page 18 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Exp-8
Aim:- Create two threads T1 and T2. The thread T1 should print numbers from
1 to 10 and thread T2 prints characters from A to J. Ensure that T2 starts first
and T1 should only start when T2 finishes. (Note: use join())
Code:-
import [Link];
//. Create two threads T1 and T2. The thread T1 should print numbers from 1 to
10 and thread T2 prints characters from A to J. Ensure that T2 starts first
class ThreadEx {
[Link]();
try {
[Link]();
}}
int start = 1;
Numbers() {
super("Number Thread");
[Link](start + i);
Page 20 of 52
Chhatrapti Shivaji Institute of Technology, Durg
}
}
int start=65;
Characters() {
super("Character Thread");
[Link](c);
}
}
}
Page 21 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Output:-
A
B
C
D
E
F
G
H
I
J
1
2
3
4
5
6
7
8
9
10
Page 22 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Exp-9
Aim:- Demonstrate using a Java program, how
DEADLOCK occurs between threads and also give
solution program
Code:- import [Link];
class DeadlockEx {
Page 23 of 52
Chhatrapti Shivaji Institute of Technology, Durg
[Link]();
[Link]();
super("Thread 1");
try {
[Link](100);
} catch (InterruptedException e) {
Page 24 of 52
Chhatrapti Shivaji Institute of Technology, Durg
DeadLockThread2() {
super("Thread 2");
synchronized (r2) {
[Link](100);
Page 25 of 52
Chhatrapti Shivaji Institute of Technology, Durg
} catch (InterruptedException e) {
synchronized (r1) {
}
}
Output:
Thread 1: holding resource 1
Thread 2: holding resource 2
Thread 1: Waiting for resource 2
Thread 2: Waiting for resource 1
after this the program gets into deadlock
Page 26 of 52
Chhatrapti Shivaji Institute of Technology, Durg
class Main2{
[Link]();
[Link]();
synchronized (r1) {
Page 27 of 52
Chhatrapti Shivaji Institute of Technology, Durg
try {
[Link](10);
} catch (Exception e) {
synchronized (r2) {
}
}
}
}
Page 28 of 52
Chhatrapti Shivaji Institute of Technology, Durg
synchronized (r1) {
[Link]("Thread 1: holding resource 1...");
try {
[Link](10);
} catch (Exception e) {
synchronized (r2) {
Page 29 of 52
Chhatrapti Shivaji Institute of Technology, Durg
}
Output:
Thread 1: holding resource 1...
Thread 1: waiting for resource 2...
Thread 1: holding 1 and 2
Thread 1: holding resource 1...
Thread 1: waiting for resource 2...
Thread 1: holding 1 and 2
Page 30 of 52
Chhatrapti Shivaji Institute of Technology, Durg
EXP-10
Aim:- Write a program to merge the contents of text files
[Link] and [Link] into [Link]. The contents of [Link]
should appear first and then [Link] in the destination file
[Link].
Code:- import [Link];
import [Link];
class MergeContent {
FileInputStream f1 = null;
FileInputStream f2 = null;
FileOutputStream o1 = null;
try {
f1 = new FileInputStream("D:\\[Link]");
f2 = new FileInputStream("D:\\[Link]");
o1 = new FileOutputStream("D:\\[Link]");
[Link](text1);
[Link]("\n".getBytes());
[Link](text2);
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
Page 32 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Exp-12
Aim:- Develop a GUI application to implement Date of
Birth validator. The DOB should only be in the form
"dd/mm/yyyy". Use customized exception handling
method as the validator.
Code:-
import [Link];
import [Link];
import [Link];
public class DobValidator{
public static boolean validateJavaDate(String strDate)
{
if ([Link]().equals(""))
{
return true;
}
else
{
SimpleDateFormat s = new
SimpleDateFormat("MM/dd/yyyy");
[Link](false);
try
{
Date javaDate = [Link](strDate);
[Link](strDate+" is valid date format");
}
catch (ParseException e)
{
[Link](strDate+" is Invalid Date format");
return false;
}
return true;
}
}
Page 33 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Page 34 of 52
Chhatrapti Shivaji Institute of Technology, Durg
EXP-13
Aim:- Develop an Applet to insert username and
password into a MySQL (or any) database.
Code:-
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
public class Table extends JApplet implements ActionListener
{
TextField username, password;
public String s1,s2,s;
String msg ="";
private Thread th;
Button submit;
Label LabelName, LabelPass;
DBConnect connect = new DBConnect();
public Table(){
}
public void init()
{
setLayout(null);
username = new TextField(8);
password = new TextField(8);
submit = new Button ("Register");
LabelName = new Label("User Name");
LabelPass = new Label("Password");
[Link](100,40,80,20);
[Link](100,80,80,20);
[Link](40,110,80,30);
[Link](20,40,80,20);
[Link](20,80,80,20);
add(LabelName);
add(username);
add(LabelPass);
add(password);
Page 35 of 52
Chhatrapti Shivaji Institute of Technology, Durg
add(submit);
[Link](this);
}
public void paint(Graphics g)
{
[Link](s1,100,275); // just for a test purpose
[Link](s2,100,300); // just for a test purpose
}
public void actionPerformed(ActionEvent evt)
{
if ([Link]() == submit) {
try
{
s1 = [Link]();
s2 = [Link]();
repaint();
[Link](s1, s2); // here is the problem
[Link](null, "you're registered");
}
catch(Exception e) {
[Link]();
[Link](null, "Something Wrong / This
user name already exists");
}
}
}
public String getS1(){
return s1;
}
public String getS2(){
return s2;
}
}
Output:-
Username:xyzabc
Password:*******
Page 36 of 52
Chhatrapti Shivaji Institute of Technology, Durg
EXP-15
Aim:- Develop two applications in Java using Sockets to
communicate with each other using text messages.
Code:-
// A Java program for a Client
import [Link].*;
import [Link].*;
public class Client
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
[Link]("Connected");
// takes input from terminal
input = new DataInputStream([Link]);
// sends output to the socket
out = new DataOutputStream([Link]());
}
catch(UnknownHostException u)
{
[Link](u);
}
catch(IOException i)
{
[Link](i);
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
Page 37 of 52
Chhatrapti Shivaji Institute of Technology, Durg
while ()
{
try
{
line = [Link]();
[Link](line);
}
catch(IOException i)
{
[Link](i);
}
}
// close the connection
try
{
[Link]();
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}
public static void main(String args[])
{
Client client = new Client("[Link]", 5000);
}
}
// A Java program for a Server
import [Link].*;
import [Link].*;
public class Server
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
Page 38 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Page 40 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Exp-16
Aim:- Develop two applications in Java using RMI to
communicate with each other using text message
Code:
//Defining the Remote Interface
import [Link];
import [Link];
// Creating Remote interface for our application
public interface Hello extends Remote {
void printMsg() throws RemoteException;
}
//Developing the Implementation Class (Remote Object)
// Implementing the remote interface
public class ImplExample implements Hello {
// Implementing the interface method
public void printMsg() {
[Link]("This is an example RMI program");
}
}
//Developing the Server Program
import [Link];
import [Link];
import [Link];
import [Link];
public class Server extends ImplExample {
public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();
// Exporting the object of implementation class
// (here we are exporting the remote object to the stub)
Hello stub = (Hello) [Link](obj, 0);
// Binding the remote object (stub) in the registry
Registry registry = [Link]();
[Link]("Hello", stub);
[Link]("Server ready");
} catch (Exception e) {
Page 41 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Page 42 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Exp-17
Aim:- Develop a Java program to demonstrate the use of
HashSet, TreeSet, ArrayList, LinkedList classes
Code:
import [Link].*;
// Develop a Java program to demonstrate the use of HashSet,
TreeSet, ArrayList, LinkedList classes
class Main {
public static void main(String[] args) {
[Link]("======== HASH SET ========");
hashSet();
[Link]();
[Link]("======== TREE SET ========");
treeSet();
[Link]();
[Link]("======== ARRAY LIST ========");
arrayList();
[Link]();
[Link]("======== LINKED LIST ========");
linkedList();
}
public static void linkedList() {
LinkedList<Integer> number = new LinkedList<>();
[Link](1);
[Link](2);
[Link](3);
[Link](number);
// size() - get the size of the arraylist
int length = [Link]();
[Link]("Length of linked list: " + length);
// removing
[Link](1);
[Link]("After deletion: ");
[Link](number);
// iterating using for loop
[Link]("loop: ");
for (int j = 0; j < [Link](); j++) {
Page 43 of 52
Chhatrapti Shivaji Institute of Technology, Durg
[Link]([Link](j) + "\t");
}
[Link]();
// iterating using iterator
[Link]("iterator: ");
Iterator<Integer> it = [Link]();
while ([Link]()) {
[Link]([Link]()+ "\t");
}
[Link]();
}
public static void arrayList() {
ArrayList<Integer> number = new ArrayList<>();
[Link](1);
[Link](3);
[Link](2);
[Link](number);
// size() - get the size of the arraylist
int length = [Link]();
[Link]("Length of arraylist: " + length);
// removing
// Note - arraylist provides two overloaded functions on with
index as parameter and other with element as parameter
[Link](1);
[Link]("After deletion: ");
[Link](number);
// iterating using for loop
[Link]("Looping: ");
for (int j = 0; j < [Link](); j++) {
[Link]([Link](j)+ "\t");
}
[Link]();
// iterating using iterator
[Link]("Iterator: ");
Iterator<Integer> it = [Link]();
while ([Link]()) {
[Link]([Link]()+ "\t");
}
Page 44 of 52
Chhatrapti Shivaji Institute of Technology, Durg
[Link]();
}
public static void treeSet() {
TreeSet<String> t = new TreeSet<>();
// add - add an element to treeset
[Link]("Hello");
[Link]("World");
[Link]("Binod");
[Link](t);
// size() - to get the size of the set
int length = [Link]();
[Link]("treeset has " + length + " elements");
// remove - reomves an element from the treeset
[Link]("Binod");
[Link]("After deletion: ");
[Link](t);
// iterating using iterator
[Link]("Iterating");
Iterator<String> it = [Link]();
while ([Link]()) {
[Link]([Link]()+ "\t");
}
[Link]();
}
public static void hashSet() {
HashSet<String> cars = new HashSet<>();
// add - addds an element into the set if it is not present in the
set.
[Link]("Volvo");
[Link]("BMW");
[Link]("Ford");
[Link]("Mazda");
[Link](cars);
// size - to get the number of elements in the hashset
int length = [Link]();
[Link]("length: "+length);
// remove - remove the elemetn from the set
[Link]("Mazda");
Page 45 of 52
Chhatrapti Shivaji Institute of Technology, Durg
EXP-18
AIM: Develop a Java program to demonstrate the use of
Vector, HashMap, TreeMap, Hashtable classes
Code:
import [Link].*;
// Develop a Java program to demonstrate the use of Vector,
HashMap, TreeMap, Hashtable classes
public class Main {
public static void main(String[] args) {
[Link]("======== VECTOR ========");
vector();
[Link]();
[Link]("======== HASH MAP ========");
hashMap();
[Link]();
[Link]("======== TREE MAP ========");
treeMap();
[Link]();
[Link]("======== HASH TABLE ========");
hashTable();
}
public static void vector() {
// it is thread safe implementation of arraylist..
Vector<String> v = new Vector<>();
// adding
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("D");
[Link](v);
Page 47 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Iterator<Integer> it = [Link]();
while ([Link]()) {
[Link]([Link]() + "\t");
}
[Link]();
}
public static void treeMap() {
TreeMap<Integer, String> student = new TreeMap<>();
// adding
[Link](1, "Ram");
[Link](2, "BalRam");
[Link](3, "Shyam");
[Link](4, "Krishna");
[Link]("Initial: " + student);
// removing
[Link](2);
// keySet - returns the collection of keys of hashmap
[Link]("Iterating using Key set");
Set<Integer> s1 = [Link]();
Iterator<Integer> it1 = [Link]();
while ([Link]()) {
[Link]([Link]() + "\t");
}
[Link]();
// values - gives all the values of the hashmap
[Link]("All the values are: ");
Collection<String> s = [Link]();
Iterator<String> it = [Link]();
while ([Link]()) {
[Link]([Link]() + "\t");
}
[Link]();
}
public static void hashTable() {
Hashtable<Integer, String> student = new Hashtable<>();
// adding
[Link](1, "Ram");
[Link](2, "BalRam");
Page 49 of 52
Chhatrapti Shivaji Institute of Technology, Durg
[Link](3, "Shyam");
[Link](4, "Krishna");
[Link]("Initial: " + student);
// size - get totoal students
[Link]("Student count: " + [Link]());
// contains - checks if elemtent exists int the Hashtable.
[Link]("Is krishna a student: " +
[Link]("Krishna"));
// removing
[Link](2);
// keySet - returns the collection of keys of hashmap
[Link]("Iterating using Key set");
Set<Integer> s1 = [Link]();
Iterator<Integer> it1 = [Link]();
while ([Link]()) {
[Link]([Link]() + "\t");
}
[Link]();
// values - gives all the values of the hashmap
[Link]("All the values are: ");
Collection<String> s = [Link]();
Iterator<String> it = [Link]();
while ([Link]()) {
[Link]([Link]() + "\t");
}
[Link]();
}
}
Output:
======== VECTOR ========
[A, B, C, D]
length of vector: 4
vector: [A, B]
AB
======== HASH MAP ========
HashMap: {Shyam=12, BalRam=13, Ram=10}
Age of ram: 10
removed: 13
Page 50 of 52
Chhatrapti Shivaji Institute of Technology, Durg
Page 51 of 52
Chhatrapti Shivaji Institute of Technology, Durg
EXP-19
AIM:-Develop a Java program to demonstrate the use of
generics
Code:
public class Main {
public static void main(String[] args) {
StoreInfo<Integer> i = new StoreInfo();
StoreInfo<Character> s = new StoreInfo();
[Link](12);
[Link](i);
[Link]('A');
[Link](s);
}
}
class StoreInfo<T> {
private T value = null;
T get() {
return [Link];
}
void set(T t) {
[Link] = t;
[Link]("Stored " + value + " succesfully");
}
@Override
public String toString() {
return "Stored value: " + [Link];
}
}
Output:
Stored 12 succesfully
Stored value: 12
Stored A succesfully
Stored value: A
Exp-20
Page 52 of 52