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

java file

Java laboratory file and lot of real problem and solutions. On the file. That usefull for ptu.

Uploaded by

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

java file

Java laboratory file and lot of real problem and solutions. On the file. That usefull for ptu.

Uploaded by

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

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 java.util.Scanner;
public class DaysInMonth {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get month and year input from user
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;
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:
System.out.println("Invalid month entered.");
System.exit(1);
}
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22

System.out.println("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


System.out.println("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 java.util.Arrays;

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


Arrays.sort(numericArray);
System.out.println("Sorted numeric array: " + Arrays.toString(numericArray));

// Sort the string array


Arrays.sort(stringArray);
System.out.println("Sorted string array: " + Arrays.toString(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 / numbers.length;

// Print the result


System.out.println("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 java.util.Scanner;
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(System.in);
System.out.print("Enter a value to search for: ");
int valueToFind = scanner.nextInt();
// 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) {
System.out.println("The array contains the value " + valueToFind + ".");
} else {
System.out.println("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 java.util.Scanner;
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(System.in);
System.out.print("Enter a value to find its index: ");
int valueToFind = scanner.nextInt();
// 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 < numbers.length; i++) {
if (numbers[i] == valueToFind) {
index = i;
break;
}
}
// Output the result
if (index != -1) {
System.out.println("The index of the value " + valueToFind + " is: " + index);
} else {
System.out.println("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 java.util.Arrays;
import java.util.Scanner;

public class RemoveElementFromArray {


public static void main(String[] args) {
// Initialize the array
int[] numbers = {10, 20, 30, 40, 50, 60};

// Display the original array


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

// Get the value to remove from the user


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value to remove: ");
int valueToRemove = scanner.nextInt();

// Find the index of the element to remove


int indexToRemove = -1;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == valueToRemove) {
indexToRemove = i;
break;
}
}

// If the element was not found, print a message and exit


if (indexToRemove == -1) {
System.out.println("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[numbers.length - 1];

// Copy elements except the one at indexToRemove


for (int i = 0, j = 0; i < numbers.length; i++) {
if (i != indexToRemove) {
newArray[j++] = numbers[i];
}
}

// Display the new array


System.out.println("Array after removing " + valueToRemove + ": " +
Arrays.toString(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 java.util.Arrays;

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[originalArray.length];

// Copy each element from the original array to the new array
for (int i = 0; i < originalArray.length; i++) {
copiedArray[i] = originalArray[i];
}

// Display the original and copied arrays


System.out.println("Original array: " + Arrays.toString(originalArray));
System.out.println("Copied array: " + Arrays.toString(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 java.util.Scanner;

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


System.out.println("Original array:");
print2DArray(array);

// Get the position and new value from the user


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the row index to insert (0-2): ");
int row = scanner.nextInt();
System.out.print("Enter the column index to insert (0-2): ");
int col = scanner.nextInt();
System.out.print("Enter the new value to insert: ");
int newValue = scanner.nextInt();

// Check if the specified position is valid


if (row >= 0 && row < array.length && 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
System.out.println("Array after inserting the new value:");
print2DArray(array);
} else {
System.out.println("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) {
System.out.print(element + " ");
}
System.out.println();
}
}
}

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 java.util.Scanner;

public class StringOperations {


public static void main(String[] args) {
// Initialize the Scanner object to take user input
Scanner scanner = new Scanner(System.in);

// Take two string inputs from the user


System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

// 1) Compare two strings


if (str1.equals(str2)) {
System.out.println("The two strings are equal.");
} else {
System.out.println("The two strings are not equal.");
}

// 2) Count string length


System.out.println("Length of the first string: " + str1.length());
System.out.println("Length of the second string: " + str2.length());

// 3) Convert upper case to lower case & vice versa


System.out.println("First string in uppercase: " + str1.toUpperCase());
System.out.println("First string in lowercase: " + str1.toLowerCase());

System.out.println("Second string in uppercase: " + str2.toUpperCase());


System.out.println("Second string in lowercase: " + str2.toLowerCase());

// 4) Concatenate two strings


String concatenatedString = str1 + str2;
System.out.println("Concatenated string: " + concatenatedString);

// 5) Print a substring
System.out.print("Enter the start index for the substring: ");
int startIndex = scanner.nextInt();
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22

System.out.print("Enter the end index for the substring: ");


int endIndex = scanner.nextInt();

// Check if the indices are valid


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 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 java.util.Scanner;

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(System.in);

// Take three numbers as input


System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();

System.out.print("Enter the second number: ");


int num2 = scanner.nextInt();

System.out.print("Enter the third number: ");


int num3 = scanner.nextInt();

// Call the method to find the smallest number


int smallest = findSmallest(num1, num2, num3);

// Output the smallest number


System.out.println("The smallest number among the three is: " + smallest);

// Close the scanner


scanner.close();
}
}
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 java.util.Scanner;

public class AverageOfThreeNumbers {


public static void main(String[] args) {
// Create a scanner object to take user input
Scanner scanner = new Scanner(System.in);

// Take three numbers as input


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();

// Calculate the average of the three numbers


double average = (num1 + num2 + num3) / 3;

// Output the average


System.out.println("The average of the three numbers is: " + average);

// Close the scanner


scanner.close();
}
}
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 java.util.Scanner;

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 = str.toLowerCase();

// Iterate through each character in the string


for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(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(System.in);

// Take a string input from the user


System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

// Call the method to count vowels


int totalVowels = countVowels(inputString);

// Output the number of vowels in the string


System.out.println("The number of vowels in the string is: " + totalVowels);

// Close the scanner


scanner.close();
}
}
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 java.util.Scanner;

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 = str.trim().split("\\s+");

// Return the length of the array which represents the number of words
return words.length;
}

public static void main(String[] args) {


// Create a scanner object to take user input
Scanner scanner = new Scanner(System.in);

// Take a string input from the user


System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

// Call the method to count words


int totalWords = countWords(inputString);

// Output the number of words in the string


System.out.println("The number of words in the string is: " + totalWords);

// Close the scanner


scanner.close();
}
}
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 java.util.Scanner;

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 || str.trim().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 = str.trim().split("\\s+");

// Return the length of the resulting array which represents the number of words
return words.length;
}

public static void main(String[] args) {


// Create a scanner object to take user input
Scanner scanner = new Scanner(System.in);

// Take a string input from the user


System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

// Call the method to count words


int totalWords = countWords(inputString);

// Output the number of words in the string


System.out.println("The number of words in the string is: " + totalWords);

// Close the scanner


scanner.close();
}
}
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 java.util.Scanner;

public class ExceptionHandlingDemo {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Handling Divide by Zero Exception


try {
System.out.print("Enter numerator: ");
int numerator = scanner.nextInt();

System.out.print("Enter denominator: ");


int denominator = scanner.nextInt();

// Attempt to divide
int result = numerator / denominator;
System.out.println("The result of division is: " + result);
} catch (ArithmeticException e) {
// Handle divide by zero error
System.out.println("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};

System.out.print("\nEnter an index to access in the array (0-4): ");


int index = scanner.nextInt();

// Attempt to access the array at the given index


System.out.println("Array element at index " + index + ": " + numbers[index]);
} catch (ArrayIndexOutOfBoundsException e) {
// Handle array index out of bounds error
System.out.println("Error: Array index out of bounds!");
}

// Close the scanner


scanner.close();
}
}
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++) {
System.out.println("Task1 - Count: " + i);
try {
Thread.sleep(500); // Sleep for 500ms to simulate work being done
} catch (InterruptedException e) {
System.out.println(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++) {
System.out.println("Task2 - Letter: " + c);
try {
Thread.sleep(500); // Sleep for 500ms to simulate work being done
} catch (InterruptedException e) {
System.out.println(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


thread1.start();
thread2.start();

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
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println(e);
}

System.out.println("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() {
System.out.println("Animal is eating.");
}
}

// Single inheritance: Dog inherits from Animal


class Dog extends Animal {
void bark() {
System.out.println("Dog is barking.");
}
}

// Multilevel Inheritance Example


class Puppy extends Dog {
void weep() {
System.out.println("Puppy is weeping.");
}
}

// Hierarchical Inheritance Example


class Cat extends Animal {
void meow() {
System.out.println("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() {
System.out.println("Person is walking.");
}
Programming In Java Laboratory Subject code: UGCA 1938
Name: MD Akbar Ali Roll no.:3180/22
@Override
public void run() {
System.out.println("Person is running.");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
// Single Inheritance demonstration
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.bark();

// Multilevel Inheritance demonstration


Puppy puppy = new Puppy();
puppy.eat(); // Inherited from Animal
puppy.bark(); // Inherited from Dog
puppy.weep();

// Hierarchical Inheritance demonstration


Cat cat = new Cat();
cat.eat(); // Inherited from Animal
cat.meow();

// Multiple Inheritance through interfaces


Person person = new Person();
person.walk();
person.run();
}
}
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() {
System.out.println("Printing from Printable interface.");
}

// Implement the show method from Showable interface


@Override
public void show() {
System.out.println("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


example.print();
example.show();
}
}
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) Calculator.java (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) Message.java (Inside mypackage package)

package mypackage;

public class Message {


public void printMessage(String message) {
System.out.println("Message: " + message);
}
}
(iii) Main.java (To access the mypackage package)

import mypackage.Calculator;
import mypackage.Message;

public class Main {


public static void main(String[] args) {
Calculator calculator = new Calculator();
Message message = new Message();

int resultAdd = calculator.add(5, 10);


int resultSubtract = calculator.subtract(15, 7);

System.out.println("Addition Result: " + resultAdd);


System.out.println("Subtraction Result: " + resultSubtract);

message.printMessage("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 java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReadWrite {


public static void main(String[] args) {
String filename = "example.txt";
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)) {
writer.write(content);
System.out.println("Content written to " + filename);
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
// Method to read from a file
public static void readFile(String filename) {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
System.out.println("\nReading from " + filename + ":");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading from the file.");
e.printStackTrace();
}
}
}
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 java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileAppendExample {


public static void main(String[] args) {
String filename = "example.txt";
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
writer.write(content);
System.out.println("Content appended to " + filename);
} catch (IOException e) {
System.out.println("An error occurred while appending to the file.");
e.printStackTrace();
}
}
// 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;
System.out.println("\nReading from " + filename + ":");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading from the file.");
e.printStackTrace();
}
}
}
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 java.io.File;

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 (directory.exists() && directory.isDirectory()) {
// Get list of all files and directories
File[] filesList = directory.listFiles();

if (filesList != null) {
System.out.println("Listing files and directories in: " + path);
for (File file : filesList) {
if (file.isDirectory()) {
System.out.println("[DIR] " + file.getName());
} else {
System.out.println("[FILE] " + file.getName());
}
}
} else {
System.out.println("The directory is empty.");
}
} else {
System.out.println("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 java.io.File;
import java.util.Scanner;

public class FileOrDirectoryChecker {


public static void main(String[] args) {
// Take pathname as input from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the path of the file or directory: ");
String pathname = scanner.nextLine();
scanner.close();

// 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 (file.exists()) {
if (file.isDirectory()) {
System.out.println("The path exists and is a directory.");
} else if (file.isFile()) {
System.out.println("The path exists and is a file.");
}
} else {
System.out.println("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 java.io.File;
import java.util.Scanner;

public class FilePermissionChecker {


public static void main(String[] args) {
// Take pathname as input from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the path of the file or directory: ");
String pathname = scanner.nextLine();
scanner.close();
// 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 (file.exists()) {
System.out.println("Checking permissions for: " + pathname);
if (file.canRead()) {
System.out.println("The file/directory has read permission.");
} else {
System.out.println("The file/directory does not have read permission.");
}
if (file.canWrite()) {
System.out.println("The file/directory has write permission.");
} else {
System.out.println("The file/directory does not have write permission.");
}
} else {
System.out.println("The specified path does not exist.");
}
}
}
Output:
Sample Run:

Or, if there are no permissions:

You might also like