[Go to site: main page, start]

0% found this document useful (0 votes)
95 views17 pages

Java Programming Lab Experiments

The document provides the details of 10 programming assignments for a Java programming lab. The assignments include: 1) Writing programs to calculate the Fibonacci sequence recursively and iteratively. 2) Writing a program to find all prime numbers up to a given integer. 3) Writing a program to check if a string is a palindrome. 4) Writing a program to sort a list of names in ascending order. 5) Demonstrating method overriding to achieve runtime polymorphism. 6) Creating and using packages in Java programs. 7) Writing a program to read integers from a line and display their sum. 8) Writing a program to get file details like name

Uploaded by

Anuradha Patnala
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views17 pages

Java Programming Lab Experiments

The document provides the details of 10 programming assignments for a Java programming lab. The assignments include: 1) Writing programs to calculate the Fibonacci sequence recursively and iteratively. 2) Writing a program to find all prime numbers up to a given integer. 3) Writing a program to check if a string is a palindrome. 4) Writing a program to sort a list of names in ascending order. 5) Demonstrating method overriding to achieve runtime polymorphism. 6) Creating and using packages in Java programs. 7) Writing a program to read integers from a line and display their sum. 8) Writing a program to get file details like name

Uploaded by

Anuradha Patnala
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MCA R20 Batch (1st Year 1st Semester)

Java Programming Lab

----------------------------------------------------------------------------------------------------

List of Experiments :-
1) Write a Java Program that uses both recursive and non recursive functions to print the
nth value of the Fibonacci sequence. (Fibonacci Sequence is 1 1 2 3 5 8 13 21 34…)

Program:- [Link]

import [Link];

class p1
{
public static void main(String args[ ])
{
[Link]("Enter a Number : ");
Scanner obj=new Scanner([Link]);
int a=[Link]();
x obj1=new x();
int b=[Link](a);
[Link]("The "+a+"th Number of the Fibonacci sequence is : "+b);
}
}

class x
{
int a=1;
int b=1;
int c=0;
int count;
int input(int a)
{
count=a;
count=fib(count);
return count;
}

int fib(int count)


{
if(count!=2)
{
c=a+b;
a=b;
b=c;
fib(--count);
}
return c;
}
}

---------------------------------------------------------------------------------------------------------------------

2) Write a Java Program that prompts the user for an integer and then prints out all the
prime numbers up to that Integer. (Prime Number sequence is 2 3 5 7 11 13 17 19…)

Program:- [Link]

import [Link];

class p2
{
public static void main(String args[ ])
{
int n;
int p;
Scanner s=new Scanner([Link]);
[Link]("Enter a Number : ");
n=[Link]();
[Link]("Prime Numbers upto "+n+" are");
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)
[Link](i);
}
}
}

---------------------------------------------------------------------------------------------------------------------

3) Write a Java Program that checks whether a given string is a palindrome or not.
(Palindrome is “abba”, “abcdcba”, “madam”, “level”, “radar”, “mom”, “refer”,….)

Program:- [Link]

import [Link];

class p3
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner([Link]);

[Link]("Enter a String : ");


str = [Link]();

int length = [Link]();

for ( int i = length - 1; i >= 0; i-- )


rev = rev + [Link](i);

if ([Link](rev))
[Link](str+" is a Palindrome");
else
[Link](str+" is Not a Palindrome");

}
}

---------------------------------------------------------------------------------------------------------------------

4) Write a Java Program for sorting a given list of names in ascending order.
Program:- [Link]

import [Link];

class Sorting
{
void sortStrings()
{
Scanner s = new Scanner([Link]);
[Link]("How many Names you want to Sort : ");
int n = [Link]();
String[] str = new String[n];
[Link]("Enter the Names : ");
for(int i = 0; i < n; i++)
{
str[i] = new String([Link]());
}
for(int i = 0; i < n; i++)
{
for(int j = i+1; j < n; j++)
{
if(str[i].compareTo(str[j])>0)
{
String temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
[Link]("\nSorted list of Names in Ascending Order :");
for(int i = 0; i < n ; i++)
{
[Link](str[i]);
}
}
}
class p4
{
public static void main(String args[])
{
Sorting obj = new Sorting();
[Link]();
}
}

---------------------------------------------------------------------------------------------------------------------

5) Write a Java Program that illustrates how runtime polymorphism is achieved. (Method
Overriding)

Program:-[Link]

public class p5
{
public static void main(String[] args)
{
Boy obj1 = new Boy();
[Link]();
}
}

class Human
{
public void eat()
{
[Link]("Human is eating");
}
}

class Boy extends Human


{
public void eat()
{
[Link]();
[Link]("Boy is eating");
}
}

---------------------------------------------------------------------------------------------------------------------

6) Write a Java Program to create and demonstrate packages.


Program 1:- [Link]

package pack; // Creates a Package pack

public class p6a


{
public void m1(int a, int b)
{
int c=a+b;
[Link]("Addition Value :" + c);
}
}

Program 2:- [Link]

import pack.p6a; //importing the Package pack and class p6a

import [Link];

public class p6b


{
public static void main(String args[])
{
p6a obj=new p6a();
Scanner s=new Scanner([Link]);
[Link]("Enter a Number 1 : ");
int n1=[Link]();
[Link]("Enter a Number 2 : ");
int n2=[Link]();
obj.m1(n1,n2);
}
}

---------------------------------------------------------------------------------------------------------------------
Note:
Compile package program with -d (it represents destination directory) and .(it represents the
current folder/Path also can be mentioned in place of “.”). Eg:- javac -d . <[Link]>

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.
Program:-[Link]

import [Link];
import [Link];

class p7
{
public static void main(String args[])
{
int n;
int sum = 0;
Scanner sc = new Scanner([Link]);
[Link]("Enter integers with one space gap : ");
String s = [Link]();
StringTokenizer st = new StringTokenizer(s, " ");
[Link]("Integers are..");
while ([Link]())
{
String temp = [Link]();
n = [Link](temp);
[Link](n);
sum = sum + n;
}
[Link]("Sum of all integers : " + sum);
[Link]();
}
}

---------------------------------------------------------------------------------------------------------------------

8) Write a Java Program that reads a file name from the user and 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.

Program:-[Link]

import [Link];

class p8
{
static void p(String s)
{
[Link](s);
}

public static void main(String args[ ])


{
File f1 = new File(args[0]);
p("File Name: " + [Link]());
p("Abs Path: " + [Link]());
p([Link]() ? "exists" : "does not exist");
p([Link]() ? "is writeable" : "is not writeable");
p([Link]() ? "is readable" : "is not readable");
p("is " + ([Link]() ? "" : "not" + " a directory"));
p([Link]() ? "is normal file" : "might be a named pipe");
p([Link]() ? "is absolute" : "is not absolute");
p("File size: " + [Link]() + " Bytes");
}
}

---------------------------------------------------------------------------------------------------------------------

9) Write a Java Program that displays the number of characters, lines and words in a
text/text file.

Program1:-[Link] (Save in the Same directory of the related Java File)

my name
is
Pradeep

Program2: [Link]

import [Link].*;
import [Link].*;

class p9
{
public static void main(String args[ ])throws IOException
{
int nl=1,nw=0;
char ch;
Scanner scr=new Scanner([Link]);
[Link]("\nEnter File name: ");
String str=[Link]();
FileInputStream f=new FileInputStream(str);
int n=[Link]();

for(int i=0;i<n;i++)
{
ch=(char)[Link]();
if(ch=='\n')
nl++;
else if(ch==' ')
nw++;
}
[Link]("\nNumber of lines : "+nl);
[Link]("\nNumber of words : "+(nl+nw));
[Link]("\nNumber of characters : "+n);
}
}

