0% found this document useful (0 votes)
49 views

Durga Oops Through Java Lab Manual Programs (Cse)

manual

Uploaded by

durgabhavani60
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Durga Oops Through Java Lab Manual Programs (Cse)

manual

Uploaded by

durgabhavani60
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

1
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

WEEK 1:

1.Use eclipse or Netbean platform and acquaint with the various menus, create a test
project, add a test class and run it see how you can use auto suggestions, auto fill. Try
code formatter and code refactoring like renaming variables, methods and classes. Try
debug step by step with a small program of about 10 to 15 lines which contains at least
one if else condition and a for loop.

Program:-
public class Prog1
{
public static void main(String[] args)
{
System.out.println("\n Prog. is showing even no");
for(int i=2;i<=20;i++)
{
if(i%2==0)
{
System.out.print("\n "+i);
}
}
}
}
Compile:-
D:>javac Prog1.java
Run:-
D:>java Prog1
Output:

2
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

1)B. Write a Java program that prints all real solutions to the quadratic equation
ax2+bx+c = 0. Read in a, b, c and use the quadratic formula.
Program:-

import java.util.Scanner;
public class QuadraticEquation
{
public static void main(String[] Strings)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of a: ");
double a = input.nextDouble();
System.out.print("Enter the value of b: ");
double b = input.nextDouble();
System.out.print("Enter the value of c: ");
double c = input.nextDouble();
double d= b * b - 4.0 * a * c;
if (d> 0.0)
{
double r1 = (-b + Math.pow(d, 0.5)) / (2.0 * a);
double r2 = (-b - Math.pow(d, 0.5)) / (2.0 * a);
System.out.println("The roots are " + r1 + " and " + r2);
}
else if (d == 0.0)
{
double r1 = -b / (2.0 * a);
System.out.println("The root is " + r1);
}
else
{
System.out.println("Roots are not real.");
} } }

OUTPUT:

3
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

1)C. Write a java program to implement Fibonacci series

Program:

import java.util.*;
public class Fibonacci
{
public static void main (String args[])
{
int i=0,j=1,nextTerm;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a Number");
int n=sc.nextInt();
for(int c=0;c<=n;c++)
{
if(c<=1)
nextTerm=c;
else
{
nextTerm=i+j;
i=j;
j=nextTerm;
}
System.out.println(nextTerm);
}
} }

Output:

4
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

WEEK 2:
2)A. Write a java program to implement method overloading and constructors
overloading.

class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloadingobj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}

OUTPUT:

a
a 10

2. A. constructors overloading:

public class Student {


//instance variables of the class
int id;
String name;

Student(){
System.out.println("this a default constructor");
}

Student(int i, String n){


id = i;
name = n;
}

public static void main(String[] args) {

5
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

//object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);

System.out.println("\nParameterized Constructor values: \n");


Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
}
}

OUTPUT:

this a default constructor

Default Constructor values:

Student Id : 0
Student Name : null

Parameterized Constructor values:

Student Id : 10
Student Name : David

2. B) Write a java program to implement method overriding.

import java.io.*;
class Override
{
public void aquire()
{
System.out.println("Marri Laxman reddyaqcures NAAC B Grade");
}
}
class Mlritm extends Override
{
public void aquire()
{
System.out.println("Marri Laxman reddyaqcures NAAC A+ Grade");
}
}
public class College
{

public static void main(String args[])


{
Override or=new Mlritm();
or.aquire();

6
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

}
}

Output:

7
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

WEEK 3:
3)A. Write a java program to check whether given string is palindrome or not

Program:

import java.util.*;
public class Palindrome
{
public static void main(String args[])
{
String str,rev="";
Scanner sc=new Scanner(System.in);
System.out.println("Enter a value");
str=sc.nextLine();
int length=str.length();
for(int i=length-1;i>=0;i--)
rev=rev+str.charAt(i);
if(str.equals(rev))
System.out.println(str + " ---> is a Palindrome");
else
System.out.println(str + " --->is a not alindrome");
}
}

