Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Java Lab Manual

Uploaded by

FLAME OF PEACE
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Lab Manual

Uploaded by

FLAME OF PEACE
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 35

INDEX

S. Title Date Pg. Re-


No. No. marks
1 WAP to calculate BMI when the weight 5
is in pound and height is in inches

2 Write a java program to generate the 6


electricity bill based on the basis of
given criteria

3 Write a program to print out all the 7


Armstrong numbers between 1 & 500.

4 Write java class that contains 8


appropriate methods to find the
greatest number, LCM for two given
Numbers.

5 Write a java program to generate all 9


the combinations of 1,2 & 3 to form
different numbers using for loop.

6 Write a program to accept 10


temperature of city in Fahrenheit &
convert the temperature into
centigrade degrees.

7 Q7) Write a menu driven program 11-13


which has the following options:-

i) Prime or not ii) Odd or even iii)


Armstrong or not

8 Write a java program to input a num- 14


ber & convert the inputted the number
in words Input: 7893 Output: Seven
Eight Nine Three

1
S. Title Date Pg. Re-
No. No. marks
9 Write a java program to input a 15-16
number & convert the inputted the
number in words Input: 78935 Output:
Seventy Eight Thousand Nine Hundred
Thirty Five Only

10 Write a java program that asks the 17


user to enter an amount and prints
number of notes (of denominations
500, 100, 50, 20, 10, 1) to be
distributed.

11 Write a program to create a class 18


Student with data ‘name, city and age’
along with method printData to
display the data.

12 Write a program in java to enter the 19


number through command line
argument if first and second number is
not entered it will generate the
exception.

13 Write a program in java to enter the 20


number through command line
argument if first and second
number .using the method divides the
first number with second and generate
the exception.

14 Write a java program in which thread 21


sleep for 5 sec and change the name
of thread.

15 Write a java program that checks 22


whether a given string is palindrome
or not.

2
S. Title Date Pg. Re-
No. No. marks
16 Write a java program to create a class 23-24
named Fun & use method overloading
to display the number of arguments &
values of those arguments.

17 Write a java program that implements 25


method overriding?

18 Write a java program to input two 26-27


double dimension matrix & display the
result after matrix multiplication?

19 Write a java program to create two 28-29


array that contains the elements in
ascending order. Now merge the
above array & maintain the order of
the list of elements in the merged
array?

20 Write a java program to input a string 30


& replace existence of “is” with “was”
in the modified string?

21 Write a java program to insert an 31-32


element into array at specific position?

22 Write a program to create an interface 33-34


named area containing data members
pi & compute method define a
rectangle class that implements the
interface & return the area. Now
define a class named circle that
implements area interface to calculate
the area of the Circle?

23 Write a java program to facilitate user 35


to handle any chance of divide by zero

3
S. Title Date Pg. Re-
No. No. marks
exception

24 Write program in Java for String 36


handling

25 Write a java program to demonstrate 37


user of super & this keyword?

4
Q1) Body Mass Index (BMI) is a measure of health on weight. It can
be calculated by taking your weight in kilograms and dividing by the
square of your height in meters. Write a program that prompts the
user to enter a weight in pounds and height in inches and displays
the BMI.

Note:- 1 pound=.45359237 Kg and 1 inch=.0254 meters.


import java.io.*;

public class Q1 {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter your weight in pounds : ");
double weight = Double.parseDouble(br.readLine());
System.out.print("Enter your height in inches : ");
double height = Double.parseDouble(br.readLine());
double bmi = (weight * 0.45359237) / ((height * 0.0254) * (height
* 0.0254));
System.out.println("Your B.M.I. is : " + bmi);
}
}

Output

5
Q2) Write a java program to generate the electricity bill based on
the following criteria

Reading(unit) Rate

For First 100 units - Rs 1.75/unit

For next 100 units -Rs 3.50/unit

Above 200 units - Rs 5.20 /unit


import java.io.*;

