0% found this document useful (0 votes)
2 views34 pages

Java Lab Manual

The document contains a series of Java programming exercises, each demonstrating different concepts such as prime number generation, matrix multiplication, text analysis, random number generation, string manipulation, multithreading, and exception handling. Each program includes code snippets and explanations for functionality, guiding users through practical implementations. The exercises range from basic to advanced topics, catering to various levels of Java programming skills.

Uploaded by

kavin.r.2024.mct
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)
2 views34 pages

Java Lab Manual

The document contains a series of Java programming exercises, each demonstrating different concepts such as prime number generation, matrix multiplication, text analysis, random number generation, string manipulation, multithreading, and exception handling. Each program includes code snippets and explanations for functionality, guiding users through practical implementations. The exercises range from basic to advanced topics, catering to various levels of Java programming skills.

Uploaded by

kavin.r.2024.mct
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

PROGRAMMING IN JAVA PRACTICALS – LAB MANUALS

Program 1:
[Link] a Java program that prompts the user for an integer and then prints out all the
prime numbers up to that Integer?
import [Link];
public class prog1prime
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
// Prompt the user for an integer
[Link]("Enter a positive integer: ");
int n = [Link]();
if (n < 2)
{
[Link]("There are no prime numbers less than 2.");
} else
{
[Link]("Prime numbers up to " + n + ":");
for (int i = 2; i <= n; i++)
{
if (isPrime(i))
{
[Link](i + " ");
}
}
}
}

// Method to check if a number is prime


public static boolean isPrime(int num)
{
if (num <= 1)
{
return false;
}
for (int i = 2; i <= [Link](num); i++)
{
if (num % i == 0)
{
return false;
}
}
return true;
}
}
PROGRAM 2
2. Write a Java program to multiply two given matrices.
import [Link];
public class labprog2 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input dimensions for the first matrix
[Link]("Enter the number of rows and columns for the first matrix:");
int rows1 = [Link]();
int cols1 = [Link]();
// Input dimensions for the second matrix
[Link]("Enter the number of rows and columns for the second matrix:");
int rows2 = [Link]();
int cols2 = [Link]();
// Check if matrices can be multiplied
if (cols1 != rows2) {
[Link]("Matrix multiplication is not possible. Number of columns in the
first matrix must equal the number of rows in the second matrix.");
return;
}
// Input elements for the first matrix
[Link]("Enter the elements of the first matrix:");
int[][] matrix1 = new int[rows1][cols1];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = [Link]();
}
}
// Input elements for the second matrix
[Link]("Enter the elements of the second matrix:");
int[][] matrix2 = new int[rows2][cols2];
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = [Link]();
}
}
// Initialize the result matrix
int[][] result = new int[rows1][cols2];

