Lab Records With Solution

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

1. The Fibonacci sequence is defined by the following rule.

The first 2 values in the


sequence are 1, 1.Every subsequent value is the sum of the 2 values preceding it.
Write a Java Program that uses bothrecursive and non-recursivefunctionsto print
thenthvalueof theFibonacci sequence.
Answer:
import java.util.*;
class Function
{
void nrcf(int a,int b,int c,int n)
{
for(int i=1;i<=n-2;i++)
{
c=a+b;
a=b;
b=c;
}
a=b=1;
System.out.println("nth value in the series using non recursive
function is : "+c);

}
void rcf(int a,int b,int c,int n)
{

if(n-2>0)
{
c=a+b;
a=b;
b=c;
rcf(a,b,c,n-1);
return;
}

System.out.println("\nnth value in the series using recursive


function is : "+c);
}
}

class Fibonacci
{
public static void main(String args[])
{
Function f=new Function();
int n,a=1,b=1,c=0;
Scanner scr=new Scanner(System.in);
System.out.println("\nEnter n value: ");
n=scr.nextInt();
f.nrcf(a,b,c,n);
f.rcf(a,b,c,n);
}
}
2. Write a Java Program that prompts the user for an integer and then prints out all
the prime numbers uptothat integer.
Answer:
import java.util.Scanner;
class PrimeNumbers
{
public static void main(String[] args)
{
int n;
int p;
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
n=s.nextInt();
for(int i=2;i<n;i++)
{
p=0;
for(int j=2;j<=i/2;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
System.out.println(i);
}
}
}
3. Writeajavaprogramtoimplement callbyvalue andcall byreferencemechanisms.
Answer:
public class CallByValue
{
public static void main(String[] args)
{
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same
here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b)
{
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}

CallByReference Example

public class CallByReference


{
public static void main(String[] args)
{
IntWrapper a = new IntWrapper(30);
IntWrapper b = new IntWrapper(45);
System.out.println("Before swapping, a = " + a.a + " and b = " + b.a);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be
different here**:");
System.out.println("After swapping, a = " + a.a + " and b is " + b.a);
}
public static void swapFunction(IntWrapper a, IntWrapper b)
{
System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a);
// Swap n1 with n2
IntWrapper c = new IntWrapper(a.a);
a.a = b.a;
b.a = c.a;
System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a);
}
}
class IntWrapper {
public int a;
public IntWrapper(int a){ this.a = a;}
}

4. WriteaJavaProgram thatchecks whether agivenstringis apalindromeornot.


Answer:
import java.util.*;
public class Palindrome
{
public static void main(String args[])
{
String a, b = "";
Scanner s = new Scanner(System.in);
System.out.print("Enter the string you want to check:");
a = s.nextLine();
int n = a.length();
for(int i = n - 1; i >= 0; i--)
{
b = b + a.charAt(i);
}
if(a.equalsIgnoreCase(b))
{
System.out.println("The string is palindrome.");
}
else
{
System.out.println("The string is not palindrome.");
}
}
}
5. WriteaJavaProgramtocheckthecompatibilityformultiplication,ifcompatiblemultiply
twomatricesand find its transpose.
Answer:
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");
}
for(int i = 0; i < q; i++)
{
for(int j = 0; j < m; j++)
{
t[i][j] = c[j][i];
}
}
System.out.println("Elements of transpose matrix T are: ");
for(int i = 0; i < q; i++)
{
for(int j = 0; j < m; j++)
{
System.out.print(t[i][j]+"\t");
}
System.out.print("\n");
}
}
}
class TransposeMatrix
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter no of rows in first matrix: ");
int m = s.nextInt();
System.out.println("Enter no of columns in first matrix: ");
int n = s.nextInt();
System.out.println("Enter no of rows in second matrix: ");
int p = s.nextInt();
System.out.println("Enter no of columns in second matrix: ");
int q = s.nextInt();
if(n == p)
{
Matrix obj = new Matrix();
obj.matrixMul(m,n,p,q);
}
else
{
System.out.println("Matrix multiplication cannot be
performed...");
}
}
}
6. WriteaJavaprogram toimplementconstructor overloadingandmethodoverloading.
Answer:
Constructor Overloading
public class ConstructorOverloading
{
//instance variables of the class
int id;
String name;
ConstructorOverloading()
{
System.out.println("this a zero argument constructor");
id=1;
name="john";
}
ConstructorOverloading(int i, String n)
{
id = i;
name = n;
}
public static void main(String[] args)
{
//object creation
ConstructorOverloading s = new ConstructorOverloading();
System.out.println("\nZero Argument Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);

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


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

Method Overloading
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
static float add(float a,float b)
{
return a+b;
}
static float add(int a,float b)
{
return a+b;
}
static float add(float a,int b)
{
return a+b;
}
}
class MethodOverloading
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
System.out.println(Adder.add(11.55f,2.66f));
System.out.println(Adder.add(10,5.66f));
System.out.println(Adder.add(10.56f,11));
}
}

