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

Java Lab Class (5)

This document outlines several Java programming exercises, including finding prime numbers, matrix multiplication, text statistics, random number generation, string manipulation, and operations using String and StringBuffer classes. Each exercise includes an aim, algorithm, program code, output examples, and a result statement confirming successful execution. The exercises demonstrate various programming concepts and techniques in Java.

Uploaded by

Yuvan SR
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java Lab Class (5)

This document outlines several Java programming exercises, including finding prime numbers, matrix multiplication, text statistics, random number generation, string manipulation, and operations using String and StringBuffer classes. Each exercise includes an aim, algorithm, program code, output examples, and a result statement confirming successful execution. The exercises demonstrate various programming concepts and techniques in Java.

Uploaded by

Yuvan SR
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Ex:1 PRIME NUMBERS

AIM
To write a java program to get an integer from user and to print all prime numbers
upto that integer.
ALGORITHM
Step 1: Start the program.
Step 2: Declare an integer variable n, p to hold the user input.
Step 3: Using a Scanner object s, to read user input from the console.
Step 4: Read the integer input from the user and store it in variable n.
Step 5: Initialize a loop with variable i=2 and continue looping until i is less than n.
Step 6: Inside this loop, set p to 0.
Step 7: Initialize another loop with variable j=2 and continue looping until j is less than i.
Step 8: Check if i is divisible by j (i % j == 0) then set p to 1 indicating that i is not prime and
break the inner loop.
Step 9: If p is 0, then i is prime, print the value of i.
Step 10: Stop the program.

Program

import java.util.Scanner;
class PrimeNumbers
{
public static void main(String[] args)
{
int n;
int p;
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
n=s.nextInt();
System.out.println("The Prime Numbers upto"+ n +"are :");
for(int i=2;i<n;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
System.out.println(i);
}
}
}

Class Diagram
OUTPUT

Enter a number:
50
The Prime Numbers upto50 are :
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

RESULT
Thus, the java program to get an integer from user and to print all prime
numbers upto that integer has been created and executed successfully.
Ex:2 MATRIX MULTIPLICATION
AIM
To write a java program to multiply two given matrices.
ALGORITHM
Step 1: Start the program.
Step 2: Declare an integer variable m, n ,p and q to store matrix dimensions and sum, c, d,
and k for loop counters.
Step 3: Read number of rows and columns for both the matrices from user.
Step 4: Using nested loops read the matrices.
Step 5: If n (columns of first matrix) is not equal to p (rows of the second matrix), then print
no matrix multiplication operation and terminate the program.
Step 6: Initialize nested loops to perform matrix operations.
Step 7: Compute multiplication and addition as sum += first[c][k] * second[k][d].
Step 8: Store sum in the result matrix as multiply[c][d] = sum.
Step 9: Print the product Matrices.
Step 10: Stop the program.

Program
import java.util.Scanner;
class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();

int first[][] = new int[m][n];


System.out.println("Enter elements of first matrix");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
first[c][d] = in.nextInt();
System.out.println("Enter the number of rows and
columns of second matrix");
p = in.nextInt();
q = in.nextInt();
if (n != p)
System.out.println("The matrices can't be multiplied with
each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];

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

for (c = 0; c < p; c++)


for (d = 0; d < q; d++)
second[c][d] = in.nextInt();

for (c = 0; c < m; c++)


{
for (d = 0; d < q; d++)
{
for (k = 0; k < p; k++)
{
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}

System.out.println("Product of the matrices:");

for (c = 0; c < m; c++)


{
for (d = 0; d < q; d++)
System.out.print(multiply[c][d]+"\t");

System.out.print("\n");
}
}
}
}

Class Diagram

OUTPUT
Enter the number of rows and columns of first matrix
2
2
Enter elements of first matrix
2
4
6
8
Enter the number of rows and columns of second matrix
2
2
Enter elements of second matrix
1
3
5
7
Product of the matrices:
22 34
46 74

RESULT
Thus, the java program to multiply two given matrices has been created
and executed successfully.
Ex:3 DISPLAYS THE NUMBER OF CHARACTERS, LINES AND WORDS
IN A TEXT

AIM
To write a java program to displays the number of characters, lines and words in a
text.
ALGORITHM
Step 1: Start the program.
Step 2: Declare a string variable filePath to store the location of the file.
Step 3: Initialize three integer counters as characterCount, lineCount, and wordCount to zero.
Step 4: Create an object br for BufferedReader class to read the specified file.
Step 5: Use a while loop and br.readLine() function to read each line in the file.
Step 6: Using line.length() function add the length to characterCount.
Step 7: Remove leading and trailing whitespace from the current line using line.trim().
Step 8: Split the line into words and update wordCount.
Step 9: Print the results for characters, lines, and words.
Step 10: Stop the program.

Program
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TextStatistics


{
public static void main(String[] args)
{
String filePath = "sample.txt";
int characterCount = 0;
int lineCount = 0;
int wordCount = 0;

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


{
String line;
while ((line = br.readLine()) != null)
{
characterCount += line.length();
lineCount++;
String[] words = line.trim().split("\\s+");
wordCount += words.length;
}
}
catch (IOException e)
{
System.err.println("Error reading the file: " + e.getMessage());
}

System.out.println("Number of characters: " + characterCount);


System.out.println("Number of lines: " + lineCount);
System.out.println("Number of words: " + wordCount);
}
}

Class Diagram

OUTPUT

Result
Thus, the java program to displays the number of characters, lines and
words in a text has been created and executed successfully.
Ex:4 GENERATE RANDOM NUMBERS BETWEEN TWO LIMITS

AIM
To write a java program to Generate random numbers between two given limits
using Random class.
ALGORITHM
Step 1: Start the program.
Step 2: Create a Scanner object to read input from the user.
Step 3: Create a Random object to generate random numbers.
Step 4: Read the lowerLimit and upperLimit integer input from the user and store it in the
variable.
Step 5: If lowerLimit is greater than or equal to upperLimit, then Display the message as
Invalid limits.
Step 6: Calculate a random number using the formula: randomNumber = random.nextInt
(upperLimit - lowerLimit) + lowerLimit.
Step 7: Compute range1 as: range1 = lowerLimit + (upperLimit - lowerLimit) / 3.
Step 8: Compute range2 as: range2 = lowerLimit + 2 * (upperLimit - lowerLimit) / 3.
Step 9: Print the random numbers and the range
Step 10: Stop the program.

Program
import java.util.Random;
import java.util.Scanner;

public class RandomNumberGenerator


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

System.out.print("Enter the lower limit: ");


int lowerLimit = scanner.nextInt();

System.out.print("Enter the upper limit: ");


int upperLimit = scanner.nextInt();
if (lowerLimit >= upperLimit)
{
System.out.println("Invalid limits! The upper limit must be
greater than the lower limit.");
return;
}

int randomNumber = random.nextInt(upperLimit - lowerLimit) + lowerLimit;


System.out.println("Generated random number: " + randomNumber);

int range1 = lowerLimit + (upperLimit - lowerLimit) / 3;


int range2 = lowerLimit + 2 * (upperLimit - lowerLimit) / 3;

if (randomNumber < range1)


{
System.out.println("The number is in the Low range.");
} else if (randomNumber >= range1 && randomNumber < range2)
{
System.out.println("The number is in the Medium range.");

} else
{
System.out.println("The number is in the High range.");
}

scanner.close();
}
}
Class Diagram

OUTPUT

Enter the lower limit: 10


Enter the upper limit: 30
Generated random number: 29
The number is in the High range.

Result
Thus, the java program to Generate random numbers between two
given limits using Random class has been created and executed successfully.
Ex:5 STRING MANIPULATION
[LENGTH, CHARACTER POSITION AND CONCATENATION]
AIM
To write a java program to find string length, character position and to compute
concatenation operations.
ALGORITHM
Step 1: Start the program.
Step 2: Create a Scanner object to read input from the user.
Step 3: Read the input string and store it in str1 and str2.
Step 4: Convert str1and str2 to a character array charArray1 and charArray2.
Step 5: Calculate and print the length of charArray1.
Step 6: Read the integer input to find the position of the character.
Step 7: Print the character of the position1 in charArray1. If position1 is between 0 and the
length of charArray1 otherwise print error message.
Step 8: Concatenate str1 and str2 and store the result in concatenatedString.
Step 9: Display Concatenated String
Step 10: Stop the program.

Program

import java.util.Scanner;

public class StringManipulation


{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();
char[] charArray1 = str1.toCharArray();

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


String str2 = scanner.nextLine();
char[] charArray2 = str2.toCharArray();

System.out.println("\nString Manipulation Results:");


System.out.println("Length of first string: " + charArray1.length);
System.out.println("Length of second string: " + charArray2.length);

System.out.print("Enter the position (0 to " + (charArray1.length - 1) + ")


to find a character in the first string: ");

int position1 = scanner.nextInt();


if (position1 >= 0 && position1 < charArray1.length)
{
System.out.println("Character at position " + position1 + ": " +
charArray1[position1]);
} else
{
System.out.println("Invalid position for the first string.");
}

System.out.print("Enter the position (0 to " + (charArray2.length - 1) + ")


to find a character in the second string: ");

int position2 = scanner.nextInt();


if (position2 >= 0 && position2 < charArray2.length)
{
System.out.println("Character at position " + position2 + ": " +
charArray2[position2]);
} else
{
System.out.println("Invalid position for the second string.");
}

String concatenatedString = str1 + str2;


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

scanner.close();
}
}

Class diagram
OUTPUT
Enter the first string: Java Programming
Enter the second string: Language

String Manipulation Results:


Length of first string: 16
Length of second string: 8
Enter the position (0 to 15) to find a character in the first string: 8
Character at position 8: g
Enter the position (0 to 7) to find a character in the second string: 5
Character at position 5: a
Concatenated string: Java ProgrammingLanguage

Result
Thus, the java program to find string length, character position and to
compute concatenation operations has been created and executed successfully.

Ex:6 STRING OPERATIONS USING STRING CLASS


[STRING CONCATENATION, SEARCH SUBSTRING AND TO EXTRACT SUBSTRING]
AIM
To write a java program to perform string concatenation, search substring and to
extract substring using string class.
ALGORITHM
Step 1: Start the program.
Step 2: Initialize a Scanner object for user input.
Step 3: Read the input from the user and store it in a variable firstString and secondString.
Step 4: Create a new variable concatenatedString by joining firstString and secondString.
Step 5: Read the substring from user to search in the firstString.
Step 6: Check if firstString contains substring print message as substring found else print not found .
Step 7: Read the input as startIndex and endindex to extract the substring.
Step 8: Extract the substring from firstString using the substring(startIndex, endIndex) method.
Step 9: Display result.
Step 10: Stop the program.

Program
import java.util.Scanner;
public class StringOperations
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String firstString = scanner.nextLine();

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


String secondString = scanner.nextLine();

String concatenatedString = firstString + secondString;


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

System.out.print("Enter a substring to search: ");


String substringToSearch = scanner.nextLine();
if (firstString.contains(substringToSearch))
{
System.out.println("The substring '" + substringToSearch + "' is found in
the first string.");
} else
{
System.out.println("The substring '" + substringToSearch + "' is NOT
found in the first string.");
}

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


int startIndex = scanner.nextInt();

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


int endIndex = scanner.nextInt();

if (startIndex >= 0 && endIndex <= firstString.length() && startIndex <


endIndex) {
String extractedSubstring = firstString.substring(startIndex, endIndex);
System.out.println("Extracted substring: " + extractedSubstring);
} else {
System.out.println("Invalid indices for substring extraction.");
}

scanner.close();
}
}

OUTPUT
Enter the first string: Hello java
Enter the second string: world
Concatenated string: Hello javaworld
Enter a substring to search: java
The substring 'java' is found in the first string.
Enter the starting index for substring extraction: 6
Enter the ending index for substring extraction: 10
Extracted substring: java
Result
Thus, the java program to perform string concatenation, search substring
and to extract substring using string class has been created and executed
successfully.

Ex: 7 STRING OPERATIONS USING STRINGBUFFER CLASS


[FIND LENGTH, REVERSE THE STRING AND TO DELETE THE SUBSTRING]
AIM
To write a java program to find the length of the given string, reverse the string and to
perform the delete operation using stringbuffer class.
ALGORITHM
Step 1: Start the program.
Step 2: Create an instance of Scanner to read input from the console.
Step 3: Read the user's input string using scanner.nextLine() as inputString.
Step 4: Create an instance of StringBuffer with inputString.
Step 5: Calculate the length of the string using stringBuffer.length().
Step 6: Compute using the reverse() method on stringBuffer to reverse the string.
Step 7: Find the starting index of substringToDelete in stringBuffer using indexOf(), storing
the result in startIndex..
Step 8: Calculate the ending index by adding the length of substringToDelete to startIndex. Delete
the substring
Step 9: Display result.
Step 10: Stop the program.

Program
import java.util.Scanner;
public class StringBufferOperations
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String inputString = scanner.nextLine();

StringBuffer stringBuffer = new StringBuffer(inputString);

System.out.println("Length of the string: " + stringBuffer.length());

StringBuffer reversedString = stringBuffer.reverse();


System.out.println("Reversed string: " + reversedString);
String reversedWord = stringBuffer.reverse().toString();
System.out.print("Enter the substring to delete: ");
String substringToDelete = scanner.nextLine();

int startIndex = stringBuffer.indexOf(substringToDelete);

if (startIndex != -1)
{
int endIndex = startIndex + substringToDelete.length();
stringBuffer.delete(startIndex, endIndex);

System.out.println("Modified string: " + stringBuffer.toString());


} else
{
System.out.println("Substring not found in the original string.");
}

scanner.close();
}
}

OUTPUT
Enter a string: Hello world welcome to java programming
Length of the string: 39
Reversed string: gnimmargorp avaj ot emoclew dlrow olleH
Enter the substring to delete: world
Modified string: Hello welcome to java programming

Result
Thus, the java program to find the length of the given string, reverse the string
and to perform the delete operation using stringbuffer class has been created and
executed successfully.

Ex:8 MULTITHREADING

AIM
To write a java program to implement a multithread application and to print random
integer for every one second in the first thread, print square for even numbers in the second
thread and third thread print cube for odd numbers.
ALGORITHM
Step 1: Start the program.
Step 2: Define RandomNumberThread Class and Create an instance of Random.
Step 3: Generate a random integer (0 to 99) and store it in randomInteger..
Step 4: Check if randomInteger is even then Create an instance of SquareThread passing
randomInteger else Create an instance of CubeThread passing randomInteger.
Step 5: Put the thread to sleep for 1 second (1000 milliseconds).
Step 6: Define SquareThread Class and an instance variable number..
Step 7: Initialize number with the passed integer.Calculate and print the square of number.
Step 8: Define CubeThread Class and an instance variable number.
Step 9: Initialize number with the passed integer. Calculate and print the cube of number.
Step 10: Stop the program.

Program
import java.util.Random;
class RandomNumberThread extends Thread
{
public void run()
{
Random random = new Random();
for (int i = 0; i < 10; i++)
{
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " +
randomInteger);
if((randomInteger%2) == 0)
{
SquareThread sThread = new SquareThread(randomInteger);
sThread.start();
}
else {
CubeThread cThread = new CubeThread(randomInteger);
cThread.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}

class SquareThread extends Thread {


int number;

SquareThread(int randomNumbern) {
number = randomNumbern;
}

public void run() {


System.out.println("Square of " + number + " = " + (number *
number));
}
}

class CubeThread extends Thread {


int number;

CubeThread(int randomNumber) {
number = randomNumber;
}

public void run() {


System.out.println("Cube of " + number + " = " + number *
number * number);
}
}

public class MultiThreadingTest


{
public static void main(String args[]) {
RandomNumberThread rnThread = new RandomNumberThread();
rnThread.start();
}
}
OUTPUT

Random Integer generated : 77


Cube of 77 = 456533
Random Integer generated : 30
Square of 30 = 900
Random Integer generated : 34
Square of 34 = 1156
Random Integer generated : 76
Square of 76 = 5776
Random Integer generated : 97
Cube of 97 = 912673
Random Integer generated : 12
Square of 12 = 144
Random Integer generated : 50
Square of 50 = 2500
Random Integer generated : 49
Cube of 49 = 117649
Random Integer generated : 91
Cube of 91 = 753571
Random Integer generated : 93
Cube of 93 = 804357

Result
Thus, the java program to implement a multithread application and to print
random integer for every one second in the first thread, print square for even numbers in the
second thread and third thread print cube for odd numbers has been created and
executed successfully.
Ex:9 THREADING USING ASYNCHRONOUS METHOD

AIM
To write a java program to implement asynchronous multithread application and to
print numbers from 1 to 10 in thread1 and 90 to 100 in thread2.
ALGORITHM
Step 1: Start the program.
Step 2: Define NumberPrinter Class and Implement the Runnable interface.
Step 3: Declare private instance variables as start and end.
Step 4: In Override run() method, using for loop print the value of i.
Step 5 Pause the thread for 100 milliseconds using Thread.sleep(100).
Step 6: If an InterruptedException occurs, Set the current thread's interrupt flag using
Thread.currentThread().interrupt().
Step 7: Create a Thread object thread1 and initialize it with NumberPrinter(1, 10).
Step 8: Create another Thread object thread2 and initialize it with NumberPrinter(90, 100).
Step 9: Start thread1 and thread2 and print the result.
Step 10: Stop the program.

Program

class NumberPrinter implements Runnable


{
private int start;
private int end;
public NumberPrinter(int start, int end)
{
this.start = start;
this.end = end;
}
@Override public void run()
{ for (int i = start; i <= end; i++)
{ System.out.println(i);
try {
Thread.sleep(100);
}
catch (InterruptedException e)
{ Thread.currentThread().interrupt();
System.err.println("Thread was interrupted");
}
}
}
}

public class AsyncNumberPrinting

{
public static void main(String[] args)
{
Thread thread1 = new Thread(new NumberPrinter(1, 10));
Thread thread2 = new Thread(new NumberPrinter(90, 100));
thread1.start();
thread2.start();
try
{
thread1.join();
thread2.join();

}
catch (InterruptedException e)
{
e.printStackTrace();

}
System.out.println("Both threads have completed their execution.");
}
}

OUTPUT
1
90
2
91
3
92
4
93
5
94
95
6
96
7
97
8
98
9
99
10
100
Both threads have completed their execution.

Result
Thus, the java program to implement asynchronous multithread application and to print
numbers from 1 to 10 in thread1 and 90 to 100 in thread2 has been created and executed
successfully.

Ex:10 EXCEPTION HANDLING

AIM
To write a java program to implement exception handling.
ALGORITHM
Step 1: Start the program.
Step 2: Create an instance of Scanner to read input from the user.
Step 3: Read the user input as an integer and store it in a variable named divisor.
Step 4: Calculate the result of dividing 100 by divisor and print the result.
Step 5: If an exception occurs (e.g., division by zero), print an appropriate error message.
Step 6: Read the user input as a string and store it in numberString.
Step 7: If an exception occurs (e.g., input is not a valid integer), print an appropriate error
message.
Step 8: Define an integer array numbers and Read the index as an integer and store it in
index.
Step 9: If an exception occurs (e.g., index is out of bounds), print an appropriate error
message.
Step 10: Read the size as an integer and store it in size.
Step 11: If an exception occurs (e.g., size is negative), print an appropriate error message.
Step 12: Stop the program.

Program
import java.util.Scanner;
public class ExceptionDemo
{

public static void main(String[] args)


{
Scanner scanner = new Scanner(System.in);

System.out.println("Demonstrating ArithmeticException:");
try
{
System.out.print("Enter a number to divide 100: ");
int divisor = scanner.nextInt();
int result = 100 / divisor;
System.out.println("Result is: " + result);
}
catch (ArithmeticException e)
{
System.out.println("Error: Division by zero is not allowed.");
}

System.out.println("\nDemonstrating NumberFormatException:");
try
{
System.out.print("Enter a number: ");
String numberString = scanner.next();
int number = Integer.parseInt(numberString);
System.out.println("You entered the number: " + number);
}
catch (NumberFormatException e)
{
System.out.println("Error: Invalid number format.");
}
System.out.println("\nDemonstrating ArrayIndexOutOfBounds Exception:");
try {
int[] numbers = {1, 2, 3};
System.out.print("Enter an index to access the array (0-2): ");
int index = scanner.nextInt();
System.out.println("Element at index " + index + ": " + numbers[index]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error: Index is out of bounds.");
}

System.out.println("\nDemonstrating NegativeArraySizeException:");
try
{
System.out.print("Enter a size for the array (must be positive): ");
int size = scanner.nextInt();
int[] array = new int[size];
System.out.println("Array created of size: " + size);
}
catch (NegativeArraySizeException e)
{
System.out.println("Error: Array size cannot be negative.");
}

scanner.close();
}
}

OUTPUT
Demonstrating ArithmeticException:
Enter a number to divide 100: 0
ERROR!
Error: Division by zero is not allowed.

Demonstrating NumberFormatException:
Enter a number: abc
ERROR!
Error: Invalid number format.

Demonstrating ArrayIndexOutOfBoundsException:
Enter an index to access the array (0-2): 5
ERROR!
Error: Index is out of bounds.

Demonstrating NegativeArraySizeException:
Enter a size for the array (must be positive): -5
ERROR!
Error: Array size cannot be negative.

Result
Thus, the java program to implement exception handling has been created and
executed successfully.
Ex:11 FILE HANDLING

AIM
To write a java program to implement file handling and to read a file name, display
the file exists, the file is readable or writable, the type and the length of the file in bytes.
ALGORITHM
Step 1: Start the program.
Step 2: Create an instance of Scanner to read input from the user.
Step 3: Read the user input as a string and store it in a variable named fileName.
Step 4: Create a new File object using the fileName entered by the user.
Step 5: Use the exists() method of the File object to check if the file exists print YES else print NO .
Step 6: Use canRead() method to check if the file is readable and print the result.
Step 7: Use canWrite() method to check if the file is writable and print the result.
Step 8: Use isDirectory() method to determine if the File represents a directory and print the
File type.
Step 9: Use length() method to get the size of the file in bytes and print the result
Step 10: Stop the program.

Program
import java.io.File;
import java.util.Scanner;
public class FileInformation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the file name (with path if not in the same directory): ");
String fileName = scanner.nextLine();

File file = new File(fileName);


if (file.exists()) {
System.out.println("File exists: Yes");
System.out.println("File is readable: " + file.canRead());
System.out.println("File is writable: " + file.canWrite());
System.out.println("File type: " + (file.isDirectory() ? "Directory" : "File"));
System.out.println("File length: " + file.length() + " bytes");
} else {
System.out.println("File exists: No");
}
scanner.close();
}
}

OUTPUT
E:\>javac FileInformation.java
E:\>java FileInformation
Enter the file name (with path if not in the same directory): e:\sample.txt
File exists: Yes
File is readable: true
File is writable: true
File type: File
File length: 60 bytes

Result
Thus, the java program to implement file handling and to read a file name, display the file
exists, the file is readable or writable, the type and the length of the file in bytes has been
created and executed successfully.

Ex:12 FRAMES AND CONTROLS

AIM
To write a java program to accept a text and change its size and font including bold
italic options using frames and controls.
ALGORITHM
Step 1: Start the program.
Step 2: Create a JFrame object and set the title to "Text Styler"and Set the size of the frame.
Step 3: Set the layout of the frame to BorderLayout.
Step 4: Initialize a JTextArea for text input and Enable line wrapping and set word wrapping
to true.
Step 5: Place the text area inside a JScrollPane to allow scrolling.
Step 6: Create a JComboBox to allow users to select a font size from the options.
Step 7: Create CheckBoxes for Bold and Italic.
Step 8: Create a JPanel to hold the controls and Add a JLabel, fontSizeComboBox,
boldCheckBox, and italicCheckBox to the control panel.
Step 9: Create a JButton labeled "Update Text Style". Add an ActionListener to the button.
Step 10: Add the JScrollPane (which contains the textArea) to the center of the frame.
Step 11: Add the controlPanel to the south position of the frame.
Step 12: Stop the program.

Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextStyler extends JFrame {
private JTextArea textArea;
private JComboBox<String> fontSizeComboBox;
private JCheckBox boldCheckBox;
private JCheckBox italicCheckBox;

public TextStyler() {
// Set up the frame
setTitle("Text Styler");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Create components
textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textArea);

// Font size options


String[] fontSizes = {"12", "14", "16", "18", "20", "24"};
fontSizeComboBox = new JComboBox<>(fontSizes);
fontSizeComboBox.setSelectedItem("16"); // Default size

// Checkboxes for bold and italic


boldCheckBox = new JCheckBox("Bold");
italicCheckBox = new JCheckBox("Italic");

// Panel for controls


JPanel controlPanel = new JPanel();
controlPanel.add(new JLabel("Font Size:"));
controlPanel.add(fontSizeComboBox);
controlPanel.add(boldCheckBox);
controlPanel.add(italicCheckBox);

// Update button
JButton updateButton = new JButton("Update Text Style");
updateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateTextStyle();
}
});

controlPanel.add(updateButton);

// Add components to the frame


add(scrollPane, BorderLayout.CENTER);
add(controlPanel, BorderLayout.SOUTH);
}

private void updateTextStyle() {


int fontSize = Integer.parseInt((String) fontSizeComboBox.getSelectedItem());
int fontStyle = Font.PLAIN;

if (boldCheckBox.isSelected()) {
fontStyle |= Font.BOLD;
}
if (italicCheckBox.isSelected()) {
fontStyle |= Font.ITALIC;
}

textArea.setFont(new Font("Serif", fontStyle, fontSize));


}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
TextStyler textStyler = new TextStyler();
textStyler.setVisible(true);
});
}
}
OUTPUT

Result
Thus, the java program to accept a text and change its size and font including bold italic
options using frames and controls has been created and executed successfully.
Ex:13 MOUSE EVENT HANDLING

AIM
To write a java program to handle all mouse events and show the event name at the
center of the window when a mouse event is fired.
ALGORITHM
Step 1: Start the program.
Step 2: Initialize the JFrame and Create a new instance of MouseEventDemo..
Step 3: Specify the dimensions (width: 400px, height: 300px) for the window.
Step 4: Use a BorderLayout for the frame to organize components.
Step 5: Create and Instantiate the JLabel to display mouse event messages.
Step 6: Add the label to the center of the frame.
Step 7: Implement a mouse listener by creating an anonymous subclass of MouseAdapter.
Step 8: Add this mouse listener to the MouseEventDemo frame using
addMouseListener() and Updating the Event Label.
Step 9: Stop the program.

Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MouseEventDemo extends JFrame {


private JLabel eventLabel;

public MouseEventDemo() {
// Set up the frame
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Create label to display event messages


eventLabel = new JLabel("Mouse Events", SwingConstants.CENTER);
eventLabel.setFont(new Font("Arial", Font.BOLD, 24));
add(eventLabel, BorderLayout.CENTER);
// Adding MouseListener using MouseAdapter (for handling all mouse events)
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
updateEventLabel("Mouse Clicked");
}

@Override
public void mousePressed(MouseEvent e) {
updateEventLabel("Mouse Pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
updateEventLabel("Mouse Released");
}

@Override
public void mouseEntered(MouseEvent e) {
updateEventLabel("Mouse Entered");
}

@Override
public void mouseExited(MouseEvent e) {
updateEventLabel("Mouse Exited");
}

@Override
public void mouseDragged(MouseEvent e) {
updateEventLabel("Mouse Dragged");
}

@Override
public void mouseMoved(MouseEvent e) {
updateEventLabel("Mouse Moved");
}
});
}

private void updateEventLabel(String eventName) {


eventLabel.setText(eventName);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
MouseEventDemo demo = new MouseEventDemo();
demo.setVisible(true);
});
}
}

OUTPUT
Result
Thus, the java program to handle all mouse events and show the event name at the center
of the window when a mouse event is fired has been created and executed successfully.

Ex:14 SIMPLE CALCULATOR


AIM
To write a java program to implement a simple calculator and use a grid layout to
arrange buttons for the digits and operations, add a text field to display the result.
ALGORITHM
Step 1: Start the program.
Step 2: Initialize the JFrame and create a new instance of SimpleCalculator.
Step 3: Use a GridLayout with 5 rows and 4 columns for the layout of buttons.
Step 4: Instantiate a JTextField called display. Set the display field to be non-editable.
Step 5: Define an array of strings containing the button labels for numbers (0-9), operations
(+, -, *, /, %, =), and a clear button (C).
Step 6: Assign an ActionListener to each button, which is the current instance of
SimpleCalculator. Add the button to the frame.
Step 7: Implement the actionPerformed(ActionEvent e) method from the ActionListener
interface.
Step 8: Retrieve the action command of the button that was pressed (stored in the command
variable).
Step 9: Handle divide-by-zero error by displaying an error message.
Step 10: Stop the program.

Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleCalculator extends JFrame implements ActionListener {


private JTextField display;
private String operator;
private double num1;

public SimpleCalculator() {
// Frame properties
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 4));

// Create display field


display = new JTextField();
display.setEditable(false);
display.setHorizontalAlignment(SwingConstants.RIGHT);
add(display);

// Create buttons for digits and operations


String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+",
"%"
};

// Add buttons to the frame


for (String text : buttons) {
JButton button = new JButton(text);
button.addActionListener(this);
add(button);
}
}

@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
case "C":
// Clear display
display.setText("");
num1 = 0;
operator = "";
break;
case "=":
// Calculate result
try {
double num2 = Double.parseDouble(display.getText());
double result;
if (operator == null) {
break;
}

switch (operator) {
case "+":
result = num1 + num2;
display.setText(String.valueOf(result));
break;
case "-":
result = num1 - num2;
display.setText(String.valueOf(result));
break;
case "*":
result = num1 * num2;
display.setText(String.valueOf(result));
break;
case "/":
if (num2 == 0) {
display.setText("Error: Divide by zero");
} else {
result = num1 / num2;
display.setText(String.valueOf(result));
}
break;
case "%":
result = num1 % num2;
display.setText(String.valueOf(result));
break;
}
} catch (NumberFormatException ex) {
display.setText("Error: Invalid Input");
}
break;
default:
// Handle digits and operator buttons
if ("+-*/%".contains(command)) {
operator = command;
num1 = Double.parseDouble(display.getText());
display.setText("");
} else {
// Handle number buttons
display.setText(display.getText() + command);
}
break;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}

OUTPUT

Result
Thus, the java program to implement a simple calculator and use a grid layout to arrange
buttons for the digits and operations, add a text field to display the result has been created
and executed successfully.

Ex:15 TRAFFIC LIGHT

AIM
To write a java program to simulate a traffic light and allow the user to select one of
three lights: red(stop), yellow(ready), or green(go) with radio buttons to implement the
color.
ALGORITHM
Step 1: Start the program.
Step 2: Initialize the JFrame and create a new instance of TrafficLightSimulator.
Step 3: Use a FlowLayout to arrange components vertically.
Step 4: Instantiate a JLabel called messageLabel to display messages related to the traffic
light state.
Step 5: Instantiate three JRadioButton objects: redButton, yellowButton, and greenButton,
each labeled accordingly.
Step 6: Add Action Listeners for each radio button to respond for the user actions
Step 7: Implement the actionPerformed(ActionEvent e) method from the ActionListener
interface..
Step 8: Stop the program.

Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TrafficLightSimulator extends JFrame implements ActionListener {


private JLabel messageLabel;
private JRadioButton redButton, yellowButton, greenButton;

public TrafficLightSimulator() {
// Set up the frame
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Create message label
messageLabel = new JLabel("");
messageLabel.setFont(new Font("Arial", Font.BOLD, 24));
messageLabel.setPreferredSize(new Dimension(250, 50));
add(messageLabel);

// Create radio buttons


redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");

// Grouping radio buttons


ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(yellowButton);
group.add(greenButton);

// Add action listeners


redButton.addActionListener(this);
yellowButton.addActionListener(this);
greenButton.addActionListener(this);

// Add buttons to the frame


add(redButton);
add(yellowButton);
add(greenButton);
}

@Override
public void actionPerformed(ActionEvent e) {
// Clear previous message
messageLabel.setText("");

// Check which button is selected and set appropriate message


if (redButton.isSelected()) {
messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED);
} else if (yellowButton.isSelected()) {
messageLabel.setText("Ready");
messageLabel.setForeground(Color.YELLOW);
} else if (greenButton.isSelected()) {
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN);
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
TrafficLightSimulator simulator = new TrafficLightSimulator();
simulator.setVisible(true);
});
}
}

OUTPUT
Result
Thus, the java program to simulate a traffic light and allow the user to select one of three
lights: red(stop), yellow(ready), or green(go) with radio buttons to implement the color has
een created and executed successfully.

You might also like