// Perform matrix multiplication


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];
}
}
}
// Display the result
[Link]("The product of the matrices is:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
[Link](result[i][j] + " ");
}
[Link]();
}
[Link]();
}
}
PROGRAM 3
3. Write a Java program that displays the number of characters, lines and words in a text?
import [Link];
class counttext
{
public static void main(String[] args)
{
Scanner s = new Scanner([Link]);
[Link]("ENTER TEXT AND TYPE $ ON A NEW LINE TO FINISH: ");
int totallines= 0;
int totalwords= 0;
int totalcharacters= 0;
while (true)
{
String text = [Link]();
char[] chararray = [Link]();
if ([Link]("$"))
{
break;
}
if([Link](' '))
{
totalwords--;
}
totallines=totallines+1;
for (char c : chararray)
{
if (c != ' ')
{
totalcharacters++;
}
}
String[] words =[Link]().split("\\s+");
totalwords = totalwords + [Link];
}
[Link]();
[Link]("PROGRAM TO COUNT LINES, WORDS AND
CHARACTERS");

[Link]("*****************************************************");
[Link]("NUMBER OF LINES: " + totallines);
[Link]("NUMBER OF WORDS: " + totalwords);
[Link]("NUMBER OF CHARACTERS: " + totalcharacters);
}
}
PROGRAM 4
/****GENERATE RANDOM NUMBERS BETWEEN TWO GIVEN LIMITS USING
RANDOM CLASS
AND PRINT MESSAGES ACCORDING TO THE RANGE OF THE VALUE
GENERATED *********/
import [Link];
import [Link];
class randomnumbers
{
public static void main(String[] args)
{
Scanner s = new Scanner([Link]);
Random r = new Random();
[Link]("RANDOM NUMBER");
[Link]("****************");
[Link]("ENTER LOWER LIMIT: ");
int lowerlimit = [Link]();
[Link]("ENTER UPPER LIMIT: ");
int upperlimit = [Link]();
if (lowerlimit >= upperlimit)
{
[Link](" UPPER LIMIT SHOULD BE HIGHER THAN
LOWER LIMIT");
return;
}
int number = [Link](upperlimit - lowerlimit + 1)+lowerlimit;
[Link]("GENERATED RANDOM NUMBER IS: " + number);
int range = (upperlimit - lowerlimit + 1) / 3;
if (number < lowerlimit + range)
{
[Link]("THE NUMBER IS IN THE LOWER RANGE");
}
else if (number < lowerlimit + 2 * range)
{
[Link]("THE NUMBER IS IN THE MIDDLE RANGE");
}
else
{
[Link]("THE NUMBER IS IN THE UPPER RANGE");
}
[Link]();
}
}
PROGRAM 5
PROGRAM 5 : STRING MANIPULATION
import [Link];

public class Prog5StringManipulation {

// Method to calculate string length using character array


public static int getStringLength(char[] charArray) {
int length = 0;
for (char c : charArray) {
length++;
}
return length;
}

// Method to find the character at a given position


public static char getCharacterAtPosition(char[] charArray, int position) {
if (position < 0 || position >= [Link]) {
throw new IllegalArgumentException("Position out of bounds");
}
return charArray[position];
}

// Method to concatenate two character arrays


public static char[] concatenateStrings(char[] firstArray, char[] secondArray) {
int totalLength = [Link] + [Link];
char[] result = new char[totalLength];
int index = 0;

for (char c : firstArray) {


result[index++] = c;
}
for (char c : secondArray) {
result[index++] = c;
}

return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Input the first string


[Link]("Enter the first string: ");
String firstString = [Link]();
char[] firstArray = [Link]();

// Input the second string


[Link]("Enter the second string: ");
String secondString = [Link]();
char[] secondArray = [Link]();

// Perform string operations


// 1. String Length
[Link]("Length of the first string: " + getStringLength(firstArray));
[Link]("Length of the second string: " + getStringLength(secondArray));

// 2. Character at a Particular Position


[Link]("Enter a position to find the character in the first string : ");
int position = [Link]();
try {
[Link]("Character at position " + position + " in the first string: " +
getCharacterAtPosition(firstArray, position-1));
} catch (IllegalArgumentException e) {
[Link]([Link]());
}

// 3. Concatenate Two Strings


char[] concatenatedArray = concatenateStrings(firstArray, secondArray);
[Link]("Concatenated string: " + new String(concatenatedArray));

[Link]();
}
}
PROGRAM 6
// Program 6
import [Link];

public class Prog6StringOperations {


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

// Input for String Concatenation


[Link]("Enter the first string: ");
String str1 = [Link]();
[Link]("Enter the second string: ");
String str2 = [Link]();

// Perform String Concatenation


String concatenatedString = [Link](str2);
[Link]("Concatenated String: " + concatenatedString);

// Input for Search a Substring


[Link]("\nEnter a string to search in: ");
String mainString = [Link]();
[Link]("Enter the substring to search for: ");
String substring = [Link]();

// Perform Substring Search


if ([Link](substring)) {
[Link]("Substring found at index: " + [Link](substring));
} else {
[Link]("Substring not found.");
}
// Input for Extracting Substring
[Link]("\nEnter a string to extract from: ");
String extractString = [Link]();
[Link]("Enter the starting index: ");
int startIndex = [Link]();
[Link]("Enter the ending index: ");
int endIndex = [Link]();

// Perform Substring Extraction


try {
String extractedSubstring = [Link](startIndex, endIndex);
[Link]("Extracted Substring: " + extractedSubstring);
} catch (IndexOutOfBoundsException e) {
[Link]("Invalid indices provided.");
}

[Link]();
}
}
PROGRAM 7
/*IMPLEMENTATION OF STRING BUFFER OPERATIONS*/

import [Link];

public class StringBufferOperations


{
public static void main(String[] args)
{
Scanner s = new Scanner([Link]);
[Link](“********************”);
[Link](“StringBufferOperations”);
[Link]("ENTER A STRING: ");
String inputString = [Link]();
StringBuffer buffer = new StringBuffer(inputString);
int length = [Link]();
[Link]("\n LENGTH OF THE STRING: " + length);
StringBuffer reversedBuffer = new StringBuffer(buffer).reverse();
[Link]("REVERSED STRING: " + reversedBuffer);
[Link]("ENTER THE START AND END INDICES OF THE
SUBSTRING TO DELETE :");
int startIndex = [Link]();
int endIndex = [Link]();
[Link](startIndex+1, endIndex+1);
[Link]("STRING AFTER DELETION: " + buffer);
[Link]();
}
}
PROGRAM 8
/***Write a java program that implements application that has three threads generates
random integer every value is even, Second the number of prints if of the a first multi-thread
threads 1 second and if the Thread computer the value is odd thread will print, the value of
cube of Square the 3rd number***/
import [Link];
public class MultiThreadApp
{
static class RandomNumberGenerator extends Thread
{
private final SharedData sharedData;
private final Random random = new Random();
public RandomNumberGenerator(SharedData sharedData)
{
[Link] = sharedData;
}
public void run()
{
while (true)
{
try
{
[Link](1000);
int num = [Link](100);
[Link]("GENERATED: " + num);
[Link](num);
}
catch (InterruptedException e)
{
[Link]();
}
}
}
}

static class SquareThread extends Thread


{
private final SharedData sharedData;
public SquareThread(SharedData sharedData)
{
[Link] = sharedData;
}
public void run()
{
while (true)
{
try
{
[Link](500);
int num = [Link]();
if (num % 2 == 0)
{
[Link]("SQUARE: " + (num * num));
}
}
catch (InterruptedException e)
{
[Link]();
}
}
}
}
static class CubeThread extends Thread
{
private final SharedData sharedData;
public CubeThread(SharedData sharedData)
{
[Link] = sharedData;
}
public void run()
{
while (true)
{
try
{
[Link](500);
int num = [Link]();
if (num % 2 != 0)
{
[Link]("CUBE: " + (num * num * num));
}
}
catch (InterruptedException e)
{
[Link]();
}
}
}
}

static class SharedData


{
private int number;
public synchronized void setNumber(int number)
{
[Link] = number;
}

public synchronized int getNumber()


{
return number;
}
}
public static void main(String[] args)
{
[Link]("MULTI THREAD");
[Link]("****************");
SharedData sharedData = new SharedData();
new RandomNumberGenerator(sharedData).start();
new SquareThread(sharedData).start();
new CubeThread(sharedData).start();
}
}
PROGRAM 9
/***********Write a threading program which uses the same method asynchronously to
print the numbers 1 to 10 using Thread1 and to print 90 to 100 using
Thread2.************/

class thread1 extends Thread


{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
[Link]("THREAD 1: "+i);
[Link](500);
}
}
catch(Exception e)
{
[Link]("EXCEPTION OCCURED IN THREAD1
!");
}
finally
{
[Link]("THREAD1 ENDED");
}
}
}
class thread2 extends Thread
{
public void run()
{
try {
for(int i=90;i<=100;i++)
{
[Link]("THREAD 2: "+i);
[Link](500);
}
}
catch(Exception e) {
[Link]("EXCEPTION OCCURED IN
THREAD2 !");
}
finally {
[Link]("THREAD2 ENDED");
}
}
}
class threadimp
{
public static void main(String arg[])
{
[Link]("IMPLEMENT THREAD BASED PROGRAM");
[Link]("*************************************”);
thread1 t1= new thread1();
thread2 t2= new thread2();
[Link]();
[Link]();
}
}
PROGRAM 10
import [Link];
public class exceptiondemo
{
private static void divideByZero()
{
try
{
int numerator = 10;
int denominator = 0;
int result = numerator / denominator;
[Link]("Result: " + result);
}
catch (ArithmeticException e)
{
[Link]("EXCEPTION DEMO")
[Link]("***************")
[Link]("Error: Cannot divide by zero.");
}
}
private static void parseIntFromString()
{
Scanner scanner = new Scanner([Link]);
try
{
[Link]("Enter a number: ");
String input = [Link]();
int number = [Link](input);
[Link]("You entered: " + number);
}
catch (NumberFormatException e)
{
[Link]("Error: Invalid number format.");
}
}
private static void accessArrayOutOfBound()
{
int[] array = {1, 2, 3};
try
{
[Link]("Element at index 3: " + array[3]);
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("Error: Array index out of bounds.");
}
}
private static void createNegativeArray()
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the array: ");
int size = [Link]();
try
{
if (size < 0)
{
throw new IllegalArgumentException("Array size cannot be
negative.");
}
int[] array = new int[size];
[Link]("Array of size " + size + " created
successfully.");
}
catch (IllegalArgumentException e)
{
[Link]("Error: " + [Link]());
}
}
public static void main(String[] args)
{
divideByZero();
parseIntFromString();
accessArrayOutOfBound();
createNegativeArray();
}
}
PROGRAM 11
import [Link];
import [Link];

public class Fileinfo {


public static void main(String[] args) {
// Create a scanner to read user input
Scanner scanner = new Scanner([Link]);

// Ask the user for the file name


[Link]("Enter the file name: ");
String fileName = [Link]();

// Create a File object with the provided file name


File file = new File(fileName);

// Check if the file exists


if ([Link]()) {
[Link]("File exists: Yes");

// Check if the file is readable


if ([Link]()) {
[Link]("File is readable: Yes");
} else {
[Link]("File is readable: No");
}

// Check if the file is writable


if ([Link]()) {
[Link]("File is writable: Yes");
} else {
[Link]("File is writable: No");
}

// Check the type of the file (whether it's a directory or a regular file)
if ([Link]()) {
[Link]("The file is a directory.");
} else if ([Link]()) {
[Link]("The file is a regular file.");
}

// Get the length of the file in bytes


[Link]("File size: " + [Link]() + " bytes");
} else {
[Link]("File does not exist.");
}

// Close the scanner


[Link]();
}
}
PROGRAM 12
// Program 12
import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class TextFontChanger {


public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("Text Font Changer");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](500, 400);
[Link](new BorderLayout());

// Text area
JTextArea textArea = new JTextArea("Enter your text here...");
[Link](new Font("Serif", [Link], 16));
JScrollPane scrollPane = new JScrollPane(textArea);
[Link](scrollPane, [Link]);

// Control panel
JPanel controlPanel = new JPanel();
[Link](new FlowLayout());

// Font size selector


JLabel fontSizeLabel = new JLabel("Font Size:");
SpinnerModel sizeModel = new SpinnerNumberModel(16, 8, 72, 1);
JSpinner fontSizeSpinner = new JSpinner(sizeModel);
[Link](fontSizeLabel);
[Link](fontSizeSpinner);

// Font style selector


JLabel fontStyleLabel = new JLabel("Font:");
String[] fonts =
[Link]().getAvailableFontFamilyNames();
JComboBox<String> fontComboBox = new JComboBox<>(fonts);
[Link](fontStyleLabel);
[Link](fontComboBox);

// Bold and Italic checkboxes


JCheckBox boldCheckBox = new JCheckBox("Bold");
JCheckBox italicCheckBox = new JCheckBox("Italic");
[Link](boldCheckBox);
[Link](italicCheckBox);

// Apply button
JButton applyButton = new JButton("Apply");
[Link](applyButton);

[Link](controlPanel, [Link]);

// Apply button action listener


[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Get selected font size
int fontSize = (int) [Link]();

// Get selected font family


String fontFamily = (String) [Link]();
// Determine font style
int fontStyle = [Link];
if ([Link]() && [Link]()) {
fontStyle = [Link] | [Link];
} else if ([Link]()) {
fontStyle = [Link];
} else if ([Link]()) {
fontStyle = [Link];
}

// Apply font to the text area


[Link](new Font(fontFamily, fontStyle, fontSize));
}
});

// Show the frame


[Link](true);
}
}
PROGRAM 13
import [Link].*;
import [Link].*;
import [Link].*;