public class Q2 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the unit : ");
double unit = Double.parseDouble(br.readLine());
double payableAmount;
if(unit <= 100){
payableAmount = unit * 1.75;
}else if(unit <= 200){
payableAmount = 175 + ((unit-100) * 3.50);
}else{
payableAmount = 175 + 350 + ((unit-200) * 5.20);
}
System.out.println("The payable bill is : " + payableAmount);
}
}

Output

6
Q3) Write a program to print out all the Armstrong numbers
between 1 & 500.
import java.io.*;

public class Q3 {
public static void main(String[] args) throws IOException{
for (int num = 1; num <= 500; num++) {
int originalNum = num;
int sum = 0;
int digits = (int) Math.log10(originalNum) + 1;
while (originalNum > 0) {
int digit = originalNum % 10;
sum += (int) Math.pow(digit, digits);
originalNum /= 10;
}
if (sum == num) {
System.out.print(num + “ ”);
}
}
}
}

Output

7
Q4) Write java class that contains appropriate methods to find the
greatest number, LCM for two given Numbers.
import java.io.*;
public class Q4 {
public static void getGCDAndLCM(int a, int b){
int gcd = 1;
for (int i = 1; i <= Math.min(a, b); ++i) {
if (a % i == 0 && b % i == 0)
gcd = i;
}
int lcm = (a*b) / gcd;
System.out.println("GCD is : " + gcd);
System.out.println("LCM is : " + lcm);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter two number to find gcd and lcm");
int num1 = Integer.parseInt(br.readLine());
int num2 = Integer.parseInt(br.readLine());
getGCDAndLCM(num1, num2);
}
}

Output

8
Q5) Write a java program to generate all the combinations of 1,2 &
3 to form different numbers using for loop.
public class Q5 {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
for (int k = 1; k <= 3; k++) {
System.out.println(i*100 + j*10 + k);
}
}
System.out.println();

}
}
}

Output

9
Q6) Write a program to accept temperature of city in Fahrenheit &
convert the temperature into centigrade degrees.
import java.io.*;

public class Q6 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter temperature in Fahrenheit : ");
double tempFahrenheit = Double.parseDouble(br.readLine());
double tempCelsius = (tempFahrenheit-32) * (5.0/9.0);
System.out.println("Temperate in degree celsius is" +
tempCelsius);
}
}

Output

10
Q7) Write a menu driven program which has the following options:-

i) Prime or not

ii) Odd or even

iii) Armstrong or not


import java.io.*;

public class Q7 {
public static void oddOrEven(int num){
if(num%2==0){
System.out.println("Even");
}else{
System.out.println("Odd");
}
}
public static void primeOrNot(int num){
int flag = 1;
for (int i = 2; (i*i) < num; i++) {
if(num%i==0){
flag = 0;
break;
}
}
if(flag == 1){
System.out.println("The number is prime");
}else{
System.out.println("The number is not prime");
}
}
public static void armstrongOrNot(int num){
int copyNum = num;
int digits = (int)Math.log(copyNum) + 1;
int sum = 0;
while(copyNum > 0){
int digit = copyNum % 10;
sum += (int) Math.pow(digit, digits);
copyNum /= 10;
}
if(sum == num){
System.out.println("The number is an armstrong number");
}else{

11
System.out.println("The number is not a armstrong number");
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int choice = 0;
do {
System.out.println("1) Prime or not\n" +
"2) Odd or even\n" +
"3) Armstrong or not\n"+
"4) Exit");
System.out.print("Enter your choice : ");
choice = Integer.parseInt(br.readLine());
System.out.print("Enter the number you want to operate on :
");
int num = Integer.parseInt(br.readLine());
switch (choice){
case 1:
primeOrNot(num);
break;
case 2:
oddOrEven(num);
break;
case 3:
armstrongOrNot(num);
break;
case 4:
System.exit(0);
break;
default:
System.out.println("Incorrect choice");
break;
}
}while ((choice >= 1) && (choice <= 4));
}
}

Output

12
13
Q8) Write a java program to input a number & convert the inputted
the number in words

Input: 7893

Output: Seven Eight Nine Three


import java.util.Scanner;

public class Q8 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
String words = numberToWordsPlaceValues(number);
System.out.println("Number in words (place values): " + words);
}