---------------------------------------------------------------------------------------------------------------------

10)Write an Applet that displays the content of a file.

Program1:-[Link] (Save in the Same directory of the related Java File)

my name
is
Pradeep

Program2:- [Link]

import [Link].*;
import [Link].*;
import [Link].*;

/*<applet code="p10" height="300" width="500"></applet>*/

public class p10 extends Applet


{
public void paint(Graphics g)
{
String content = "";
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new FileInputStream("[Link]");
while([Link]()!=0)
{
ch = (char)[Link]();
[Link](ch);
}
[Link]();
content = new String(buff);
}
catch(FileNotFoundException e)
{
[Link]("Cannot find the specified file...");
}
catch(IOException i)
{
[Link]("Cannot read file...");
}
[Link](content,20,20);
}
}

---------------------------------------------------------------------------------------------------------------------

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.

Program:-[Link]

import [Link].*;
import [Link].*;
import [Link].*;

/*<applet code="p11" width=300 height=300></applet>*/


public class p11 extends Applet implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;

public void init()


{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);

for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}

add=new Button("add"); sub=new Button("sub"); mul=new Button("mul");


div=new Button("div"); mod=new Button("mod"); clear=new Button("clear");
EQ=new Button("EQ");

[Link](this);

add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);}
add(add); add(sub); add(mul);
add(div); add(mod); add(clear); add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
[Link](this); [Link](this);
[Link](this); [Link](this);
[Link](this); [Link](this);
[Link](this);
}

public void actionPerformed(ActionEvent ae)


{
String str=[Link](); char ch=[Link](0);
if ( [Link](ch))
[Link]([Link]()+str);
else
if([Link]("add"))
{
v1=[Link]([Link]());
OP='+';
[Link]("");
}
else if([Link]("sub"))
{
v1=[Link]([Link]());
OP='-';
[Link]("");
}
else if([Link]("mul"))
{
v1=[Link]([Link]());
OP='*';
[Link]("");
}
else if([Link]("div"))
{
v1=[Link]([Link]());
OP='/';
[Link]("");
}
else if([Link]("mod"))
{
v1=[Link]([Link]());
OP='%';
[Link]("");
}

if([Link]("EQ"))
{
v2=[Link]([Link]());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
[Link](""+result);
}

if([Link]("clear"))
{
[Link]("");
}
}
}

---------------------------------------------------------------------------------------------------------------------

12) Write a Java Program for handling mouse events.

Program:-[Link]

import [Link].*;
import [Link].*;
import [Link].*;

/* <applet code="p12" width=300 height=100> </applet> */

public class p12 extends Applet implements MouseListener, MouseMotionListener


{
String msg = "";
int mouseX = 0, mouseY = 0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me)


{
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked."; repaint();
}

public void mouseEntered(MouseEvent me)


{
mouseX = 0;
mouseY = 10;
msg = "Mouse entered."; repaint();
}

public void mouseExited(MouseEvent me)


{
mouseX = 0;
mouseY = 10;
msg = "Mouse exited."; repaint();
}

public void mousePressed(MouseEvent me)


{
mouseX = [Link]();
mouseY = [Link]();
msg = "Pressed";
repaint();
}

public void mouseReleased(MouseEvent me)


{
mouseX = [Link]();
mouseY = [Link]();
msg = "Released";
repaint();
}

public void mouseDragged(MouseEvent me)


{
showStatus("Dragging mouse at " + mouseX + ", " + mouseY); repaint();
}

public void mouseMoved(MouseEvent me)


{
showStatus("Moving mouse at " + [Link]() + ", " + [Link]());
}

public void paint(Graphics g)


{
[Link](msg, mouseX, mouseY);
}
}

---------------------------------------------------------------------------------------------------------------------

13) Write a Java Program demonstrating the life cycle of a thread.

Program:-[Link]