public class MouseEventDemo extends JFrame {


private String eventName = ""; // To hold the name of the current mouse event

public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Custom panel to handle painting


JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
[Link](g);
[Link](new Font("Arial", [Link], 20));
FontMetrics fm = [Link]();
int x = (getWidth() - [Link](eventName)) / 2;
int y = (getHeight() / 2);
[Link](eventName, x, y);
}
};

add(panel);

// Add mouse listener using adapter classes


MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
eventName = "Mouse Clicked";
[Link]();
}

@Override
public void mousePressed(MouseEvent e) {
eventName = "Mouse Pressed";
[Link]();
}

@Override
public void mouseReleased(MouseEvent e) {
eventName = "Mouse Released";
[Link]();
}

@Override
public void mouseEntered(MouseEvent e) {
eventName = "Mouse Entered";
[Link]();
}

@Override
public void mouseExited(MouseEvent e) {
eventName = "Mouse Exited";
[Link]();
}
@Override
public void mouseDragged(MouseEvent e) {
eventName = "Mouse Dragged";
[Link]();
}

@Override
public void mouseMoved(MouseEvent e) {
eventName = "Mouse Moved";
[Link]();
}
};

// Attach listeners to the panel


[Link](mouseAdapter);
[Link](mouseAdapter);

setVisible(true);
}