public static String numberToWordsPlaceValues(int number) {


if (number == 0) {
return "Zero";
}
String[] units = {"", "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine"};
String words = "";
while (number > 0) {
int digit = number % 10;
words = units[digit] + " " + words;
number /= 10;
}
return words.trim(); // Remove leading/trailing spaces
}
}

Output

14
Q9) Write a java program to input a number & convert the inputted
the number in words

Input: 78935

Output: Seventy Eight Thousand Nine Hundred Thirty Five Only


import java.util.Scanner;

public class Q9 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
String words = numberToWords(number);
System.out.println("Number in words: " + words);
}

public static String numberToWords(int number) {


if (number == 0) {
return "Zero";
}
String[] units = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine"};
String[] teens = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen"};
String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty",
"Ninety"};
String words = "";
if (number < 10) {
words = units[number];
} else if (number < 20) {
words = teens[number - 10];
} else if (number < 100) {
words = tens[number / 10] + ((number % 10 != 0) ? " " + units[number % 10] : "");
} else if (number < 1000) {
words = units[number / 100] + " Hundred" + ((number % 100 != 0) ? " " +
numberToWords(number % 100) : "");
} else if (number < 1000000) {
words = numberToWords(number / 1000) + " Thousand" + ((number % 1000 != 0) ? " "
+ numberToWords(number % 1000) : "");
} else {
// Handle larger numbers (millions, billions, etc.) if needed
words = "Number out of range";

15
}
return words;
}
}

Output

16
Q10) Write a java program that asks the user to enter an amount
and prints number of notes (of denominations 500, 100, 50, 20, 10,
1) to be distributed. For example, if the user enters $451, then 4
note of 100, 1 note of 50 and 1 note of 1 is required.
import java.util.Scanner;

public class Q10 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the amount: ");
int amount = scanner.nextInt();
int[] notes = {500, 100, 50, 20, 10, 1};
System.out.println("Number of notes required:");
for (int note : notes) {
int count = amount / note;
amount %= note;
System.out.println(note + " rupee notes: " + count);
}
}
}

Output

17
Q11) Write a program to create a class Student with data ‘name,
city and age’ along with method printData to display the data.
Create the two objects s1 ,s2 to declare and access the values.
class Student {
String name;
String city;
int age;
public void printData() {
System.out.println("Name: " + name);
System.out.println("City: " + city);
System.out.println("Age: " + age);
}
}
public class Q11 {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Alice";
s1.city = "New York";
s1.age = 20;
s1.printData();
Student s2 = new Student();
s2.name = "Bob";
s2.city = "London";
s2.age = 22;
s2.printData();
}
}

Output

18
Q12) Write a program in java to enter the number through command
line argument if first and second number is not entered it will
generate the exception. Also divide the first number with second
number and generate the arithmetic exception.
public class Q12 {
public static void main(String[] args) {
if (args.length < 2) {
throw new IllegalArgumentException("Please provide two numbers as command-line
arguments.");
}
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
if (num2 == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
int result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);

} catch (NumberFormatException e) {
System.err.println("Invalid input. Please enter integers only.");
} catch (ArithmeticException e) {
System.err.println(e.getMessage());
}
}
}

Output

19
Q13) Write a program in java to enter the number through command
line argument if first and second number .using the method divides
the first number with second and generate the exception.
public class Q13 {
public static void main(String[] args) {
if (args.length < 2) {
throw new IllegalArgumentException("Please provide two numbers as command-line
arguments.");
}
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int result = divide(num1, num2);
System.out.println(num1 + " / " + num2 + " = " + result);
} catch (NumberFormatException e) {
System.err.println("Invalid input. Please enter integers only.");
} catch (ArithmeticException e) {
System.err.println("Division by zero is not allowed.");
}
}
public static int divide(int dividend, int divisor) throws ArithmeticException {
if (divisor == 0) {
throw new ArithmeticException("Division by zero");
}
return dividend / divisor;
}
}

Output