OUTPUT:

8
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

3)B. Write a java program to create an abstract class named Shape that contains two
integers and an empty method named printArea(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class Shape.
Each one of the classes contain only the method printArea( ) that prints the area of the
given shape.

Program:

import java.util.*;
abstract class shape
{
int x,y;
abstract void printArea(double x,double y);
}
class Rectangle extends shape
{
void printArea(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void printArea(double x,double y)
{
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
{
void printArea(double x,double y)
{
System.out.println("Area of triangle is :"+(0.5*x*y));
}

9
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

}
public class AbstactDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.printArea(2,5);
Circle c=new Circle();
c.printArea(5,5);
Triangle t=new Triangle();
t.printArea(2,5);
}
}

OUTPUT:

10
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

WEEK 4:
4).A Write a program that creates a user interface to perform integer divisions. The
user enters two numbers in the text fields, Num1 and Num2. The division of Num1 and
Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or
Num2 were not an integer, the program would throw a NumberFormatException. If
Num2 were Zero, the program would throw an Arithmetic Exception Display the
exception in a message dialog box.

Program:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Add1 extends Applet implements ActionListener
{
String msg;
TextField num1, num2, res;
Label l1, l2, l3;
Button div;
public void init()
{
l1 = new Label("Number 1");
l2 = new Label("Number 2");
l3 = new Label("result");
num1 = new TextField(10);
num2 = new TextField(10);
res = new TextField(30);
div = new Button("DIV");
div.addActionListener(this);
add(l1);
add(num1);
add(l2);
add(num2);
add(l3);
add(res);
add(div);
}
public void actionPerformed(ActionEvent ae)
{
String arg = ae.getActionCommand();
if (arg.equals("DIV"))
{
String s1 = num1.getText();
String s2 = num2.getText();
int num1 = Integer.parseInt(s1);
int num2 = Integer.parseInt(s2);
if (num2 == 0)
{

11
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

msg = "Arithemetic Exception ";


repaint();
}
else if ((num1 < 0) || (num2 < 0))
{
msg = "NumberFormat Exception";
repaint();
}
else
{
int num3 = num1 / num2;
msg = String.valueOf(num3);
}
res.setText(msg);
}
}
public void paint(Graphics g)
{
//g.drawString(msg, 30, 70);
}
}

File 2: Add1.hml

<html>
<head>
</head>
<body>
<applet code="Add1.class"width=350 height=300>
</applet>
</body>
</html>

OUTPUT:

12
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

4)B. Write a java program to create user defined exception class and test this class.

Program:

// class representing custom exception


class MyCustomException extends Exception
{

// class that uses custom exception MyCustomException


public class TestCustomException2
{
// main method
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new MyCustomException();
}
catch (MyCustomException ex)
{
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}

System.out.println("rest of the code...");


}

13
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

OUTPUT:

14
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

5). A) Write a Java program to list all the files in a directory including the files present
in all its subdirectories.

Program:
import java.io.File;
public class GFG
{
static void RecursivePrint(File[] arr,intindex,int level)
{// terminate condition
if(index == arr.length)
return; // tabs for internal levels
for (int i = 0; i< level; i++)
System.out.print("\t"); // for files
if(arr[index].isFile())
System.out.println(arr[index].getName()); // for sub-directories
else if(arr[index].isDirectory())
{
System.out.println("[" + arr[index].getName() + "]");// recursion for sub-directories
RecursivePrint(arr[index].listFiles(), 0, level + 1);
}// recursion for main directory
RecursivePrint(arr,++index, level);
} // Driver Method
public static void main(String[] args)
{ // Provide full path for directory(change accordingly)
String maindirpath = "D:\\Java-MLRITM-ECE\\Student notes";
// File object
File maindir = new File(maindirpath);
if(maindir.exists() &&maindir.isDirectory())
{
// array for files and sub-directories
// of directory pointed by maindir

15
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

File arr[] = maindir.listFiles();


System.out.println("**********************************************");
System.out.println("Files from main directory : " + maindir);
System.out.println("**********************************************");
// Calling recursive method
RecursivePrint(arr,0,0);
}
}
}
OUTPUT:

16
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

5)B. Write a java program that displays the number of characters, lines and words in a
text file.

Program:

//Program to count number of lines,characters,and words in a text file


import java.util.*;
import java.io.*;
class Countfile
{
public static void main(String args[])throws IOException
{
int nl=1,nw=0;
char ch;
Scanner scr=new Scanner(System.in);
System.out.print("\nEnter File name: ");
String str=scr.nextLine();
FileInputStream f=new FileInputStream(str);
int n=f.available();
for(int i=0;i<n;i++)
{
ch=(char)f.read();
if(ch=='\n')
nl++;
else if(ch==' ')
nw++;

}
System.out.println("\nNumber of lines : "+nl);
System.out.println("\nNumber of words : "+(nl+nw));
System.out.println("\nNumber of characters : "+n);

}
}

OUTPUT:

17
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

6)A. Write a Java program that implements a multi-thread application that has three
threads. First thread generates random integer every 1 second and if the value is even,
second thread computes the square of the number and prints. If the value is odd, the
third thread will print the value of cube of the number.
program
import java.util.*;
import java.io.*;
class even implements Runnable
{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Thread Name:Even Thread and " + x + "is even Number
and Square of " + x + " is: " + x * x);
}
}
class odd implements Runnable
{
public int x;
public odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Thread Name:ODD Thread and " + x + " is odd
number and Cube of " + x + " is: " + x * x * x);
}

18
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

}
class A extends Thread
{
public String tname;
public Random r;
public Thread t1, t2;
public A(String s)
{
tname = s;
}
public void run()
{
int num = 0;
r = new Random();
try
{
for (int i = 0; i< 5; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
if (num % 2 == 0)
{
t1 = new Thread(new
even(num));
t1.start();
}
else
{
t2 = new Thread(new odd(num));
t2.start();
}

19
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class Mthread
{
public static void main(String[] args)
{
A a = new A("One");
a.start();
}
}
OUTPUT:

20
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

6)B. Write a Java program that correctly implements the producer – consumer problem
using the concept of interthread communication.

// Java program to implement solution of producer


// consumer problem.

import java.util.LinkedList;

public class Threadexample {


public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();

// Create producer thread


Thread t1 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();

21
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

}
}
});

// Create consumer thread


Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Start both threads


t1.start();
t2.start();

// t1 finishes before t2
t1.join();
t2.join();
}

// This class has a list, producer (adds items to list


// and consumer (removes items).
public static class PC {

// Create a list shared by producer and consumer


// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;

// Function called by producer thread


public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size() == capacity)
wait();

System.out.println("Producer produced-"
+ value);

22
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

// to insert the jobs in the list


list.add(value++);

// notifies the consumer thread that


// now it can start consuming
notify();

// makes the working of program easier


// to understand
Thread.sleep(1000);
}
}
}

// Function called by consumer thread


public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size() == 0)
wait();

// to retrieve the ifrst job in the list


int val = list.removeFirst();

System.out.println("Consumer consumed-"+ val);

// Wake up producer thread


notify();

// and sleep
Thread.sleep(1000);
}
}
}
}
}

OUTPUT:

23
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

Note :Press Ctrl+C to stop the flow of output

24
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

7. Write a Java program that loads names and phone numbers from a text file where
the data is organized as one line per record and each field in a record are separated by a
tab (\t). It takes a name or phone number as input and prints the corresponding other
value from the hash table (hint: use hash tables).

