Java File 35 Programs

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

Course Code: UGCA1938

Course Name: Programming in Java Laboratory

Program: BCA L: 0 T: 0 P:4


Branch: Computer Applications Credits: 2
Semester: 5th Contact hours: 4 hours per week
Theory/Practical: Practical Percentage of numerical/design problems: 90%
Internal max. marks: 60 Duration of end semester exam (ESE): 3hrs
External max. marks: 40 Elective status: Core
Total marks: 100

Prerequisite: - Basic knowledge of Programming language like Programming in C.


Co requisite: - Knowledge of Object Oriented Concepts through any language like C++.
Additional material required in ESE: - Minor Project.

Course Outcomes: Students will be able to


CO# Course Outcomes
CO1 Implement Core Java concepts.
CO2 Solve computational problems using various operators of Java.
CO3 Design solutions to complex by handling exceptions that may occur in the programs.
CO4 Solve complex and large problems using the concept of multithreading.
CO5 Implement interfaces and design packages.

Instructions: All programs are to be developed in Java programming language.


List of assignments:
S.No. LECTURE PROGRAM
Write a program to perform following operations on two numbers
1. L1 input by the user:
1) Addition 2) subtraction 3) multiplication 4) division
Write a Java program to print result of the following operations.
1. -15 +58 * 45
2. L2 2. (35+8) % 6
3. 24 + -5*3 / 7
4. 15 + 18 / 3 * 2 - 9 % 3
Write a Java program to compute area of:
3. L3
1) Circle2) rectangle 3) triangle 4) square
Write a program to convert temperature from Fahrenheit to Celsius
4. L4
degree using Java.
Write a program through Java that reads a number in inches, converts
5. L5
it to meters.
6. L6 Write a program to convert minutes into a number of years and days.
7. L7 Write a Java program that prints current time in GMT.
8. L8 Design a program in Java to solve quadratic equations using if, if else
9. L9 Write a Java program to determine greatest number of three numbers.
Write program that gets a number from the user and generates an
L10
10. integer between 1 and 7 subsequently should display the name of the
weekday as per that number.
L11
11. Construct a Java program to find the number of days in a month.
12. L12 Write a program to sum values of an Single Dimensional array.
L13 Design & execute a program in Java to sort a numeric array and a
13.
string array.
L14
14. Calculate the average value of array elements through Java Program.
L15
15. Write a Java program to test if an array contains a specific value.
L16
16. Find the index of an array element by writing a program in Java.
L17
17. Write a Java program to remove a specific element from an array.
L18
18. Design a program to copy an array by iterating the array.
L19 Write a Java program to insert an element (on a specific position) into
19.
Multidimensional array.
Write a program to perform following operations on strings: 1)
L20 Compare two strings. 2) Count string length. 3) Convert upper case to
20.
lower case & vice versa. 4) Concatenate two strings. 5) Print a
substring.
L21 Developed Program & design a method to find the smallest number
21.
among three numbers.
L22
22. Compute the average of three numbers through a Java Program.
L23
23. Write a Program & design a method to count all vowels in a string.
L24
24. Write a Java method to count all words in a string.
L25
25. Write a method in Java program to count all words in a string.
L26 Write a Java program to handle following exceptions: 1) Divide by
26.
Zero Exception. 2) Array Index Out Of B bound Exception.
L27
27. To represent the concept of Multithreading write a Java program.
L28 To represent the concept of all types of inheritance supported by Java,
28.
design a program.
L29
29. Write a program to implement Multiple Inheritance using interface.
L30
30. Construct a program to design a package in Java.
L31
31. To write and read a plain text file, write a Java program.
L32
32. Write a Java program to append text to an existing file.
L33 Design a program in Java to get a list of all file/directory names from
33.
the given.
L34 Develop a Java program to check if a file or directory specified by
34.
pathname exists or not.
L35 Write a Java program to check if a file or directory has read and write
35.
permission.
Text Books:
1. Programming with Java A Primer, 5th Edition, E. Balagurusamy, TMH.
2. Java Programming for Core and Advanced Learners, Sagayaraja, Denis, Karthik, Gajalakshmi,
Universities Press.
3. Java Fundamentals, A Comprehensive Introduction, H. Schildt, D. Skrien, TMH. I

Reference Books:
1. Java, The complete Reference, H. Schildt, 7th Edition, TMH.
2. Data Analytics using R, Seema Acharya, TMH.
1. Write a program to perform following operations on two numbers
input by the user:
1) Addition 2) subtraction 3) multiplication 4) division
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int first, second, add, subtract, multiply;
float 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:
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
package com.company;
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:
3. Write a Java program to compute area of:
1) Circle2) rectangle 3) triangle 4) square
package com.company;
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:
4. Write a program to convert temperature from Fahrenheit to Celsius degree
using Java
package com.company;
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:
5. Write a program through Java that reads a number in inches, converts it to
meters.
package com.company;
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:
6. Write a program to convert minutes into a number of years and days
package com.company;
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:
7. Write a Java program that prints current time in GMT
package com.company;
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:
8. Design a program in Java to solve quadratic equations using if, if else
package com.company;
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:
9. Write a Java program to determine greatest number of three numbers
package com.company;
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:
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
package com.company;
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:
11. Construct a Java program to find the number of days in a month
package com.company;
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:
12. Write a program to sum values of an Single Dimensional array
package com.company;
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:
13. Design & execute a program in Java to sort a numeric array and a string
array
package com.company;
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:
14. Calculate the average value of array elements through Java Program.
package com.company;
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:
15. Write a Java program to test if an array contains a specific value
package com.company;
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:
16. Find the index of an array element by writing a program in Java
package com.company;
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:
17. Write a Java program to remove a specific element from an array
package com.company;
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:

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


package com.company;
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:
19. Write a Java program to insert an element (on a specific position) into
Multidimensional array
package com.company;
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


package com.company;
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
package com.company;
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
package com.company;
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
package com.company;
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
package com.company;
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.

//save by A.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.

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

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(Exception e)
{ e.printStackTrace();
}
}
}

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

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

You might also like