JAVALabManualdocx__2024_11_23_14_36_01
JAVALabManualdocx__2024_11_23_14_36_01
JAVALabManualdocx__2024_11_23_14_36_01
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
OBJECTIVE:
The objective of the Java code is to create a program that performs the following
tasks:
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:
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:
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:
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:
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:
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
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:
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
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:
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
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:
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:
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
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";
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
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:
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
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));
OUTPUT:
SAMPLE VIVA-VOVE QUESTIONS:
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:
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:
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));
OUTPUT:
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:
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.
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 {
Output
22. Compute the average of three numbers through a Java Program.
import java.util.Scanner;
public class JavaExample {
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();
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 {
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.
OUTPUT
B) Array Index Out Of B bound Exception
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
// 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;
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);
while (i != -1) {
System.out.print((char) i);
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);
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 {
}
}
OUTPUT
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 {