Program:
import java.util.*;
import java.io.*;
public class Hashtbl {
public static void main(String[] args) {
try {
FileInputStream fs = new FileInputStream("D:\\Java-MLRITM-ECE\\JavaPrograms\\WEEK
9\\ph.txt");
Scanner sc = new Scanner(fs).useDelimiter("\\s+");
Hashtable<String, String>ht = new Hashtable<String, String>();
String[] arrayList;
String a;
System.out.println("HASH TABLE IS");
System.out.println("--------------------------");
System.out.println("KEY : VALUE");
while (sc.hasNext()) {
a = sc.nextLine();
arrayList = a.split("\\s+");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" + arrayList[1]);
}
System.out.println("----MENU------");
System.out.println("----1.Search by Name------");
System.out.println("----2.Search by Mobile------");
System.out.println("----3.Exit------");
String opt = "";
String name, mobile;

25
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

Scanner s = new Scanner(System.in);


while (opt != "3") {
System.out.println("Enter Your Option 1,2,3");
opt = s.next();
switch (opt) {
case "1": {
System.out.println("Enter Name");
name = s.next();
if (ht.containsKey(name)) {
System.out.println("Mobile is " + ht.get(name));
} else {
System.out.println("Not Found");
}}
break;
case "2": {
System.out.println("Enter mobile");
mobile = s.next();
if (ht.containsValue(mobile)) {
for (@SuppressWarnings("rawtypes") Map.Entrye :ht.entrySet()) {
if (mobile.equals(e.getValue())) {
System.out.println("Name is " + e.getKey());
}}} else {
System.out.println("Not Found");
}}
break;
case "3": {
opt = "3";
System.out.println("Menu Successfully Exited");
}
break;

26
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

default:
System.out.println("Choose Option betwen 1 and Three");
break;
}}}
catch (Exception ex) {
System.out.println(ex.getMessage());
}}}

ph.txt file

OUTPUT:

27
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

28
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

8. (A) Write a Java Program to count occurrence of each character in a string.

import java.util.Scanner;

public class OccuranceCount{


public static void main(String...args){
System.out.println("Enter a string");
Scanner s = new Scanner(System.in);
char[] ch = s.nextLine().toCharArray();
int count = 0;
System.out.println("Enter a character to check its OccurrenceCount: ");
char c = s.nextLine().charAt(0);
for(int i=0; i<ch.length;i++){
if(ch[i] == c)
count++;
}
System.out.println("The Character \'"+c+"\' has Occurred "+count+" times in
the String");
}

Output:

8. (B) Write a Java Program to remove duplicate words from a string.

import java.util.Scanner;

public class RemoveDuplicates{


public static void main(String args[]){
Scanner s = new Scanner(System.in);
System.out.println("Enter a String");
String str = s.nextLine();
System.out.println(str);
String[] words = str.split(" ");
for (int i = 0; i<words.length; i++){

29
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

for (int j = 0; j <words.length; j++){


if (words[i].equals(words[j])){
if (i != j)
words[i] = "";
}
}
}
System.out.println("After Removing Duplicate words:");
for (int i = 0; i<words.length; i++){
if (words[i] != "")
System.out.print(words[i]+" ");
}
}
}

Output:

8. (C) Write a Java Program to print all permutations of a string.

// Java program to print all the permutations


// of the given string
import java.util.Scanner;
public class GFG {

// Function to print all the permutations of str


static void printPermutn(String str, String ans)
{

// If string is empty
if (str.length() == 0) {
System.out.print(ans + " ");
return;
}

for (int i = 0; i<str.length(); i++) {

// ith character of str


char ch = str.charAt(i);

// Rest of the string after excluding


// the ith character
String ros = str.substring(0, i) +

30
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

str.substring(i + 1);

// Recursive call
printPermutn(ros, ans + ch);
}
}

// Driver code
public static void main(String[] args)
{
System.out.println("enter the string");
Scanner sr=new Scanner(System.in);
String s = sr.nextLine();
printPermutn(s, "");
}
}

Output:

31
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

9. A) Write programs to add, retrieve & remove element from Array List

import java.util.ArrayList;
import java.util.Scanner;

class ArrayListDemo{
public static void main(String...args){
ArrayList<String>al = new ArrayList<>();
Scanner s = new Scanner(System.in);

// adding elements to the arrayList dynamically


System.out.println("How Many Elements do you want to insert...");

int asize = s.nextInt();


s.nextLine();
for(int i=0; i<asize; i++){
System.out.println("Enter Element no: "+i);
al.add(s.nextLine());
}

// Retrieving elements from the arrayList using for-each loop


for(String str: al){
System.out.print(str+" ");
}

// Retrieving elements from the arrayList directly using the arrayList object.

System.out.println("\n"+al);

// Removing Elements from the arrayList.

System.out.println("How Many Elements do you want to remove form the


arrayList");
int rsize = s.nextInt();
s.nextLine();
for(int i=0; i<rsize; i++){
System.out.println("Enter Element no: "+i);
al.remove(s.nextLine());
}

System.out.println(al);
}
}

Output:

32
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

9. B) Write programs to Sort & reverse the Linked List elements

import java.util.LinkedList;
import java.util.Scanner;
import java.util.Collections;

class LinkedListDemo{
public static void main(String...args){
LinkedList<String>ll = new LinkedList<>();
Scanner s = new Scanner(System.in);

// adding elements to the LinkedList dynamicllly


System.out.println("How Many Elements do you want to insert...");

int asize = s.nextInt();


s.nextLine();
for(int i=0; i<asize; i++){
System.out.println("Enter Element no: "+i);
ll.add(s.nextLine());
}

// Retrieving elements from the LinkedList using for-each loop


for(String str: ll){
System.out.print(str+" ");
}
System.out.println();

// Sorting Elements of the LinkedList.


Collections.sort(ll);
System.out.println("Sorted List: "+ll);

// Reversing Elements of the LinkedList.


Collections.reverse(ll);
System.out.println("Reversed List: "+ll);

33
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

}
}

Output:

9. C) Write programs to sort Array List using Comparable and Comparator


Comparable:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

class Brands implements Comparable<Brands> {


private String bname;

public Brands(String name) {


this.bname = name;
}

@Override
public int compareTo(Brands bs) {
// Compare based on age
return (this.bname).compareTo(bs.bname);
}

@Override
public String toString() {
return bname;
}
}

// This is the Primary Class

public class Comparable_ALSort {


public static void main(String[] args) {
ArrayList<Brands>als = new ArrayList<>();
Scanner s = new Scanner(System.in);

34
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

// adding elements to the arrayList dynamically


System.out.println("How Many Elements do you want to insert...");

int asize = s.nextInt();


s.nextLine();
for(int i=0; i<asize; i++){
System.out.println("Enter Element no: "+(i+1));
als.add(new Brands(s.nextLine()));
}

System.out.println("Before sorting:");
for (Brands bs :als) {
System.out.println(bs);
}

Collections.sort(als);

System.out.println("\nAfter sorting:");
for (Brands bs :als) {
System.out.println(bs);
}
}
}

Output:

Comparator:

// Use a custom comparator.


import java.util.Comparator;
import java.util.ArrayList;
import java.util.Scanner;

35
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

class MyComparator implements Comparator<String>{


public int compare(String str1, String str2){
return str1.compareTo(str2);
}
}

// ArrayListSort Class using Comparator.

public class Comparator_ALSort{


public static void main(String args[]) {
// Create a tree set.
ArrayList<String> al = new ArrayList<String>();
Scanner s = new Scanner(System.in);

// adding elements to the arrayList dynamically


System.out.println("How Many Elements do you want to insert...");

int asize = s.nextInt();


s.nextLine();
for(int i=0; i<asize; i++){
System.out.println("Enter Element no: "+i);
al.add(s.nextLine());
}

// Retrieving elements from the arrayList using for-each loop


for(String str: al){
System.out.print(str+" ");
}
System.out.println();

System.out.println("Before sorting: "+ al);


al.sort(new MyComparator());
System.out.println("After sorting: "+ al);
}
}

Output:

36
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

37
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

10. A) Write a program to copy elements from Hash Set to Array

Program:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Arrays;

class HashSetDemo{
public static void main(String...args){
HashSet<String>hs = new HashSet<String>();
Scanner s = new Scanner(System.in);

// adding elements to the hashset dynamically


System.out.println("How Many Elements do you want to insert...");

int asize = s.nextInt();


s.nextLine();
for(int i=0; i<asize; i++){
System.out.println("Enter Element no: "+(i+1));
hs.add(s.nextLine());
}

// Printing the elements of the HashSet


System.out.println("Printing of HashSet Elements: ");
for (String str :hs)
System.out.println(str);

// Converting HashSet into an Array


String[] sarray =
((Arrays.toString(hs.toArray()).replace("[","")).replace("]","")).split(", ");

System.out.println("Printing of Array Elements after Conversion: ");


for (String str :sarray)
System.out.println(str);

}
}

Output:

38
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

10. B) Write a program to remove duplicate key from hash table


import java.util.Hashtable;
import java.util.Map;
import java.util.Scanner;

class HashTableDemo{
public static void main(String...args){
Hashtable<Integer,String>ht = new Hashtable<>();
Scanner s = new Scanner(System.in);

// adding elements to the hashtable dynamically


System.out.println("How Many Elements do you want to insert...");
int asize = s.nextInt();

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


System.out.println("Student ID: "+(i+1));
int ii = s.nextInt();

s.nextLine();
System.out.println("Student Name: ");
String ss = s.nextLine();
ht.put(ii, ss);
}

// Printing the elements of the Hashtable


System.out.println("Printing of Hashtable Elements: ");
for (Map.Entry<Integer, String> me: ht.entrySet())
System.out.println(me.getKey()+" -- "+me.getValue());
}
}

