BSc III Year (sem V)
Programming in Java
Lab programs
1. Write a program to find the largest of n natural numbers.
class Large
{
public static void main(String args[])
{
int i,n,large,a[]={20,30,40,100,10};
large = a[0];
for(i=1;i<5;i++)
{
if(large<a[i])
{
large = a[i];
}
}
[Link]("Largest of "+5+" elements in an array = "+large);
}
}
Output:
I:\Javaprg>javac [Link]
I:\ Javaprg>java Large
Largest of 5 elements in an array = 100
2. Write a program to find whether a given number is prime or not
class Prime
{
public static void main(String[] args)
{
int i,n,res,count;
n=7;
count=0;
i=1;
while(i<=n)
{
res=n%i;
if(res==0)
count++;
i++;
if(count==2)
[Link](n+" is prime number");
else
[Link](n+" is not a prime number");
}
}
Output:
I:\ Javaprg>javac [Link]
I: \Javaprg>java Prime
7 is prime number
Java lab practicals Sem V -paper V Page 1
3. Write a menu driven program for following:
a. Display a Fibonacci series
b. Compute Factorial of a number
import [Link];
class FibonacciNFactorial
{
public static void main(String args[])
{
int i,num,fact=1;
char repeat;
Scanner in = new Scanner([Link]);
do{
[Link]("1. Fibonacci Series");
[Link]("2. Factorial ");
[Link]("Enter your choice: ");
int ch = [Link]();
switch (ch)
{
case 1:
int a = 0, b = 1;
[Link](a + " " + b);
for (i = 3; i <= 10; i++)
{
int term = a + b;
[Link](" " + term);
a = b;
b = term;
}
break;
case 2:
[Link]("Enter number: ");
num = [Link]();
for (i=1;i<=num;i++)
fact=fact*i;
[Link]("Factorial of "+num+" is: "+fact);
break;
}
[Link]("\nDo you want to continue-type y for Yes and n for no:");
repeat=[Link]().charAt(0);
}while(repeat=='y');
}
}
Output:
I:\ Javaprg>javac [Link]
I:\ Javaprg>java FibonacciNFactorial
1. Fibonacci Series
2. Factorial
Enter your choice: 1
0 1 1 2 3 5 8 13 21 34
Do you want to continue-type y for Yes and n for no:
y
Java lab practicals Sem V -paper V Page 2
1. Fibonacci Series
2. Factorial
Enter your choice: 2
Enter number: 5
Factorial of 5 is: 120
4. Write a program to check whether a given number is odd or even.
import [Link];
public class EvenOdd
{
public static void main(String[] args)
{
Scanner reader = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
if(num % 2 == 0)
[Link](num + " is even");
else
[Link](num + " is odd");
}
}
Output:
I:\ Javaprg>javac [Link]
I:\ Javaprg>java EvenOdd
Enter a number: 28
28 is even
5. Write a program to check whether a given string is palindrome or not.
class PalindromeExample
{
public static void main(String args[])
{
int r,sum=0,temp;
int n=454;//It is the number variable to be checked for palindrome
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
[Link](temp+" is a palindrome number ");
else
[Link](temp+ "is not a palindrome number");
}
}
Output:
I:\ \Javaprg>javac [Link]
I: \Javaprg>java PalindromeExample
454 is a palindrome number
Java lab practicals Sem V -paper V Page 3
6. Write a program to print the sum and product of digits of an Integer and reverse the
Integer.
import [Link];
class SumNmul
{
public static void main(String args[])
{
int m,number,r, digit, sum = 0,mul=1,rem;
Scanner sc = new Scanner([Link]);
[Link]("Enter the number : ");
number = [Link]();
m=number;
r=number;
while(number > 0)
{
digit = number % 10;
sum = sum + digit;
number = number / 10;
}
[Link]("Sum of Digits: "+sum);
while (m!= 0)
{
mul = mul * (m % 10);
m = m / 10;
}
[Link]("Multiplication of Digits: "+mul);
sum=0;
while(r>0)
{
rem = r % 10;
sum = (sum*10) + rem;
r = r / 10;
}
[Link]("reverse of given digit is "+ sum);
}
}
Output:
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java SumNmul
Enter the number : 156
Sum of Digits: 12
Multiplication of Digits: 30
reverse of given digit is 651
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 Array {
public static void main(String[] args) {
Java lab practicals Sem V -paper V Page 4
Scanner input = new Scanner([Link]);
int arr[] = new int[10];
int checkG = 0, checkE = 0, checkL = 0;
[Link]("Enter 10 numbers");
for (int i = 0; i < 10; i++) {
arr[i] = [Link]();
}
[Link]("Enter another number: ");
int n = [Link]();
for (int i = 0; i < 10; i++) {
if (arr[i] < n)
checkL++;
else if (arr[i] == n)
checkE++;
else
checkG++;
}
[Link]("The count of numbers that are equal to the number passed is : " +
checkE);
[Link]("The count of numbers that are Less than the number passed is : " +
checkL);
[Link]("The count of numbers that are Greater than the number passed is : "
+ checkG);
}
}
Output:
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java Array
Enter 10 numbers
1
5
8
7
7
10
6
5
11
10
Enter another number:
10
The count of numbers that are equal to the number passed is : 2
The count of numbers that are Less than the number passed is : 7
The count of numbers that are Greater than the number passed is : 1
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 PricesAverage
{
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
float avg, sum = 0.0f;
Java lab practicals Sem V -paper V Page 5
float price[] = new float[5];
[Link]("Enter the prices: ");
for (int i = 0; i < 5; i++) {
[Link]("Price " + (i + 1) + " ");
price[i] = [Link]();
sum = sum + price[i];
}
avg = (float) (sum / 5);
[Link]("Prices that are higher than average %.2f are: ", avg);
for (int i = 0; i < 5; i++) {
if (avg < price[i]) {
[Link](" " + price[i]);
} else
continue;
}
}
}
Output:
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java PricesAverage
Enter the prices:
Price 1
150
Price 2
450
Price 3
782
Price 4
199
Price 5
244
Prices that are higher than average 365.00 are: , 450.0 , 782.0
9. Write a program in java to input N numbers in an array and print out the Armstrong
numbers from the set.
import [Link].*;
import [Link];
class Armstrong {
static void ArmstrongCheck(int n) {
int rem, sum = 0;
int temp = n;
while (n > 0) {
rem = n % 10;
sum = sum + (int) [Link](rem, 3);
n = n / 10;
}
if (sum == temp) {
[Link](" " + temp);
}
Java lab practicals Sem V -paper V Page 6
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter how many numbers are Entering: ");
int n = [Link]();
[Link]("Ok! Now Enter numbers:");
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
[Link]();
[Link]("Armstrong numbers from entered numbers are: ");
for (int i = 0; i < [Link]; i++) {
ArmstrongCheck(arr[i]);
}
}
}
Output:
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java Armstrong
Enter how many numbers are Entering:
5
Ok! Now Enter numbers:
153
371
300
456
195
Armstrong numbers from entered numbers are:
153
371
10. a. Write java program to find Addition of two matrices
import [Link].*;
class AddMatrix {
public static void main(String[] ab) {
Scanner input = new Scanner([Link]);
[Link]("Enter the size of matrix");
int row = [Link]();
int a[][] = new int[row][row];
int b[][] = new int[row][row];
int c[][] = new int[row][row];
// input
[Link]("Enter the elements of matrix a");
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
a[i][j] = [Link]();
}
}
[Link]("Enter the elements of matrix b");
for (int i = 0; i < row; i++) {
Java lab practicals Sem V -paper V Page 7
for (int j = 0; j < row; j++) {
b[i][j] = [Link]();
}
}
// display
[Link]("matrix a");
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
[Link](" " + a[i][j]);
}
[Link]();
}
[Link]("matrix b");
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
[Link](" " + b[i][j]);
}
[Link]();
}
// addition
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
// display sum
[Link]("matrix sum");
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
[Link](" " + c[i][j]);
}
[Link]();
}
}
}.
Output:
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java AddMatrix
Enter the size of matrix
2
Enter the elements of matrix a
1
2
3
4
Enter the elements of matrix b
5
6
7
8
matrix a
1 2
3 4
matrix b
5 6
7 8
Java lab practicals Sem V -paper V Page 8
matrix sum
6 8
10 12
10 b. Write java program to find Transpose of a matrix
import [Link];
public class TransposeMatrix
.{
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter the no. of rows: ");
int row = [Link]();
[Link]("Enter the no. of coloumns: ");
int col = [Link]();
int a[][] = new int[row][col];
int b[][] = new int[col][row];
// input
[Link]("Enter the elements of Original matrix");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
a[i][j] = [Link]();
}
}
// display
[Link]("Original matrix");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
[Link](" " + a[i][j]);
}
[Link]();
}
// Transpose
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
b[j][i] = a[i][j];
}
}
// display result
[Link]("Transpose matrix ");
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
[Link](" " + b[i][j]);
}
[Link]();
}
}
}
Output:
Java lab practicals Sem V -paper V Page 9
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java TransposeMatrix
Enter the no. of rows:
3
Enter the no. of coloumns:
3
Enter the elements of Original matrix
1
2
3
4
5
6
7
8
9
Original matrix
1 2 3
4 5 6
7 8 9
Transpose matrix
1 4 7
2 5 8
3 6 9
11. Write a java program that computes the area of a circle, rectangle and a Cylinder using
function overloading.
public class FunctionOverloading
{
void area(float x) {
[Link](" the area of the square is " + (x * x) + " 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 Cylinder is " + z + " sq units.");
}
public static void main(String[] args) {
FunctionOverloading input = new FunctionOverloading();
[Link](5);
[Link](11, 12);
[Link](2.5);
}
}
Output:
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java FunctionOverloading
Java lab practicals Sem V -paper V Page 10
the area of the square is 25.0 sq units.
the area of the rectangle is 132.0 sq units.
the area of the Cylinder is 19.625 sq units.
12. Write a Java program for the implementation of multiple inheritance using interfaces to
calculate the area of a rectangle and triangle.
public class MultipleInheritence
{
public static void main(String[] args)
{
Rectangle a = new Rectangle();
Triangle b = new Triangle();
Cal_Area find;
find = a;
[Link]("The area of rectangle is " + [Link](5, 9));
find = b;
[Link]("The area of Triangle is " + [Link](8, 12));
}
}
interface Cal_Area
{
float area(float x, float y);
}
class Rectangle implements Cal_Area
{
public float area(float l, float b)
{
return l * b;
}
}
class Triangle implements Cal_Area
{
public float area(float b, float h)
{
return (b * h / 2);
}
}
Output:
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java MultipleInheritence
The area of rectangle is 45.0
The area of Triangle is 48.0
13. Write a java program to create a frame window in an Applet.
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
/*
<applet code=" AppleFrame" width=400 height=60>
Java lab practicals Sem V -paper V Page 11
</applet>
*/
//creates subclass of Frame
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g) {
[Link]("This is in frame window", 10, 40);
}
}
class MyWindowAdapter extends WindowAdapter {
SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame sampleFrame) {
[Link] = sampleFrame;
}
public void windowClosing(WindowEvent we) {
[Link](false);
}
}
// Create frame window
public class AppletFrame extends Applet {
Frame f;
public void init() {
f = new SampleFrame("A Frame Window");
[Link](150, 150);
[Link](true);
}
public void start() {
[Link](true);
}
public void stop() {
[Link](false);
}
public void paint(Graphics
g) {
[Link]("This is in applet window", 15, 30);
}
}
Java lab practicals Sem V -paper V Page 12
14. Write a java program to draw a line between two coordinates in a window.
import [Link];
import [Link];
public class DrawLineExample extends Applet {
public void paint(Graphics g) {
[Link](10, 10, 50, 10);
// here line is drawn between(x1,y1) and (x2,y2)
}
}
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];
import [Link].*;
/*<applet code="GraphicsEx" width=400 height=400></applet>*/
public class GraphicsEx extends Applet {
public void paint(Graphics g) {
[Link](new Font("Cambria", [Link], 15));
[Link]("Drawing different shapes in Applet window", 15, 15);
[Link](10, 20, 60, 40);
[Link](70, 70, 70, 70);
[Link](120, 160, 100, 50);
[Link](60, 125, 8, 40, 180, 180);
int x[] = { 210, 230, 240, 250, 310, 340 };
int y[] = { 310, 340, 150, 140, 130, 110 };
int n = 6;
Polygon pg = new Polygon(x, y, n);
[Link](pg);
}
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 ExceptionEx {
public static void main(String[] args) throws Exception {
try {
int a, b;
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the values of a and b:");
a = [Link]([Link]());
b = [Link]([Link]());
[Link]("the entered numbers are a="+a+" b="+b);
Java lab practicals Sem V -paper V Page 13
} catch (NumberFormatException ex) {
[Link]([Link]() + " is not a number");
[Link](0);
}
}
Output:
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java ExceptionEx
Enter the values of a and b:
10
20
the entered numbers are a=10 b=20
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java ExceptionEx
Enter the values of a and b:
S
For input string: "S" 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
public class StringOperations
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = "World";
[Link]("The concatenated string is: " + [Link](str2));
[Link](str1 + " is equals to " + str2 + " " + [Link](str2));
[Link]("Length of " + str1 + " is " + [Link]());
[Link]("Length of " + str2 + " is " + [Link]());
}
}
Output:
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java StringOperations
The concatenated string is: HelloWorld
Hello is equals to World false
Length of Hello is 5
Length of World is 5
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
import [Link];
Java lab practicals Sem V -paper V Page 14
public class Fraction {
public Fraction() throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("Please enter two numbers: ");
int numerator = [Link]();
int denominator = [Link]();
int result = numerator / denominator;
[Link]("The result is: " + result);
}
void display() {
[Link]("Devided by Zero Exception Example");
public static void main(String[] args) throws Exception {
try {
Fraction f = new Fraction();
[Link]();
} catch (ArithmeticException e) {
[Link]("Can't be divided by Zero \n" + e);
}
}
}
Output:
I:\ \Javaprg> javac [Link]
I:\ \Javaprg> java Fraction
Please enter two numbers:
10
0
Can't be divided by Zero
[Link]: / by zero
Java lab practicals Sem V -paper V Page 15