0% found this document useful (0 votes)
2 views29 pages

Java Lab Record

The document outlines a series of programming tasks in Java, including finding the largest of n natural numbers, checking for prime numbers, and implementing matrix operations. It also covers string manipulation, graphics in applets, and exception handling. Each task is accompanied by code examples and expected outputs, aimed at enhancing practical programming skills for B.Sc. Computer Science students at Osmania University.

Uploaded by

HelloItsAdi
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)
2 views29 pages

Java Lab Record

The document outlines a series of programming tasks in Java, including finding the largest of n natural numbers, checking for prime numbers, and implementing matrix operations. It also covers string manipulation, graphics in applets, and exception handling. Each task is accompanied by code examples and expected outputs, aimed at enhancing practical programming skills for B.Sc. Computer Science students at Osmania University.

Uploaded by

HelloItsAdi
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

[Link] PROGRAMS PG.

NO
Write a program to find the largest of n 2
1. natural numbers.
3
2. Write a program to find whether a given
number is prime or not.

4
3. Write a menu driven program for following:
a. Display a Fibonacci series
b. Compute Factorial of a number

5
4. Write a program to check whether a given
number is odd or even.

6
5. Write a program to check whether a given
string is palindrome or not.

7
6. Write a program to print the sum and product
of digits of an Integer and reverse the Integer.

8
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.
9
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.
Programming in Java Lab

9. Write a program in java to input N numbers 10


in an array and print out the Armstrong
numbers from the set.

11-12
10. Write java program for the following matrix
operations:
a. Addition of two matrices
b. Transpose of a matrix
13
11. Write a java program that computes the area
of a circle, rectangle and a Cylinder using
function overloading

14
12. Write a Java program for the implementation
of multiple inheritance using interfaces to
calculate the area of a rectangle and triangle.

15-17
13. Write a java program to create a frame
window in an Applet. Display your name,
address and qualification in the frame
window.

18
14. Write a java program to draw a line between
two coordinates in a window.

19
15. Write a java program to display the following
graphics in an applet window.
a. Rectangles b. Circlesc. Ellipses d. Arcs e.
Polygons
20
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

2|Page
Programming in Java Lab

the error is caught by


NumberFormatException object. After that
[Link] () prints the information about
the error occurring causes.

21
17. Write a program for the following string
operations:
a. Compare two strings b. concatenate two
strings c. Compute length of a string
22
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

INDEX

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

4|Page
Programming in Java Lab

Enter number of elements in the array: 5


Enter elements of array: 6 2 7 4 1
Largest number is: 7
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
5|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
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++){
6|Page
Programming in Java Lab

mul=mul*i;
}
[Link]("Factorial of "+num+"is"+mul);
}}
Output:
Enter any number:5
Factorial of 5is120
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
7|Page
Programming in Java Lab

The number 6 is even


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)
{
//Take input from the user
//Create instance of the Scanner class
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);
}
}

9|Page
Programming in Java Lab

Output:
Enter any number:456
Reverse:654
Sum of digits:15
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++;

10 | P a g e
Programming in Java Lab

}
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);
[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]+" ");
}
}
12 | P a g e
Programming in Java Lab

}
}
Output:
Enter five prices:10 20 30 40 50
Average of five prices is:30.0
Prices higher than average are:40 50
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;
13 | P a g e
Programming in Java Lab

}
if (sum == num) {
return true;
}
else{
return false; }}
Output:
Enter a number
1000
Armstrong number between 0 to 1000
0
1
153
370
371
470
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} };
// Adding Two matrices
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];

14 | P a g e
Programming in Java Lab

}
}

// Displaying the result


[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
b)Transpose of a matrix
public class Transpose {
public static void main(String[] args) {
int row = 2, column = 3;
int[][] matrix = { {2, 3, 4}, {5, 6, 4} };
// Display current matrix
display(matrix);
// Transpose the matrix
int[][] transpose = new int[column][row];
for(int i = 0; i< row; i++) {
for (int j = 0; j < column; j++) {

15 | P a g e
Programming in Java Lab

transpose[j][i] = matrix[i][j];
}
}
// Display transposed matrix
display(transpose);
}
public static void display(int[][] matrix) {
[Link]("The matrix is: ");
for(int[] row : matrix) {
for (int column : row) {
[Link](column + " ");
}
[Link]();
}
Output:
The matrix is:
2 3 4
5 6 4
The matrix is:
2 5
3 6
4 4
11. Write a java program that computes the area of a circle,
rectangle and a Cylinder using function overloading.
class OverloadDemo
{
void area(float h,float r)
{

16 | P a g e
Programming in Java Lab

[Link]("the area of the Cylinder is "+[Link]*r*(h+r)


+" sq units");
}
void area(float x, float y)
{
[Link]("the area of the rectangle is "+x*y+" sq units");
}
void area(double x)
{
double z = 3.14 * x * x;
[Link]("the area of the circle is "+z+" sq units");
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemoob = new OverloadDemo();
[Link](8.4,3.6);
[Link](11,12);
[Link](2.5);
}
}
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

17 | 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.
// [Link]
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;
18 | P a g e
Programming in Java Lab

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
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
19 | P a g e
Programming in Java Lab

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
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();

20 | P a g e
Programming in Java Lab

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);
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){

21 | P a g e
Programming in Java Lab

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);

22 | P a g e
Programming in Java Lab

[Link](submit_btn);
[Link](output_txtArea);
}
// 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
{
23 | P a g e
Programming in Java Lab

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]

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]);
24 | P a g e
Programming in Java Lab

[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);
}
}
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

25 | P a g e
Programming in Java Lab

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);
}
[Link]("valid numbers");
26 | P a g e
Programming in Java Lab

}
}
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
27 | P a g e
Programming in Java Lab

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
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:
28 | P a g e
Programming in Java Lab

Enter two numbers: 4 0


Cannot divide by zero [Link]:/ by zero
Enter two numbers: 27 3
Result is:9Divide by Zero Exception Example

29 | P a g e

You might also like