[Link] PROGRAMS PG.
NO
Write a program to find the largest of n natural numbers.
1. 2
2. Write a program to find whether a given number is prime or not. 3
3. Write a menu driven program for following: 4
a. Display a Fibonacci series
b. Compute Factorial of a number
4. Write a program to check whether a given number is odd or even. 5
5. Write a program to check whether a given string is palindrome or 6
not.
6. Write a program to print the sum and product of digits of an 7
Integer and reverse the Integer.
7. Write a program to create an array of 10 integers. Accept values 8
from the user in that
Array. Input another number from the user and find out how
many numbers are equal to the number passed, how many are
greater and how many are less than the number passed.
8. Write a program that will prompt the user for a list of 5 prices. 9
Compute the average of the prices and find out all the prices that
are higher than the calculated average.
9. Write a program in java to input N numbers in an array and print 10
out the Armstrong numbers from the set.
10. Write java program for the following matrix operations: 11-12
a. Addition of two matrices
b. Transpose of a matrix
11. Write a java program that computes the area of a circle, rectangle 13
and a Cylinder using function overloading
12. Write a Java program for the implementation of multiple 14
inheritance using interfaces to calculate the area of a rectangle and
triangle.
Programming in Java Lab
13. Write a java program to create a frame window in an Applet. 15-17
Display your name, address and qualification in the frame
window.
14. Write a java program to draw a line between two coordinates in a 18
window.
15. Write a java program to display the following graphics in an 19
applet window.
a. Rectangles b. Circlesc. Ellipses d. Arcs e. Polygons
16. Write a program that reads two integer numbers for the variables 20
a and b. If any other character except number (0-9) is entered then
the error is caught by Number Format Exception object. After
that [Link] () prints the information about the error
occurring causes.
17. Write a program for the following string operations: 21
a. Compare two strings
b. concatenate two strings
c. Compute length of a string
18. Create a class called Fraction that can be used to represent the 22
ratio of two integers. Include appropriate constructors and
methods. If the denominator becomes zero, throw and handle an
exception
2|Page
Programming in Java Lab
OSMANIA UNIVERSITY
FACULTY OF SCIENCE
[Link]. (Computer Science)
SEMESTER – V
Programming in Java Lab Practical
3 Hours/Week 1 Credit Marks: 50
1. Write a program to find the largest of n natural numbers.
import [Link];
public class LargestNaturalNumber
{
public static void main(String[]arg)
{
int n,max;
Scanner s=new Scanner([Link]);
[Link]("Enter number of elements in the array:");
n=[Link]();
int arrElements[]=new int[n];
[Link]("Enter elements of array:");
for(int i=0;i<n;i++)
{
arrElements[i]=[Link]();
}
max=arrElements[0];
for(int i=0;i<n;i++)
{
if(max<arrElements[i])
{
max=arrElements[i];}
}
[Link]("Largest number is:"+ max);
}}
Output:
Enter number of elements in the array: 5
Enter elements of array: 6 2 7 4 1
Largest number is: 7
3|Page
Programming in Java Lab
2. Write a program to find whether a given number is prime or not.
import [Link];
public class check_prime
{
public static void main(String args[])
{
Scanner s=new Scanner([Link]);
[Link]("enter any number:");
int num=[Link]();
for(int i=2; i<num;i++)
{
if(num%i==0)
{
[Link](num+"is not a prime number");
return;
}
}
[Link](num+" is a prime number");
}
}
Output:
enter any number: 8
8 is not a prime number
enter any number: 3
is a prime number
4|Page
Programming in Java Lab
[Link] a menu driven program for following:
a)Display a Fibonacci series
import [Link];
public class Fibonacci
{
public static void main(String[]args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter number of terms for the fibonacci series:");
int num=[Link]();
[Link]("Fibonacci Series:");
int prev=0,curr=0,next=1;
for(int i=1; i<=num;i++)
{
prev=curr;
curr=next;
next=prev+curr;
[Link](prev+" ");
}
}
}
Output:
Enter number of terms for the fibonacci series:10
Fibonacci Series:0 1 1 2 3 5 8 13 21 34
5|Page
Programming in Java Lab
b. Compute Factorial of a number
import [Link];
public class Factorial
{
public static void main(String[]args)
{
int num, mul=1;
Scanner s=new Scanner([Link]);
[Link]("Enter any number:");
num=[Link]();
for(int i=1; i<=num; i++)
{
mul=mul*i;
}
[Link]("Factorial of "+num+"is"+mul);
}
}
Output:
Enter any number:5
Factorial of 5is120
6|Page
Programming in Java Lab
4. Write a program to check whether a given number is odd or even.
import [Link];
public class OddorEven
{
public static void main(String[] args)
{
Scanner s= new Scanner([Link]);
[Link]("Enter any number:");
int num=[Link]();
if ( num %2==0)
{
[Link]("The numer"+num +"is even");
}
else
{
[Link]("The number"+num +" is odd");
}
}
}
Output:
Enter any number:6
The number 6 is even
7|Page
Programming in Java Lab
5. Write a program to check whether a given string is palindrome or not.
import [Link].*;
public class Palindrome
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the number: ");
String reverse = "";
String num = [Link]();
int length = [Link]();
for ( int i = length - 1; i>= 0; i-- )
reverse = reverse + [Link](i);
if ([Link](reverse))
[Link]("The entered string " +num +" is a palindrome.");
else
[Link]("The entered string " +num +" isn't a palindrome.");
}
}
Output:
8|Page
Programming in Java Lab
6. Write a program to print the sum and product of digits of an Integer and reverse
the Integer.
import [Link];
public class Use_Do_While
{
public static void main(String[] args)
{
int n, a, m = 0, sum = 0;
Scanner s = new Scanner([Link]);
[Link]("Enter any number:");
n = [Link]();
do
{
a = n % 10;
m = m * 10 + a;
sum = sum + a;
n = n / 10;
}
while( n > 0);
[Link]("Reverse:"+m);
[Link]("Sum of digits:"+sum);
}
}
Output:
Enter any number:456
Reverse:654
Sum of digits:15
9|Page
Programming in Java Lab
7. Write a program to create an array of 10 integers. Accept values from the user in
that Array. Input another number from the user and find out how many numbers
are equal to the number passed, how many are greater and how many are less than
the number passed.
import [Link];
public class NumberArray
{
public static void main(String[]args)
{
int countEqual=0,countGreater=0,countLess=0;
Scanner s= new Scanner([Link]);
int[]arrNumbers=new int[10];
[Link]("Enter ten numbers:");
for(int i=0;i<10;i++)
{
arrNumbers[i]=[Link]();
}
[Link]("Enter another number:");
int num=[Link]();
for(int i=0;i<10;i++)
{
if(arrNumbers[i]==num)
{
countEqual++;
}
else if(arrNumbers[i]>num)
{
countGreater++;
}
else
{
countLess++;
}
}
[Link]("Count of numbers equal to given number is:"+ countEqual);
[Link]("Count of numbers greater than given number is:"+ countGreater);
10 | P a g e
Programming in Java Lab
[Link]("Count of numbers less than given number is:"+ countLess);
}
}
Output:
Enter ten numbers:3 5 8 15 34 56 1 15 23 43
Enter another number:15
Count of numbers equal to given number is:2
Count of numbers greater than given number is:4
Count of numbers less than given number is:4
11 | P a g e
Programming in Java Lab
8. Write a program that will prompt the user for a list of 5 prices. Compute the
average of the prices and find out all the prices that are higher than the calculated
average.
import [Link];
public class AveragePrice
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
int[] arrPrices = new int[5];
float total = 0, avg;
[Link]("Enter five prices:");
for(int i=0; i<5; i++)
{
arrPrices[i]=[Link]();
total = total+ arrPrices[i];
}
avg = total/5;
[Link]("Average of five prices is:"+ avg);
[Link]("Prices higher than average are:");
for (int i=0;i<5;i++)
{
if(arrPrices[i]>avg)
{
[Link](arrPrices[i]+" ");
}
}
}
}
Output:
Enter five prices:10 20 30 40 50
Average of five prices is:30.0
Prices higher than average are:40 50
12 | P a g e
Programming in Java Lab
9. Write a program in java to input N numbers in an array and print out the
Armstrong numbers from the set.
import [Link];
public class ArmstrongSeries
{
public static void main(String[] args)
{
double N;
int i;
Scanner scanner;
scanner = new Scanner([Link]);
[Link]("Enter a Number");
N = [Link]();
[Link]("Armstrong Number between 0 to " + (int) N);
for (i = 0; i< N; i++) {
if (isArmstrongNumber(i))
{
[Link](i + " ");
}
}
}
public static booleanisArmstrongNumber(int num)
{
int sum = 0, rightDigit, temp;
temp = num;
while (temp != 0)
{
rightDigit = temp % 10;
sum = sum + (rightDigit * rightDigit * rightDigit);
temp = temp / 10;
}
if (sum == num)
{
return true;
}
else
13 | P a g e
Programming in Java Lab
{
return false;
}
}
Output:
Enter a number
1000
Armstrong number between 0 to 1000
0
1
153
370
371
470
14 | P a g e
Programming in Java Lab
10. Write java program for the following matrix operations:
a. Addition of two matrices
public class AddMatrices
{
public static void main(String[] args)
{
int rows = 2, columns = 3;
int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3} };
int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} };
int[][] sum = new int[rows][columns];
for(int i = 0; i< rows; i++)
{
for (int j = 0; j < columns; j++)
{
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}
[Link]("Sum of two matrices is: ");
for(int[] row : sum)
{
for (int column : row)
{
[Link](column + " ");
}
[Link]();
}
}
}
Output:
Sum of two matrices is:
-2 8 7
10 8 6
15 | P a g e
Programming in Java Lab
b)Transpose of a matrix
public class MatrixTranspose
{
public static void main(String[] args)
{
int[][] matrix =
{
{1, 2, 3},
{4, 5, 6}
};
int rows = [Link];
int cols = matrix[0].length;
int[][] transpose = new int[cols][rows];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
transpose[j][i] = matrix[i][j];
}
}
[Link]("Original Matrix:");
for (int[] row : matrix)
{
for (int value : row)
{
[Link](value + " ");
}
[Link]();
}
[Link]("\nTranspose Matrix:");
for (int[] row : transpose)
{
for (int value : row)
{
16 | P a g e
Programming in Java Lab
[Link](value + " ");
}
[Link]();
}
}
}
Output:
The matrix is:
2 3 4
5 6 4
The matrix is:
2 5
3 6
4 4
17 | P a g e
Programming in Java Lab
11. Write a java program that computes the area of a circle, rectangle and a
Cylinder using function overloading.
import [Link];
class Area
{
void area(double radius)
{
double circleArea = [Link] * radius * radius;
[Link]("Area of Circle = " + circleArea);
}
void area(double length, double breadth)
{
double rectangleArea = length * breadth;
[Link]("Area of Rectangle = " + rectangleArea);
}
void area(double radius, double height, int x)
{
double cylinderArea = 2 * [Link] * radius * (radius + height);
[Link]("Total Surface Area of Cylinder = " + cylinderArea);
}
}
public class FunctionOverloadingArea
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
Area obj = new Area();
[Link]("Enter radius of circle: ");
double r = [Link]();
[Link](r);
[Link]("\nEnter length of rectangle: ");
double l = [Link]();
[Link]("Enter breadth of rectangle: ");
double b = [Link]();
[Link](l, b);
18 | P a g e
Programming in Java Lab
[Link]("\nEnter radius of cylinder: ");
double cr = [Link]();
[Link]("Enter height of cylinder: ");
double h = [Link]();
[Link](cr, h, 1);
[Link]();
}
}
Output:
the area of the Cylinder is 135.71680sq units
the area of the rectangle is 132.0 sq units
the area of the circle is 19.625 sq units
19 | P a g e
Programming in Java Lab
12. Write a Java program for the implementation of multiple inheritance using
interfaces to calculate the area of a rectangle and triangle.
import [Link].*;
interface area{
float compute(float x, float y);
}
class rectangle {
public float compute(float x, float y) {
return (x*y);
} }
class triangle {
public float compute(float x, float y) {
return (x*y/2);
}}
class result extends rectangle implements area {
public float compute(float x, float y){
return (x*y);
}}
class result1 extends triangle implements area {
public float compute(float x, float y){
return (x*y/2);
}}
class InterfaceMain{
public static void main(String args[]){
result rect = new result();
result1 tri = new result1();
area a;
a = rect;
[Link]("\nArea of rectangle = " + [Link](10,20));
a = tri;
[Link]("\nArea of triangle = " +[Link](10,2));
}}
Output:
Area of rectangle = 200.0
Area of triangle = 10.0
20 | P a g e
Programming in Java Lab
13. Write a java program to create a frame window in an Applet. Display your
name, address and qualification in the frame window.
import [Link].*;
import [Link].*;
import [Link].*; // importing event package for event listener
class myinfo {
//Creating Static variables
static JTextFieldname_txt ;
static JTextFieldsname_txt ;
static JTextFieldcname_txt ;
static JTextFieldpincode_txt;
static JButtonsubmit_btn;
static JTextAreaoutput_txtArea;
public static void main(String args[])
{
/* ----------------------- Creating JFrame -----------
------------------------------- */
// Step 1 : Creating a frame using JFrame class
JFrame frame=new JFrame("MY INFORMATION");
[Link](true);
[Link](700,700,700,700 );
[Link](JFrame.EXIT_ON_CLOSE);
// Step 2 : setting background color of Frame.
Container c=[Link]();
[Link](null);
[Link]([Link]);
/*-------------------- Creating JLabel for Heading Text ------
----------------- */
Font f=new Font("Arial",[Link],32); // Creating font
style and size for heading
// step 3 : creating JLabel for Heading
JLabelheading_lbl=new JLabel();
heading_lbl.setBounds(250,70,400,40);
heading_lbl.setText("MY INFORMATION");
// applying font on heading Label
21 | P a g e
Programming in Java Lab
heading_lbl.setFont(f);
/* ------------- Creating Global Font style for all components
----------- */
Font f1=new Font("Arial",[Link],20);
/* ------------- Creating components for Registration details
-------------- */
// Step 4 : Creating JLabel for Name
JLabelname_lbl=new JLabel("Name : ");
name_lbl.setBounds(50,150,200,30);
// Creating JTextField for Name
name_txt=new JTextField();
name_txt.setBounds(180,150,250,30);
// Creating JLabel for Street
JLabelsname_lbl=new JLabel("Street : ");
sname_lbl.setBounds(50,230,200,30);
// Creating JTextField for Street
sname_txt=new JTextField();
sname_txt.setBounds(180,230,250,30);
// Creating JLabel for the City
JLabelcname_lbl=new JLabel("City : ");
cname_lbl.setBounds(50,310,200,30);
// Creating JTextArea for the City
cname_txt= new JTextField();
cname_txt.setBounds(180,310,250,30);
// Setting Cursor for components
Cursor cur=new Cursor(Cursor.HAND_CURSOR);
//CreatingJLabel for the pincode
JLabelpincode_lbl=new JLabel("Pincode: ");
pincode_lbl.setBounds(50,390,200,30);
// CreatingJTextField for the pincode
pincode_txt=new JTextField();
pincode_txt.setBounds(180,390,250,30);
// CreatingJButton for submit the details
submit_btn=new JButton("MyInfo");
submit_btn.setBounds(300,450,160,40);
22 | P a g e
Programming in Java Lab
submit_btn.setCursor(cur); // Applying hand cursor on the button
// Adding ActionListener on submit button
submit_btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
submit_action(event);
} });
// CreatingJTextArea for output
output_txtArea=new JTextArea();
output_txtArea.setBounds(500,200,500,500);
// Applying Global Font on all the JLabels
name_lbl.setFont(f1);
sname_lbl.setFont(f1);
pincode_lbl.setFont(f1);
cname_lbl.setFont(f1);
// Applying Font on all JTextFields
name_txt.setFont(f1);
sname_txt.setFont(f1);
cname_txt.setFont(f1);
pincode_txt.setFont(f1);
submit_btn.setFont(f1);
output_txtArea.setFont(f1);
// Adding label components to the container
[Link](heading_lbl);
[Link](name_lbl);
[Link](sname_lbl);
[Link](cname_lbl);
[Link](pincode_lbl);
// AddingJTextField to the container
[Link](cname_txt);
[Link](sname_txt);
[Link](name_txt);
[Link](pincode_txt);
[Link](submit_btn);
[Link](output_txtArea);
}
23 | P a g e
Programming in Java Lab
// Reading value from the MY INFORMATION
public static void submit_action(ActionEvent event)
{
String name=name_txt.getText();
String cname=cname_txt.getText();
String sname=sname_txt.getText();
String pincode=pincode_txt.getText();
// displaying value in the JTextArea
output_txtArea.setText(" Name : " +name + "\n\n Street : " +sname + "\n\n City :
"+cname +" \n\n Pincode : "+pincode + "\n ");
}
}//End of class
Output:
14. Write a java program to draw a line between two coordinates in a window.
import [Link];
import [Link];
public class LineDemo extends Applet
{
public void paint (Graphics g)
{
[Link](40,50,110,100);
}
}
Output:
C:\users\hcw>cd Desktop
C:\users\hcw\Desktop>javac [Link]
C:\users\hcw\Desktop>appletviewer [Link]
24 | P a g e
Programming in Java Lab
15. Write a java program to display the following graphics in an applet window.
a. Rectangles b. Circles c. Ellipses d. Arcs e. Polygons
import [Link];
import [Link].*;
public class GraphicsDemo extends Applet{
public void init(){
[Link]("Applet started");
}
public void paint(Graphics g){
[Link]([Link]);
[Link]("Welcome",50,50);
[Link]([Link]);
[Link](20,30,20,300);
[Link]([Link]);
[Link](70,100,30,30);
[Link]([Link]);
[Link](170,100,30,30);
[Link]([Link]);
[Link](70,200,30,30);
[Link]([Link]);
[Link](170,200,30,30);
[Link]([Link]);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
int x[]={110,130,140,150,210,240,};
int y[]={210,240,150,140,130,110};
int n=6;
Polygon pg=new Polygon(x,y,n);
[Link]([Link]);
[Link](pg);
25 | P a g e
Programming in Java Lab
}
}
Output:
C:\users\hcw>cd Desktop
C:\users\hcw\Desktop>javac [Link]
C:\users\hcw\Desktop>appletviewer [Link]
C:\users\hcw\Desktop>appletviewer [Link]
Applet started
16. Write a program that reads two integer numbers for the variables a and b. If
any other character except number (0-9) is entered then the error is caught by
NumberFormatException object. After that [Link] () prints the information
about the error occurring causes.
import [Link];
public class ExceptionExample
{
public static void main(String args []) throws Exception
{
try
{
Scanner s = new Scanner([Link]);
[Link]("Enter two values");
int num1=[Link]([Link]());
int num2=[Link]([Link]());
}
catch(NumberFormatException ex)
{
[Link]([Link]() +"is not a number");
[Link](0);
}
26 | P a g e
Programming in Java Lab
[Link]("valid numbers");
}
}
Output:
Enter two values 12
Abc
For input string: “Abc” is not a number
17. Write a program for the following string operations: a. Compare two strings b.
concatenate two strings c. Compute length of a string
import [Link];
public class StringOperation
{
public static void main(String[] args)
{
Scanner s =new Scanner([Link]);
[Link]("Entera string:");
String str1=[Link]();
[Link]("Enter another string:");
String str2 =[Link]();
String res=[Link](str2);
[Link]("Concatenated string is:"+res);
booleanisEqual= [Link](str2);
[Link]("str1 is equal to str2 is:"+isEqual);
[Link]("Length of string1 is:"+[Link]());
[Link]("Length of string2 is:"+[Link]());
}
}Length of string2 is:5
Output:
Entera string:john
Enter another string:peter
Concatenated string is:johnpeter
str1 is equal to str2 is:false
Length of string1 is:4
18. Create a class called Fraction that can be used to represent the ratio of two
integers. Include appropriate constructors and methods. If the denominator
becomes zero, throw and handle an exception
27 | P a g e
Programming in Java Lab
public class Fraction {
public Fraction() throws ArithmeticException {
Scanner sc=new Scanner([Link]);
[Link](“enter two numbers”);
int num=[Link]();
int den=[Link]();
int res=num/den;
[Link](“Result is:”+res);
}
void display(){
[Link](“Divide by Zero Exception Example”);
}
public static void main(String args[]){
try{
Fraction obj=new Fraction();
[Link]();
}
Catch(ArithmeticException e){
[Link](“Cannot divide by zero”+e”);
}}}
Output:
Enter two numbers: 4 0
Cannot divide by zero [Link]:/ by zero
Enter two numbers: 27 3
Result is:9Divide by Zero Exception Example
28 | P a g e