7. WriteaJavaProgram thatillustrates howruntimepolymorphismis achieved.


Answer:
abstract class Figure
{
int dim1, dim2;
Figure(int x, int y)
{
dim1 = x;
dim2 = y;
}
abstract void area();
}
class Triangle extends Figure
{
Triangle(int x, int y)
{
super(x,y);
}
void area()
{
System.out.println("Area of triangle is: "+(dim1*dim2)/2);
}
}
class Rectangle extends Figure
{
Rectangle(int x, int y)
{
super(x,y);
}
void area()
{
System.out.println("Area of rectangle is: "+(dim1*dim2));
}
}
class RuntimePoly
{
public static void main(String args[])
{
Figure f;
Triangle t = new Triangle(20,30);
Rectangle r = new Rectangle(20,30);
f = t;
f.area();
f = r;
f.area();
}
}
8. WriteaJavaProgramthat illustratestheuseof superkeyword.
Answer:
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();
}
}

9. WriteaJavaProgramtocreateanddemonstrate packages.
Answer:
package FirstPackage;
 
// Class in which the above created package belong to
class Welcome {
    // main driver method
    public static void main(String[] args)
    {
        // Print statement for the successful
        // compilation and execution of the program
        System.out.println(
            "This Is The First Program Geeks For Geeks..");
    }
}
Command: javac -d . Welcome.java
Command: java FirstPackage.Welcome

10. Write a Java Program, using String Tokenizer class, which reads a line of
integers and then displayseachinteger and the sumof all integers.
Answer:
import java.util.*;
 
class StringTokenizerDemo {
    public static void main(String args[]) {
        int n;
        int sum = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter integers with one space gap:");
        String s = sc.nextLine();
        StringTokenizer st = new StringTokenizer(s, " ");
        while (st.hasMoreTokens()) {
            String temp = st.nextToken();
            n = Integer.parseInt(temp);
            System.out.println(n);
            sum = sum + n;
        }
        System.out.println("sum of the integers is: " + sum);
        sc.close();
    }
}

11. Write a Java Program that reads on file name form the user then displays
information about whetherthe file exists, whether the file is readable/ writable, the
type of file and the length of the file in bytesanddisplay thecontent of theusing
FileInputStream class.
Answer:
import java.io.*;
class filedemo
{
public static void p(String str)
{
System.out.println(str);
}
public static void analyze(String s)
{
File f=new File(s);
if(f.exists())
{
p(f.getName()+" is a file");
p(f.canRead()?" is readable":" is not readable");
p(f.canWrite()?" is writable":" is not writable");
p("Filesize:"+f.length()+" bytes");
p("File last mdified:"+f.lastModified());
}
if(f.isDirectory())
{
p(f.getName()+" is directory");
p("List of files");
String dir[]=f.list();
for(int i=0;i<dir.length;i++)
p(dir[i]);
}
}

}
public class FileDetails
{
public static void main(String rr[])throws IOException
{
filedemo fd=new filedemo();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the file name:");
String s=br.readLine();
fd.analyze(s);
}
}

12. WriteaJavaProgramthatdisplays thenumber of characters,linesand


wordsinatext/textfile.
Answer:
import java.util.*;
import java.io.*;
class CFile
{
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);

}
}

