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

java file (1)

The document contains a series of Java programming exercises completed by a student named Bhavika, including operations on numbers, area calculations, temperature conversions, and solving quadratic equations. Each exercise is accompanied by source code and sample output demonstrating the functionality of the programs. The exercises cover a range of topics suitable for a programming laboratory course, showcasing the student's understanding of Java syntax and logic.

Uploaded by

bhavikas392
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

java file (1)

The document contains a series of Java programming exercises completed by a student named Bhavika, including operations on numbers, area calculations, temperature conversions, and solving quadratic equations. Each exercise is accompanied by source code and sample output demonstrating the functionality of the programs. The exercises cover a range of topics suitable for a programming laboratory course, showcasing the student's understanding of Java syntax and logic.

Uploaded by

bhavikas392
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Name:-Bhavika Subject :-Programming in Java Laboratory

Roll No :-3133/22 Course Code: UGCA1938

1. Write a program to perform following operations on two numbers input by the


user: 1) Addition 2) subtraction 3) multiplication 4) division .

import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int first, second, add, subtract, multiply;
float devide;
Scanner scanner = new Scanner(System.in);

System.out.print("Enter Two Numbers : ");


first = scanner.nextInt();
second = scanner.nextInt();

add = first + second;


subtract = first - second;
multiply = first * second;
devide = (float) first / second;
System.out.println("Sum = " + add);
System.out.println("Difference = " + subtract);
System.out.println("Multiplication = " + multiply);
System.out.println("Division = " + devide);
}
}

1
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

Output :-

Enter two number : 50


50
Sum = 100
Diffrence = 0
Multiplication = 2500
Division = 1

2
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

2. Write a Java program to print result of the following operations.


a) -15 +58 * 45
b) (35+8) % 6
c) 24 + -5*3 / 7
d) 15 + 18 / 3 * 2 - 9 % 3

public class JavaProgram {


public static void main(String[] args) {
int result1 = -15 + 58 * 45;
int result2 = (35 + 8) % 6;
int result3 = 24 + -5 * 3 / 7;
int result4 = 15 + 18 / 3 * 2 - 9 % 3;

System.out.println("Result of -15 + 58 * 45: " + result1);


System.out.println("Result of (35 + 8) % 6: " + result2);
System.out.println("Result of 24 + -5 * 3 / 7: " + result3);
System.out.println("Result of 15 + 18 / 3 * 2 - 9 % 3: " + result4);
}
}
Output :-

Result of -15 + 58 *45 : 2595


Result of (35 + 8) % 6 : 1
Result of 24 + -5 * 3 / 7 : 22
Result of 15 + 18 /3 * 2 – 9 % 3 : 27

3
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

3. Write a Java program to compute area of:


1) Circle
2) rectangle
3) triangle
4) square

import java.util.Scanner;

public class AreaCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Circle
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
double areaCircle = Math.PI * radius * radius;
System.out.println("Area of the circle: " + areaCircle);

// Rectangle
System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble();
double areaRectangle = length * width;
System.out.println("Area of the rectangle: " + areaRectangle);

// Triangle
System.out.print("Enter the base of the triangle: ");
double base = scanner.nextDouble();
System.out.print("Enter the height of the triangle: ");
double height = scanner.nextDouble();
double areaTriangle = 0.5 * base * height;
System.out.println("Area of the triangle: " + areaTriangle);

// Square
System.out.print("Enter the side of the square: ");
double side = scanner.nextDouble();
double areaSquare = side * side;
System.out.println("Area of the square: " + areaSquare);

scanner.close();
4
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

}
}

Output :-

Enter the radius of the circle : 8


Area of circle : 201.06192
Enter the length of the rectangle : 7
Enter the width of rectangle : 5
Area of rectangle : 35.0
Enter the base of the triangle : 4
Enter the height of the triangle : 6
Area of the triangle : 12.0
Enter the side of the square : 5
Area of the square : 25.0

5
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

4. Write a program to convert temperature from Fahrenheit to Celsius


degree using Java.

import java.util.Scanner;