public static void main(String[] args) {


[Link](MouseEventDemo::new);
}
}
PROGRAM 14
//Java program to create a Simple Calculator

import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class SimpleCalculator1 extends JFrame implements ActionListener {


private JTextField textField;
private String operator;
private double num1, num2, result;

public SimpleCalculator1() {
setTitle("Calculator");
setSize(350, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10)); // Add spacing between components

// Create text field with bigger font and more space


textField = new JTextField();
[Link](false);
[Link](new Font("Arial", [Link], 32)); // Make text larger
[Link]([Link]); // Align text to the right
[Link](new Dimension(350, 80)); // Increase height
[Link]([Link]); // Ensure a clear background
[Link]([Link](10, 10, 10, 10)); // Add padding
add(textField, [Link]);

// Create a panel for buttons with GridLayout (better alignment)


JPanel panel = new JPanel();
[Link](new GridLayout(4, 4, 10, 10)); // Rows x Columns with gaps

// Buttons for the calculator


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

for (String text : buttons) {


JButton button = new JButton(text);
[Link](new Font("Arial", [Link], 20)); // Bigger button font
[Link](false); // Remove focus border
[Link](this);
[Link](button);
}

add(panel, [Link]);

// Set background color for a modern look


[Link](Color.LIGHT_GRAY);
}