20
Q14) Write a java program in which thread sleep for 5 sec and
change the name of thread.
public class Q14 {
public static void main(String[] args) {
Thread currentThread = Thread.currentThread();
String originalThreadName = currentThread.getName();
try {
currentThread.setName("MyThread");
System.out.println("Thread Name before sleep: " + currentThread.getName());
Thread.sleep(5000);
System.out.println("Thread Name after sleep: " + currentThread.getName());
System.out.println("Thread slept for 5 seconds.");

} catch (InterruptedException e) {
e.printStackTrace();
} finally {
currentThread.setName(originalThreadName);
}
}
}

Output

21
Q15) Write a java program that checks whether a given string is
palindrome or not.
public class Q15 {
public static boolean isPalindrome(String str) {
String cleanStr = str.replaceAll("\\s+", "").toLowerCase();
int left = 0;
int right = cleanStr.length() - 1;
while (left < right) {
if (cleanStr.charAt(left) != cleanStr.charAt(right)) {
return false; // If characters don't match, it's not a palindrome
}
left++;
right--;
}
return true; // If the loop completes, it's a palindrome
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
if (isPalindrome(input)) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}
}
}

Output

22
Q16) Write a java program to create a class named Fun & use
method overloading to display the number of arguments & values of
those arguments.

class Fun {
public void display() {
System.out.println("Number of arguments: 0");
}
public void display(int a) {
System.out.println("Number of arguments: 1");
System.out.println("Value of argument 1: " + a);
}
public void display(int a, int b) {
System.out.println("Number of arguments: 2");
System.out.println("Value of argument 1: " + a);
System.out.println("Value of argument 2: " + b);
}
public void display(int a, int b, int c) {
System.out.println("Number of arguments: 3");
System.out.println("Value of argument 1: " + a);
System.out.println("Value of argument 2: " + b);
System.out.println("Value of argument 3: " + c);
}
}
public class Q16 {
public static void main(String[] args) {
Fun obj = new Fun();
obj.display();
obj.display(10);
obj.display(10, 20);
obj.display(10, 20, 30);
}
}

Output

23
Q17) Write a java program that implements method overriding?
class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
public class Q17 {
public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound(); // Output: Generic animal sound
Animal dog = new Dog();
dog.makeSound(); // Output: Woof! (Dog's implementation is called)
Animal cat = new Cat();
cat.makeSound(); // Output: Meow! (Cat's implementation is called)
}
}

Output

24
Q18) Write a java program to input two double dimension matrix &
display the result after matrix multiplication?
import java.util.Scanner;

public class Q18 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get dimensions of matrices
System.out.print("Enter the number of rows for matrix 1: ");
int rows1 = scanner.nextInt();
System.out.print("Enter the number of columns for matrix 1: ");
int cols1 = scanner.nextInt();
System.out.print("Enter the number of rows for matrix 2: ");
int rows2 = scanner.nextInt();
System.out.print("Enter the number of columns for matrix 2: ");
int cols2 = scanner.nextInt();
// Check if matrices can be multiplied
if (cols1 != rows2) {
System.out.println("Matrix multiplication not possible. Number of columns in matrix 1
must be equal to the number of rows in matrix 2.");
return;
}
// Create matrices
double[][] matrix1 = new double[rows1][cols1];
double[][] matrix2 = new double[rows2][cols2];
double[][] result = new double[rows1][cols2];
// Get matrix 1 elements
System.out.println("Enter elements for matrix 1:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = scanner.nextDouble();
}
}
// Get matrix 2 elements
System.out.println("Enter elements for matrix 2:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = scanner.nextDouble();
}
}
// Multiply matrices
for (int i = 0; i < rows1; i++) {

25
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Display result matrix
System.out.println("Resultant matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}

Output

26
Q19) Write a java program to create two array that contains the
elements in ascending order. Now merge the above array &
maintain the order of the list of elements in the merged array?
import java.util.Arrays;

public class Q19 {


public static int[] mergeSortedArrays(int[] arr1, int[] arr2) {
int n1 = arr1.length;
int n2 = arr2.length;
int[] mergedArray = new int[n1 + n2];
int i = 0, j = 0, k = 0;
// Merge the two sorted arrays
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
mergedArray[k++] = arr1[i++];
} else {
mergedArray[k++] = arr2[j++];
}
}
// Copy remaining elements of arr1, if any
while (i < n1) {
mergedArray[k++] = arr1[i++];
}
// Copy remaining elements of arr2, if any
while (j < n2) {
mergedArray[k++] = arr2[j++];
}
return mergedArray;
}
public static void main(String[] args) {
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8};
int[] mergedArray = mergeSortedArrays(arr1, arr2);
System.out.println("Merged array: " + Arrays.toString(mergedArray));
}
}

