OOPS Through Java Lab Manual - Student
OOPS Through Java Lab Manual - Student
Course Outcomes: At the end of the course, students will be able to Knowledge
Level (K)#
CO1 Identify classes, objects, members of a class and the relationship among K3
them needed for a specific problem
CO2 Implement programs to distinguish different forms of inheritance K4
CO3 Create packages and to reuse them K3
CO4 Develop programs using Exception Handling mechanism K3
CO5 Develop multithreaded application using synchronization concept. K6
CO6 Design GUI based applications using Swings and AWT. K6
List of programs to be executed:
1. The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are
1, 1Every subsequent value is the sum of the 2 values preceding it. Write a Java Program that
uses both recursive and non-recursive functions to print the nth value of the Fibonacci sequence.
2. Write a Java Program that prompts the user for an integer and then prints out all the prime
numbers upto that integer.
3. Write a java program to implement call by value and call by reference mechanisms.
4.Write a Java Program that checks whether a given string is a palindrome or not.
5.Write a Java Program to check the compatibility for multiplication, if compatible multiply
two matrices and find its transpose.
6.Write a Java program to implement constructor overloading and method overloading.
7.Write a Java Program that illustrates how run time polymorphism is achieved.
8.Write a Java Program that illustrates the use of super keyword.
9.Write a Java Program to create and demonstrate packages.
10.Write a Java Program, using String Tokenizer class, which reads a line of integers and
then display search integer and the sum of all integers.
11.Write a Java Program that reads on file name form the user then displays information
about whether the file exists, whether the file is readable/ writable, the type of file and the
length of the file in bytes and display the content of the using File Input Stream class.
12.Write a Java Program that displays the number of characters, lines and words in a text/text
file.
13.Write a Java Program to implement a Queue, using user defined Exception Handling (also
make use ofthrow, throws).
14. Write a Java Program that creates 3 threads by extending Thread class. First thread
displays “Good Morning” every 1 sec, the second thread displays “Hello” every 2 seconds
and the third displays“Welcome”every 3 seconds. (Repeat the same by implementing
Runnable).
15.Write a Java Program demonstrating the life cycle of a thread.
16. Write an Applet that displays the content of a file.
17.Write a Java Program that works as a simple calculator. Use a gridlay out to arrange
buttons for the digits and for the +-*?% operations. Add a text field to display the result.
18.Writea Java Program for handling mouse events, keyboard events.
19. Write a Java Program that allows user to draw lines, rectangles and ovals.
20.Write a Java Program that lets users create Piecharts. Design your own user interface (with
Swings & AWT).
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
1. AIM: -The Fibonacci sequence is defined by the following rules: The first two values in the
sequence are 1and 1. Every subsequent values is the sum of the two values preceding it.
Write a java program that uses both recursive and non-recursive functions to print the nth
value in the Fibonacci sequence.
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
2. AIM: - Write a program that prompts the user for an integer and then prints out all prime
numbers up to that integer.
import java.io.*;
class Primenos
{
public static void main(String[] args) throws Exception
{
int n,fact;
System.out.println("Enter the range of Prime No U want");
DataInputStream dis=new DataInputStream(System.in);
n=Integer.parseInt(dis.readLine());
System.out.println("Prime No's from 1 to "+n+" is");
for(int i=1;i<=n;i++)
{
fact=1;
for(int x=1;x<i;x++)
if(i%x==0)
fact++;
if(fact==2)
System.out.print(i+"\t");
}
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
3. AIM: -Write a java program to implement callbyvalue and call byreference mechanisms.
Call By Value
OUTPUT: -
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
Call By Reference
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
4. AIM: - Write a Java Program that checks whether a given string is a palindrome or not.
PROGRAM: -
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( inti = length - 1; i>= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
5. AIM: - Write a Java Program to check the compatibility for multiplication, if compatible
multiply two matrices and find its transpose.
PROGRAM: -
import java.util.Scanner;
class Matrix
{
void matrixMul(int m, int n, int p, int q)
{
int[][] a,b,c,t;
a = new int[m][n];
b = new int[p][q];
c = new int[m][q];
t = new int[q][m];
Scanner s = new Scanner(System.in);
System.out.println("Enter the elements of matrix A: ");
for(int i = 0; i< m; i++)
{
for(int j = 0; j < n; j++)
{
a[i][j] = s.nextInt();
}
}
System.out.println("Enter the elements of matrix B: ");
for(int i = 0; i< p; i++)
{
for(int j = 0; j < q; j++)
{
b[i][j] = s.nextInt();
}
}
for(int i = 0; i< m; i++)
{
for(int j = 0; j < q; j++)
{
for(int k = 0; k < n; k++)
{
c[i][j] += a[i][k]*b[k][j];
}
}
}
System.out.println("Elements of result matrix C are: ");
for(int i = 0; i< m; i++)
{
for(int j = 0; j < q; j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.print("\n");
}
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
Constructor Overloading
Student(){
System.out.println("this a default constructor");
}
OUTPUT: -
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
Method Overloading
// Driver code
public static void main(String args[])
{
MethodOverloading s = new MethodOverloading();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
OUTPUT: -
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
7. AIM:- Write a Java Program that illustrates how runtime polymorphism is achieved
POLYMORPHISMEX-1
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
POLYMORPHISMEX-2
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
POLYMORPHISMEX-3
class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
PROGRAM-1
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
PROGRAM-2
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
PROGRAM-3
class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
PROGRAM-1
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
PROGRAM-2
// Print message
System.out.println("Hi Everyone");
}
// Method 2 - To show()
public void view()
{
// Print message
System.out.println("Hello");
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
10. AIM: - Write a Java Program, using String Tokenizer class, which reads a line of integers
and then displays each integer and the sum of all integers.
PROGRAM
import java.util.*;
class StringTokenDemo
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Enter a line of numbers: ");
String input = s.next();
StringTokenizerst = new StringTokenizer(input,"@");
int sum = 0;
while(st.hasMoreTokens())
{
int n = 0;
n = Integer.parseInt(st.nextToken());
System.out.println("Number is: "+n);
sum += n;
}
System.out.println("Sum of the numbers is: "+sum);
}
}
OUTPUT:-
11. AIM:- Write a Java Program that reads on file name form the user then displays
information about Whether the file exists, whether the file is readable/ writable, the type of
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
file and the length of the file in bytes and display the content of the using FileInputStream
class.
PROGRAM
import java.io.*;
import javax.swing.*;
class FileDemo
{
public static void main(String args[])
{
String filename = JOptionPane.showInputDialog("Enter filename: ");
File f = new File(filename);
System.out.println("File exists: "+f.exists());
System.out.println("File is readable: "+f.canRead());
System.out.println("File is writable: "+f.canWrite());
System.out.println("Is a directory: "+f.isDirectory());
System.out.println("length of the file: "+f.length()+" bytes");
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStreamfis = new FileInputStream(filename);
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
System.out.println("\nContents of the file are: ");
System.out.println(buff);
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOExceptioni)
{
System.out.println("Cannot read file...");
}
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
12. AIM:- Write a Java Program that displays the number of characters, lines and words in a
text/text file.
PROGRAM
import java.io.*;
class FileDemo
{
public static void main(String args[])
{
try
{
int lines=0,chars=0,words=0;
int code=0;
FileInputStreamfis = new FileInputStream("sample.txt");
while(fis.available()!=0)
{
code = fis.read();
if(code!=10)
chars++;
if(code==32)
words++;
if(code==13)
{
lines++;
words++;
}
}
System.out.println("No.of characters = "+chars);
System.out.println("No.of words = "+(words+1));
System.out.println("No.of lines = "+(lines+1));
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOExceptioni)
{
System.out.println("Cannot read file...");
}
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
13. AIM:- Write a Java Program to implement a Queue, using user defined Exception
Handling (also make use ofthrow, throws).
PROGRAM
import java.io.*;
class myException extends Exception
{ myException()
{ System.out.println("Error:Password too short");
}
myException(int n)
{ System.out.println("Error:Only adults can join");
}
}
class user_exception
{
public static void main(String s[]) throws IOException,myException
{ BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
try
String n=br.readLine();
String m=br.readLine();
if(m.length() <6)
int o=Integer.parseInt(br.readLine());
if(o<18)
catch(Exception e)
{ }
OUTPUT :-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
14. AIM:- Write a Java Program that creates 3 threads by extending Thread class. First thread
displays “Good Morning” every 1 sec, the second thread displays “Hello” every 2 seconds
and
the third displays“Welcome”every 3 seconds. (Repeat the same by implementing Runnable).
PROGRAM
OUTPUT :-
15. AIM:- Write a Java Program demonstrating the life cycle of a thread.
PROGRAM
import java.util.*;
class ChildThread implements Runnable
{
Thread t;
ChildThread()
{
t = new Thread(this);
System.out.println("Thread is in new state");
t.start();
}
public void run()
{
System.out.println("Thread is in runnable state");
Scanner s = new Scanner(System.in);
System.out.println("Thread entering blocked state");
System.out.print("Enter a string: ");
String str = s.next();
for(int i = 1; i<= 3; i++)
{
try
{
System.out.println("Thread suspended");
t.sleep(1000);
System.out.println("Thread is running");
}
catch(InterruptedException e)
{
System.out.println("Thread interrupted");
}
System.out.println("Thread terminated");
t.stop();
}
}
}
class Driver
{
public static void main(String[] args)
{
new ChildThread();
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
PROGRAM :
import java.applet.*;
import java.awt.*;
import java.io.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
String content = "";
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStreamfis = new FileInputStream("sample.txt");
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
fis.close();
content = new String(buff);
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOExceptioni)
{
System.out.println("Cannot read file...");
}
g.drawString(content,20,20);
}
}
/*
<applet code="MyApplet" height="300" width="500">
</applet>
*/
OUTPUT :
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
17. Aim: Write a Java Program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +-*?% operations. Add a text field to display the result
PROGRAM :
T1.addActionListener(this);
for(int i=0;i<10;i++) {
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++) {
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+")){
num1=Integer.parseInt (T1.getText());
Operation='+';
T1.setText ("");
}
if(str.equals("-")){
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*")){
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/")){
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
}
if(str.equals("%")){
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("=")) {
num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e) {
result=num2;
JOptionPane.showMessageDialog(this,"Divided by zero");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear")) {
T1.setText("");
}
}
}
OUTPUT :
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
18. AIM: Write a Java Program for handling mouse events, keyboard events.
PROGRAM :
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Handle mouse wheel moved.
public void mouseWheelMoved(MouseWheelEvent me) {
// show status
showStatus("Mouse Wheel Moving at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}
OUTPUT :
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
19. AIM :Write a Java Program that allows user to draw lines, rectangles and ovals.
PROGRAM :
import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*
</applet>
*/
{
public void paint(Graphics g)
super.paint(g);
g.setColor(Color.red);
g.drawLine(5,30,350,30);
g.setColor(Color.blue);
g.drawRect(5,40,90,55);
g.fillRect(100,40,90,55);
g.setColor(Color.cyan);
g.fillRoundRect(195,40,90,55,50,50);
g.drawRoundRect(290,40,90,55,20,20);
g.setColor(Color.yellow);
g.draw3DRect(5,100,90,55,true);
g.fill3DRect(100,100,90,55,false);
g.setColor(Color.magenta);
g.drawOval(195,100,90,55);
g.fillOval(290,100,90,55);
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
OUTPUT :
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22
20. AIM :Write a Java Program that lets users create Piecharts. Design your own user
interface (with Swings & AWT).
PROGRAM :
import java.awt.*;
import java.applet.*;
setBackground(Color.green);
g.drawString("PI CHART",200,40);
g.setColor(Color.blue);
g.fillOval(50,50,150,150);
g.setColor(Color.white);
g.drawString("40%",130,160);
g.setColor(Color.magenta);
g.fillArc(50,50,150,150,0,90);
g.setColor(Color.white);
g.drawString("25%",140,100);
g.setColor(Color.yellow);
g.fillArc(50,50,150,150,90,120);
g.setColor(Color.black);
g.drawString("35%",90,100);
g.setColor(Color.yellow);
g.fillOval(250,50,150,150);
g.setColor(Color.black);
g.drawString("15%",350,150);
g.setColor(Color.magenta);
g.fillArc(250,50,150,150,0,30);
g.setColor(Color.black);
g.drawString("5%",360,120);
g.setColor(Color.blue);
g.fillArc(250,50,150,150,30,120);
g.setColor(Color.white);
g.drawString("30%",330,100);
g.setColor(Color.black);
g.fillArc(250,50,150,150,120,180);
g.setColor(Color.white);
g.drawString("50%",280,160);
}
}
OUTPUT:-
ST.ANN’S COLLEGE OF ENGINEERING & TECHNOLOGY: CHIRALA
(AUTONOMOUS)
ECE - UG – R22