public class FahrenheitToCelsius {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter temperature in Fahrenheit: ");


double fahrenheit = scanner.nextDouble();

double celsius = (fahrenheit - 32) * 5 / 9;


System.out.println(fahrenheit + " degree Fahrenheit is equal to
" + celsius + " degree Celsius.");
}
}

Output :-

Enter temprature in Fahrenheit : 95.7


95.7 degree is equal to 35.3888

6
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

5. Write a program through Java that reads a number in inches,


converts it to meters.
import java.util.Scanner;
public class InchesToMetersConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a value for inch: ");
double inches = scanner.nextDouble();
double meters = inches * 0.0254;
System.out.println(inches + " inch is " + meters + " meters");
scanner.close();
}
}
Output :-

Input a value for a inch : 15


15.0 inch is 0.381 meters

7
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

6. Write a program to convert minutes into a number of years and days.

import java.util.Scanner;
public class MinutesToYearsDays {
public static void main(String[] args) {
double minutesInYear = 60 * 24 * 365;
Scanner input = new Scanner(System.in);
System.out.print("Input the number of minutes: ");
double minutes = input.nextDouble();

long years = (long) (minutes / minutesInYear);


int days = (int) (minutes / 60 / 24) % 365;

System.out.println(minutes + " minutes is approximately " + years + "


years and " + days + " days.");
}
}
Output :-

Input the number of minutes : 1012102


1012102.0 minutes is approximately 1 years and 337 days.

8
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

7. Write a Java program that prints current time in GMT.

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class CurrentTimeInGMT {


public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String gmtTime = sdf.format(now);
System.out.println("Current time in GMT: " + gmtTime);
}
}
Output :-

Current time in GMT: 2024-09-04 15:02:50


=== Code Execution Successful ===

9
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

8. Design a program in Java to solve quadratic equations using if, if else.


import java.util.Scanner;
public class QuadraticEquationSolver {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter coefficient a: ");
double a = scanner.nextDouble();
System.out.print("Enter coefficient b: ");
double b = scanner.nextDouble();
System.out.print("Enter coefficient c: ");
double c = scanner.nextDouble();
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The roots are real and distinct.");
System.out.println("Root 1: " + root1);
System.out.println("Root 2: " + root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
System.out.println("The root is real and repeated.");
System.out.println("Root: " + root);
} else {
double realPart = -b / (2 * a);
double imaginaryPart = Math.sqrt(-discriminant) / (2 * a);
System.out.println("The roots are complex and imaginary.");

10
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

System.out.println("Root 1: " + realPart + " + " + imaginaryPart +


"i");
System.out.println("Root 2: " + realPart + " - " + imaginaryPart +
"i");
}
scanner.close();
}
}

OUTPUT:

Enter coefficient a: 2
Enter coefficient b: 5
Enter coefficient c: 3
The roots are real and distinct.
Root 1: -1.0
Root 2: -1.5

11
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

9. Write a Java program to determine greatest number of three numbers.


import java.util.Scanner;
public class GreatestOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scanner.nextDouble();
if (num1 >= num2 && num1 >= num3) {
System.out.println("The greatest number is: " + num1);
} else if (num2 >= num1 && num2 >= num3) {
System.out.println("The greatest number is: " + num2);
} else {
System.out.println("The greatest number is: " + num3);
}
scanner.close();
}
}

OUTPUT:- Enter the first number: 20


Enter the second number: 30
Enter the third number: 25
The greatest number is: 30.0

12
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

10. Write program that gets a number from the user and generates an integer
between 1 and 7 subsequently should display the name of the weekday as
per that number.
import java.util.Scanner;
public class WeekdayGenerator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number between 1 and 7: ");
int number = scanner.nextInt();
if (number < 1 || number > 7) {
System.out.println("Please enter a valid number between 1 and 7.");
} else {
String weekday = "";
switch (number) {
case 1:
weekday = "Monday";
break;
case 2:
weekday = "Tuesday";
break;
case 3:
weekday = "Wednesday";
break;
case 4:
weekday = "Thursday";
break;
case 5:

13
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

weekday = "Friday";
break;
case 6:
weekday = "Saturday";
break;
case 7:
weekday = "Sunday";
break;
}
System.out.println("The day of the week is: " + weekday);
}
scanner.close();
}
}

OUTPUT:

Enter a number between 1 and 7: 5


The day of the week is: Friday

14
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

11. Construct a Java program to find the number of days in a month.


import java.util.Scanner;
public class DaysInMonth {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the month (1-12): ");
int month = scanner.nextInt();
System.out.print("Enter the year: ");
int year = scanner.nextInt();
int days = 0;
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8
|| month == 10 || month == 12) {
days = 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
days = 30;
} else if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
} else {
System.out.println("Invalid month entered.");
System.exit(0);
}

15
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

System.out.println("Number of days in month " + month + " of year "


+ year + " is: " + days);

scanner.close();
}
}

OUTPUT:-

Enter the month (1-12): 8


Enter the year: 2019
Number of days in month 8 of year 2019 is: 31

16
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

12. Write a program to sum values of an Single Dimensional array.


import java.util.Scanner;
public class SumArray {
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[] array = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
int sum = 0;
for (int i = 0; i < size; i++) {
sum += array[i];
}
System.out.println("The sum of the array elements is: " + sum);
scanner.close();
}
}
Enter the size of the array: 5
OUTPUT:- Enter the elements of the array:

The sum of the array elements is: 20

17
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

13. Design & execute a program in Java to sort a numeric array and a string array.
import java.util.Arrays;
public class SortArrays {
public static void main(String[] args) {
int[] numericArray = {5, 2, 8, 1, 3};
String[] stringArray = {"Banana", "Apple", "Cherry", "Mango",
"Blueberry"};
Arrays.sort(numericArray);
// Sorting string array
Arrays.sort(stringArray);
System.out.println("Sorted numeric array: " +
Arrays.toString(numericArray));
System.out.println("Sorted string array: " +
Arrays.toString(stringArray));
}
}

OUTPUT:-

Sorted numeric array: [1, 2, 3, 5, 8]


Sorted string array: [Apple, Banana, Blueberry, Cherry, Mango ]

18
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

14. Calculate the average value of array elements through Java Program.
import java.util.Scanner;
public class AverageArray {
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();
double[] array = new double[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextDouble();
}
double sum = 0;
for (int i = 0; i < size; i++) {
sum += array[i];
}
double average = sum / size;
System.out.println("The average value of the array elements is: " +
average);
scanner.close();
}
Enter the size of the array: 3
}
Enter the elements of the array:
OUTPUT:-
5
5
10
The average value of the array elements is: 6.666666666666667

19
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

15. Write a Java program to test if an array contains a specific value.


import java.util.Scanner;
public class ArrayContainsValue {
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[] array = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.print("Enter the value to search for: ");
int valueToSearch = scanner.nextInt();
boolean found = false;
for (int i = 0; i < size; i++) {
if (array[i] == valueToSearch) {
found = true;
break;
}
}
if (found) {
System.out.println("The array contains the value " +
valueToSearch);
} else {
System.out.println("The array does not contain the value " +
valueToSearch);

20
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

}
scanner.close();
}
}
OUTPUT:-

Enter the size of the array: 3


Enter the elements of the array:
13
15
20
Enter the value to search for: 13
The array contains the value 13

21
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

16. Find the index of an array element by writing a program in Java.


import java.util.Scanner;
public class FindIndex {
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[] array = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.print("Enter the value to find: ");
int valueToFind = scanner.nextInt();
int index = -1;
for (int i = 0; i < size; i++) {
if (array[i] == valueToFind) {
index = i;
break;
}
}
if (index == -1) {
System.out.println("The value " + valueToFind + " is not in the
array.");
} else {
System.out.println("The value " + valueToFind + " is at index " +
index + ".");

22
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

}
scanner.close();
}
}

OUTPUT:-

Enter the size of the array: 5


Enter the elements of the array:
1
2
3
4
5
Enter the value to find: 3
The value 3 is at index 2.

23
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

17. Write a Java program to remove a specific element from an array.


import java.util.Scanner;
public class RemoveElement {
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[] array = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.print("Enter the value to remove: ");
int valueToRemove = scanner.nextInt();
int[] newArray = new int[size - 1];
int index = 0;
for (int i = 0; i < size; i++) {
if (array[i] != valueToRemove) {
newArray[index++] = array[i];
}
}
System.out.println("Array after removing " + valueToRemove + ":");
for (int i = 0; i < index; i++) {
System.out.print(newArray[i] + " ");
}
scanner.close();
}}
24
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

OUTPUT:-

Enter the size of the array: 5


Enter the elements of the array:
12
13
11
10
15
Enter the value to remove: 11
Array after removing 11:
12 13 10 15

25
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

18. Design a program to copy an array by iterating the array.


import java.util.Scanner;
public class CopyArray {
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[] originalArray = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
originalArray[i] = scanner.nextInt();
}
int[] copyArray = new int[size];
for (int i = 0; i < size; i++) {
copyArray[i] = originalArray[i];
}
System.out.println("The copied array is:");
for (int i = 0; i < size; i++) {
System.out.print(copyArray[i] + " ");
}
scanner.close(); Enter the size of the array: 5

} Enter the elements of the array:

} 1

2
OUTPUT:-
3

The copied array is:


26 12313
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

19. Write a Java program to insert an element (on a specific position) into
Multidimensional array.
import java.util.Scanner;
public class InsertElementIn2DArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int columns = scanner.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
array[i][j] = scanner.nextInt();
}
}
System.out.print("Enter the row position to insert the element: ");
int rowPos = scanner.nextInt();
System.out.print("Enter the column position to insert the element: ");
int colPos = scanner.nextInt();
System.out.print("Enter the element to insert: ");
int element = scanner.nextInt();
if (rowPos >= 0 && rowPos < rows && colPos >= 0 && colPos <
columns) {
array[rowPos][colPos] = element;
} else {

27
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

System.out.println("Invalid position entered.");


System.exit(0);
}
System.out.println("The updated array is:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}

OUTPUT:-

Enter the number of rows: 2


Enter the number of columns: 2
Enter the elements of the array:
1
2
3
4
Enter the row position to insert the element: 1
Enter the column position to insert the element: 2
Enter the element to insert: 3
Invalid position entered

28
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

20. Write a program to perform following operations on strings: 1)


Compare two strings. 2) Count string length. 3) Convert upper case to
lower case & vice versa. 4) Concatenate two strings. 5) Print a substring
import java.util.Scanner;
public class StringOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();
System.out.print("Enter the second string: ");
String str2 = scanner.nextLine();
if (str1.equals(str2)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are not equal.");
}
System.out.println("Length of the first string: " + str1.length());
System.out.println("Length of the second string: " + str2.length());
System.out.println("First string in uppercase: " +
str1.toUpperCase());
System.out.println("Second string in lowercase: " +
str2.toLowerCase());
String concatenatedString = str1 + str2;
System.out.println("Concatenated string: " + concatenatedString);
System.out.print("Enter the starting index for the substring: ");
int startIndex = scanner.nextInt();
System.out.print("Enter the ending index for the substring: ");
int endIndex = scanner.nextInt();

29
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

if (startIndex >= 0 && endIndex <= str1.length() && startIndex <


endIndex) {
System.out.println("Substring of the first string: " +
str1.substring(startIndex, endIndex));
} else {
System.out.println("Invalid substring indices.");
}
scanner.close();
}
}
OUTPUT:-

Enter the first string: Bhavika


Enter the second string: Sharma
The strings are not equal.
Length of the first string: 5
Length of the second string: 6
First string in uppercase: BHAVIKA
Second string in lowercase: sharma
Concatenated string: Bhavikasharma
Enter the starting index for the substring:

30
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

21. Developed Program & design a method to find the smallest number
among three numbers.
import java.util.Scanner;
public class SmallestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scanner.nextDouble();
double smallest = findSmallest(num1, num2, num3);
System.out.println("The smallest number is: " + smallest);
scanner.close();
}
public static double findSmallest(double a, double b, double c) {
if (a <= b && a <= c) {
return a;
} else if (b <= a && b <= c) {
return b;
} else {
return c;
}
}
}

31
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

OUTPUT:-

Enter the first number: 30


Enter the second number: 20
Enter the third number: 50
The smallest number is: 20.0

32
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

22. Compute the average of three numbers through a Java Program.


import java.util.Scanner.
public class AverageOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scanner.nextDouble();
double average = (num1 + num2 + num3) / 3;
System.out.println("The average of the three numbers is: " +
average);
scanner.close();
}
}
OUTPUT:-

Enter the first number: 23


Enter the second number: 34
Enter the third number: 22
The average of the three numbers is: 26.333333333333332

33
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

23. Write a Program & design a method to count all vowels in a string.
import java.util.Scanner;
public class VowelCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
int vowelCount = countVowels(input);
System.out.println("The number of vowels in the string is: " +
vowelCount);
scanner.close();
}
public static int countVowels(String str) {
int count = 0;
str = str.toLowerCase(); // Convert the string to lowercase for easier
comparison
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++;
}
}
return count;
}
}
Enter a string: junaid
OUTPUT:-
The number of vowels in the string is: 3

34
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

24. Write a Java method to count all words in a string.


import java.util.Scanner;
public class WordCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
int wordCount = countWords(input);
System.out.println("The number of words in the string is: " +
wordCount);
scanner.close();
}
public static int countWords(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
String[] words = str.split("\\s+");
return words.length;
}
}
OUTPUT:-

Enter a string: my name is Bhavika


The number of words in the string is:
4

35
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

25. Write a method in Java program to count all words in a string.


import java.util.Scanner;
public class WordCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
int wordCount = countWords(input);
System.out.println("The number of words in the string is: " +
wordCount);
scanner.close();
}
public static int countWords(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
String[] words = str.split("\\s+");
return words.length;
}
}
OUTPUT:-

Enter a string: Bhavika is always right


The number of words in the string is: 4

36
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

26. Write a Java program to handle following exceptions: 1) Divide by Zero


Exception. 2) Array Index Out Of B bound Exception.
import java.util.Scanner;
public class ExceptionHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter the denominator: ");
int denominator = scanner.nextInt();
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
try {
int[] array = {1, 2, 3, 4, 5};
System.out.print("Enter the index to access: ");
int index = scanner.nextInt();
System.out.println("Element at index " + index + ": " +
array[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds.");
}
scanner.close();
}

37
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

OUTPUT:-

Enter the numerator: 2


Enter the denominator: 6
Result: 0
Enter the index to access: 2
Element at index 2: 3

38
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

27. To represent the concept of Multithreading write a Java program.


class MyThread extends Thread {
private String threadName;
MyThread(String name) {
threadName = name;
}
public void run() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + ": " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
System.out.println(threadName + " exiting.");
}
}
public class MultithreadingDemo {
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread-1");
MyThread thread2 = new MyThread("Thread-2");
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
39
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

OUTPUT:-

Thread-2: 1
Thread-1: 1
Thread-2: 2
Thread-1: 2
Thread-2: 3
Thread-1: 3
Thread-2: 4
Thread-1: 4
Thread-2: 5
Thread-1: 5
Thread-2 exiting.
Thread-1 exiting.
Main thread exiting.

40
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

28. To represent the concept of all types of inheritance supported by Java,


design a program.
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("The puppy weeps.");
}
}
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}
interface CanRun {
void run();
}
interface CanSwim {
void swim();

41
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

}
class Labrador extends Dog implements CanRun, CanSwim {
public void run() {
System.out.println("The Labrador runs fast.");
}
public void swim() {
System.out.println("The Labrador swims well.");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
Puppy puppy = new Puppy();
puppy.eat();
puppy.bark();
puppy.weep();
Cat cat = new Cat();
cat.eat();
cat.meow();
Labrador labrador = new Labrador();
labrador.eat();
labrador.bark();
labrador.run();
labrador.swim();
}
42
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

OUTPUT:-

This animal eats food.


The dog barks.
This animal eats food.
The dog barks.
The puppy weeps.
This animal eats food.
The cat meows.
This animal eats food.
The dog barks.
The Labrador runs fast.
The Labrador swims well.

43
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

29. To represent the concept of all types of inheritance supported by Java,


design a program.
interface CanFly {
void fly();
}
interface CanSwim {
void swim();
}
class Duck implements CanFly, CanSwim {
public void fly() {
System.out.println("The duck flies.");
}
public void swim() {
System.out.println("The duck swims.");
}
}
public class MultipleInheritanceDemo {
public static void main(String[] args) {
Duck duck = new Duck();
duck.fly();
duck.swim();
}
}
OUTPUT:-

The duck flies.


The duck swims.

44
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

30. Construct a program to design a package in Java.


1st programg:-
File: com/example/HelloWorld.java
package com.example;
public class HelloWorld {
public void sayHello() {
System.out.println("Hello, World!");
}
}

2nd program:_ File: com/example/Greetings.java.


package com.example;
public class Greetings {
public void sayGreetings() {
System.out.println("Greetings from the package!");
}
}

3rd main program:- File: Main.java.


import com.example.HelloWorld;
import com.example.Greetings;
public class Main {
public static void main(String[] args) {
HelloWorld hello = new HelloWorld();
hello.sayHello();

Greetings greetings = new Greetings();


45
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

greetings.sayGreetings();
}
}

OUTPUT:-

javac com/example/HelloWorld.java
javac com/example/Greetings.java
javac Main.java
java Main

Hello, World!
Greetings from the package!

46
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

31. To write and read a plain text file, write a Java program.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadWrite {
public static void main(String[] args) {
String filePath = "example.txt";
String contentToWrite = "Hello, this is a sample text.";
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(filePath))) {
writer.write(contentToWrite);
System.out.println("Content written to file successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
String line;
System.out.println("Reading content from file:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading from the
file.");
47
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

e.printStackTrace();
}
}
}

OUTPUT:-

Content written to file successfully.


Reading content from file:
Hello, this is a sample text.

48
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

32. Write a Java program to append text to an existing file.


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class AppendToFile {
public static void main(String[] args) {
String filePath = "example.txt";
String textToAppend = "This is the appended text.";
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(filePath, true))) {
writer.write(textToAppend);
writer.newLine(); // Add a new line after the appended text
System.out.println("Text appended to file successfully.");
} catch (IOException e) {
System.out.println("An error occurred while appending to the
file.");
e.printStackTrace();
}
}
}

OUTPUT:-

Text appended to file successfully.

49
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

33. Design a program in Java to get a list of all file/directory names from
the given.
import java.io.File;
public class ListFilesAndDirectories {
public static void main(String[] args) {
String directoryPath = "path/to/your/directory";
File directory = new File(directoryPath);
String[] fileList = directory.list();
if (fileList != null) {
System.out.println("Files and directories in " + directoryPath + ":");
for (String fileName : fileList) {
System.out.println(fileName);
}
} else {
System.out.println("The specified path is not a directory or an error
occurred.");
}
}
}

OUTPUT:-

The specified path is not a directory or an


error occurred.

50
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

34. Develop a Java program to check if a file or directory specified by


pathname exists or not.
import java.io.File;
import java.util.Scanner;
public class FileExistenceCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the pathname of the file or directory: ");
String pathname = scanner.nextLine();
File file = new File(pathname);
if (file.exists()) {
System.out.println("The file or directory exists.");
} else {
System.out.println("The file or directory does not exist.");
}
scanner.close();
}
}

OUTPUT:-

Enter the pathname of the file or directory: myfile


The file or directory does not exist.

51
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

35. Write a Java program to check if a file or directory has read and write
permission.
import java.io.File;
import java.util.Scanner;
public class FilePermissionsCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the pathname of the file or directory: ");
String pathname = scanner.nextLine();
File file = new File(pathname);
if (file.exists()) {
if (file.canRead()) {
System.out.println("The file or directory has read permission.");
} else {
System.out.println("The file or directory does not have read
permission.");
}
if (file.canWrite()) {
System.out.println("The file or directory has write permission.");
} else {
System.out.println("The file or directory does not have write
permission.");
}
} else {
System.out.println("The file or directory does not exist.");
}
scanner.close();
}
52
Name:-Bhavika Subject :-Programming in Java Laboratory
Roll No :-3133/22 Course Code: UGCA1938

OUTPUT:-

Enter the pathname of the file or directory:


Bhavika file
The file or directory does not exist.

53

You might also like