39
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

Output:

10. C) Write a program to iterate Tree Map

import java.util.TreeMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Iterator;
import java.util.Set;

class TreeMapDemo{
public static void main(String...args){
TreeMap<Integer,String> tm = new TreeMap<>();
Scanner s = new Scanner(System.in);

// adding elements to the TreeMap dynamically


System.out.println("How Many Elements do you want to insert...");

int asize = s.nextInt();

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


System.out.println("Student ID: "+(i+1));
int ii = s.nextInt();

s.nextLine();
System.out.println("Student Name: ");
String ss = s.nextLine();
tm.put(ii, ss);
}

// Printing the elements of the TreeMap


System.out.println("Printing of TreeMap Elements: ");
for (Map.Entry<Integer, String> me: tm.entrySet())
System.out.println(me.getKey()+" - "+me.getValue());

40
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

// Printing the elments of TreeMap using iterator() method.


System.out.println("Printing of TreeMap Elements using iterator(): ");
Set<Integer> k = tm.keySet();
Iterator<Integer> it = k.iterator();
while(it.hasNext()){
int key = it.next();
String value = tm.get(key);
System.out.println(key + " = " + value);
}

}
}

Output:

41
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

11). Suppose that a table named Table.txt is stored in a text file. The first line in the file
is the header, and the remaining lines correspond to rows in the table. The elements are
separated by commas. Write a java program to display the table using Labels in Grid
Layout.

Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class Table1 extends JFrame
{
int i=0;
int j=0,k=0;
Object data[][]=new Object[5][4];
Object list[][]=new Object[5][4];
JButton save;
JTable table1;
FileInputStreamfis;
DataInputStream dis;
public Table1()
{
String d= " ";
Container con=getContentPane();
con.setLayout(new BorderLayout());
final String[] colHeads={"Name","RollNumber","Department","Percentage"};
try
{
String s=JOptionPane.showInputDialog("Enter the File name present in the current
directory");
FileInputStreamfis=new FileInputStream(s);
DataInputStream dis = new DataInputStream(fis);
while ((d=dis.readLine())!=null)
{
StringTokenizer st1=new StringTokenizer(d,",");
while (st1.hasMoreTokens())
{
for (j=0;j<4;j++){
data[i][j]=st1.nextToken();
System.out.println(data[i][j]);
}
i++;}
System.out.println ("______________");}
} catch (Exception e){
System.out.println ("Exception raised" +e.toString());
}
table1=new JTable(data,colHeads);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

42
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

JScrollPane scroll=new JScrollPane(table1,v,h);


con.add(scroll,BorderLayout.CENTER);
}
public static void main(String args[]){
Table1 t=new Table1();
t.setBackground(Color.green);
t.setTitle("Display Data");
t.setSize(500,300);
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}

Info.txt:- //Create text file with following data …..save as Info.txt


Rapolu Satheesh, 593, Computer Science, 30
Pawan Kalyan, 491, Electrical and Electronics, 22
Ravi Teja, 492, ECE, 23
Naresh, 495, ECE-B,22

OUTPUT:

Screen 1:

Screen 2:

43
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

44
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

Week 12
12.A) Write a Java program that handles all mouse events and shows the event name at
the centre of the window when a mouse event is fired (Use Adapter classes).
Program:
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample()
{
addMouseListener(this);
//addMouseMotionListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
repaint();
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
repaint();
}

45
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

public void mousePressed(MouseEvent e) {


l.setText("Mouse Pressed");
repaint();
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
repaint();
}
public static void main(String[] args) {
new MouseListenerExample();
} }

