Lab Records With Solution
Lab Records With Solution
Lab Records With Solution
}
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;
}
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
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));
}
}
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);
}
}
}
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 ");
}
}
}
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{ 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>*/
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());
}
}
// 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>
*/
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