0% found this document useful (0 votes)
2 views52 pages

Java Lab Manual 4th Sem

The document contains multiple Java programming exercises from Chhatrapti Shivaji Institute of Technology, covering various concepts such as reading employee details, using constructors, object counting, shape interfaces, exception handling, string methods, threading, and deadlock demonstration. Each exercise includes an aim, code implementation, and output examples. The exercises are designed to enhance understanding of Java programming fundamentals and object-oriented concepts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views52 pages

Java Lab Manual 4th Sem

The document contains multiple Java programming exercises from Chhatrapti Shivaji Institute of Technology, covering various concepts such as reading employee details, using constructors, object counting, shape interfaces, exception handling, string methods, threading, and deadlock demonstration. Each exercise includes an aim, code implementation, and output examples. The exercises are designed to enhance understanding of Java programming fundamentals and object-oriented concepts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Chhatrapti Shivaji Institute of Technology, Durg

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

Scanner in = new Scanner([Link]);


[Link]("Enter the name: ");
name = [Link]();
[Link]("Enter the department: ");
department = [Link]();
[Link]("Enter the age: ");
age = [Link]();
[Link]("Enter the salary: ");
salary = [Link]();
}
void getOutput() {
[Link]("Employee name = "+ name);
[Link]("Employee department = "+ department);
[Link]("Employee age = "+ age);
[Link]("Employee Salary = "+ salary);
}
}
Output:-
Enter the details of 1st employee
Enter the name: Ashu
Enter the department: managing
Enter the age: 27
Enter the salary: 50000

Enter the details of 2st employee


Enter the name: Tushar
Enter the department: marketing
Enter the age: 35
Enter the salary: 45000

Enter the details of 3st employee


Page 2 of 52
Chhatrapti Shivaji Institute of Technology, Durg

Enter the name: abc


Enter the department: developing
Enter the age: 33
Enter the salary: 76600

Enter the details of 4st employee


Enter the name: xyz
Enter the department: testing
Enter the age: 45
Enter the salary: 80000

Enter the details of 5st employee


Enter the name: pqr
Enter the department: sdffg
Enter the age: 23
Enter the salary: 45649
=========================================Details=======================
========
Employee name = Ashu
Employee department = managing
Employee age = 27
Employee Salary = 50000

Employee name = Tushar


Employee department = marketing
Employee age = 35
Employee Salary = 45000

Employee name = abc


Employee department = developing
Employee age = 33
Employee Salary = 76600

Employee name = xyz


Employee department = testing
Employee age = 45
Employee Salary = 80000

Page 3 of 52
Chhatrapti Shivaji Institute of Technology, Durg

Employee name = pqr


Employee department = sdffg
Employee age = 23
Employee Salary = 45649

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

[Link]("object garabage collected: "+this);


}
}

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();
}

class Circle implements Shape{ //subclass Circle


double radius;
public Circle(double r){
radius = r;
}
public double area(){
return 3.14 * radius * radius;
}
}
class Triangle implements Shape{ //subclass Triangle
double base;
double height;
public Triangle(double l, double b){
base = l;
Page 8 of 52
Chhatrapti Shivaji Institute of Technology, Durg

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]();

[Link]("Enter the height of the Triangle:");


double height = [Link]();
Triangle t = new Triangle(base,height);
[Link]("Area of rectangle: " + [Link]()+”\n”);
}
}
Page 9 of 52
Chhatrapti Shivaji Institute of Technology, Durg

Output:-
==========Area of Circle===================

Enter the radius of the circle:


3
Area of circle: 28.259999999999998

==========Area of Triangle===================

Enter the width of the Triangle:


3
Enter the height of the Triangle:
4
Area of rectangle: 6.0

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{

Scanner s = new Scanner([Link]);

[Link]("Enter a whole number");

int num=[Link]();

if (num < 0) {

throw new NegativeNumException();

[Link]("You passed the first test. Yayy!!");

Page 11 of 52
Chhatrapti Shivaji Institute of Technology, Durg

[Link]("numerator: ");

double numerator=[Link]();

[Link]("denominator: ");

double denominator=[Link]();

double div=numerator / denominator;

[Link]("result of division: " + div);


[Link]("Your basics of meth are on point");
FileInputStream fis = null;
try{
fis = new FileInputStream("B:/[Link]");
}catch(FileNotFoundException fnfe){
[Link]("The specified file is not " +
"present at the given path");
}
int k;
try{
while(( k = [Link]() ) != -1)
{
[Link]((char)k);
}
[Link]();
}catch(IOException ioe){
Page 12 of 52
Chhatrapti Shivaji Institute of Technology, Durg

[Link]("I/O error occurred: "+ioe);


}
}
}
class NegativeNumException extends Exception {

@Override

public String toString() {

return "GO and revise your math basics";

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

String str2 = new String("How");


[Link]([Link](7, str2, 0, 3));
}
}

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