OUTPUT:

46
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

12.B) Write a java program to demonstrate the key event handlers.

Program:
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener{
Label l;
TextArea area;
KeyListenerExample()
{
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}

47
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

public void keyReleased(KeyEvent e) {


l.setText("Key Released");
}
public void keyTyped(KeyEvent e) {
l.setText("Key Typed");
}
public static void main(String[] args) {
new KeyListenerExample();
}
}

OUTPUT:
Note: When you type some Text on keyboard

When you released keys

48
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

49
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

Extra Programs

1.a) Write a Java program to create multiple thread by using extends mechanism.
class Hello extends Thread{

public void run()


{
for(int i=1;i<=5;i++)
{
System.out.println("Hello Hai");

try {
Thread.sleep(1000);}
catch(Exception e) {}
}
}
}
class GoodMorning extends Thread
{

public void run()


{
for(int i=1;i<=5;i++)
{
System.out.println("Good Morning");

try {
Thread.sleep(1000);
}catch(Exception e) {

}
}
}

}
public class Multithreading
{
public static void main(String args[])
{
Hello obj1=new Hello();
GoodMorning obj2=new GoodMorning();

obj1.start();
obj2.start();

}
}

50
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

13.b) Write a Java program to create multiple thread by using implements (using
Interface) mechanism.

Program:
class Hello1 implements Runnable {

public void run()


{
for(int i=1;i<=5;i++)
{
System.out.println("Hello Hai");

try {
Thread.sleep(5000);}
catch(Exception e) {}
}
}
}
class GoodMorning1 implements Runnable
{

public void run()


{
for(int i=1;i<=5;i++)
{
System.out.println("Good Morning");

try {
Thread.sleep(5000);
} catch(Exception e) {}
}
}

public class ThreadInterface {

public static void main(String args[])


{
Runnable obj1=new Hello1();
Runnable obj2=new GoodMorning1();

Thread t1=new Thread(obj1);


Thread t2=new Thread(obj2);

t1.start();
try {
Thread.sleep(10000);

51
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering

} catch(Exception e) {}
t2.start();

}
}

52

You might also like