0% found this document useful (0 votes)
5 views38 pages

LabManual_Comp-213_Programming-2

lab manula for Java programming

Uploaded by

aasifaftab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views38 pages

LabManual_Comp-213_Programming-2

lab manula for Java programming

Uploaded by

aasifaftab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Lab 1

Methods – Week 1
Objectives:
 To define and call void methods with formal parameters and with actual
parameters (i.e., arguments).
 To define and call methods with a return value.
Examples:
Example01. Write Java program to define and call void myMethod() function.
myMethod() function prints a message “I just got executed!”:

public class firstprogram {


static void myMethod()
{
System.out.println("I just got called and executed!");
}
public static void main(String[] args)
{
myMethod();
}
}

Output:
I just got called and executed!

Example02. Write Java program to define void myMethod() function with a


single formal parameter „fname‟, where myMethod(String fname) function print a
string. Call myMethod() function with a single actual parameter “Muhammad”:
public class secondprogram { Output:
static void myMethod(String fname) {
System.out.println(fname + "Ali");
Muhammad Ali
}

public static void main(String[] args) {


myMethod("Muhammad");
}
}

Example03. Write Java program to define and call myMethod(int firstNumber, int
secondNumber) function with a return value, where myMethod(int firstNumber,
int secondNumber) function returns the sum of firstNumber and secondNumber
parameters:

public class thirdprogram{


static int myMethod(int firstNumber,int secondNumber)
{
return firstNumber + secondNumber;
}
public static void main(String[] args)
{
System.out.println(myMethod(4, 6));
}
}

Output :

10
Exercises:
Write a class that contains the following two methods:
 public static double footToMeter(double foot) /** Convert from feet to meters
*/
 public static double meterToFoot(double meter) /** Convert from meters to feet */
Where the formula for the conversion is 1 meter = 0.305 * foot, and 1 foot = 3.279 * meter.
Consider the following values feets (1.0, 2.0, 3.0) and meters (20.0, 21.0, 22.0):

public class thirdprogram


{
public static double footToMeter(double foot)
{

return (0.305 * foot);


}

public static double meterToFoot(double meter)


{

return (3.279 * meter);


}
public static void main(String[] args)
{
System.out.println(footToMeter(4.5));
System.out.println( meterToFoot(5.5));
}
}
Lab 02
Chapter 06 Methods – Week 02
Objectives:
 To pass arguments by value.
 To use method overloading. To use Swapping in method
Examples:
Example01. Write Java program to show the value of x variable before and after passing a value
to increment(int n) function:

public class fourthprogram{

public static void increment(int n)

n++;

System.out.println("n inside the method is " + n);

public static void main(String[] args) {

int x = 1;

System.out.println("Before the call, x is " + x);

increment(x);

System.out.println("After the call, x is " + x);

Output:

Before the call, x is 1

n inside the method is 2 After the call, x is 1


Example02. Write Java program to create two functions named max. The first max(int num1,
int num2) finds the maximum integer between two integer number, and the second
max(double num1, double num2) finds the maximum double between two double numbers:

public class fifthprogram {

public static void main(String[] args)

int num1 =0;

int num2 =1;

System.out.println("The max of 3 and 4 is "+ max(3, 4));

System.out.println("The max of 9.45 and 2.9 is " + max(9.45, 2.9));

public static int max(int num1, int num2)

if (num1 > num2)

return num1;

else

return num2;

public static double max(double num1, double num2) {

if (num1 > num2) return num1;

else

return num2;

}
Output:

The max of 3 and 4 is 4

The max of 9.45 and 2.9

is 9.45

Example03. Write Java program to create method name swap(int firstnumber , int
secondnumber) to exchange the value of two variable.

public class TestPassByValue {

/** Main method */

public static void main(String[] args) {

// Declare and initialize variables

int num1 = 1;

int num2 = 2;

System.out.println("Before invoking the swap method, num1 is " + num1 + " and num2 is "
+ num2);

// Invoke the swap method to attempt to swap two variables

swap(num1, num2);

System.out.println("After invoking the swap method, num1 is " + num1 + " and num2 is " +
num2);

/** Swap two variables */

public static void swap(int n1, int n2)


{

System.out.println("\tInside the swap method");

System.out.println("\t\tBefore swapping, n1 is " + n1 + " and n2 is " + n2);

// Swap n1 with n2

int temp = n1;

n1 = n2;

n2 = temp;

System.out.println("\t\tAfter swapping, n1 is " + n1 + " and n2 is " + n2);

public class TestPassByValue


{

public static void main(String[] args) {


int num1 = 10;
int num2 = 20;
System.out.println("Before invoking the swap method, num1 is " + num1 + " and num2 is "+ num2);
swap(num1, num2);
}

public static void swap(int n1, int n2)


{
int temp = n1;
n1 = n2;
n2 = temp;
System.out.println("After swapping, n1 is " + n1 + " and n2 is " + n2);
}
}
Week 3

Objectives:
 To determine the scope of variables.
 To solve mathematical problems by using the methods in the Math class
Examples:
Example 01. Write Java program with the same method twice where it takes a single argument.
The program prints the value of x squared to the screen:
a. What is the difference between x and y variables in terms of scope ?

public class Square

public static void printSquare(double y)

System.out.println(y*y);

return;

public static void main(String[] argv)

double x = 5.0;

printSquare(3.0);

printSquare(x);

Output :

9.0

25.0
Example02. Write Java program to call suitable functions from the Math class solve the
following mathematical questions:
 Round a floating-point value up of 7.343 to the nearest integer value.
 Find the value of 2 raised to the power of 8.
 Find the logarithm of 1.
°
 Find the cosine value of 45 in radians.

import java.lang.Math;

public class maths {

public static void main(String[] args)

double ceil = Math.ceil(7.343);

System.out.println("Ceiling of 7.343 is " + ceil);

double pow = Math.pow(2,8);

System.out.println("2 to the power of 8 is " + pow);

double log1= Math.log(1);

System.out.println("Logarithm of 1 is " + log1);

double cos = Math.cos(45);

System.out.println("The cosine value of 45 is " + cos);

Output:

Ceiling of 7.343 is 8.0

2 to the power of 8 is 256.0

Logarithm of 1 is 0.0

The cosine value of 45 is 0.525


Exercise 01. Write a Java program to define and call CalculateAreaCylinder(double height,
double radius) function to calculate the area of three cylinders using Math class with the
following specifications: first cylinder (7,6), second cylinder (4.3 ,2.5), and third cylinder (-
4.5,6.9).
Note the area of cylinder is calculated using the following formulae:

public class CylinderAreaCalculator {

public static void main(String[] args) {


double area1 = Cylinder(7, 6);
System.out.println("Cylinder 1 Area: " + area1);
double area2 = Cylinder(4.3, 2.5);
System.out.println("Cylinder 2 Area: " + area2);
double area3 = Cylinder(-4.5, 6.9);
System.out.println("Cylinder 3 Area: " + area3);
}

public static double Cylinder(double height, double radius)


{
return 2 * Math.PI * radius * (height + radius);
}

public static double Cylinder(int height, int radius)


{
return 2 * Math.PI * radius * (height + radius);
}
}

OUTPUT:-
Cylinder 1 Area: 490.08
Cylinder 2 Area: 106.81
Cylinder 3 Area: 104.04
Lab 4
Week 4
Objectives:
 To implement recursive methods.

Example 1. Write a Java program to calculate factorial of a given number using recursion.

public class Factorial

{ class Factorial
{
public static void main(String[] args) public static int fact(int num)
{
{ if (num == 0)
return 1;
int num = 5; else
return num * fact(num-1);
long factorial = multiplyNumbers(num); }
public static void main(String[] args)
System.out.println("Factorial of " + num + " = " + factorial); {
int fact_num = fact(4);
} System.out.println(fact_num);
}
public static long multiplyNumbers(int num) }

if (num >= 1)

return num * multiplyNumbers(num - 1);

else

return 1;

Example 2. Write a Java for Summation of numbers using Recursion:

public class AddNumbers

public static void main(String[] args)


{
class SumNumber
{
int number = 10; public static int AddNumber(int num)
{
int sum = addNumbers(number); if (num != 0)
return num + AddNumber(num-1);
System.out.println("Sum = " + sum); else
return num;
} }

public static void main(String[] args)


public static int addNumbers(int num) {
int n = 10;
{ int a = AddNumber(n);
System.out.println("The sum of given number is : " + a);
if (num != 0) }
}
return num + addNumbers(num - 1);
OUTPUT :
The sum of given number is : 55
else

return num;

Example 3. Write a Java program to generate fibonacci Series using recursion 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

public class Fibonnaci

{ class Fibonacci
{
public static long fib(long n) public static int fib(int n)
{
if (n <= 1)
{ return n;
return fib(n-1) + fib(n-2);
if ((n == 0) || (n == 1)) }

return n; public static void main(String[] args)


{
else return fib(n - 1) + fib(n - 2); // int fib_num = fib(6);
// System.out.println(fib_num);
System.out.println("The Fibbonic series
}
number of 6 is : " +fib(6));
}
public static void main(String[] args) }

{ OUTPUT : 8

System.out.println("The 0th fibonacci number is: " + fib(0));


System.out.println("The 7th fibonacci number is: " + fib(7));

System.out.println("The 12th fibonacci number is: " + fib(12));

}
Lab 5
Single-dimensional Arrays –Week 5

Objectives:
 To create single-dimensional arrays and access array elements using indexes.
 To initialize an array using an array initializer.
 To program common array operations (displaying arrays, summing all elements)
 To invoke methods with array arguments and return values.

Example 01. Write Java program to create two 1-dimensional arrays, myFirstArray and
mySecondArray, with the following specifications:
 Declare myFirstArray variable with int type.
 Initialize mySecondArray variable with double type and size of 5 using Array Initializer.
 Assign five elements of double type with 5.6, 4.5, 3.3, 13.2, and 4.0 values, and
assigns its reference to mySecondArray.
 Add 20 on the first index of mySecondArray.
 Print the first index, middle index, and the last index of mySecondArray.

public class firstarray {

public static void main(String[] args) {

int[] myFirstArray;

double[] mySecondArray = new double[5];

mySecondArray[0] = 5.6;

mySecondArray[1] = 4.5;

mySecondArray[2] = 3.3;

mySecondArray[3] = 13.2;

mySecondArray[4] = 4.0;

mySecondArray[0] = mySecondArray[0] + 20;

System.out.println("The first index is " + mySecondArray[0]);

System.out.println("The middle index is " + mySecondArray[2]);

System.out.println("The last index is " + mySecondArray[4]);


}

Output:

The first index is 25.6

The middle index is 3.3

The last index is 4.0

Example 02. Set up a string array to hold the following names: Ali, Ahmed, and Khalid. Write a
//WAP IN JAVA TO ENTER THE DATA IN STRING ARRAY
program to print them. BY USER USING Scanner library//
import java.util.Scanner;
import java.util.Scanner; public class StringArrayExample {
public static void main(String[] args)
{
public class Exercise { Scanner scanner = new Scanner(System.in); // Prompt
user for the size of the array//
public static void main(String[] args) { System.out.print("Enter the number of strings: ");
int size = scanner.nextInt();
String[] Array = {"Ali", "Mohammed", scanner.nextLine(); // Consume the newline character///

"Khalid"}; for (int i = 0; i < Array.length; String[] strings = new String[size]; // Create the string
array//
i++) { // Input strings from the user//
for (int i = 0; i < size; i++)
String element = Array[i]; {
System.out.print("Enter string " + (i + 1) + ": ");
System.out.println(element); strings[i] = scanner.nextLine();
}
}
// Display the strings//
System.out.println("\nYou entered the following
} strings:");
for (String str : strings)
} {
System.out.println(str);
}
scanner.close(); // Close the scanner//
}
}
Example 03..Write a Java program to calculate the average value of array elements.

import java.util.Scanner;

public class Exercise

public static void main(String[] args)

int[] numbers = new int[] {20, 30, 25, 35, 16, 60, 100};

//calculate sum of all array elements

int sum = 0;

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

sum = sum + numbers[i];

//calculate average value

double average = sum / numbers.length;

System.out.println("Average value of the array elements is : " + average);

}
Lab 6
Single-dimensional Arrays –Week 6

Example 01. Write a Java program to swap number by passing a array to method.

public class TestPassArray {

/** Main method */

public static void main(String[] args)

int[] a = {1, 2};

// Swap elements using the swap method

System.out.println("Before invoking swap");

System.out.println("array is {" + a[0] + ", " + a[1] + "}");

swap(a[0], a[1]);

System.out.println("After invoking swap");

System.out.println("array is {" + a[0] + ", " + a[1] + "}");

// Swap elements using the swapFirstTwoInArray method

System.out.println("Before invoking swapFirstTwoInArray");

System.out.println("array is {" + a[0] + ", " + a[1] + "}");

swapFirstTwoInArray(a);

System.out.println("After invoking swapFirstTwoInArray");

System.out.println("array is {" + a[0] + ", " + a[1] + "}");

/** Swap two variables */

public static void swap(int n1, int n2) {

int temp = n1;


n1 = n2;

n2 = temp;

/** Swap the first two elements in the array */

public static void swapFirstTwoInArray(int[] array) {

int temp = array[0];

array[0] = array[1];

array[1] = temp;

Output:

Before invoking swap

array is {1, 2}

After invoking swap

array is {1, 2}

Before invoking swapFirstTwoInArray

array is {1, 2}

After invoking swapFirstTwoInArray

array is {2, 1}
Example 02. Write a program to find a element from a list of elements(Linear Search).

Step 1: Traverse the array.

Step 2: Match the key element with array element.

Step 3: If key element is found, return the index position of the array element.

Step 4: If key element is not found, return -1.

public class LinearSearch {

/** The method for finding a key in the list */

public static int linearSearch(int[] list, int key) {

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

if (key == list[i])

return i;

return -1;

public static void main(String[] args) {

int[] list = {4, 5, 1, 2, 9, -3};

System.out.println(linearSearch(list, 2));

Output:

3
Exercise01. Write a Java program to create a method that finds the smallest element in an array
of double values using the following header:

public static double min(double[] array)

Exercise02. Write a program that reads ten integers and displays them in the reverse of the order
in which they were read.
Lab 7th Week

Q1) Write a Java program that will read n integers from the user and store them in an array
called arr. Then do the following:

1. Print all the elements of arr in the order they were entered.

2. Print the elements of the array in reverse.

3. Print even and odd numbers.


import java.util.Scanner;
import java.util.Scanner; public class ReadArray
{
public class ReadArray { public static void main(String[] args)
{
public static void main(String[] args) { Scanner input = new Scanner(System.in);
System.out.print("Please enter how many numbers: ");
int n = input.nextInt();
Scanner input = new Scanner(System.in); int arr[]= new int[n];
System.out.print("Please enter the numbers:");
System.out.print("Please enter how many numbers: "); // Reading//
for (int i=0; i< n; i++)
int n = input.nextInt(); arr[i] = input.nextInt();
// Printing in order//
int arr[]= new int[n]; System.out.print("The numbers in order:");
for (int i=0 ; i < n; i++)
System.out.print(arr[i]+" ");
System.out.print("Please enter the numbers:"); System.out.println(" ");
// Printing in reverse//
// Reading System.out.print("The numbers in reverse:");
for (int i= n-1 ; i >= 0 ;i-- )
for (int i=0; i< n; i++) System.out.print(arr[i]+" ");
System.out.println(" ");
for (int i = 0; i < n; i++)
arr[i] = input.nextInt();
{
if (arr[i] % 2 == 0)
// Printing in order {
System.out.println(arr[i] + " is an Even number.");
System.out.print("The numbers in order:"); }
else
for (int i=0 ; i < n; i++) {
System.out.println(arr[i] + " is an Odd number.");
}
System.out.print(arr[i]+" "); }
}
// Printing in reverse }

System.out.print("The numbers in reverse:");

for (int i= n-1 ; i>=0 ;i-- )


System.out.print(arr[i]+" ");

for (int i = 0; i < n; i++)

if (arr[i] % 2 == 0)

System.out.println(arr[i] + " is an Even number.");

else

System.out.println(arr[i] + " is an Odd number.");

Sample Run:

Please enter how many numbers: 7

Please enter the numbers: 1 2 3 4 5 6 7

The numbers in order: 1 2 3 4 5 6 7

The numbers in reverse: 7 6 5 4 3 2 1


Q2) Write a Java program to find maximum and total value of the given values.

public class TestArray {

public static void main(String[] args) {

double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements

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

System.out.println(myList[i] + " ");

// Summing all elements

double total = 0;

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

total += myList[i];

System.out.println("Total is " + total);

// Finding the largest element

double max = myList[0];

for (int i = 1; i < myList.length; i++) {

if (myList[i] > max) max = myList[i];

System.out.println("Max is " + max);

Output :

1.9

2.9
3.4

3.5

Total is 11.7

Max is 3.5

Q.3) Write a program to find the a) Smallest element in the array b) Largest element in the array
c) Second largest element in the array.

import java.util.Scanner;

public class max

public static void main(String[] args) {

Scanner in=new Scanner(System.in);

int n;

System.out.println("Enter the Limit :");

n=in.nextInt();

int arr[] =new int[n];

System.out.println("Enter the Values :");

for(int i=0;i<n;i++) //Storing the values

arr[i]=in.nextInt();

for(int i=0;i<n;i++) //Array Sorting

for(int j=0;j<n-i-1;j++)

{
if(arr[j]>arr[j+1]){

int temp=arr[j];

arr[j]=arr[j+1];

arr[j+1]=temp;

System.out.println("Smallest element = "+arr[0]);

System.out.println("Largest element = "+arr[n-1]);

System.out.println("2nd Largest element = "+arr[n-2]);

Exercise 01: Write a Java Program to print odd and even elements in an array.
Lab 8 & Lab 9

Objectives:

 To declare two-dimensional arrays, and access array elements in a two- dimensional array using
row and column indexes.

 To program common operations for two-dimensional arrays (displaying arrays, summing all
elements).

Example01. Write a Java program to create two multi-dimensional arrays, myFirstMatrix, and
mySecondMatrix with the following specifications:

 Initialize myFirstMatrix variable with int type and size of 5x5 or 5-by-5 (i.e., five rows, five
columns).

 Print the value of first index, and the value of last index of myFirstMatrix.

 Initialize mySecondMatrix variable with double type and size of 4-by-3 (i.e., four rows, 3
columns) using Array Initializer.

 Assign the following elements of double type with (1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0),
(10.0, 11.0, 12.0), and assigns its reference to mySecondMatrix.

 Print the value of first index, and the value of last index of mySecondMatrix.

public class Example01 {

public static void main(String[] args) { int[][] myFirstMatrix;

int firstMatrixRowNum = 5; int firstMatrixColumnNum = 5;

myFirstMatrix= new int[firstMatrixRowNum][firstMatrixColumnNum];

System.out.println("The value of first index of myFirstMatrix is " + myFirstMatrix[0][0]);

System.out.println("The value of last index of myFirstMatrix is " + myFirstMatrix[4][4]);

double[][] mySecondMatrix = {{1.0, 2.0, 3.0}, {4, 5, 6},{7.0, 8, 9.0}, {10, 11.0, 12}};

System.out.println("The value of the first index of mySecondMatrix is " + mySecondMatrix[0][0]);

System.out.println("The value of the last index of mySecondMatrix is " + mySecondMatrix[3][2]);

}
}

Output:

The value of first index of myFirstMatrix is 0

The value of last index of myFirstMatrix is 0

The value of the first index of mySecondMatrix is 1.0

the last index of mySecondMatrix is 12.0

Example02. Write a Java program to create a two-dimensional array, myThirdMatrix, with the following
specifications:

 Initialize myThirdMatrix with int type and size of 2-by-4.

 Allow the user to input values using for loop. Use length() function to get the array length.

 Print the myThirdMatrix using a for loop.

import java.util.Scanner;

public class Example02 {

public static void main(String[] args) {

java.util.Scanner input = new Scanner(System.in);

int[][] myThirdMatrix = new int[2][4];

System.out.println("Enter " + myThirdMatrix.length + " rows and " + myThirdMatrix[0].length + "


columns: ");

for (int row = 0; row < myThirdMatrix.length; row++)

for (int column = 0; column < myThirdMatrix[row].length;column++) {

myThirdMatrix[row][column] = input.nextInt();

for (int row = 0; row < myThirdMatrix.length; row++) {

for (int column = 0; column < myThirdMatrix[row].length;


column++) {

System.out.print(myThirdMatrix[row][column] + " "); }

System.out.println();

Output:

Enter 2 rows and 4 columns:

2468

1357

Example 03. Write a program to input Two dimensional array and compute the sum of all elements of
the array.

import java.util.Scanner;

public class Example03 {


public static void main(String[] args) {

int[][] m = getArray(); // Get an array

// Display sum of elements

System.out.println("\nSum of all elements is " + sum(m));

public static int[][] getArray()

// Create a Scanner

Scanner input = new Scanner(System.in);

int[][] m = new int[3][4];

System.out.println("Enter " + m.length + " rows and “ + m*0+.length + " columns: ");

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

for (int j = 0; j < m[i].length; j++)

m[i][j] = input.nextInt();

return m;

public static int sum(int[][] m) {

int total = 0;

for (int row = 0; row < m.length; row++) {

for (int column = 0; column < m[row].length; column++) {

total += m[row][column];

return total;

}
}

Enter 3 rows and 4 columns:

1234

4567

8 9 10 11

Sum of all elements is 70

Example 04. Write a Java program to multiply two matrices.

public class Example04{

public static void main(String args[]){

//creating two matrices

int a[][]={{1,1,1},{2,2,2},{3,3,3}};

int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices

int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices

for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

c[i][j]=0;

for(int k=0;k<3;k++)

c[i][j]+=a[i][k]*b[k][j];

}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element

}//end of j loop

System.out.println();//new line

}}

Example 05. Write a Java program to add two matrices.

public class Example05{

public static void main(String args[]){

int a[][]={{1,2,3},{4,5,6},{7,8,9}};

int b[][]={{1,1,1},{1,1,1},{1,1,1}};

int c[][]=new int[3][3];

for(int i = 0;i<3;i++){

for(int j = 0;j<3;j++){

c[i][j] = a[i][j]+b[i][j];

System.out.print(c[i][j]+" ");

System.out.println();

Output:

234

567
8 9 10
Lab 10
Objec&ve
1. **File Class** - Represents a file or directory path in the file system.
2. **FileReader and FileWriter**- Used for reading from and wri?ng to text
files.
3. **BufferedReader and BufferedWriter**- Provide buffering for reading and
wri?ng, improving performance.

Example 1. Using the File Class. ```java

import java.io.File;

public class FileExample {


public sta?c void main(String[] args) {
File file = new File("example.txt");

// Check if the file exists


if (file.exists()) {
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
}
}
}

OUTPUT:
File does exist.

=== Code Execu&on Successful ===


Example 2: Reading from a File using FileReader and BufferedReader java.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOExcep?on;

public class ReadFileExample {


public sta?c void main(String[] args) {
String filePath = "example.txt";

try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {


String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOExcep?on e) {
e.printStackTrace();
}
}
}

Output:
File does exit.
Else.
java.io.FileNotFoundExcep&on: example.txt (No such file or directory)
at java.base/java.io.FileInputStream.open0(Na&ve Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
=== Code Execu+on Successful ===
Example 3: Wri&ng to a File using FileWriter and BufferedWriter java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOExcep?on;

public class WriteFileExample {


public sta?c void main(String[] args) {
String filePath = "example.txt";

try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) {


bw.write("Hello, World!");
bw.newLine();
bw.write("Welcome to file handling in Java.");
} catch (IOExcep?on e) {
e.printStackTrace();
}
}
}

Output:
Hello World
Welcome to file handling in Java
Else.
java.io.FileNotFoundExcep&on: example.txt (Permission denied)
at java.base/java.io.FileOutputStream.open0(Na&ve Method)
at java.base/java.io.FileOutputStream.open(FileOutputStream.java:298)
=== Code Execu+on Successful ===
Lab 11
Objec&ve
1. *PrintWriter**
- Provides convenient methods to write forma7ed text to files.
2. **FileInputStream and FileOutputStream**
- Used for reading and wriDng binary files.
3. **SerializaDon**
- ConverDng an object into a byte stream for saving to a file.
4. **NIO (New Input/Output)**
- Introduces classes like `Path`, `Files` for advanced file operaDons.

Example 1. Using PrintWriter to Write to a File java

import java.io.FileNotFoundExcepDon;
import java.io.PrintWriter;

public class PrintWriterExample {


public staDc void main(String[] args) {
String filePath = "example.txt";

try (PrintWriter pw = new PrintWriter(filePath)) {


pw.println("PrinDng to a file using PrintWriter.");
pw.prinZ("Number: %d, String: %s%n", 10, "Java");
} catch (FileNotFoundExcepDon e) {
e.printStackTrace();
}
}
}
OUTPUT:
PrinDng to a file using PrintWriter
File is updated

=== Code Execu&on Successful ===


Example 2: Reading and Wri&ng Binary Files using FileInputStream and
FileOutputStream by java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOExcepDon;

public class BinaryFileExample {


public staDc void main(String[] args) {
String filePath = "data.bin";

// WriDng binary data


try (FileOutputStream fos = new FileOutputStream(filePath)) {
fos.write(65); // WriDng the ASCII value of 'A'
fos.write(66); // WriDng the ASCII value of 'B'
} catch (IOExcepDon e) {
e.printStackTrace();
}

// Reading binary data


try (FileInputStream fis = new FileInputStream(filePath)) {
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data); // Convert to character and print
}
} catch (IOExcepDon e) {
e.printStackTrace();
}
}
}

Output:
File does exit.
Else.
java.io.FileNotFoundExcep&on: data.bin (Permission denied)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:126)
at BinaryFileExample.main(BinaryFileExample.java:13)
java.io.FileNotFoundExcep&on: data.bin (No such file or directory
=== Code Execu+on Successful ===

You might also like