class x
{
synchronized void m1(int n)
{
for(int i=1;i<=5;i++)
{
[Link](n*i);
try
{
[Link](200);
}
catch(Exception e)
{
[Link](e);
}
}

}
}
public class p13
{
public static void main(String args[])
{
x obj = new x();

Thread t1=new Thread() {


public void run()
{
obj.m1(5);
}
};
Thread t2=new Thread() {
public void run()
{
obj.m1(100);
}
};

[Link]();
[Link]();
}
}

---------------------------------------------------------------------------------------------------------------------

14)Write a Java Program to illustrate user defined Exception Handling (also make use of
throw, throws).

Program1:-[Link](throw)

class p14a
{
public static void main(String args[])
{
try
{
throw new MyException();
}
catch(MyException e)
{
[Link](e) ;
}
}
}

class MyException extends Exception


{
public String toString()
{
return ("My Exception Raised");
}
}

---------------------------------------------------------------------------------------------------------------------

Program2:-[Link](throws)

class p14b
{
public static void main(String args[]) throws InterruptedException
{
for(int i=1;i<=5;i++)
{
[Link](700);
[Link](i);
}
}
}

---------------------------------------------------------------------------------------------------------------------

Common questions

Powered by AI

The recursive implementation of the Fibonacci sequence calls itself with smaller values, building up the sequence through repeated calls, which can lead to a large number of redundant calculations and a higher time complexity of O(2^n). The non-recursive implementation uses iteration to build the sequence, typically using a loop to calculate the nth term directly, which is more efficient with a time complexity of O(n) due to the elimination of repeated calculations .

The Java program for checking a palindrome reads a string and compares it with its reversed version. Essential components include a loop that constructs the reverse of the input string by iterating over it from the last character to the first, and a conditional check using 'str.equals(rev)' to determine if the string is equal to its reverse .

User-defined exceptions in Java are subclasses of the Exception class, allowing developers to create specific error types relevant to their applications. In the document, MyException is an example of a user-defined exception, demonstrated with the "throw" keyword to manually trigger exceptions and "throws" to denote exception throwing potential in method signatures. This provides controlled and meaningful error handling .

The Java program uses a GridLayout to create a simple calculator interface with buttons for digits and arithmetic operations, and a text field for displaying results. Challenges include managing event handling to ensure correct operations and state maintenance, as well as arranging components so they are intuitive and functional, especially handling the layout constraints of a grid .

The Java program handles mouse events by implementing both MouseListener and MouseMotionListener interfaces. It captures events like mouse clicks, movements, and drags, updating the display accordingly with messages like 'Mouse clicked' or coordinates during dragging. This provides immediate interactive feedback to the user based on mouse actions .

The life cycle of a thread in Java, as depicted in the code, involves creation, running, and termination stages. Threads are created and started using the Thread class, executing synchronized methods to print numbers. Synchronization ensures threads do not interfere with each other's output as they attempt to access shared resources in 'x' class, maintaining data consistency .

The Java program performs operations like checking if the file exists, if it's readable or writable, its absolute path, type, and size using methods provided by the File class. Additionally, it attempts to read the file content using FileInputStream, handling exceptions like FileNotFoundException and IOException to ensure proper error management during file operations .

The document shows packages through a simple Java example where a package 'pack' contains a class 'p6a' performing addition operations. This is imported into another class 'p6b' to access its methods. Packages in Java allow better organization of code, prevent name conflicts, and control access with visibility constraints like "public" and package-private .

The StringTokenizer class in Java is used to split a string of integers separated by spaces into individual tokens. The program reads each token as an integer, displays it, and computes the sum of these integers. This process effectively converts a space-separated string into separate integer values for processing .

Runtime polymorphism in Java is demonstrated through method overriding, where a subclass provides a specific implementation of a method already defined in its superclass. In the example from the document, the class "Boy" overrides the "eat" method of its superclass "Human". When an instance of "Boy" calls "eat", the overridden version in "Boy" is executed, thus achieving polymorphism .

You might also like