CHAITANYA ENGINEERING COLLEGE
KOMMADI, VISAKHAPATNAM
(Approved by AICTE, New Delhi & Affiliated to JNTU Gurajada Vizianagaram)
NBA & NAAC Accredited
JAVA PROGRAMMING LAB MANUAL
For
MCA I YEAR I SEMESTER
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CHAITANYAVALLEY, KOMMADI, MADHURWADA, VISAKHAPATNAM-530048
CHAITANYA ENGINEERING COLLEGE
CHAITANYAVALLEY, KOMMADI, MADHURWADA, VISAKHAPATNAM-530048
CERTIFICATE
This is to certify that
is a student studying
PIN NO. branch has done
no. of experiments during the year
in the subject
Head of Department External Examiner Lecture-in-charge
INDEX
EXP.NO. CONTENTS DATE PAGE
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 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 up to that Integer.
3. Write a Java Program that checks whether a given string is a
palindrome or not. Ex. MALAYALAM is a palindrome
4. Write a Java Program for sorting a given list of names in
ascending order.
5. Write a Java Program that illustrates how runtime
polymorphism is achieved.
6. Write a Java Program to create and demonstrate packages.
7. Write a Java Program, using StringTokenizer class, which
reads a line of integers and then displays each integer and the
sum of all integers.
8. 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 FileInputStream class.
9. Write a Java Program that displays the number of
characters, lines and words in a text/text file.
10. Write an Applet that displays the content of a file.
11. 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.
12. Write a Java Program for handling mouse events.
13. Write a Java Program demonstrating the life cycle of a
thread.
14. Write a Java Program that lets users create Pie charts. Design
your own user interface (with Swings& AWT).
15. Write a Java Program to implement a Queue, using user
defined Exception Handling (also make use of throw,
throws).
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 both recursive and non recursive functions to print the nth value of the Fibonacci
sequence.
Without Recursion
class FibonacciExample1{
public static void main(String args[])
{
int n1=1,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 1 and 1
for(i=2;i<count;++i)//loop starts from 2 because 1 and 1 are already printed
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}
Output:
D:\maha>javac FibonacciExample1.java
D:\maha>java FibonacciExample1
1 1 2 3 5 8 13 21 34 55
With Recursion
class FibonacciExample2{
static int n1=1,n2=1,n3=0;
static void printFibonacci(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
}
}
public static void main(String args[]){
int count=10;
System.out.print(n1+" "+n2);//printing 1 and 1
printFibonacci(count-2);//n-2 because 2 numbers are already printed
}
}
Output:
D:\maha>javac FibonacciExample2.java
D:\maha>java FibonacciExample2
1 1 2 3 5 8 13 21 34 55
2. Write a Java Program that prompts the user for an integer and then prints out all the
prime numbers up to that Integer.
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;j++){
if(i%j==0)
p=1;
}
if(p==0)
System.out.println(i);
}
}
}
Output:
D:\maha>javac PrimeNumbers.java
D:\maha>java PrimeNumbers
Enter a number:
20
prime numbers are:2
prime numbers are:3
prime numbers are:5
prime numbers are:7
prime numbers are:11
prime numbers are:13
prime numbers are:17
prime numbers are:19
3. Write a Java Program that checks whether a given string is a palindrome or not. Ex.
MALAYALAM is a palindrome
import java.util.Scanner;
class ChkPalindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
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 not a palindrome");
}
}
Output:
D:\maha>javac ChkPalindrome.java
D:\maha>java ChkPalindrome
Enter a string:
maha
maha is not a palindrome
D:\maha>javac ChkPalindrome.java
D:\maha>java ChkPalindrome
Enter a string:
malayalam
malayalam is a palindrome
4. Write a Java Program for sorting a given list of names in ascending order.
import java.util.Scanner;
public class Ascending_Order
{
public static void main(String[] args)
{
int n;
String temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
n = s.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{
names[i] = s1.nextLine();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
}
Output:
D:\maha>javac Ascending_Order.java
D:\maha>java Ascending_Order
Enter number of names you want to enter:4
Enter all the names:
satish
yoshitha
maha
mani
Names in Sorted Order:maha,mani,satish,yoshitha
5. Write a Java Program that illustrates how runtime polymorphism is achieved.
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing a square");
}
}
public class Poly_example {
public static void main(String[] args) {
Shape s1 = new Circle();
Shape s2 = new Square();
s1.draw(); // Calls draw() of Circle class
s2.draw(); // Calls draw() of Square class
}
}
Output:
D:\maha>javac Poly_example.java
D:\maha>java Poly_example
Drawing a circle
Drawing a square
6. Write a Java Program to create and demonstrate packages.
(i) Creating a package:
Steps:
1. First declare the name of the package using package keyword
Example: package mypack;
2. Type the following SOURCE-CODE under this package statement. In package : class
data, methods all are public
package mypack
public class box
{
public int
l=10,b=20;
public void
display()
{
System.out.println(l);
System.out.println(b);
}
}
3. Create sub directory with a name same that of package name under the current working
directory by as follows. d:\>md mypack
4. Under this subdirectory store the above SOURCE-CODE with a file name “box.java”.
(ii) importing a package:
Steps:
1. packages can be accessed by using the import statement
General form: import pack1[.pack2].(classname/*);Example:
import java.io.*;
Here pack1 is name of top level package and pack2 is name of sub package
2. Type the following SOURCE-CODE under the current working directory and save the
SOURCE-CODE with a file name “example.java”.
import
mypack.bo
x;class
packagede
mo
{
public static void main(String args[])
{
box
b1=new
box();
b1.display(
);
}
}
3. Now compile the above SOURCE-CODE in the current working directory d:\
javac packagedemo.java
4. Execute the above SOURCE-CODE in current working directory
java packagedemo
OUT-PUT:
10
20
7. Write a Java Program, using StringTokenizer class, which reads a line of integers and
then displays each integer and the sum of all integers.
import java.util.*;
class Demo_string_tokenizer{
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();
}
}
Output:
D:\maha>javac Demo_string_tokenizer.java
D:\maha>java Demo_string_tokenizer
Enter integers with one space gap:
21
2
1
sum of the integers is: 3
8.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 FileInputStream class.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Files_example {
public static void main(String args[]) {
//Creating a Path object
Path path = Paths.get("D:/maha/sample.txt");
//Verifying if the file is readable
boolean bool = Files.isReadable(path);
if(bool) {
System.out.println("readable");
} else {
System.out.println("not readable");
}
bool = Files.isWritable(path);
if(bool) {
System.out.println("writable");
} else {
System.out.println("not writable");
}
bool = Files.isExecutable(path);
if(bool) {
System.out.println("executable");
} else {
System.out.println("not executable");
}
}
}
Output:
D:\maha>javac Files_example.java
D:\maha>java Files_example
not readable
not writable
not executable
9. Write a Java Program that displays the number of characters, lines and words in a
text/text file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Word_countin_file
{
public static void main(String[] args)
{
BufferedReader reader = null;
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
try
{
reader = new BufferedReader(new FileReader("D:/maha/sample.txt"));
String currentLine = reader.readLine();
while (currentLine != null)
{
lineCount++;
String[] words = currentLine.split(" ");
wordCount = wordCount + words.length;
for (String word : words){
charCount = charCount + word.length();
}
currentLine = reader.readLine();
}
System.out.println("Number Of Chars In A File : "+charCount);
System.out.println("Number Of Words In A File : "+wordCount);
System.out.println("Number Of Lines In A File : "+lineCount);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
reader.close(); //Closing the reader
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output:
D:\maha>javac Word_countin_file.java
D:\maha>java Word_countin_file
Number Of Chars In A File : 86
Number Of Words In A File : 14
Number Of Lines In A File : 4
10. Write an Applet that displays the content of a file.
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>
Output:
11. 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.
import java.awt.*;
import java.awt.event.*;
public class MyCalculator extends Frame implements ActionListener {
double num1,num2,result;
Label lbl1,lbl2,lbl3;
TextField tf1,tf2,tf3;
Button btn1,btn2,btn3,btn4;
char op;
MyCalculator() {
lbl1=new Label("Number 1: ");
lbl1.setBounds(50,100,100,30);
tf1=new TextField();
tf1.setBounds(160,100,100,30);
lbl2=new Label("Number 2: ");
lbl2.setBounds(50,170,100,30);
tf2=new TextField();
tf2.setBounds(160,170,100,30);
btn1=new Button("+");
btn1.setBounds(50,250,40,40);
btn2=new Button("-");
btn2.setBounds(120,250,40,40);
btn3=new Button("*");
btn3.setBounds(190,250,40,40);
btn4=new Button("/");
btn4.setBounds(260,250,40,40);
lbl3=new Label("Result : ");
lbl3.setBounds(50,320,100,30);
tf3=new TextField();
tf3.setBounds(160,320,100,30);
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);
add(lbl1); add(lbl2); add(lbl3);
add(tf1); add(tf2); add(tf3);
add(btn1); add(btn2); add(btn3); add(btn4);
setSize(400,500);
setLayout(null);
setTitle("Calculator");
setVisible(true);
public void actionPerformed(ActionEvent ae) {
num1 = Double.parseDouble(tf1.getText());
num2 = Double.parseDouble(tf2.getText());
if(ae.getSource() == btn1)
{
result = num1 + num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn2)
{
result = num1 - num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn3)
{
result = num1 * num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn4)
{
result = num1 / num2;
tf3.setText(String.valueOf(result));
}
}
public static void main(String args[]) {
MyCalculator calc=new MyCalculator();
}
}
Output:
D:\maha>javac MyCalculator.java
D:\maha>java MyCalculator
12. Write a Java Program for handling mouse events.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Mouse_Event implements MouseListener,ActionListener
{
static JFrame frame;
static JTextField text;
//Driver function
public static void main(String[] args)
{
frame=new JFrame("Mouse Event");
frame.setBackground(Color.white);
frame.setSize(500,500);
frame.setLayout(null);
//Create a TextField
text=new JTextField();
text.setBounds(0,0,500,50);
frame.add(text);
//Create a exit button to close the frame
JButton exit=new JButton("Exit");
exit.setBounds(220,235,60,30);
frame.add(exit);
//Create an object of the class Mouse_Event
Mouse_Event obj=new Mouse_Event();
//Associate MouseListener with the frame
frame.addMouseListener(obj);
//Associate ActionListener with button exit
exit.addActionListener(obj);
//Display frame
frame.setVisible(true);
}
//function to dispose the frame on click of exit button
@Override
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
//function to get co-ordinates from where cursor entered the frame
@Override
public void mouseEntered(MouseEvent e)
{
text.setText("");
text.setText("Mouse Entered the frame from point ");
text.setText(text.getText()+e.getX()+" "+e.getY());
}
//function to get co-ordinates from where cursor exited the frame
@Override
public void mouseExited(MouseEvent e)
{
text.setText("");
text.setText("Mouse Exited the frame from point ");
text.setText(text.getText()+e.getX()+" "+e.getY());
}
//function to get co-ordinates where mouse was released
@Override
public void mouseReleased(MouseEvent e)
{
text.setText("");
String button="Right";
if(e.getButton()==MouseEvent.BUTTON1)
button="Left";
text.setText(button+" Button Released at point ");
text.setText(text.getText()+e.getX()+" "+e.getY());
}
//function to get co-ordinates where and which button of mouse was pressed
@Override
public void mousePressed(MouseEvent e)
{
text.setText("");
String button="Right";
if(e.getButton()==MouseEvent.BUTTON1)
button="Left";
text.setText(button+" Button Pressed at point ");
text.setText(text.getText()+e.getX()+" "+e.getY());
}
//function to get co-ordinates where and which button of mouse was clicked
@Override
public void mouseClicked(MouseEvent e)
{
text.setText("");
String button="Right";
if(e.getButton()==MouseEvent.BUTTON1)
button="Left";
text.setText(button+" Button Clicked at point ");
text.setText(text.getText()+e.getX()+" "+e.getY());
}
}
Output:
D:\maha>javac Mouse_Event.java
D:\maha>java Mouse_Event
13. Write a Java Program demonstrating the life cycle of a thread.
class MyThread implements Runnable {
@Override
public void run() {
try {
// Running state
System.out.println(Thread.currentThread().getName() + " is RUNNING");
// Simulating waiting state using sleep
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " is in WAITING/SLEEPING");
synchronized (this) {
// Simulating timed waiting state using wait with timeout
wait(1000);
System.out.println(Thread.currentThread().getName() + " is in TIMED_WAITING");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// Thread terminates, moves to TERMINATED state
System.out.println(Thread.currentThread().getName() + " is TERMINATED");
}
}
public class ThreadStatesDemo {
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread, "MyThread");
// New state
System.out.println(thread.getName() + " is in NEW state");
// Starting the thread, moves to RUNNABLE
thread.start();
System.out.println(thread.getName() + " is RUNNABLE");
// Main thread waits for the child thread to finish
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
D:\maha>javac ThreadStatesDemo.java
D:\maha>java ThreadStatesDemo
MyThread is in NEW state
MyThread is RUNNABLE
MyThread is RUNNING
MyThread is in WAITING/SLEEPING
MyThread is in TIMED_WAITING
MyThread is TERMINATED
14. Write a Java Program that lets users create Pie charts. Design your own user interface
(with Swings& AWT).
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
class Slice {
double value;
Color color;
public Slice(double value, Color color) {
this.value = value;
this.color = color;
}
}
class MyComponent extends JComponent {
Slice[] slices = {
new Slice(5, Color.black), new Slice(33, Color.green), new Slice(20, Color.yellow), new
Slice(15, Color.red)
};
MyComponent() {}
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), slices);
}
void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {
double total = 0.0D;
for (int i = 0; i < slices.length; i++) {
total += slices[i].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i < slices.length; i++) {
startAngle = (int) (curValue * 360 / total);
int arcAngle = (int) (slices[i].value * 360 / total);
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
curValue += slices[i].value;
}
}
}
public class Frame_pie {
public static void main(String[] argv) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MyComponent());
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Output:
D:\maha>javac Frame_pie.java
D:\maha>java Frame_pie
15. Write a Java Program to implement a Queue, using user defined Exception Handling
(also make use of throw, throws).
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 Exception_queue
{
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();
}
}
}
Output:
D:\maha>javac Exception_queue.java
D:\maha>java Exception_queue
Queue test using Array
Enter size of Queue array: 4
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter integer number to insert:23
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 3
Queue is: 23
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 2
Removed 23 from Queue
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 23
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 3
QueueError: Queue is Empty
at Que.display(Exception_queue.java:81)
at Exception_queue.main(Exception_queue.java:126)
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 4