13. Write a Java Program to implement a Queue, using user defined Exception
Handling (also make use ofthrow, throws).
Answer:
import java.util.*;
import java.lang.*;
class QueueError extends Exception
{
public QueueError(String msg)
{
super(msg);
}
}
class Que
{
private int size;
private int front = -1;
private int rear = -1;
private Integer[] queArr;
public Que(int size)
{
this.size = size;
queArr = new Integer[size];
}
public void insert(int item) throws Exception,QueueError
{
try
{
if(rear == size-1)
{
throw new QueueError("Queue Overflow");
}
else if(front==-1)
{
rear++;
queArr[rear] = item;
front = rear;
}
else
{
rear++;
queArr[rear] = item;
}
}
catch(QueueError qe)
{
qe.printStackTrace();
}
}
public void delete() throws Exception,QueueError
{
try
{
if(front == -1)
{
throw new QueueError("Queue Underflow");
}
else if(front==rear)
{
System.out.println("\nRemoved "+queArr[front]+" from Queue");
queArr[front] = null;
front--;
rear--;
}
else
{
System.out.println("\nRemoved "+queArr[front]+" from Queue");
queArr[front] = null;
for(int i=front+1;i<=rear;i++)
{
queArr[i-1]=queArr[i];
}
rear--;
}
}
catch(QueueError qe)
{
qe.printStackTrace();
}
}
public void display() throws Exception,QueueError
{
try
{
if(front==-1)
throw new QueueError("Queue is Empty");
else
{
System.out.print("\nQueue is: ");
for(int i=front;i<=rear;i++)
{
System.out.print(queArr[i]+"\t");
}
System.out.println();
}
}
catch(QueueError qe)
{
qe.printStackTrace();
}
}
}
class QueueEx
{
public static void main(String[] args) throws Exception,QueueError
{
System.out.println("\n\n\tQueue test using Array\n\n");
Scanner scan = new Scanner(System.in);
System.out.print("Enter size of Queue array: ");
int size = scan.nextInt();
Que que = new Que(size);
char ch;
try
{
while(true)
{
System.out.println("\n\n\tQueue operations \n");
System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Display");
System.out.println("4. Exit\n");
System.out.print("Enter your choice: ");
int choice = scan.nextInt();
switch(choice)
{
case 1: System.out.print("\nEnter integer number to insert:");
que.insert(scan.nextInt());
break;
case 2:que.delete();
break;
case 3:que.display();
break;
case 4:return ;
}
}
}
catch(QueueError qe)
{
qe.printStackTrace();
}
}
}

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
thesamebyimplementingRunnable).
Answer:
import java.io.*;
class One extends Thread
{
public void run()
{
for(int i=0;i<100;i++)
{
try{
Thread.sleep(1000); }
catch(InterruptedException e){
System.out.println(e); }
System.out.println("Good Morning");
}
}
}
class Two extends Thread
{
public void run()
{
for(int i=0;i<100;i++)
{
try{
Thread.sleep(2000); }
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("Hello ");
}
}
}

class Three implements Runnable


