Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
11. Construct a Java program to find the number of days in a month.
import [Link];
public class DaysInMonth {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Get month and year input from user
[Link]("Enter the month (1-12): ");
int month = [Link]();
[Link]("Enter the year: ");
int year = [Link]();
int days = 0;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31;
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
case 2:
// Check if the year is a leap year
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
break;
default:
[Link]("Invalid month entered.");
[Link](1);
}
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
[Link]("Number of days: " + days);
}
}
Output :
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
12. Write a program to sum values of an Single Dimensional array.
public class ArraySum {
public static void main(String[] args) {
// Initialize an array
int[] numbers = {5, 10, 15, 20, 25};
int sum = 0;
// Loop through the array and add each element to the sum
for (int number : numbers) {
sum += number;
}
// Print the sum
[Link]("The sum of array elements is: " + sum);
}
}
Output :
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
13. Design & execute a program in Java to sort a numeric array and a
string array.
import [Link];
public class ArraySort {
public static void main(String[] args) {
// Initialize numeric and string arrays
int[] numericArray = {5, 1, 12, 3, 7};
String[] stringArray = {"Apple", "Orange", "Banana", "Grapes", "Pineapple"};
// Sort the numeric array
[Link](numericArray);
[Link]("Sorted numeric array: " + [Link](numericArray));
// Sort the string array
[Link](stringArray);
[Link]("Sorted string array: " + [Link](stringArray));
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
14. Calculate the average value of array elements through Java Program.
public class ArrayAverage {
public static void main(String[] args) {
// Initialize an array
int[] numbers = {10, 20, 30, 40, 50};
// Calculate the sum of all elements
int sum = 0;
for (int number : numbers) {
sum += number;
}
// Calculate the average
double average = (double) sum / [Link];
// Print the result
[Link]("The average value of the array elements is: " + average);
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
15. Write a Java program to test if an array contains a specific value.
import [Link];
public class ArrayContainsValue {
public static void main(String[] args) {
// Initialize the array
int[] numbers = {3, 8, 15, 23, 42, 56};
// Get the value to search for from the user
Scanner scanner = new Scanner([Link]);
[Link]("Enter a value to search for: ");
int valueToFind = [Link]();
// Flag to indicate if the value is found
boolean found = false;
// Check if the array contains the specified value
for (int number : numbers) {
if (number == valueToFind) {
found = true;
break;
}
}
// Display the result
if (found) {
[Link]("The array contains the value " + valueToFind + ".");
} else {
[Link]("The array does not contain the value " + valueToFind + ".");
}
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
16. Find the index of an array element by writing a program in Java.
import [Link];
public class ArrayIndexFinder {
public static void main(String[] args) {
// Initialize the array
int[] numbers = {10, 20, 30, 40, 50, 60};
// Get the value to search for from the user
Scanner scanner = new Scanner([Link]);
[Link]("Enter a value to find its index: ");
int valueToFind = [Link]();
// Variable to store the index of the element
int index = -1;
// Loop through the array to find the index of the specified value
for (int i = 0; i < [Link]; i++) {
if (numbers[i] == valueToFind) {
index = i;
break;
}
}
// Output the result
if (index != -1) {
[Link]("The index of the value " + valueToFind + " is: " + index);
} else {
[Link]("The value " + valueToFind + " is not in the array.");
}
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
17. Write a Java program to remove a specific element from an array.
import [Link];
import [Link];
public class RemoveElementFromArray {
public static void main(String[] args) {
// Initialize the array
int[] numbers = {10, 20, 30, 40, 50, 60};
// Display the original array
[Link]("Original array: " + [Link](numbers));
// Get the value to remove from the user
Scanner scanner = new Scanner([Link]);
[Link]("Enter the value to remove: ");
int valueToRemove = [Link]();
// Find the index of the element to remove
int indexToRemove = -1;
for (int i = 0; i < [Link]; i++) {
if (numbers[i] == valueToRemove) {
indexToRemove = i;
break;
}
}
// If the element was not found, print a message and exit
if (indexToRemove == -1) {
[Link]("The value " + valueToRemove + " is not in the array.");
} else {
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
// Create a new array with one less element
int[] newArray = new int[[Link] - 1];
// Copy elements except the one at indexToRemove
for (int i = 0, j = 0; i < [Link]; i++) {
if (i != indexToRemove) {
newArray[j++] = numbers[i];
}
}
// Display the new array
[Link]("Array after removing " + valueToRemove + ": " +
[Link](newArray));
}
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
18. Design a program to copy an array by iterating the array.
import [Link];
public class ArrayCopy {
public static void main(String[] args) {
// Initialize the original array
int[] originalArray = {5, 10, 15, 20, 25};
// Create a new array of the same length as the original array
int[] copiedArray = new int[[Link]];
// Copy each element from the original array to the new array
for (int i = 0; i < [Link]; i++) {
copiedArray[i] = originalArray[i];
}
// Display the original and copied arrays
[Link]("Original array: " + [Link](originalArray));
[Link]("Copied array: " + [Link](copiedArray));
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
19. Write a Java program to insert an element (on a specific position) into
Multidimensional array.
import [Link];
public class MultiDimensionalArrayInsert {
public static void main(String[] args) {
// Initialize a 2D array
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Display the original array
[Link]("Original array:");
print2DArray(array);
// Get the position and new value from the user
Scanner scanner = new Scanner([Link]);
[Link]("Enter the row index to insert (0-2): ");
int row = [Link]();
[Link]("Enter the column index to insert (0-2): ");
int col = [Link]();
[Link]("Enter the new value to insert: ");
int newValue = [Link]();
// Check if the specified position is valid
if (row >= 0 && row < [Link] && col >= 0 && col < array[0].length) {
// Insert the new value at the specified position
array[row][col] = newValue;
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
// Display the modified array
[Link]("Array after inserting the new value:");
print2DArray(array);
} else {
[Link]("Invalid row or column index.");
}
}
// Method to print a 2D array
public static void print2DArray(int[][] array) {
for (int[] row : array) {
for (int element : row) {
[Link](element + " ");
}
[Link]();
}
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
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 [Link];
public class StringOperations {
public static void main(String[] args) {
// Initialize the Scanner object to take user input
Scanner scanner = new Scanner([Link]);
// Take two string inputs from the user
[Link]("Enter the first string: ");
String str1 = [Link]();
[Link]("Enter the second string: ");
String str2 = [Link]();
// 1) Compare two strings
if ([Link](str2)) {
[Link]("The two strings are equal.");
} else {
[Link]("The two strings are not equal.");
}
// 2) Count string length
[Link]("Length of the first string: " + [Link]());
[Link]("Length of the second string: " + [Link]());
// 3) Convert upper case to lower case & vice versa
[Link]("First string in uppercase: " + [Link]());
[Link]("First string in lowercase: " + [Link]());
[Link]("Second string in uppercase: " + [Link]());
[Link]("Second string in lowercase: " + [Link]());
// 4) Concatenate two strings
String concatenatedString = str1 + str2;
[Link]("Concatenated string: " + concatenatedString);
// 5) Print a substring
[Link]("Enter the start index for the substring: ");
int startIndex = [Link]();
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
[Link]("Enter the end index for the substring: ");
int endIndex = [Link]();
// Check if the indices are valid
if (startIndex >= 0 && endIndex <= [Link]() && startIndex < endIndex) {
[Link]("Substring of the first string: " + [Link](startIndex,
endIndex));
} else {
[Link]("Invalid indices for substring.");
}
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
21. Developed Program & design a method to find the smallest number
among three numbers.
import [Link];
public class SmallestNumber {
// Method to find the smallest number among three numbers
public static int findSmallest(int num1, int num2, int num3) {
int smallest = num1; // Assume the first number is the smallest initially
// Compare the first number with the second number
if (num2 < smallest) {
smallest = num2;
}
// Compare the current smallest with the third number
if (num3 < smallest) {
smallest = num3;
}
return smallest; // Return the smallest number
}
public static void main(String[] args) {
// Create a scanner object to take user input
Scanner scanner = new Scanner([Link]);
// Take three numbers as input
[Link]("Enter the first number: ");
int num1 = [Link]();
[Link]("Enter the second number: ");
int num2 = [Link]();
[Link]("Enter the third number: ");
int num3 = [Link]();
// Call the method to find the smallest number
int smallest = findSmallest(num1, num2, num3);
// Output the smallest number
[Link]("The smallest number among the three is: " + smallest);
// Close the scanner
[Link]();
}
}
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
22. Compute the average of three numbers through a Java Program.
import [Link];
public class AverageOfThreeNumbers {
public static void main(String[] args) {
// Create a scanner object to take user input
Scanner scanner = new Scanner([Link]);
// Take three numbers as input
[Link]("Enter the first number: ");
double num1 = [Link]();
[Link]("Enter the second number: ");
double num2 = [Link]();
[Link]("Enter the third number: ");
double num3 = [Link]();
// Calculate the average of the three numbers
double average = (num1 + num2 + num3) / 3;
// Output the average
[Link]("The average of the three numbers is: " + average);
// Close the scanner
[Link]();
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
23. Write a Program & design a method to count all vowels in a string.
import [Link];
public class VowelCount {
// Method to count vowels in a string
public static int countVowels(String str) {
int vowelCount = 0;
// Convert the string to lowercase to handle case insensitivity
str = [Link]();
// Iterate through each character in the string
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
// Check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++; // Increment vowel count
}
}
return vowelCount; // Return the total count of vowels
}
public static void main(String[] args) {
// Create a scanner object to take user input
Scanner scanner = new Scanner([Link]);
// Take a string input from the user
[Link]("Enter a string: ");
String inputString = [Link]();
// Call the method to count vowels
int totalVowels = countVowels(inputString);
// Output the number of vowels in the string
[Link]("The number of vowels in the string is: " + totalVowels);
// Close the scanner
[Link]();
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
24. Write a Java method to count all words in a string.
import [Link];
public class WordCount {
// Method to count words in a string
public static int countWords(String str) {
// Trim leading and trailing spaces and split the string by spaces
String[] words = [Link]().split("\\s+");
// Return the length of the array which represents the number of words
return [Link];
}
public static void main(String[] args) {
// Create a scanner object to take user input
Scanner scanner = new Scanner([Link]);
// Take a string input from the user
[Link]("Enter a string: ");
String inputString = [Link]();
// Call the method to count words
int totalWords = countWords(inputString);
// Output the number of words in the string
[Link]("The number of words in the string is: " + totalWords);
// Close the scanner
[Link]();
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
25. Write a method in Java program to count all words in a string.
import [Link];
public class WordCount {
// Method to count words in a string
public static int countWords(String str) {
// Trim leading and trailing spaces, then split by one or more spaces
if (str == null || [Link]().isEmpty()) {
return 0; // Return 0 if the string is null or empty
}
// Split the string by spaces and filter out empty strings caused by multiple spaces
String[] words = [Link]().split("\\s+");
// Return the length of the resulting array which represents the number of words
return [Link];
}
public static void main(String[] args) {
// Create a scanner object to take user input
Scanner scanner = new Scanner([Link]);
// Take a string input from the user
[Link]("Enter a string: ");
String inputString = [Link]();
// Call the method to count words
int totalWords = countWords(inputString);
// Output the number of words in the string
[Link]("The number of words in the string is: " + totalWords);
// Close the scanner
[Link]();
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
26. Write a Java program to handle following exceptions:
1) Divide by Zero Exception.
2) Array Index Out Of B bound Exception.
import [Link];
public class ExceptionHandlingDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Handling Divide by Zero Exception
try {
[Link]("Enter numerator: ");
int numerator = [Link]();
[Link]("Enter denominator: ");
int denominator = [Link]();
// Attempt to divide
int result = numerator / denominator;
[Link]("The result of division is: " + result);
} catch (ArithmeticException e) {
// Handle divide by zero error
[Link]("Error: Cannot divide by zero!");
}
// Handling Array Index Out of Bounds Exception
try {
// Create an array of 5 elements
int[] numbers = {1, 2, 3, 4, 5};
[Link]("\nEnter an index to access in the array (0-4): ");
int index = [Link]();
// Attempt to access the array at the given index
[Link]("Array element at index " + index + ": " + numbers[index]);
} catch (ArrayIndexOutOfBoundsException e) {
// Handle array index out of bounds error
[Link]("Error: Array index out of bounds!");
}
// Close the scanner
[Link]();
}
}
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
Output:
For Divide by Zero Exception:
For Array Index Out of Bounds Exception:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
27. To represent the concept of Multithreading write a Java program.
// Class that extends Thread to create a custom thread
class Task1 extends Thread {
@Override
public void run() {
// Simulate a task by printing numbers
for (int i = 1; i <= 5; i++) {
[Link]("Task1 - Count: " + i);
try {
[Link](500); // Sleep for 500ms to simulate work being done
} catch (InterruptedException e) {
[Link](e);
}
}
}
}
// Another class that extends Thread to create a second custom thread
class Task2 extends Thread {
@Override
public void run() {
// Simulate a task by printing alphabets
for (char c = 'A'; c <= 'E'; c++) {
[Link]("Task2 - Letter: " + c);
try {
[Link](500); // Sleep for 500ms to simulate work being done
} catch (InterruptedException e) {
[Link](e);
}
}
}
}
public class MultithreadingDemo {
public static void main(String[] args) {
// Create instances of Task1 and Task2 threads
Task1 thread1 = new Task1();
Task2 thread2 = new Task2();
// Start both threads
[Link]();
[Link]();
try {
// Wait for both threads to finish execution before the main thread exits
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Both threads have finished their tasks.");
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
28. To represent the concept of all types of inheritance supported by Java,
design a program.
// Single Inheritance Example
class Animal {
void eat() {
[Link]("Animal is eating.");
}
}
// Single inheritance: Dog inherits from Animal
class Dog extends Animal {
void bark() {
[Link]("Dog is barking.");
}
}
// Multilevel Inheritance Example
class Puppy extends Dog {
void weep() {
[Link]("Puppy is weeping.");
}
}
// Hierarchical Inheritance Example
class Cat extends Animal {
void meow() {
[Link]("Cat is meowing.");
}
}
// Multiple Inheritance through Interfaces
interface Walkable {
void walk();
}
interface Runnable {
void run();
}
// A class implementing multiple interfaces
class Person implements Walkable, Runnable {
@Override
public void walk() {
[Link]("Person is walking.");
}
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
@Override
public void run() {
[Link]("Person is running.");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
// Single Inheritance demonstration
Dog dog = new Dog();
[Link](); // Inherited from Animal
[Link]();
// Multilevel Inheritance demonstration
Puppy puppy = new Puppy();
[Link](); // Inherited from Animal
[Link](); // Inherited from Dog
[Link]();
// Hierarchical Inheritance demonstration
Cat cat = new Cat();
[Link](); // Inherited from Animal
[Link]();
// Multiple Inheritance through interfaces
Person person = new Person();
[Link]();
[Link]();
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
29. Write a program to implement Multiple Inheritance using interface.
// First interface
interface Printable {
void print();
}
// Second interface
interface Showable {
void show();
}
// A class that implements both Printable and Showable interfaces
class MultipleInheritanceExample implements Printable, Showable {
// Implement the print method from Printable interface
@Override
public void print() {
[Link]("Printing from Printable interface.");
}
// Implement the show method from Showable interface
@Override
public void show() {
[Link]("Showing from Showable interface.");
}
public static void main(String[] args) {
// Create an object of the class that implements both interfaces
MultipleInheritanceExample example = new MultipleInheritanceExample();
// Call both methods
[Link]();
[Link]();
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
30. Construct a program to design a package in Java.
Steps
1)Create a Package: Define a package in Java using the package keyword.
2)Create Classes in the Package: Add classes to this package
3)Access the Package from Another Class: Import and use the package in a main class.
(i) [Link] (Inside mypackage package)
package mypackage;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}
(ii) [Link] (Inside mypackage package)
package mypackage;
public class Message {
public void printMessage(String message) {
[Link]("Message: " + message);
}
}
(iii) [Link] (To access the mypackage package)
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
Message message = new Message();
int resultAdd = [Link](5, 10);
int resultSubtract = [Link](15, 7);
[Link]("Addition Result: " + resultAdd);
[Link]("Subtraction Result: " + resultSubtract);
[Link]("Hello, this is a message from the package!");
}
}
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
Compilation and Execution:
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
31. To write and read a plain text file, write a Java program.
import [Link];
import [Link];
import [Link];
import [Link];
public class FileReadWrite {
public static void main(String[] args) {
String filename = "[Link]";
String contentToWrite = "Hello, this is a sample text file.\nThis file demonstrates file
reading and writing in Java.";
// Write to the file
writeFile(filename, contentToWrite);
// Read from the file
readFile(filename);
}
// Method to write to a file
public static void writeFile(String filename, String content) {
try (FileWriter writer = new FileWriter(filename)) {
[Link](content);
[Link]("Content written to " + filename);
} catch (IOException e) {
[Link]("An error occurred while writing to the file.");
[Link]();
}
}
// Method to read from a file
public static void readFile(String filename) {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
[Link]("\nReading from " + filename + ":");
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]("An error occurred while reading from the file.");
[Link]();
}
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
32. Write a Java program to append text to an existing file.
import [Link];
import [Link];
import [Link];
import [Link];
public class FileAppendExample {
public static void main(String[] args) {
String filename = "[Link]";
String contentToAppend = "\nThis is additional text appended to the file.";
// Append text to the file
appendToFile(filename, contentToAppend);
// Read and display the content of the file
readFile(filename);
}
// Method to append text to a file
public static void appendToFile(String filename, String content) {
try (FileWriter writer = new FileWriter(filename, true)) { // 'true' enables append mode
[Link](content);
[Link]("Content appended to " + filename);
} catch (IOException e) {
[Link]("An error occurred while appending to the file.");
[Link]();
}
}
// Method to read and display the content of a file
public static void readFile(String filename) {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
[Link]("\nReading from " + filename + ":");
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]("An error occurred while reading from the file.");
[Link]();
}
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
33. Design a program in Java to get a list of all file/directory names from
the given.
import [Link];
public class ListFilesAndDirectories {
public static void main(String[] args) {
// Specify the directory path
String directoryPath = "path/to/your/directory"; // Replace with the actual directory path
// List all files and directories
listFilesAndDirectories(directoryPath);
}
// Method to list all files and directories in the given path
public static void listFilesAndDirectories(String path) {
File directory = new File(path);
// Check if the directory exists and is a directory
if ([Link]() && [Link]()) {
// Get list of all files and directories
File[] filesList = [Link]();
if (filesList != null) {
[Link]("Listing files and directories in: " + path);
for (File file : filesList) {
if ([Link]()) {
[Link]("[DIR] " + [Link]());
} else {
[Link]("[FILE] " + [Link]());
}
}
} else {
[Link]("The directory is empty.");
}
} else {
[Link]("The specified path does not exist or is not a directory.");
}
}
}
Output:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
34. Develop a Java program to check if a file or directory specified by
pathname exists or not.
import [Link];
import [Link];
public class FileOrDirectoryChecker {
public static void main(String[] args) {
// Take pathname as input from the user
Scanner scanner = new Scanner([Link]);
[Link]("Enter the path of the file or directory: ");
String pathname = [Link]();
[Link]();
// Check if the file or directory exists
checkFileOrDirectoryExists(pathname);
}
// Method to check if the specified file or directory exists
public static void checkFileOrDirectoryExists(String pathname) {
File file = new File(pathname);
if ([Link]()) {
if ([Link]()) {
[Link]("The path exists and is a directory.");
} else if ([Link]()) {
[Link]("The path exists and is a file.");
}
} else {
[Link]("The specified path does not exist.");
}
}
}
Output:
Sample Run:
Or, if the specified path does not exist:
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
35. Write a Java program to check if a file or directory has read and write
permission.
import [Link];
import [Link];
public class FilePermissionChecker {
public static void main(String[] args) {
// Take pathname as input from the user
Scanner scanner = new Scanner([Link]);
[Link]("Enter the path of the file or directory: ");
String pathname = [Link]();
[Link]();
// Check read and write permissions
checkPermissions(pathname);
}
// Method to check read and write permissions of a file or directory
public static void checkPermissions(String pathname) {
File file = new File(pathname);
if ([Link]()) {
[Link]("Checking permissions for: " + pathname);
if ([Link]()) {
[Link]("The file/directory has read permission.");
} else {
[Link]("The file/directory does not have read permission.");
}
if ([Link]()) {
[Link]("The file/directory has write permission.");
} else {
[Link]("The file/directory does not have write permission.");
}
} else {
[Link]("The specified path does not exist.");
}
}
}
Output:
Sample Run:
Or, if there are no permissions: