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

Java

1. The first document demonstrates encapsulation by defining a private name variable within a class that can only be accessed by the class's printName method. 2. The second document demonstrates method overloading as a way to implement polymorphism. It defines an add method that can add integers, doubles, and strings depending on the parameters passed. 3. The third document provides another example of constructor overloading to allow initializing a class with different parameters.

Uploaded by

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

Java

1. The first document demonstrates encapsulation by defining a private name variable within a class that can only be accessed by the class's printName method. 2. The second document demonstrates method overloading as a way to implement polymorphism. It defines an add method that can add integers, doubles, and strings depending on the parameters passed. 3. The third document provides another example of constructor overloading to allow initializing a class with different parameters.

Uploaded by

ankit sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Q1- WAP that implements the concept of Encapsulation.

PROGRAM:-
public class CLG_01_Encapsulation {
public void printName() {
private String name;
name = maya;
System.out.println("Name: " + name);
}
public static void main(String[] args) {
CLG_01_Encapsulation namePrinter = new CLG_01_Encapsulation();
namePrinter.printName();
}
}
OUTPUT:-

1
Q2- WAP to demonstrate concept of function overloading of Polymorphism

PROGRAM:-
public class CLG_02_overloading {

public int add(int a, int b) {


return a + b;
}

public double add(double a, double b) {


return a + b;
}

public String add(String str1, String str2) {


return str1 + str2;
}

public static void main(String[] args) {


CLG_02_overloading example = new CLG_02_overloading();

int sumInt = example.add(5, 10);


System.out.println("Sum of integers: " + sumInt);

double sumDouble = example.add(3.5, 2.7);


System.out.println("Sum of doubles: " + sumDouble);

String concatenatedString = example.add("Hello, ", "World!");


System.out.println("Concatenated string: " + concatenatedString);
}
}

OUTPUT:-

2
Q3- WAP to demonstrate concept of function overloading of Polymorphism

PROGRAM:-
public class CLG_03_ConstructorOverloadingExample {

private int value;

public CLG_03_ConstructorOverloadingExample() {
this.value = 0;
}

public CLG_03_ConstructorOverloadingExample(int value) {


this.value = value;
}

public CLG_03_ConstructorOverloadingExample(int a, int b) {


this.value = a + b;
}

public void displayValue() {


System.out.println("Value: " + value);
}

public static void main(String[] args) {


CLG_03_ConstructorOverloadingExample example1 = new
CLG_03_ConstructorOverloadingExample();
example1.displayValue();

CLG_03_ConstructorOverloadingExample example2 = new


CLG_03_ConstructorOverloadingExample(10);
example2.displayValue();

CLG_03_ConstructorOverloadingExample example3 = new


CLG_03_ConstructorOverloadingExample(5, 8);
example3.displayValue();
}
}

OUTPUT:-

3
Q4- WAP to use Boolean data type and print the Prime Number series up to 50.

PROGRAM:-
public class CLG_04_PrimeNumberSeries {

public static boolean isPrime(int num) {


if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

public static void main(String[] args) {


System.out.println("Prime Numbers up to 50:");

for (int i = 2; i <= 50; i++) {


if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
}

OUTPUT:-

4
Q5- WAP to print first 10 number of the following series using do while loop
0,1,1,2,3,5,8,11.

PROGRAM:-
public class CLG_05_FibonacciSeries {

public static void main(String[] args) {


int n = 10; // Number of terms to print
int count = 0;
int first = 0;
int second = 1;

System.out.println("First " + n + " numbers of the series:");

do {
System.out.print(first + " ");

int next = first + second;


first = second;
second = next;

count++;
} while (count < n);
}
}

OUTPUT:-

5
Q6- WAP to check the given number is Armstrong or not.

PROGRAM:-
import java.util.Scanner;

public class CLG_06_ArmstrongNumberCheck {

public static boolean isArmstrong(int number) {


int originalNumber, remainder, result = 0, n = 0;

originalNumber = number;

while (originalNumber != 0) {
originalNumber /= 10;
++n;
}

originalNumber = number;

while (originalNumber != 0) {
remainder = originalNumber % 10;
result += Math.pow(remainder, n);
originalNumber /= 10;
}
return result == number;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number to check if it's an Armstrong number: ");


int number = scanner.nextInt();

if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
scanner.close();
}
}

OUTPUT:-

6
Q7- WAP to find the factorial of any given number.

PROGRAM:-
import java.util.Scanner;

public class CLG_07_FactorialCalculator {

public static long calculateFactorial(int number) {


if (number < 0) {
return -1;
} else if (number == 0 || number == 1) {
return 1;
} else {
long factorial = 1;
for (int i = 2; i <= number; i++) {
factorial *= i;
}
return factorial;
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number to calculate its factorial: ");


int number = scanner.nextInt();

long result = calculateFactorial(number);

if (result == -1) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
System.out.println("Factorial of " + number + " is: " + result);
}

scanner.close();
}
}

OUTPUT:-

7
Q8- WAP to sort the elements of One Dimensional Array in Ascending order.

PROGRAM:-
public class CLG_08_ArraySorting {

public static void sortArrayAscending(int[] array) {


int n = array.length;
boolean swapped;

do {
swapped = false;
for (int i = 1; i < n; i++) {
if (array[i - 1] > array[i]) {
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
swapped = true;
}
}
n--;
} while (swapped);
}

public static void main(String[] args) {


int[] numbers = {5, 2, 9, 1, 5, 6};

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


for (int number : numbers) {
System.out.print(number);
}

sortArrayAscending(numbers);

System.out.println("\nSorted array in ascending order: ");


for (int number : numbers) {
System.out.print(number);
}
}
}

OUTPUT:-

8
Q9- WAP for matrix multiplication using input/output stream.

PROGRAM:-
import java.io.*;
public class CLG_09_MatrixMultiplication {

public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {


int rows1 = matrix1.length;
int cols1 = matrix1[0].length;
int cols2 = matrix2[0].length;

int[][] result = new int[rows1][cols2];

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


for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

return result;
}

public static void printMatrix(int[][] matrix) {


for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}

public static void main(String[] args) throws IOException {


BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the dimensions of the first matrix:");


System.out.print("Rows: ");
int rows1 = Integer.parseInt(reader.readLine());
System.out.print("Columns: ");
int cols1 = Integer.parseInt(reader.readLine());

int[][] matrix1 = new int[rows1][cols1];

System.out.println("Enter the elements of the first matrix:");


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
System.out.print("Element at position [" + (i + 1) + "][" + (j + 1) + "]: ");
matrix1[i][j] = Integer.parseInt(reader.readLine());
}
9
}

System.out.println("Enter the dimensions of the second matrix:");


System.out.print("Rows: ");
int rows2 = Integer.parseInt(reader.readLine());
System.out.print("Columns: ");
int cols2 = Integer.parseInt(reader.readLine());

int[][] matrix2 = new int[rows2][cols2];

System.out.println("Enter the elements of the second matrix:");


for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
System.out.print("Element at position [" + (i + 1) + "][" + (j + 1) + "]: ");
matrix2[i][j] = Integer.parseInt(reader.readLine());}}
if (cols1 != rows2) {
System.out.println("Matrix multiplication is not possible due to incompatible
dimensions.");
} else {
int[][] resultMatrix = multiplyMatrices(matrix1, matrix2);
System.out.println("Resultant matrix after multiplication:");
printMatrix(resultMatrix);}}}
OUTPUT:-

10
Q10- WAP for matrix addition using input/output stream class.

PROGRAM:-
import java.io.*;

public class CLG_10_MatrixMultiplication {


public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {
int rows1 = matrix1.length;
int cols1 = matrix1[0].length;
int cols2 = matrix2[0].length;

int[][] result = new int[rows1][cols2];

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


for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] + matrix2[k][j];
}
}
}

return result;
}

public static void printMatrix(int[][] matrix) {


for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");}
System.out.println();
}}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the dimensions of the first matrix:");
System.out.print("Rows: ");
int rows1 = Integer.parseInt(reader.readLine());
System.out.print("Columns: ");
int cols1 = Integer.parseInt(reader.readLine());
int[][] matrix1 = new int[rows1][cols1];
System.out.println("Enter the elements of the first matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
System.out.print("Element at position [" + (i + 1) + "][" + (j + 1) + "]: ");
matrix1[i][j] = Integer.parseInt(reader.readLine());
}}
System.out.println("Enter the dimensions of the second matrix:");
System.out.print("Rows: ");
int rows2 = Integer.parseInt(reader.readLine());
System.out.print("Columns: ");
int cols2 = Integer.parseInt(reader.readLine());
int[][] matrix2 = new int[rows2][cols2];
11
System.out.println("Enter the elements of the second matrix:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
System.out.print("Element at position [" + (i + 1) + "][" + (j + 1) + "]: ");
matrix2[i][j] = Integer.parseInt(reader.readLine());
}}
if (cols1 != rows2) {
System.out.println("Matrix multiplication is not possible due to incompatible
dimensions.");
} else {
int[][] resultMatrix = multiplyMatrices(matrix1, matrix2);
System.out.println("Resultant matrix after multiplication:");
printMatrix(resultMatrix);
}}}

OUTPUT:-

12
Q11- WAP for matrix transposes using input/output stream class.

PROGRAM:-
import java.io.*;
public class CLG_11_MatrixTranspose {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Enter the number of rows: ");
int rows = Integer.parseInt(reader.readLine());
System.out.print("Enter the number of columns: ");
int cols = Integer.parseInt(reader.readLine());
int[][] matrix = new int[rows][cols];
System.out.println("Enter the matrix elements:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print("Matrix[" + (i + 1) + "][" + (j + 1) + "]: ");
matrix[i][j] = Integer.parseInt(reader.readLine());
}}
System.out.println("\nOriginal Matrix:");
printMatrix(matrix);
int[][] transposeMatrix = transpose(matrix);
System.out.println("\nTranspose Matrix:");
printMatrix(transposeMatrix);
} catch (IOException | NumberFormatException e) {
e.printStackTrace();
}}
private static int[][] transpose(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int[][] transposeMatrix = new int[cols][rows];
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
transposeMatrix[i][j] = matrix[j][i];
}}
return transposeMatrix;
}

private static void printMatrix(int[][] matrix) {


for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + "\t");
}
System.out.println();
}}}

13
OUTPUT:-

14
Q12- WAP to add the elements of vector as arguments of main method(Run time) and
rearrange them and copy it into an array

PROGRAM:-
import java.util.*;

public class CLG_12_VectorToArrayExample {


public static void main(String[] args) {
Vector v1= new Vector();
v1.addElement("Kullu");
v1.addElement("Lav");
v1.addElement("rush");
v1.addElement("he");
v1.addElement("Sachme");
v1.insertElementAt("mohan", 5);
for(int i=0;i<v1.size();i++){
System.out.println(v1.get(i) + " ");
}
String a[]= new String[6];
v1.copyInto(a);
for(int j=0;j<6;j++){
System.out.print(a[j]+ " ");
}
}
}

OUTPUT:-

15
Q13- WAP that implements different methods available in vector class.

PROGRAM:-
import java.util.Vector;

public class CLG_23_Vector {


public static void main(String[] args) {
Vector v1= new Vector();
v1.addElement("Kullu");
v1.addElement("Lav");
v1.addElement("rush");
v1.addElement("he");
v1.addElement("Sachme");
v1.insertElementAt("mohan", 5);

int size = v1.size();


System.out.println("Size is: " + size);

int capacity = v1.capacity();


System.out.println("Default capacity is: " + capacity);

String element = (v1.get(1)).toString();


System.out.println("Vector element is: " + element);

String firstElement = (v1.firstElement()).toString();


System.out.println("The first later of the vector is: " + firstElement);

String lastElement = (v1.lastElement()).toString();


System.out.println("The last later of the vector is: " + lastElement);

v1.remove("rush");

System.out.println("Elements are: " + v1);


}
}

OUTPUT:-

16
Q14- WAP to check that the given String is palindrome or not.

PROGRAM:-
import java.util.Scanner;

public class CLG_13_PalindromeChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();

if (isPalindrome(input)) {
System.out.println("The given string is a palindrome.");
System.out.println("The given string is not a palindrome.");
}
}

static boolean isPalindrome(String s) {


s = s.replaceAll("\\s", "").toLowerCase();
int length = s.length();

for (int i = 0; i < length / 2; i++) {


if (s.charAt(i) != s.charAt(length - i - 1)) {
return false;
}
}
return true;
}
}

OUTPUT:-

17
Q15- WAP to arrange the string in alphabetical order.

PROGRAM:-
import java.util.Scanner;

public class CLG_14_AlphabeticalOrder {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();

String result = arrangeAlphabetically(input);


System.out.println("String in alphabetical order: " + result);
}

static String arrangeAlphabetically(String s) {


char[] charArray = s.toCharArray();
java.util.Arrays.sort(charArray);
return new String(charArray);
}
}

OUTPUT:-

18
Q16- WAP forStringBuffer class which perform the all the methods of that class.

PROGRAM:-
public class CLG_15_StringBufferExample {
public static void main(String[] args) {
StringBuffer stringBuffer = new StringBuffer("Hello");
System.out.println("StringBuffer: " + stringBuffer);

stringBuffer.append(" World");
System.out.println("StringBuffer: " + stringBuffer);

stringBuffer.insert(5, " Java");


System.out.println("StringBuffer: " + stringBuffer);

stringBuffer.delete(11, 16);
System.out.println("StringBuffer: " + stringBuffer);

stringBuffer.reverse();
System.out.println("StringBuffer: " + stringBuffer);

stringBuffer.setLength(5);
System.out.println("StringBuffer: " + stringBuffer);

stringBuffer.append("!");
System.out.println("StringBuffer: " + stringBuffer);

int capacity = stringBuffer.capacity();


int length = stringBuffer.length();

}
}

OUTPUT:-

19
Q17- WAP to calculate Simple Interest using the Wrapper Class.

PROGRAM:-
import java.util.Scanner;

public class CLG_16_SimpleInterestCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter principal amount: ");


double principal = scanner.nextDouble();

System.out.print("Enter rate of interest: ");


double rate = scanner.nextDouble();

System.out.print("Enter time in years: ");


double time = scanner.nextDouble();

Double simpleInterest = (principal * rate * time) / 100;

System.out.println("Principal Amount: " + principal);


System.out.println("Rate of Interest: " + rate);
System.out.println("Time in Years: " + time);
System.out.println("Simple Interest: " + simpleInterest);
}
}

OUTPUT:-

20
Q18- WAP to calculate Area of various geometrical figures using the abstract class.

PROGRAM:-
import java.util.Scanner;

abstract class Shape {


abstract double calculateArea();
}

class Circle extends Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}

class Rectangle extends Shape {


double length;
double width;

Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
double calculateArea() {
return length * width;
}
}

class Triangle extends Shape {


double base;
double height;

Triangle(double base, double height) {


this.base = base;
this.height = height;
}

@Override
double calculateArea() {
return 0.5 * base * height;
}}
21
public class CLG_17_geometrical {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose a shape to calculate area:");
System.out.println("1. Circle");
System.out.println("2. Rectangle");
System.out.println("3. Triangle");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
Circle circle = new Circle(radius);
System.out.println("Area of the circle: " + circle.calculateArea());
break;
case 2:
System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble();
Rectangle rectangle = new Rectangle(length, width);
System.out.println("Area of the rectangle: " + rectangle.calculateArea());
break;
case 3:
System.out.print("Enter the base of the triangle: ");
double base = scanner.nextDouble();
System.out.print("Enter the height of the triangle: ");
double height = scanner.nextDouble();
Triangle triangle = new Triangle(base, height);
System.out.println("Area of the triangle: " + triangle.calculateArea());
break;
default:
System.out.println("Invalid choice");}}}

OUTPUT:-

22
Q19- WAP where Single class implements more than one interfaces and with help of
interface reference variable user call the methods.

PROGRAM:-
interface Shape2 {
void draw();
}

interface Color {
void setColor(String color);
}

class Circle2 implements Shape2, Color {


private String color;

@Override
public void draw() {
System.out.println("Drawing a circle.");
}

@Override
public void setColor(String color) {
this.color = color;
System.out.println("Setting color to " + color);
}

public void displayInfo() {


System.out.println("Circle with color: " + color);
}
}

public class CLG_18_main {


public static void main(String[] args) {
Shape2 shape = new Circle2();
shape.draw();

Color color = new Circle2();


color.setColor("Blue");

((Circle2) color).displayInfo();
}
}
OUTPUT:-

23
Q20- WAP that use the multiple catch statements within the try-catch mechanism.

PROGRAM:-
import java.util.Scanner;

public class CLG_19_MultipleCatchExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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

System.out.print("Enter another number: ");


int denominator = scanner.nextInt();

int result = numerator / denominator;

System.out.println("Result: " + result);


} catch (ArithmeticException e) {
System.err.println("Error: " + e.getMessage());
} catch (java.util.InputMismatchException e) {
System.err.println("Error: Invalid input. " + e.getMessage());
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
}

System.out.println("Program continues after the try-catch block.");


}
}

OUTPUT:-

24
Q21- WAP where user will create a self-Exception using the “throw” keyword.

PROGRAM:-
import java.util.Scanner;

class CustomException extends Exception {


public CustomException(String message) {
super(message);
}
}

public class CLG_20_CustomExceptionExample {


public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter a age: ");
try {
int age = sc.nextInt();
if (age < 0) {
throw new CustomException("Age cannot be negative");
} else {
System.out.println("Age is: " + age);
}
} catch (CustomException e) {
System.err.println("Custom Exception: " + e.getMessage());
}
}
}

OUTPUT:-

25
Q22- WAP for multithread using the isAlive() and synchronized() methods of Thread
class

PROGRAM:-
package clg;
class Ab extends Thread {
public synchronized void run() {
System.out.println("Thread A=");
for (int i = 0; i <= 5; i++) {
System.out.println("Thread one is running A=" + i);}}}
class Bb extends Thread {
public synchronized void run() {
System.out.println("Thread B=");
for (int j = 0; j <= 5; j++) {
System.out.println("Thread two is running B=" + j);}}}
public class CLG_21_MyThread {
public static void main(String arg[]) {
Ab a1 = new Ab();
a1.start();
Bb b1 = new Bb();
b1.start();
if (a1.isAlive()) {
System.out.println("Thread one is alive");
} else {
System.out.println("Thread one is not alive");}}}
OUTPUT:-

26
Q23- WAP for multithreading using the suspend(), resume(), sleep(t) method of Thread
class.

PROGRAM:-9i
class MyThread extends Thread {
private boolean suspended = false;

public synchronized void mySuspend() {


suspended = true;
}

public synchronized void myResume() {


suspended = false;
notify();
}

@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);

// Check if suspended
synchronized (this) {
while (suspended) {
wait();
}
}

Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.err.println("Thread interrupted");
}
}
}

public class CLG_24_sleep {


public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();

try {
Thread.sleep(2000);

myThread.mySuspend();
System.out.println("Thread suspended for 2 seconds");

Thread.sleep(2000);

27
myThread.myResume();
System.out.println("Thread resumed");
} catch (InterruptedException e) {
System.err.println("Main thread interrupted");
}

try {
myThread.join();
} catch (InterruptedException e) {
System.err.println("Main thread interrupted");
}

System.out.println("Main thread exiting");


}
}

OUTPUT:-

28
Q24- WAP to create a package and one package will import another package.

PROGRAM:-
1) First package program.
package newpack;
public class inputclass {
public void fun(){
System.out.println("hi it's me mariyo");
}
}
2) Second package program.
package new2pack;
import newpack.*;
public class output {
public static void main(String[] args) {
inputclass i= new inputclass();
i.fun();
}
}

OUTPUT:-

29
Q25- WAP for JDBC to display the records from the existing table.

STEPS:-

1. Create a table in MS Access.


2. Save the table in a folder.
3. Open control penal in windows.
4. Open Administrative Tools.
5. Open ODBC Data Sources.
6. Add your database.
7. Run the program.
PROGRAM:-
import java.sql.*;

public class CLG_22_conne {


public static void main(String[] args) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:db");
Statement s1 = con.createStatement();
ResultSet r = s1.executeQuery("select * from student");
while(r.next()) {
System.out.println(r.getInt(1) + " " + r.getString(2) + " " + r.getString(3));
}
}
catch(Exception e){
System.out.println(e);
}
}
}

OUTPUT:-

30
Q26- WAP for demonstration of switch statement, continue and break.

PROGRAM:-
import java.util.Scanner;
public class CLG_26_Breck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose an option:");
System.out.println("1. Print Hello");
System.out.println("2. Print World");
System.out.println("3. Print Hello World");
System.out.println("4. Exit");
while (true) {
System.out.print("Enter your choice (1-4): ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Hello");
break;
case 2:
System.out.println("World");
break;
case 3:
System.out.println("Hello World");
continue;
case 4:
System.out.println("Exiting the program.");
scanner.close();
System.exit(0);
default:
System.out.println("Invalid choice. Please enter a number between 1 and 4.");
}
System.out.println("This is after the switch statement.");
}}}

OUTPUT:-

31
Q27- WAP a program to read and write on file using File Reader and file Writer class.

PROGRAM:-
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
public class CLG_27_readwrite {
public static void main(String[] args) {
String inputFile = "input.txt";
String outputFile = "output.txt";
writeToFile(outputFile, "Hello, this is a sample text.\n");
String content = readFromFile(inputFile);
System.out.println("Content read from file:\n" + content);
}

private static void writeToFile(String filePath, String content) {


try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write(content);
System.out.println("Content written to file successfully.");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}}
private static String readFromFile(String filePath) {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}} catch (IOException e) {
System.err.println("Error reading from file: " + e.getMessage());
}
return content.toString();
}}
OUTPUT:-

32

You might also like