{
public void run()
{
for(int i=0;i<100;i++)
{
try{
Thread.sleep(3000); }
catch(InterruptedException e){
System.out.println(e); }
System.out.println("Welcome");
}
}
}
class ThreadEx
{
public static void main(String[] args)
{
One t1=new One();
Two t2=new Two();
Three tt=new Three();
Thread t3=new Thread(tt);
t1.setName("One");
t2.setName("Two");
t3.setName("Three");
System.out.println(t1);
System.out.println(t2);
System.out.println(t3);
Thread t=Thread.currentThread();
System.out.println(t);
t1.start();t2.start();t3.start();
}
}
15. WriteaJavaProgram demonstratingthe lifecycleofathread.
Answer:
class A1 extends Thread {
public void run() {
System.out.println("Thread A");
System.out.println("i in Thread A ");
for (int i = 1; i <= 5; i++) {
System.out.println("i = " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread A Completed.");
}
}
class B extends Thread {
public void run() {
System.out.println("Thread B");
System.out.println("i in Thread B ");
for (int i = 1; i <= 5; i++) {
System.out.println("i = " + i);
}
System.out.println("Thread B Completed.");
}
}
public class ThreadLifeCycleDemo {
public static void main(String[] args) {
// life cycle of Thread
// Thread's New State
A1 threadA = new A1();
B threadB = new B();
// Both the above threads are in runnable state
// Running state of thread A & B
threadA.start();
// Move control to another thread
threadA.yield();
// Blocked State of thread B
try {
threadA.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadB.start();
System.out.println("Main Thread End");
}
}

16. Write an Applet that displays the content of a file.


Answer:
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("");
FileInputStream fis = 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(IOException i)
{
System.out.println("Cannot read file...");
}
g.drawString(content,20,20);
}
}
/*
<applet code="MyApplet" height="300" width="500">
</applet>
*/
Command:javac MyApplet.java
Command:appletviewer MyApplet.java
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 atext field to
display the result
Answer:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Calculator1" width=300 height=300></applet>*/
public class Calculator1 extends Applet implements ActionListener
{
TextField t;
Button b[]=new Button[15];
Button b1[]=new Button[6];
String op2[]={"+","-","*","%","=","C"};
String str1="";
int p=0,q=0;
String oper;
public void init()
{
setLayout(new GridLayout(5,4));
t=new TextField(20);
setBackground(Color.pink);
setFont(new Font("Arial",Font.BOLD,20));
int k=0;
t.setEditable(false);
t.setBackground(Color.white);
t.setText("0");
for(int i=0;i<10;i++)
{
b[i]=new Button(""+k);
add(b[i]);
k++;
b[i].setBackground(Color.pink);
b[i].addActionListener(this);
}

for(int i=0;i<6;i++)
{
b1[i]=new Button(""+op2[i]);
add(b1[i]);
b1[i].setBackground(Color.pink);
b1[i].addActionListener(this);
}
add(t);
}
public void actionPerformed(ActionEvent ae)
{

String str=ae.getActionCommand();

if(str.equals("+")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("-")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("*")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("%")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("=")) { str1="";
if(oper.equals("+")) {
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p+q)));}

else if(oper.equals("-")) {
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p-q))); }

else if(oper.equals("*")){
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p*q))); }
else if(oper.equals("%")){
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p%q))); }
}

else if(str.equals("C")){ p=0;q=0;


t.setText("");
str1="";
t.setText("0");
}

else{ t.setText(str1.concat(str));
str1=t.getText();
}

}
Command1:javac Calculator1.java
Command2:appletviewer Calculator1.java

18. Writea Java Program for handling mouse events, keyboard events.
Answer:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="MouseEvents" width=300 height=100></applet>*/

public class MouseEvents extends Applet implements MouseListener,


MouseMotionListener,MouseWheelListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(this);
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}

// Handle mouse entered.


public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";

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
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);
}
}
Command1:javac MouseEvents.java
Command2:appletviewer MouseEvents.java

19. Write a Java Program that allows user to draw lines, rectangles and ovals.
Answer:
import java.applet.*;

import java.awt.*;

import javax.swing.*;

/*

<applet code="Lro" height="400" width="500" border="1">

</applet>

*/

public class Lro extends JApplet

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

}
Command1:javac Lro.java
Command2:appletviewer Lro.java

20. Write a Java Program that lets users create Piecharts. Design your own user
interface (with Swings & AWT).
Answer:
import java.applet.*;
import java.awt.*;
public class Pie_Chart extends Applet
{
int[] data_values;
Color[] data_clr;
int total;
//Function to create a data set
public void init()
{
setBackground(Color.white);
//Create a data set to represent in pie-chart
data_values=new int[]{10,25,12,15,15,18,5};
data_clr=new Color[]{Color.red,Color.blue,Color.green,Color.yellow,
Color.orange,Color.black,Color.white};
}
//Function to get the sum of all data values
public void start()
{
int n = data_values.length;
int i;
total=0;
for(i=0;i<n;i++)
{
total+=data_values[i];
}
}
//Function to draw the pie chart
public void paint(Graphics g)
{
int i;
int start_angle = 0;
for(i=0;i<data_values.length;i++)
{
int arc_angle = (int)(data_values[i]*360 / total);
g.drawArc(100,100,300,300,start_angle,arc_angle);
g.setColor(data_clr[i]);
g.fillArc(100,100,300,300,start_angle,arc_angle);
start_angle+=arc_angle;
}
}
}
/*
<applet code = Pie_Chart.class width=500 height=500>
</applet>
*/
Command1:javac Pie_Chart.java
Command2:appletviewer Pie_Chart.java

You might also like