Output

27
Q20) Write a java program to input a string & replace existence of
“is” with “was” in the modified string?
import java.io.*;

public class Q20 {


public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a string: ");
String input = reader.readLine();
StringBuffer sb = new StringBuffer(input);
int index = sb.indexOf("is");
while (index != -1) {
sb.replace(index, index + 2, "was");
index = sb.indexOf("is", index + 3);
}
System.out.println("Modified string: " + sb.toString());
}
}

Output

28
Q21) Write a java program to insert an element into array at specific
position?
import java.util.Scanner;

public class Q21 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] arr = new int[20]; // Fixed-size array
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
System.out.print("Enter the position to insert the element: ");
int pos = scanner.nextInt();
// Validate insertion position
if (pos < 0 || pos > size - 1) {
System.out.println("Invalid insertion position. Position should be
within 0 and " + (size - 1));
return;
}
System.out.print("Enter the element to be inserted: ");
int element = scanner.nextInt();
// Shift elements to the right
for (int i = size - 1; i >= pos; i--) {
arr[i + 1] = arr[i];
}
// Insert the element
arr[pos] = element;
// Print the modified array
System.out.print("Array after insertion: ");
for (int i = 0; i <= size; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}

Output

29
30
Q22) Write a program to create an interface named area containing
data members pi & compute method define a rectangle class that
implements the interface & return the area. Now define a class
named circle that implements area interface to calculate the area of
the Circle?
interface Area {
double pi = 3.14159; // Constant pi

double compute(); // Method to compute area


}
class Rectangle implements Area {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double compute() {
return length * width;
}
}
class Circle implements Area {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double compute() {
return pi * radius * radius;
}
}
public class Q22 {
public static void main(String[] args) {
Rectangle rect = new Rectangle(5.0, 3.0);
System.out.println("Area of rectangle: " + rect.compute());
Circle circle = new Circle(2.5);
System.out.println("Area of circle: " + circle.compute());
}
}

31
Output

32
Q23) Write a java program to facilitate user to handle any chance of
divide by zero exception
import java.util.Scanner;

public class Q23 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter the denominator: ");
int denominator = scanner.nextInt();
try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
scanner.close();
}
}

Output

33
Q24) Write program in Java for String handling which perform
followings

i) Checks the capacity of StringBuffer objects

ii) Reverse the contents of a string given on console and convert the
resultant string in upper case.

iii) Read a string from console and append it to the resultant string
of ii.
import java.util.Scanner;

public class Q24 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get input string
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
// Create StringBuffer
StringBuffer sb = new StringBuffer(inputString);
// Check capacity
System.out.println("Initial capacity of StringBuffer: " + sb.capacity());
// Reverse and convert to uppercase
sb.reverse();
sb.toString().toUpperCase();
System.out.println("Reversed and uppercase string: " + sb);
// Append another string
System.out.print("Enter another string to append: ");
String appendString = scanner.nextLine();
sb.append(appendString);
System.out.println("String after appending: " + sb);
}
}

Output

34
Q25) Write a java program to demonstrate user of super & this
keyword?

class Person {
String name;
Person(String name) {
this.name = name;
}
void displayPerson() {
System.out.println("Person Name: " + name);
}
}
class Students extends Person {
int studentID;
Students(String name, int studentID) {
// Calling parent class constructor using super
super(name);
this.studentID = studentID;
}
void displayStudent() {
System.out.println("Student ID: " + studentID);
super.displayPerson();
}
}
public class Q25 {
public static void main(String[] args) {
Students student = new Students("Alice", 12345);
student.displayStudent();
}
}

Output

35

You might also like