@Override
public void actionPerformed(ActionEvent e) {
String command = [Link]();

if ([Link](0) >= '0' && [Link](0) <= '9') {


[Link]([Link]() + command);
} else if ([Link]("C")) {
[Link]("");
num1 = num2 = result = 0;
} else if ([Link]("=")) {
try {
num2 = [Link]([Link]());
switch (operator) {
case "+": result = num1 + num2; break;
case "-": result = num1 - num2; break;
case "*": result = num1 * num2; break;
case "%":
if (num2 == 0) throw new ArithmeticException("Cannot divide by zero");
result = num1 % num2;
break;
}
[Link]([Link](result));
} catch (Exception ex) {
[Link]("Error");
}
} else {
num1 = [Link]([Link]());
operator = command;
[Link]("");
}
}
public static void main(String[] args) {
[Link](() -> {
new SimpleCalculator1().setVisible(true);
});
}
}
PROGRAM 15
import [Link].*;
import [Link].*;

public class trafficlightmini


{
public static void main(String[] args)
{
JFrame frame = new JFrame("Traffic Light");
[Link](250, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new FlowLayout());

JLabel message = new JLabel();


JRadioButton red = new JRadioButton("Red"), yellow = new JRadioButton("Yellow"),
green = new JRadioButton("Green");

ButtonGroup group = new ButtonGroup();


[Link](red); [Link](yellow); [Link](green);

[Link](message); [Link](red); [Link](yellow); [Link](green);

[Link](e -> { [Link]("STOP");


[Link]([Link]); });
[Link](e -> { [Link]("READY");
[Link]([Link]); });
[Link](e -> { [Link]("GO");
[Link]([Link]); });

[Link](true);
}
}

You might also like