//and T1 should only start when T2 finishes. (Note: use join())

class ThreadEx {

public static void main(String[] args) {

Numbers n = new Numbers();

Characters c = new Characters();

[Link]();

try {

[Link](); } catch (Exception e) {


Page 19 of 52
Chhatrapti Shivaji Institute of Technology, Durg

[Link]();

}}

class Numbers extends Thread {

int start = 1;

Numbers() {

super("Number Thread");

public void run() {

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

[Link](start + i);

Page 20 of 52
Chhatrapti Shivaji Institute of Technology, Durg

}
}

class Characters extends Thread {

int start=65;

Characters() {

super("Character Thread");

public void run() {

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

char c= (char) (start + i);

[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];

// Demonstrate using a Java program, how DEADLOCK occurs


between

//threads and also give solution program

//============= Deadlock ==========

class DeadlockEx {

public static String r1 = "ratan";

public static String r2 = "ahsaan";

public static void main(String[] args) {

DeadLockThread1 t1 = new DeadLockThread1();

DeadLockThread2 t2 = new DeadLockThread2();

Page 23 of 52
Chhatrapti Shivaji Institute of Technology, Durg

[Link]();

[Link]();

static class DeadLockThread1 extends Thread


{ DeadLockThread1() {

super("Thread 1");

public void run() {

synchronized (r1) { [Link]("Thread 1: holding


resource 1");

try {

[Link](100);

} catch (InterruptedException e) {

Page 24 of 52
Chhatrapti Shivaji Institute of Technology, Durg

[Link]("Thread 1: Waiting for resource 2");


synchronized (r2) {

[Link]("Thread 1: locked resource 1 and 2");


}
}
}
}
static class DeadLockThread2 extends Thread {

DeadLockThread2() {

super("Thread 2");

public void run() {

synchronized (r2) {

[Link]("Thread 2: holding resource 2");


try {

[Link](100);

Page 25 of 52
Chhatrapti Shivaji Institute of Technology, Durg

} catch (InterruptedException e) {

[Link]("Thread 2: Waiting for resource 1");

synchronized (r1) {

[Link]("Thread 2: locked resource 1 and 2");

}
}
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

//======= Solution =====

class Main2{

static String r1= "hello";

static String r2 = "world";

public static void main(String[] args) {

synchronizedT1 t1 = new synchronizedT1();

synchronizedT2 t2 = new synchronizedT2();

[Link]();

[Link]();

static class synchronizedT1 extends Thread {

public void run() {

synchronized (r1) {

Page 27 of 52
Chhatrapti Shivaji Institute of Technology, Durg

[Link]("Thread 1: holding resource 1...");

try {

[Link](10);

} catch (Exception e) {

[Link]("Thread 1: waiting for resource 2...");

synchronized (r2) {

[Link]("Thread 1: holding 1 and 2");

}
}
}
}

static class synchronizedT2 extends Thread{

public void run() {

Page 28 of 52
Chhatrapti Shivaji Institute of Technology, Durg

synchronized (r1) {
[Link]("Thread 1: holding resource 1...");

try {

[Link](10);

} catch (Exception e) {

[Link]("Thread 1: waiting for resource 2...");

synchronized (r2) {

[Link]("Thread 1: holding 1 and 2");

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];

// 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].

class MergeContent {

public static void main(String[] args) {

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]");

byte[] text1= [Link]();

[Link](text1);

[Link]("\n".getBytes());

byte[] text2 = [Link]();


Page 31 of 52
Chhatrapti Shivaji Institute of Technology, Durg

[Link](text2);

[Link]();

[Link]();

[Link]();

} catch (Exception e) {

// File 1 - Helllo from file 1......

// File 2- Helllo from file 2..


Output:-
Output of File3:
Helllo from file 1......
Helllo from file 2.........

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

public static void main(String args[]){


validateJavaDate("12/29/2016");
validateJavaDate("12-29-2016");
validateJavaDate("12,29,2016");
}
}
Output:-
12/29/2016 is valid date format
12-29-2016 is Invalid Date format
12,29,2016 is Invalid Date format

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 (![Link]("Over"))
{
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

// constructor with port


public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
[Link]("Server started");
[Link]("Waiting for a client ...");
socket = [Link]();
[Link]("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream([Link]()));
String line = "";
// reads message from client until "Over" is sent
while (![Link]("Over"))
{
try
{
line = [Link]();
[Link](line);
}
catch(IOException i)
{
[Link](i);
}
}
[Link]("Closing connection");
// close connection
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}
Page 39 of 52
Chhatrapti Shivaji Institute of Technology, Durg

public static void main(String args[])


{
Server server = new Server(5000);
}
}
Output:
Then you can start typing messages in the Client window. Here
is a sample input to the Client
Hello
I made my first socket connection
Over
Which the Server simultaneously receives and shows,
Hello
I made my first socket connection
Over
Closing connection

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

[Link]("Server exception: " + [Link]());


[Link]();
}
}
}
//Developing the Client Program
import [Link];
import [Link];
public class Client {
private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = [Link](null);
// Looking up the registry for the remote object
Hello stub = (Hello) [Link]("Hello");
// Calling the remote method using the obtained object
[Link]();
// [Link]("Remote method invoked");
} catch (Exception e) {
[Link]("Client exception: " + [Link]());
[Link]();
}
}
}

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

[Link]("After deletion: ");


[Link](cars);
// iterator method returns an iterator that can be used to iterate
over the set.
[Link]("iterating: ");
Iterator<String> it = [Link]();
while ([Link]()) {
[Link]([Link]() + "\t");
}
[Link]();
}
}
Output:
======== HASH SET ========
[Volvo, Mazda, Ford, BMW]
length: 4
After deletion:
[Volvo, Ford, BMW]
iterating:
Volvo Ford BMW
======== TREE SET ========
[Binod, Hello, World]
treeset has 3 elements
After deletion:
[Hello, World]
Iterating
Hello World
======== ARRAY LIST ========
[1, 3, 2]
Length of arraylist: 3
After deletion:
[1, 2]
Looping:
12
Iterator:
12
======== LINKED LIST ========
[1, 2, 3]
Page 46 of 52
Chhatrapti Shivaji Institute of Technology, Durg

Length of linked list: 3


After deletion:
[1, 3]
loop:
1 3
iterator:
1 3

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

// length of the vector


int length = [Link]();
[Link]("length of vector: " + length);
// removes element
[Link]("C");
[Link](2);
[Link]("vector: " + v);
// printing via loop
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i) + "\t");
}
[Link]();
}
public static void hashMap() {
HashMap<String, Integer> h = new HashMap<>();
// put - adds a key value pair to the hashmap
[Link]("Ram", 10);
[Link]("Shyam", 12);
[Link]("BalRam", 13);
[Link]("HashMap: " + h);
// [Link](key) - reutrns the value of key.
Integer ageOfRam = [Link]("Ram");
[Link]("Age of ram: " + ageOfRam);
// remove(key) - removes the value from the map.
Integer val = [Link]("BalRam");
[Link]("removed: " + val);
[Link]("HashMap: " + h);
// keySet - returns the collection of keys of hashmap
[Link]("Iterating using Key set");
Set<String> s1 = [Link]();
Iterator<String> it1 = [Link]();
while ([Link]()) {
[Link]([Link]() + "\t");
}
[Link]();
// values - gives all the values of the hashmap
[Link]("All the values are: ");
Collection<Integer> s = [Link]();
Page 48 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

HashMap: {Shyam=12, Ram=10}


Iterating using Key set
Shyam Ram
All the values are:
12 10
======== TREE MAP ========
Initial: {1=Ram, 2=BalRam, 3=Shyam, 4=Krishna}
Iterating using Key set
134
All the values are:
Ram Shyam Krishna
======== HASH TABLE ========
Initial: {4=Krishna, 3=Shyam, 2=BalRam, 1=Ram}
Student count: 4
Is krishna a student: true
Iterating using Key set
431
All the values are:
Krishna Shyam Ram

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

You might also like