0% found this document useful (0 votes)
179 views

Java Lab MCA R20 Programs

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
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
179 views

Java Lab MCA R20 Programs

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
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

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:- p1.java

import java.util.Scanner;

class p1
{
public static void main(String args[ ])
{
System.out.print("Enter a Number : ");
Scanner obj=new Scanner(System.in);
int a=obj.nextInt();
x obj1=new x();
int b=obj1.input(a);
System.out.println("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:- p2.java

import java.util.Scanner;

class p2
{
public static void main(String args[ ])
{
int n;
int p;
Scanner s=new Scanner(System.in);
System.out.print("Enter a Number : ");
n=s.nextInt();
System.out.println("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)
System.out.println(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:- p3.java

import java.util.Scanner;

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

System.out.print("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");

}
}

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

4) Write a Java Program for sorting a given list of names in ascending order.
Program:- p4.java

import java.util.Scanner;

class Sorting
{
void sortStrings()
{
Scanner s = new Scanner(System.in);
System.out.print("How many Names you want to Sort : ");
int n = s.nextInt();
String[] str = new String[n];
System.out.println("Enter the Names : ");
for(int i = 0; i < n; i++)
{
str[i] = new String(s.next());
}
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;
}
}
}
System.out.println("\nSorted list of Names in Ascending Order :");
for(int i = 0; i < n ; i++)
{
System.out.println(str[i]);
}
}
}
class p4
{
public static void main(String args[])
{
Sorting obj = new Sorting();
obj.sortStrings();
}
}

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

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

Program:-p5.java

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

class Human
{
public void eat()
{
System.out.println("Human is eating");
}
}

class Boy extends Human


{
public void eat()
{
super.eat();
System.out.println("Boy is eating");
}
}

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

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


Program 1:- p6a.java

package pack; // Creates a Package pack

public class p6a


{
public void m1(int a, int b)
{
int c=a+b;
System.out.println("Addition Value :" + c);
}
}

Program 2:- p6b.java

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

import java.util.Scanner;

public class p6b


{
public static void main(String args[])
{
p6a obj=new p6a();
Scanner s=new Scanner(System.in);
System.out.print("Enter a Number 1 : ");
int n1=s.nextInt();
System.out.print("Enter a Number 2 : ");
int n2=s.nextInt();
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 . <pgmName.Java>

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:-p7.java

import java.util.Scanner;
import java.util.StringTokenizer;

class p7
{
public static void main(String args[])
{
int n;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter integers with one space gap : ");
String s = sc.nextLine();
StringTokenizer st = new StringTokenizer(s, " ");
System.out.println("Integers are..");
while (st.hasMoreTokens())
{
String temp = st.nextToken();
n = Integer.parseInt(temp);
System.out.println(n);
sum = sum + n;
}
System.out.println("Sum of all integers : " + sum);
sc.close();
}
}

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

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:-p8.java

import java.io.File;

class p8
{
static void p(String s)
{
System.out.println(s);
}

public static void main(String args[ ])


{
File f1 = new File(args[0]);
p("File Name: " + f1.getName());
p("Abs Path: " + f1.getAbsolutePath());
p(f1.exists() ? "exists" : "does not exist");
p(f1.canWrite() ? "is writeable" : "is not writeable");
p(f1.canRead() ? "is readable" : "is not readable");
p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
p(f1.isFile() ? "is normal file" : "might be a named pipe");
p(f1.isAbsolute() ? "is absolute" : "is not absolute");
p("File size: " + f1.length() + " Bytes");
}
}

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

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

Program1:-text.txt (Save in the Same directory of the related Java File)

my name
is
Pradeep

Program2: p9.java

import java.util.*;
import java.io.*;

class p9
{
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);
}
}

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

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

Program1:-text.txt (Save in the Same directory of the related Java File)

my name
is
Pradeep

Program2:- p10.java

import java.applet.*;
import java.awt.*;
import java.io.*;

/*<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("text.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);
}
}

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

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:-p11.java

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<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");

t1.addActionListener(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);
}
add.addActionListener(this); sub.addActionListener(this);
mul.addActionListener(this); div.addActionListener(this);
mod.addActionListener(this); clear.addActionListener(this);
EQ.addActionListener(this);
}

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("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}

if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
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;
t1.setText(""+result);
}

if(str.equals("clear"))
{
t1.setText("");
}
}
}

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

12) Write a Java Program for handling mouse events.

Program:-p12.java

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/* <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 = me.getX();
mouseY = me.getY();
msg = "Pressed";
repaint();
}

public void mouseReleased(MouseEvent me)


{
mouseX = me.getX();
mouseY = me.getY();
msg = "Released";
repaint();
}

public void mouseDragged(MouseEvent me)


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

public void mouseMoved(MouseEvent me)


{
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}

public void paint(Graphics g)


{
g.drawString(msg, mouseX, mouseY);
}
}

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

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

Program:-p13.java

class x
{
synchronized void m1(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(200);
}
catch(Exception e)
{
System.out.println(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);
}
};

t1.start();
t2.start();
}
}

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

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

Program1:-p14a.java(throw)

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

class MyException extends Exception


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

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

Program2:-p14b.java(throws)

class p14b
{
public static void main(String args[]) throws InterruptedException
{
for(int i=1;i<=5;i++)
{
Thread.sleep(700);
System.out.println(i);
}
}
}

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy