Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JAVALabManualdocx__2024_11_23_14_36_01

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 55

Lab Manual of Programming in Java

Laboratory
(UGCA UGCA 1938)

COURSE: BCA
SESSION: July-Dec 2024
FACULTY:
SESSION: July-Dec 2024
FACULTY:

List of Experiments:

1. Write a program to perform following operations on two numbers input by the user:
1) Addition 2) subtraction 3) multiplication 4) division
2. Write a Java program to print result of the following operations.
1. -15 +58 * 45
2. (35+8) % 6
3. 24 + -5*3 / 7
4. 15 + 18 / 3 * 2 - 9 % 3
3. Write a Java program to compute area of:
1) Circle2) rectangle 3) triangle 4) square
4. Write a program to convert temperature from Fahrenheit to Celsius degree using
Java.
5. Write a program through Java that reads a number in inches, converts it to meters.
6. Write a program to convert minutes into a number of years and days.
7. Write a Java program that prints current time in GMT.
8. Design a program in Java to solve quadratic equations using if, if else
9. Write a Java program to determine greatest number of three numbers.
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.
11. Construct a Java program to find the number of days in a month.
12. Write a program to sum values of an Single Dimensional array.
13. Design & execute a program in Java to sort a numeric array and a string array.
14. Calculate the average value of array elements through Java Program.
15 Write a Java program to test if an array contains a specific value.
16 Find the index of an array element by writing a program in Java.
17 Write a Java program to remove a specific element from an array.
18 Design a program to copy an array by iterating the array.
19 Write a Java program to insert an element (on a specific position) into
Multidimensional array.
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.
21 Developed Program & design a method to find the smallest number among three
numbers.
22 Compute the average of three numbers through a Java Program.
23 Write a Program & design a method to count all vowels in a string.
24 Write a Java method to count all words in a string.
25 Write a method in Java program to count all words in a string.
26 Write a Java program to handle following exceptions: 1) Divide by Zero Exception. 2)
Array Index Out Of B bound Exception.
27 To represent the concept of Multithreading write a Java program.
28 To represent the concept of all types of inheritance supported by Java, design a
program.
29 Write a program to implement Multiple Inheritance using interface.
30 Construct a program to design a package in Java.
31 To write and read a plain text file, write a Java program.
32 Write a Java program to append text to an existing file.
33 Design a program in Java to get a list of all file/directory names from the given.
34 Develop a Java program to check if a file or directory specified by pathname exists or
not.
35 Write a Java program to check if a file or directory has read and write permission.
EXPERIMENT-1

Aim:Write a program to perform following operations on two


numbers input by the user:
1) Addition 2) subtraction 3) multiplication 4) division

OBJECTIVE:

The objective of the Java code is to create a program that performs the following
tasks:

1. Input: Prompt the user to enter two integer numbers.


2. Arithmetic Operations: Perform basic arithmetic operations on the
entered numbers:
○ Addition (+)
○ Subtraction (-)
○ Multiplication (*)
○ Division (/)
3. Output: Display the results of these operations (sum, difference, product,
and quotient) to the user.

Source Code:
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int first, second, add, subtract, multiply;
float divide;
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;
divide = (float) first / second;
System.out.println("Sum = " + add);
System.out.println("Difference = " + subtract);
System.out.println("Multiplication = " + multiply);
System.out.println("Division = " + divide);
}
}

OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:

Q1)- What does the import java.util.Scanner; statement do in Java?


Q2)- Why is it necessary to create a Scanner object in the program?
Q3)- What would happen if the user does not enter any values when prompted by the program?
EXPERIMENT-2

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


1. -15 +58 * 45
2. (35+8) % 6
3. 24 + -5*3 / 7
4. 15 + 18 / 3 * 2 - 9 % 3
OBJECTIVE:
1. The program demonstrates the use of arithmetic operators (+, -, *, /, %) in Java to perform addition,
subtraction, multiplication, division, and modulus operations.
2. It illustrates how Java evaluates expressions based on operator precedence rules (multiplication and
division before addition and subtraction).
3. Variables a, b, c, and d are assigned their respective calculated values and then printed to the console
using System.out.println().

Source Code:
public class Main
{
public static void main(String args[])
{
int a,b,c,d;
a=-15 +58 * 45;
b=(35+8) % 6;
c=24 + -5*3 / 7;
d=15 + 18 / 3 * 2 - 9 % 3;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:


Q1)- What happens if parentheses are removed from the expression b = (35 + 8) % 6;?
Q2)- What is the significance of the expression a = -15 + 58 * 45;?
Q3)- What are the variables a, b, c, and d used for in the program?
EXPERIMENT-3

3. Write a Java program to compute area of:


1) Circle2) rectangle 3) triangle 4) square
OBJECTIVE:
1. The program showcases method overloading, where multiple methods with the same name
(calculateArea) are defined but differ in the type or number of their parameters.
2. By using method overloading, the program demonstrates polymorphism in Java, where the
appropriate calculateArea method is selected based on the type and number of arguments passed
during method invocation.
3. The methods accept different types of parameters (float, double, int) to calculate areas of
geometric shapes, illustrating how Java handles method invocation based on parameter type matching.

Source Code:
public class Main {
void calculateArea(float x) {
System.out.println("Area of the square: " + x * x + " sq units");
}
void calculateArea(float x, float y) {
System.out.println("Area of the rectangle: " + x * y + " sq units");
}
void calculateArea(double r) {
double area = 3.14 * r * r;
System.out.println("Area of the circle: " + area + " sq units");
}
void calculateArea(int x, int y) {
double area = (x * y) / 2;
System.out.println("Area of the triangle: " + area + " sq units");
}
public static void main(String args[]) {
Main obj = new Main();
obj.calculateArea(6.1f);
obj.calculateArea(10, 22);
obj.calculateArea(6.1);
obj.calculateArea(12, 5);
}
}

OUTPUT:
SAMPLE VIVA-VOVE QUESTIONS:

Q1)- What are the advantages of method overloading in Java?


Q2)- Explain the concept of polymorphism as demonstrated in the provided program.
Q3)- What is method overloading in Java? How does the provided program demonstrate
method overloading?
EXPERIMENT-4

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


degree using Java

OBJECTIVE:
1.The conversion from Fahrenheit to Celsius is based on the formula, which accurately calculates
the temperature in Celsius.
2.Arithmetic operations and expression evaluation in Java, specifically for temperature conversion.
3.The program provides immediate feedback to the user by displaying the converted temperature
in Celsius, ensuring clarity and transparency in the conversion process.

Source Code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
double celsius, fahrenheit;
Scanner s = new Scanner(System.in);
System.out.print("Enter temperature in Fahrenheit:");
fahrenheit = s.nextDouble();
celsius = (fahrenheit-32)*(0.5556);
System.out.println("Temperature in Celsius:"+celsius);
}
}
OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:

Q1)- What is the purpose of importing java.util.Scanner in the program?


Q2)- Explain how the program converts temperature from Fahrenheit to Celsius using the formula
(fahrenheit - 32) * 0.5556.
Q3)- Discuss the significance of using double data type for variables celsius and fahrenheit in
the program.
EXPERIMENT-5

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


converts it to meters.
OBJECTIVE:
1. The conversion factor 0.0254 is based on the international standard for converting inches to meters.
2. The program provides immediate feedback to the user by displaying the converted length in meters,
ensuring clarity and transparency in the conversion process.

Source Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter length in inches");
int inches = in.nextInt();
double meters = 0.0254 * inches;
System.out.println("inches is equal to=" + meters);
}
}
OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:

Q1)- Discuss the significance of the conversion factor 0.0254 used in the program. How does it convert
inches to meters?
Q2)- What happens if you input a negative value for length in inches? Does the program handle negative
values appropriately?
Q3)- Discuss potential limitations of using double for storing the converted length in meters (double
meters = 0.0254 * inches;)
EXPERIMENT-6

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


days

OBJECTIVE:
1. The objective of the above Java code is to calculate and display the approximate number of years and
days equivalent to a given number of minutes entered by the user.

Source Code:
import java.util.Scanner;
public class Main{
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 min=input.nextDouble();
long years = (long) (min / minutesInYear);
int days = (int) (min / 60 / 24) % 365;
System.out.println((int) min + " minutes is approximately " + years + " years and " + days + " days");
}
}

OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:

Q1)- Explain the purpose of the double minutesInYear = 60 * 24 * 365; line in the code.
Why is it important for the calculation?
Q2)- Explain the casting used in long years = (long) (min / minutesInYear);. Why is the
result cast to long?
Q3)-How could you modify the program to account for leap years when calculating the number of days?
EXPERIMENT-7

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


OBJECTIVE:
1. The program demonstrates how to customize date and time formatting using SimpleDateFormat,
allowing precise control over how dates and times are displayed.

Source Code:
import java.util.*;
import java.text.*;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss zzz");
Date date = new Date();
System.out.println("Local Time: " + sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT Time : " + sdf.format(date));
}
}

OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:

Q1)- Explain the purpose of importing java.util.* and java.text.* in the program. Why are
these packages necessary?
Q2)- What is the significance of "yyyy MMM dd HH:mm:ss zzz" in SimpleDateFormat sdf =
new SimpleDateFormat("yyyy MMM dd HH:mm:ss zzz");? How does it specify the date and
time format?
Q3)-What would happen if you used a different time zone identifier (e.g., "PST", "EST" instead of
"GMT")? How would the output change?
EXPERIMENT-8

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


else
OBJECTIVE:
1. The objective of the above Java code is to solve a quadratic equation entered by the user, calculate its
roots (if they are real), and display the results.
2. Students learn how conditional statements (if, else if, else) to handle different scenarios based
on the value of the discriminant (result).

Source Code:
import java.util.Scanner;
public class Main{
public static void main(String[] Strings) {
Scanner input = new Scanner(System.in);
System.out.print("Input a: ");
double a = input.nextDouble();
System.out.print("Input b: ");
double b = input.nextDouble();
System.out.print("Input c: ");
double c = input.nextDouble();
double result = b * b - 4.0 * a * c;
if (result > 0.0) {
double r1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
double r2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
System.out.println("The roots are " + r1 + " and " + r2);
}
else if (result == 0.0) {
double r1 = -b / (2.0 * a);
System.out.println("The root is " + r1);
}
else {
System.out.println("The equation has no real roots.");
}
}
}
OUTPUT:
SAMPLE VIVA-VOVE QUESTIONS:

Q1)-Describe the significance of input.nextDouble() in double a = input.nextDouble();,


double b = input.nextDouble();, and double c = input.nextDouble();. What type of
input does the program expect?
Q2)- Explain the calculation of result = b * b - 4.0 * a * c;. What does this variable
result represent in the context of solving a quadratic equation?
Q3)- How does the program handle the scenario when result > 0.0? Explain the computation of r1
and r2 using the quadratic formula ((-b ± sqrt(b^2 - 4ac)) / 2a).
EXPERIMENT-9

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


numbers
OBJECTIVE:
1. The objective of the above Java code is to determine the largest number among three integers input
by the user
2. Students learn how to use of temp=a>b?a:b; and largest=c>temp?c:temp; demonstrates the
compact form of conditional logic in Java to determine the maximum value.

Source Code:
import java.util.Scanner;
public class Main{
public static void main(String[] Strings) {
int a, b, c, largest, temp;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number:");
a = sc.nextInt();
System.out.println("Enter the second number:");
b = sc.nextInt();
System.out.println("Enter the third number:");
c = sc.nextInt();
temp=a>b?a:b;
largest=c>temp?c:temp;
System.out.println("The largest number is: "+largest);
}
}
OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:

Q1)-Discuss the line temp = a > b ? a : b;. How does this line determine the larger of the first
two numbers (a and b)?
Q2)- Explain the purpose of largest = c > temp ? c : temp;. How does this line determine
the largest number among a, b, and c using the previously assigned temp variable?
Q3)- What happens if you input negative numbers? Does the program correctly identify the largest
negative number among the inputs?and r2 using the quadratic formula ((-b ± sqrt(b^2 - 4ac))
EXPERIMENT-10

10. Write program that gets a number from the user and generates an
integer between 1and 7 subsequently should display the name of the
weekday as per that number.

OBJECTIVE:
1. The students learn how to utilizes a switch statement within the getDayName method to match
the input day with predefined cases (1 through 7), each representing a specific day of the week.
2. The objective of the above Java code is to prompt the user to input a number representing a day of
the week (1 for Monday, 2 for Tuesday, ..., 7 for Sunday), and then use a method (getDayName) to
convert this numeric input into the corresponding day name in English.

Source Code:
import java.util.Scanner;
public class Main{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
int day = in.nextInt();
System.out.println(getDayName(day));
}
public static String getDayName(int day) {
String dayName = "";
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
case 4: dayName = "Thursday"; break;
case 5: dayName = "Friday"; break;
case 6: dayName = "Saturday"; break;
case 7: dayName = "Sunday"; break;
default:dayName = "Invalid day range";
}
return dayName;
}
}

OUTPUT:
SAMPLE VIVA-VOVE QUESTIONS:

Q1)-What happens if the user enters a number outside the range 1-7 when prompted for input? How
does the program handle this scenario?
Q2)-Discuss the significance of the getDayName method. What parameters does it take, and what does
it return?
Q3)- Explain how the switch statement inside the getDayName method works. How does it map
numeric inputs (day) to corresponding day names (dayName)?
EXPERIMENT-11

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


month
OBJECTIVE:
1. The objective of the above Java code is to determine the number of days in a specified month of a
given year based on user input.
2. Implements a leap year check within the case 2 (February) to dynamically determine whether
February has 28 or 29 days based on the given year.

Source Code:
import java.util.Scanner;
public class Main{
public static void main(String[] strings) {
Scanner input = new Scanner(System.in);

int number_Of_DaysInMonth = 0;
String MonthOfName = "Unknown";

System.out.print("Input a month number: ");


int month = input.nextInt();

System.out.print("Input a year: ");


int year = input.nextInt();

switch (month) {
case 1:
MonthOfName = "January";
number_Of_DaysInMonth = 31;
break;
case 2:
MonthOfName = "February";
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
number_Of_DaysInMonth = 29;
} else {
number_Of_DaysInMonth = 28;
}
break;
case 3:
MonthOfName = "March";
number_Of_DaysInMonth = 31;
break;
case 4:
MonthOfName = "April";
number_Of_DaysInMonth = 30;
break;
case 5:
MonthOfName = "May";
number_Of_DaysInMonth = 31;
break;
case 6:
MonthOfName = "June";
number_Of_DaysInMonth = 30;
break;
case 7:
MonthOfName = "July";
number_Of_DaysInMonth = 31;
break;
case 8:
MonthOfName = "August";
number_Of_DaysInMonth = 31;
break;
case 9:
MonthOfName = "September";
number_Of_DaysInMonth = 30;
break;
case 10:
MonthOfName = "October";
number_Of_DaysInMonth = 31;
break;
case 11:
MonthOfName = "November";
number_Of_DaysInMonth = 30;
break;
case 12:
MonthOfName = "December";
number_Of_DaysInMonth = 31;
}
System.out.print(MonthOfName + " " + year + " has " + number_Of_DaysInMonth + " days\n");
}
}

OUTPUT:
SAMPLE VIVA-VOVE QUESTIONS:

Q1)-How does the program determine the number of days in February (number_Of_DaysInMonth)
based on the input year (year)?
Q2)-What happens if the user enters a month number that is not between 1 and 12? How does the
program handle this scenario?
Q3)- Describe the variables number_Of_DaysInMonth and MonthOfName. What are their roles in
the program?
EXPERIMENT-12

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


OBJECTIVE:
1. Demonstrates basic array operations such as initialization, element assignment, and calculation of the
sum of elements.

Source Code:
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String args[]){
System.out.println("Enter the required size of the array :: ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one ");
for(int i=0; i<size; i++){
myArray[i] = s.nextInt();
sum = sum + myArray[i];
}
System.out.println("Elements of the array are: "+Arrays.toString(myArray));
System.out.println("Sum of the elements of the array ::"+sum);
}
}

OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:

Q1)-What happens if the user enters a negative number or zero for the size of the array (size)? How
does the program handle such cases?
Q2)-Explain how the program determines the size of the array (size). What input does the user
provide, and how is it processed?
Q3)- Discuss the significance of the myArray array. How is it initialized, and what values does it hold
after user input?
EXPERIMENT-13

13. Design & execute a program in Java to sort a numeric array


and a string array.
OBJECTIVE:
1. Demonstrates how to initialize arrays using both literal values and an array initializer list .
2. Illustrates the usage of Arrays.sort() method to sort arrays. Arrays are sorted in-place,
modifying the original arrays.

Source Code:
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String[] args){

int[] my_array1 = {
10, 2, 34, 56, 20,
58, 24, 12, 72, 65,
14, 21, 1, 29};

String[] my_array2 = {
"Java",
"Python",
"PHP",
"C Programming",
};
System.out.println("Original numeric array : "+Arrays.toString(my_array1));
Arrays.sort(my_array1);
System.out.println("Sorted numeric array : "+Arrays.toString(my_array1));

System.out.println("Original string array : "+Arrays.toString(my_array2));


Arrays.sort(my_array2);
System.out.println("Sorted string array : "+Arrays.toString(my_array2));
}
}

OUTPUT:
SAMPLE VIVA-VOVE QUESTIONS:

Q1)-Explain the purpose of the Arrays.toString() method used in this program.


Q2)-What does Arrays.sort(my_array1) do to the array my_array1? How does it change the
order of elements?
Q3)- What would happen if you tried to sort an array containing both integers and strings using
Arrays.sort()?
EXPERIMENT-14

14. Calculate the average value of array elements through Java


Program.
OBJECTIVE:
1. Students learn how to define the size of the array at runtime, making it flexible for different input
scenarios.

Source Code:
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter array size: ");
int size = s.nextInt();
int[] array = new int[size];
System.out.println("Enter array values : ");
for (int i = 0; i < size; i++) {
int value = s.nextInt();
array[i] = value;
}
int length = array.length;
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
double average = sum / length;
System.out.println("Average of array : " + average);
}
}
OUTPUT:
SAMPLE VIVA-VOVE QUESTIONS:

Q1)-What does the nextInt() method of Scanner class do? How is it used to read the size of the
array and its elements?
Q2)-Discuss the significance of using double for the average variable instead of int. How does it
affect the precision of the average calculation?
Q3)- How does the for loop iterate through the array to populate it with user-provided values?
15. Write a Java program to test if an array contains a specific
value
OBJECTIVE:
The objective of the program is to determine whether a specified number exists within an array . The
code achieves this objective by iterating through each element of the array using a for loop. During each
iteration, it checks if the current element of the array is equal to the specified number . If a match is
found, it prints the message "Array contains the given element".

Source Code:

import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
int[] myArray = {55, 45, 69, 44};
int num = 55;
for(int i = 0; i<myArray.length; i++){
if(num == myArray[i]){
System.out.println("Array contains the given element");
}
}
}
}
OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:

Q1)-What does int[] myArray = {55, 45, 69, 44}; do?


Q2)-How does the for loop (for(int i = 0; i < myArray.length; i++)) work in this code?
Q3)-What does the condition if(num == myArray[i]) check?
16. Find the index of an array element by writing a program in
Java
OBJECTIVE:
The objective of the Program is to define a static method findIndex that searches for a specified
integer (t) within an integer array (my_array). The findIndex method returns the index of the first
occurrence of t in my_array, or -1 if t is not found.

Source Code:

import java.util.Scanner;
public class Main {
static int findIndex (int[] my_array, int t) {
if (my_array == null) return -1;
int len = my_array.length;
int i = 0;
while (i < len) {
if (my_array[i] == t) return i;
else i=i+1;
}
return -1;
}
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
System.out.println("Index position of 25 is: " + findIndex(my_array, 25));
System.out.println("Index position of 77 is: " + findIndex(my_array, 77));
}
}

OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:

Q1)-What is the purpose of the findIndex method in this code?


Q2)-Explain the significance of the static keyword in the findIndex method signature.
Q3)-What happens if you pass an empty array (new int[] {}) to the findIndex method
17. Write a Java program to remove a specific element from an
array
OBJECTIVE:
The objective of the above Java code is to demonstrate how to delete a specific element
(elementToBeDeleted) from an integer array (arr) and shift the remaining elements to fill the gap
left by the deleted element. The code then prints the modified array (newArr) after the deletion and
shifting process.

Source Code:

import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {3,1,6,5,2,8,4};
int[] newArr = null;
int elementToBeDeleted = 5;
System.out.println("Original Array is: "+Arrays.toString(arr));

for (int i = 0; i < arr.length-1; i++) {


if(arr[i] == elementToBeDeleted){
newArr = new int[arr.length - 1];
for(int index = 0; index < i; index++){
newArr[index] = arr[index];
}
for(int j = i; j < arr.length - 1; j++){
newArr[j] = arr[j+1];
}
break;
}
}
System.out.println("New Array after deleting element = "+elementToBeDeleted+" and shifting: "+
Arrays.toString(newArr));
}
}

OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:


Q1)-Explain the significance of Arrays.toString(arr) in the System.out.println statement.
Q2)-Why is newArr initialized as null initially?
Q3)-What happens if elementToBeDeleted is not found in the array arr?
18.Design a program to copy an array by iterating the array
OBJECTIVE:
The objective of the above Java code is to demonstrate how to create a copy of an existing integer array
(my_array) into a new array (new_array). The code accomplishes this by iterating through each
element of my_array and copying it to new_array. Finally, it prints both the original array
(my_array) and the newly created copy (new_array) to verify the copy operation.

Source Code:

import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
int[] new_array = new int[10];
System.out.println("Source Array : "+Arrays.toString(my_array));
for(int i=0; i < my_array.length; i++) {
new_array[i] = my_array[i];
}
System.out.println("New Array: "+Arrays.toString(new_array));
}
}
OUTPUT:

SAMPLE VIVA-VOVE QUESTIONS:

Q1)-Why is it important to use a loop to copy array elements instead of assigning arrays directly
(new_array = my_array)?
Q2)-What happens if you change the size of new_array to a value smaller than my_array.length?
Q3)-How would you verify that the array copying operation was successful?
19. Write a Java program to insert an element (on a specific position) into
Multidimensional array

import java.util.Scanner;
public class Main {
public static void main(String[] input)
{
int i, element, n;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Size of Array: ");
n = scan.nextInt();
int[] arr = new int[n+1];
System.out.print("Enter " +n+ " Elements: ");
for(i=0; i<n; i++)
arr[i] = scan.nextInt();
System.out.print("Enter an Element to Insert: ");
element = scan.nextInt();
arr[i] = element;
System.out.println("\nNow the new array is: ");
for(i=0; i<(n+1); i++)
System.out.print(arr[i]+ " ");
}
}
OUTPUT:
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.

1) Compare two strings


import java.util.Scanner;
public class Main {
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
}
}

OUTPUT:
2) Count string length
import java.util.Scanner;
public class Main {
public static void main(String args[]){
String s1="java";
String s2="python";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}
OUTPUT:
3) Convert upper case to lower case & vice versa

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String str1="Java Programming";
StringBuffer newStr=new StringBuffer(str1);
for(int i = 0; i < str1.length(); i++) {
if(Character.isLowerCase(str1.charAt(i))) {
newStr.setCharAt(i, Character.toUpperCase(str1.charAt(i)));
}
else if(Character.isUpperCase(str1.charAt(i))) {
newStr.setCharAt(i, Character.toLowerCase(str1.charAt(i)));
}
}
System.out.println("String after case conversion : " + newStr);
}
}
OUTPUT:
4) Concatenate two strings
public class Main {
public static void main(String args[]){
String s1="Java ";
String s2="Programming";
String s3=s1.concat(s2);
System.out.println(s3);
}
}

OUTPUT:
5) Print a substring
public class Main {
public static void main(String args[]){
String s="JavaProgramming";
System.out.println("Original String: " + s);
System.out.println("Substring starting from index 4: " +s.substring(4));
System.out.println("Substring starting from index 0 to 4: "+s.substring(0,4));
}
}
OUTPUT:
21. Developed Program & design a method to find the smallest number
among three numbers.
import java.util.Scanner;
public class Exercise1 {

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);
System.out.print("Input the first number: ");
double x = in.nextDouble();
System.out.print("Input the Second number: ");
double y = in.nextDouble();
System.out.print("Input the third number: ");
double z = in.nextDouble();
System.out.print("The smallest value is " + smallest(x, y, z)+"\n" );
}

public static double smallest(double x, double y, double z)


{
return Math.min(Math.min(x, y), z);
}
}

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

import java.util.Scanner;
public class JavaExample {

public static void main(String[] args)


{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scan.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scan.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scan.nextDouble();
scan.close();
System.out.print("The average of entered numbers is:" + avr(num1, num2, num3) );
}

public static double avr(double a, double b, double c)


{
return (a + b + c) / 3;
}
}

OUTPUT
23. Write a Program & design a method to count all vowels in a string

import java.util.Scanner;
public class CountingVowels {
public static void main(String args[]){
int count = 0;
System.out.println("Enter a sentence :");
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();

for (int i=0 ; i<sentence.length(); i++){


char ch = sentence.charAt(i);
if(ch == 'a'|| ch == 'e'|| ch == 'i' ||ch == 'o' ||ch == 'u'||ch == ' '){
count ++;
}
}
System.out.println("Number of vowels in the given sentence is "+count);
}
}

OUTPUT

Enter a sentence :
Hi how are you? welcome to JAVA
Number of vowels in the given sentence is 12
24. Write a Java method to count all words in a string

import java.util.Scanner;
public class Exercise5 {

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);
System.out.print("Input the string: ");
String str = in.nextLine();

System.out.print("Number of words in the string: " + count_Words(str)+"\n");


}

public static int count_Words(String str)


{
int count = 0;
if (!(" ".equals(str.substring(0, 1))) || !(" ".equals(str.substring(str.length() - 1))))
{
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ' ')
{
count++;
}
}
count = count + 1;
}
return count; // returns 0 if string starts or ends with space " ".
}
}

OUTPUT
Input the string: The quick brown fox jumps over the lazy dog
Number of words in the string: 9
25 . Write a method in Java program to count all words in a string.

public class WordCount {


static int wordcount(String string)
{
int count=0;

char ch[]= new char[string.length()];


for(int i=0;i<string.length();i++)
{
ch[i]= string.charAt(i);
if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
count++;
}
return count;
}
public static void main(String[] args) {
String string =" India Is My Country";
System.out.println(wordcount(string) + " words.");
}
1. }
Output:
4 words.
26. Write a Java program to handle following exceptions: 1) Divide by Zero Exception. 2) Array Index
Out Of B bound Exception
A) Divide by Zero Exception

// Java Program to Handle Divide By Zero Exception


import java.io.*;
class Program1 {
public static void main(String[] args)
{
int a = 5;
int b = 0;
try {
System.out.println(a / b); // throw Exception
}
catch (ArithmeticException e) {
// Exception handler
System.out.println(
"Divided by zero operation cannot possible");
}
}
}

OUTPUT
B) Array Index Out Of B bound Exception

// Java Program to Handle multiple exception


import java.io.*;

class Program1 {
public static void main(String[] args)
{
try {
int number[] = new int[20];
number[21] = 30 / 9;
// this statement will throw
// ArrayIndexOutOfBoundsException e
}
catch (ArrayIndexOutOfBoundsException
| ArithmeticException e) {
System.out.println(e.getMessage());
// print the message
}
}
}

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

// Java code for thread creation by extending


// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
public class Program1 {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}

OUTPUT
28. To represent the concept of all types of inheritance supported by Java, design a program

package com.company;
class Student {

String name =
"ROHIT"; int age
=19;
String city =
"Mohali"; int
marks = 55;
String tutorial =
"JAVA"; public void
show() {
System.out.println("Student inheriting properties from Person:"); } }
class Main extends Student {
int marks = 65;

String tutorial = "TechVidvan Tutorial of


Java"; public static void main(String[] args)
{
Student obj = new
Student(); obj.show();
System.out.println("Name of the student is: " + obj.name);
System.out.println("Age of the student is: " + obj.age);
System.out.println("Student lives in: " + obj.city);
System.out.println("Student learns from: " + obj.tutorial);
System.out.println("Marks obtained by the student is: " +
obj.marks);} }
OUTPUT

29. Write a program to implement Multiple Inheritance using interface


interface Printable{
void print();
}
interface Showable{
void show();
}
class Program1 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


Program1 obj = new Program1();
obj.print();
obj.show();
}
}
OUTPUT
30. Construct a program to design a package in Java.

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

OUTPUT
31. To write and read a plain text file, write a Java program.
import java.io.BufferedInputStream;
import java.io.FileInputStream;

class B {
public static void main(String[] args) {
try {

// Creates a FileInputStream
FileInputStream file = new FileInputStream("input.txt");

// Creates a BufferedInputStream
BufferedInputStream input = new BufferedInputStream(file);

// Reads first byte from file


int i = input .read();

while (i != -1) {
System.out.print((char) i);

// Reads next byte from the file


i = input.read();
}
input.close();
}

catch (Exception e) {
e.getStackTrace();
}
}
}
32. Write a Java program to append text to an existing file.

import java.io.*;
public class Program32 {
public static void main(String[] args) throws
Exception { File file = new File("C:\\Users\\CC\\
IdeaProjects\\Java-
learning\\src\\com\\learning\\textfile.txt");
BufferedReader br = new BufferedReader(new
FileReader((file))); String before;
System.out.println("***Before Append
text***"); while ((before=br.readLine())!
=null){
System.out.println(before);

}String str1 = "\nappend text";


String filename = "C:\\Users\\CC\\IdeaProjects\\
Java- learning\\src\\com\\learning\\textfile.txt";
BufferedWriter bw = new BufferedWriter(new
FileWriter(filename,true)); bw.write(str1);
bw.close();

BufferedReader b_read = new BufferedReader(new


FileReader((file))); String after;
System.out.println("***After Append
text***"); while ((after=b_read.readLine())!
=null){
System.out.println(after);
}}}

OUTPUT:
33. Design a program in Java to get a list of all file/directory names from the
given.

OBJECTIVE:
import java.io.File;
public class Program33 {

public static void main(String[]


args) { File filePath = new
File("C:\\Users"); String[]
contents = filePath.list();
System.out.println("List of files and directories in the specified
path:"); assert contents != null;
for (String content :
contents)
{ System.out.println(c
ontent);
}

}
}
OUTPUT

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


exists or not.
import java.io.File;

public class {
public static void main(String[]
args) { try {
File file = new File("C:\\Users\\CC\\IdeaProjects\\
Java- learning\\src\\com\\learning\\textfile.txt");
System.out.println(file.exists());
}
catch(Except
ion e)
{ e.printStac
kTrace();
}

}
}
OUTPUT

35.Write a Java program to check if a file or directory has read and write permission.

OBJECTIVE:
The objective of this Java program is to check the read and write permissions of a
specified file. The program creates a File object representing the file at the given path
and then checks if the file can be read and written to. It prints messages indicating
whether the file has read and write permissions.
import java.io.File;
public class Program35 {

public static void main(String[] args) {


File file = new File("C:\\Users\\CC\\IdeaProjects\\
Java- learning\\src\\com\\learning\\textfile.txt");
if (file.canWrite()){
System.out.println(file.getAbsolutePath() + " can write.\n");
} else {
System.out.println(file.getAbsolutePath() + " cannot write.\n");
}
if (file.canRead()){
System.out.println(file.getAbsolutePath() + " can read.\n");
} else {
System.out.println(file.getAbsolutePath() + " cannot read.\n");
}
}
}
OUTPUT

Sample Viva Voce questions :

Q. 1 What method is used to check if the file can be written to?

Q.2 What method is used to check if the file can be read?

Q.3 What is the significance of the getAbsolutePath() method in this program?


Q.4 What will happen if the file does not exist at the specified path?

Q.5 Explain the importance of the File class in Java.

You might also like