Durga Oops Through Java Lab Manual Programs (Cse)
Durga Oops Through Java Lab Manual Programs (Cse)
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
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:
Student(){
System.out.println("this a default constructor");
}
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);
OUTPUT:
Student Id : 0
Student Name : null
Student Id : 10
Student Name : David
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
{
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
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:
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
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:
}
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.
import java.util.LinkedList;
21
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
}
}
});
// t1 finishes before t2
t1.join();
t2.join();
}
System.out.println("Producer produced-"
+ value);
22
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
// and sleep
Thread.sleep(1000);
}
}
}
}
}
OUTPUT:
23
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
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
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
import java.util.Scanner;
Output:
import java.util.Scanner;
29
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
Output:
// If string is empty
if (str.length() == 0) {
System.out.print(ans + " ");
return;
}
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);
// Retrieving elements from the arrayList directly using the arrayList object.
System.out.println("\n"+al);
System.out.println(al);
}
}
Output:
32
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
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);
33
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
}
}
Output:
@Override
public int compareTo(Brands bs) {
// Compare based on age
return (this.bname).compareTo(bs.bname);
}
@Override
public String toString() {
return bname;
}
}
34
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
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:
35
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
Output:
36
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
37
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
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);
}
}
Output:
38
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
class HashTableDemo{
public static void main(String...args){
Hashtable<Integer,String>ht = new Hashtable<>();
Scanner s = new Scanner(System.in);
s.nextLine();
System.out.println("Student Name: ");
String ss = s.nextLine();
ht.put(ii, ss);
}
39
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
Output:
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);
s.nextLine();
System.out.println("Student Name: ");
String ss = s.nextLine();
tm.put(ii, ss);
}
40
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
}
}
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
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
OUTPUT:
46
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
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
OUTPUT:
Note: When you type some Text on keyboard
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{
try {
Thread.sleep(1000);}
catch(Exception e) {}
}
}
}
class GoodMorning extends Thread
{
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 {
try {
Thread.sleep(5000);}
catch(Exception e) {}
}
}
}
class GoodMorning1 implements Runnable
{
try {
Thread.sleep(5000);
} catch(Exception e) {}
}
}
t1.start();
try {
Thread.sleep(10000);
51
OOPS Through JAVA LAB Manual Dept of Computer Science & Engineering
} catch(Exception e) {}
t2.start();
}
}
52