[Go to site: main page, start]

0% found this document useful (0 votes)
10 views50 pages

Java Multithreading and File Reading Examples

This document outlines multiple Java programming examples demonstrating various concepts such as multithreading, ArrayLists, file reading, applet creation, and web page information retrieval. Each section includes an aim, algorithm, program code, and output results, showcasing successful execution of the programs. The examples serve as practical applications for learning Java programming techniques.
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)
10 views50 pages

Java Multithreading and File Reading Examples

This document outlines multiple Java programming examples demonstrating various concepts such as multithreading, ArrayLists, file reading, applet creation, and web page information retrieval. Each section includes an aim, algorithm, program code, and output results, showcasing successful execution of the programs. The examples serve as practical applications for learning Java programming techniques.
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

1.

Multithreading Example in Java

Aim:

The aim of this program is to illustrate the concept of multithreading in Java. We


create two classes, Parent and Child, both extending the Thread class, and
demonstrate the concurrent execution of these threads using various thread
class methods.

Algorithm:

STEP-1:

Create a class Parent that extends the Thread class.

STEP-2:

Override the run() method in the Parent class to define the behavior of the parent
thread.

STEP-3:

Inside the run() method of the Parent class:

a. Print a message indicating that the parent thread is running.

b. Use a for loop to iterate from 1 to 5.

c. Within the loop, print messages with the current iteration and sleep the thread
for 1 second using [Link](1000) to simulate some work.

d. Handle any exceptions that may occur during thread sleep.

e. After the loop, print a message indicating that the parent thread is finished.

STEP-4:

Create a class Child that extends the Thread class.

STEP-5:

Override the run() method in the Child class to define the behavior of the child
thread.

STEP-6:
Inside the run() method of the Child class:

a. Print a message indicating that the child thread is running.

b. Use a for loop to iterate from 1 to 5.

c. Within the loop, print messages with the current iteration and sleep the thread
for 0.5 seconds using [Link](500) to simulate some work.

d. Handle any exceptions that may occur during thread sleep.

e. After the loop, print a message indicating that the child thread is finished.

STEP-7:

Create a MultithreadingExample class with the main method.

STEP-8:

In the main method:

a. Create instances of the Parent and Child classes.

b. Start both threads using the start() method.

c. Use the join() method to wait for both threads to finish executing.

d. Print a message indicating that both threads have finished.

This algorithm demonstrates the creation and concurrent execution of two


threads (parent and child) using Java's multithreading capabilities. The output of
the program will show interleaved messages from both threads, highlighting their
concurrent behavior.
PROGRAM:

class Parent extends Thread {

public void run() {

[Link]("Parent Thread is running.");

for (int i = 1; i <= 5; i++) {

[Link]("Parent Thread: " + i);

try {

[Link](1000); // Sleep for 1 second

} catch (InterruptedException e) {

[Link](e);

[Link]("Parent Thread is finished.");

class Child extends Thread {

public void run() {

[Link]("Child Thread is running.");

for (int i = 1; i <= 5; i++) {

[Link]("Child Thread: " + i);

try {

[Link](500); // Sleep for 0.5 seconds

} catch (InterruptedException e) {

[Link](e);
}

[Link]("Child Thread is finished.");

public class MultithreadingExample {

public static void main(String[] args) {

[Link]("Multithreading Example");

Parent parentThread = new Parent();

Child childThread = new Child();

[Link](); // Start the Parent thread

[Link](); // Start the Child thread

// Wait for both threads to finish

try {

[Link]();

[Link]();

} catch (InterruptedException e) {

[Link](e);

[Link]("Both threads have finished.");


}

}
OUTPUT:

Multithreading Example

Parent Thread is running.

Child Thread is running.

Parent Thread: 1

Child Thread: 1

Child Thread: 2

Parent Thread: 2

Child Thread: 3

Parent Thread: 3

Child Thread: 4

Parent Thread: 4

Child Thread: 5

Parent Thread: 5

Child Thread is finished.

Parent Thread is finished.

Both threads have finished.

RESULT:

Thus the java program was executed successfully.


2. Creating a List of Books and Using an Iterator

Aim:

The aim of this program is to demonstrate the use of an ArrayList in Java.


Specifically, we aim to create an ArrayList named "Books," add book titles to it,
and then use an Iterator to traverse and display the list of books.

Algorithm:

STEP-1:

Create an empty ArrayList named "Books" to store book titles.

STEP-2:

Add book titles to the "Books" ArrayList using the add() method. You can add as
many books as needed.

STEP-3:

Create an Iterator for the "Books" ArrayList using the iterator() method. This will
allow you to traverse the elements of the ArrayList.

STEP-4:

Initialize a loop to iterate through the ArrayList using the Iterator:

a. Check if there is another element in the ArrayList using [Link]().

b. If there is another element, retrieve it using [Link]() and store it in a


variable (e.g., bookTitle).

c. Print or process the bookTitle as needed.

STEP-5:

Continue the loop until there are no more elements in the ArrayList.

STEP-6:

Display the list of books, along with a suitable title.


PROGRAM:

import [Link];

import [Link];

import [Link];

public class BooksListExample {

public static void main(String[] args) {

// Create an ArrayList to store book titles

List<String> books = new ArrayList<>();

// Add book titles to the ArrayList

[Link]("The Great Gatsby");

[Link]("To Kill a Mockingbird");

[Link]("1984");

[Link]("Pride and Prejudice");

[Link]("The Catcher in the Rye");

// Create an Iterator for the ArrayList

Iterator<String> iterator = [Link]();

// Display the list of books using the Iterator

[Link]("List of Books:");

while ([Link]()) {

String bookTitle = [Link]();


[Link](bookTitle);

}
OUTPUT:

List of Books:

The Great Gatsby

To Kill a Mockingbird

1984

Pride and Prejudice

The Catcher in the Rye

RESULT:

Thus the program was executed successfully.


[Link] Content Reader using FileInputStream and InputStreamReader in Java

Aim:

The aim of this program is to demonstrate how to read the contents of a file using
the FileInputStream and InputStreamReader classes in Java. It opens a specified
file, reads its content character by character, and displays the content to the
console.

Algorithm:

STEP-1:

Start the program.

STEP-2:

Declare a String variable fileName to store the path of the file to be read.

STEP-3:

Open a try-catch block to handle potential IOException during file operations.

STEP-4:

Inside the try block:

a. Create a FileInputStream object named fileInputStream and initialize it with the


specified fileName.

b. Create an InputStreamReader object named inputStreamReader and initialize


it with fileInputStream. This allows us to read the file's content while handling
character encoding.

c. Declare an integer variable data to store the read character as an integer.

d. Print a message indicating that we are displaying the contents of the file.

e. Enter a loop to read the file character by character:

Read a character from inputStreamReader using the read() method. If the end of
the file is reached (i.e., read() returns -1), exit the loop.

Convert the integer data to a character and print it to the console.

f. Close the inputStreamReader and fileInputStream to release system


resources.
STEP-5:

Catch any IOException that may occur during file operations and print an error
message.

STEP-6:

End
PROGRAM:

import [Link].*;

public class InputStreamReaderExample {

public static void main(String[] args) {

String fileName = "[Link]"; // Replace with the actual file path

try {

FileInputStream fileInputStream = new FileInputStream(fileName);

InputStreamReader inputStreamReader = new


InputStreamReader(fileInputStream);

int data;

[Link]("Contents of the file '" + fileName + "':");

while ((data = [Link]()) != -1) {

[Link]((char) data);

[Link]();

[Link]();

} catch (IOException e) {

[Link]("Error reading the file: " + [Link]());

}
}
OUTPUT:

RESULT:

Thus the program was executed successfully.


4. Interactive Traffic Signal Simulator Applet

Aim:

The aim of this program is to create a simple interactive Java applet that
simulates a traffic signal with three lights (red, yellow, and green). The program
allows users to cycle through the lights, simulating the typical behavior of a traffic
signal.

Algorithm:

STEP-1:

Initialization:

Initialize the applet with a specified size.

Define colors for the traffic lights (red, yellow, green, and off).

Initialize a variable to keep track of the active light (0 for red, 1 for yellow, 2 for
green).

STEP-2:

Painting:

In the paint method, call the drawTrafficSignal method to draw the traffic signal.

STEP-3:

Drawing the Traffic Signal:

In the drawTrafficSignal method:

Draw a black rectangle to represent the background of the traffic signal.

Draw three circles for the traffic lights:

The top circle represents the red light.

The middle circle represents the yellow light.

The bottom circle represents the green light.

Use the drawCircle helper method to draw each circle.

STEP-4:
Drawing Individual Circles:

In the drawCircle method:

Draw a black circle to represent the light's housing.

Fill the circle with the appropriate color based on whether the light is active or
not.

STEP-5:

Updating the Active Light:

Implement an updateLight method:

Increment the activeLight variable to cycle through the lights (red -> yellow ->
green -> red -> ...).

Repaint the applet to reflect the new active light.

STEP-6:

User Interaction:

Provide a mechanism for user interaction, such as a button or event handler.

When the user interacts with the program (e.g., clicking a button), call the
updateLight method to change the active light.

STEP-7:

Execution:

Compile the Java program.

Run it using a Java applet viewer or an IDE that supports applet execution.
PROGRAM:

import [Link];

import [Link];

import [Link];

public class TrafficSignalApplet extends Applet {

private Color redColor = [Link];

private Color yellowColor = [Link];

private Color greenColor = [Link];

private Color offColor = [Link];

private int activeLight = 0; // 0: red, 1: yellow, 2: green

public void init() {

setSize(200, 400);

public void paint(Graphics g) {

drawTrafficSignal(g);

public void drawTrafficSignal(Graphics g) {

// Background rectangle

[Link]([Link]);

[Link](50, 50, 100, 300);


// Red light

drawCircle(g, 100, 100, redColor, activeLight == 0);

// Yellow light

drawCircle(g, 100, 200, yellowColor, activeLight == 1);

// Green light

drawCircle(g, 100, 300, greenColor, activeLight == 2);

private void drawCircle(Graphics g, int x, int y, Color color, boolean active) {

[Link]([Link]);

[Link](x - 20, y - 20, 40, 40);

[Link](color);

if (active) {

[Link](x - 15, y - 15, 30, 30);

} else {

[Link](x - 10, y - 10, 20, 20);

public void updateLight() {

activeLight = (activeLight + 1) % 3;

repaint();

}
OUTPUT:

RESULT:

Thus the program was executed successfully.


5. Website IP Address Retrieval Application

Aim:

The aim of this application is to create a simple Java program that allows users
to input a website URL and retrieves and displays its corresponding IP address.
The program should handle invalid or unreachable websites gracefully.

Algorithm:

STEP-1:

Start

STEP-2:

Display the title: "Website IP Address Retrieval Application"

STEP-3:

Initialize a Scanner object for user input.

STEP-4:

Try the following:

a. Prompt the user to enter a website URL.

b. Read the user's input and store it in a variable website.

STEP-5:

Use a try-catch block to handle exceptions:

a. Inside the try block:

i. Use [Link](website) to retrieve the IP address of the entered


website and store it in ipAddress.

ii. Display a message with the retrieved IP address.

b. Catch the UnknownHostException:

i. Display an error message for an invalid or unreachable website.

STEP-6:
Close the Scanner object to release system resources.

STEP-7:

End
PROGRAM:

import [Link];

import [Link];

import [Link];

public class IPAddressRetrieval {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("IP Address Retrieval Application");

try {

// Input: Get the website URL from the user

[Link]("Enter the website URL: ");

String website = [Link]();

// Retrieve the IP address

InetAddress ipAddress = [Link](website);

// Output: Display the IP address

[Link]("The IP address for " + website + " is " +


[Link]());

} catch (UnknownHostException e) {

[Link]("Invalid or unreachable website!");

} finally {
[Link]();

}
OUTPUT:

IP Address Retrieval Application

Enter the website URL: [Link]

The IP address for [Link] is [Link]

RESULT:

Thus the program was executed successfully.


5. (B) Web Page Information Retrieval Application

Aim:

The aim of this application is to create a Java program that retrieves the content
of a given URL and provides various web page-related information such as the
title, HTTP status code, content type, and more. The program should handle both
valid and invalid URLs gracefully.

Procedure:

STEP-1:

Start

STEP-2:

Display the title: "Web Page Information Retrieval Application"

STEP-3:

Initialize a Scanner object for user input.

STEP-4:

Try the following:

a. Prompt the user to enter a website URL.

b. Read the user's input and store it in a variable url.

STEP-5:

Use a try-catch block to handle exceptions:

a. Inside the try block:

i. Create a URL object from the user-provided url.

ii. Open a connection to the URL using HttpURLConnection.

iii. Get the HTTP response code using the getResponseCode() method.

iv. Retrieve the content type from the getContentType() method.

v. Retrieve the page title by parsing the HTML content for <title> tags.

b. Catch the following exceptions:


i. MalformedURLException: Display an error message for an invalid URL format.

ii. IOException: Display an error message for connection or reading issues.

iii. NullPointerException: Display an error message if the title cannot be found.

STEP-6:

Display the following web page-related information:

URL

HTTP status code

Content type

Page title

STEP-7:

Close the Scanner object to release system resources.

STEP-8:

End
PROGRAM:

import [Link].*;

import [Link].*;

import [Link];

import [Link].*;

public class WebPageInformationRetrieval {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Web Page Information Retrieval Application");

try {

// Input: Get the website URL from the user

[Link]("Enter the website URL: ");

String url = [Link]();

// Create a URL object

URL webpageUrl = new URL(url);

// Open a connection to the URL

HttpURLConnection connection = (HttpURLConnection)


[Link]();

// Get HTTP response code


int responseCode = [Link]();

// Get content type

String contentType = [Link]();

// Read the HTML content

BufferedReader reader = new BufferedReader(new


InputStreamReader([Link]()));

String line;

StringBuilder content = new StringBuilder();

while ((line = [Link]()) != null) {

[Link](line);

// Use regex to extract the page title from HTML

Pattern titlePattern = [Link]("<title>(.*?)</title>",


Pattern.CASE_INSENSITIVE);

Matcher titleMatcher = [Link]([Link]());

String pageTitle = [Link]() ? [Link](1) : "Title not found";

// Output: Display web page information

[Link]("URL: " + url);

[Link]("HTTP Status Code: " + responseCode);

[Link]("Content Type: " + contentType);

[Link]("Page Title: " + pageTitle);


// Close the reader and connection

[Link]();

[Link]();

} catch (MalformedURLException e) {

[Link]("Invalid URL format. Please enter a valid URL.");

} catch (IOException e) {

[Link]("An error occurred while connecting to the website.");

} catch (NullPointerException e) {

[Link]("Page title not found in the HTML content.");

} finally {

[Link]();

}
OUTPUT:

Web Page Information Retrieval Application

Enter the website URL: [Link]

URL: [Link]

HTTP Status Code: 200

Content Type: text/html; charset=UTF-8

Page Title: Title not found

RESULT:

Thus the program was executed successfully.


6. Registration Form Application

Aim:

The aim of this Registration Form Application is to create a graphical user


interface (GUI) using Java's AWT (Abstract Window Toolkit) controls for user
registration. Users will be able to enter their name, email address, and password
into text fields. When they click the "Submit" button, their entered information will
be displayed in a dialog box.

Algorithm:

STEP-1:

Create a frame for the registration form with a specified title.

STEP-2:

Create labels, text fields, and a submit button for name, email, and password.

STEP-3:

Create a panel to organize these components using a grid layout.

STEP-4:

Add the components to the panel in an orderly fashion.

STEP-5:

Register an action listener for the submit button to capture user input.

STEP-6:

When the submit button is clicked, retrieve the text from the text fields.

STEP-7:

Display the entered information in a dialog box with a suitable title.

STEP-8:

Set up the frame's size and visibility properties.

STEP-9:

Register a window listener to handle the window close event.


STEP-10:

Run the program to create the registration form GUI.


PROGRAM:

import [Link].*;

import [Link].*;

public class RegistrationForm {

public static void main(String[] args) {

// Create a frame

Frame frame = new Frame("Registration Form");

// Create labels, text fields, and a button

Label nameLabel = new Label("Name:");

TextField nameField = new TextField(20);

Label emailLabel = new Label("Email:");

TextField emailField = new TextField(20);

Label passwordLabel = new Label("Password:");

TextField passwordField = new TextField(20);

[Link]('*');

Button submitButton = new Button("Submit");

// Create a panel to hold the components

Panel panel = new Panel();

[Link](new GridLayout(4, 2));


[Link](nameLabel);

[Link](nameField);

[Link](emailLabel);

[Link](emailField);

[Link](passwordLabel);

[Link](passwordField);

[Link](new Label()); // Empty space for alignment

[Link](submitButton);

// Add action listener to the submit button

[Link](new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

String name = [Link]();

String email = [Link]();

String password = [Link]();

// Display the result in a dialog box

String result = "Name: " + name + "\nEmail: " + email + "\nPassword: " +
password;

[Link](frame, result, "Registration Successful",


JOptionPane.INFORMATION_MESSAGE);

});

// Add the panel to the frame


[Link](panel);

// Set frame properties

[Link](300, 200);

[Link](true);

// Handle window close event

[Link](new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent) {

[Link](0);

});

}
OUTPUT:

Name: John Doe

Email: johndoe@[Link]

Password: ********

RESULT:

Thus the program was executed successfully.


7. Simple Calculator Application

Aim:

To create a simple calculator application that allows users to perform basic


arithmetic operations (addition, subtraction, multiplication, and division) on two
numbers and display the result.

Algorithm:

STEP-1:

Start

STEP-2:

Create a graphical user interface (GUI) with the following components:

Text field to input the first number (number1)

Text field to input the second number (number2)

Buttons for addition, subtraction, multiplication, and division

Text field to display the result (resultField)

STEP-3:

Initialize variables:

Initialize number1 to 0

Initialize number2 to 0

STEP-4:

Create event listeners for each button:

Addition Button:

When the addition button is clicked,

Read the values of number1 and number2 from the text fields.

Calculate the sum of number1 and number2.


Display the result in the resultField.

Subtraction Button:

When the subtraction button is clicked,

Read the values of number1 and number2 from the text fields.

Calculate the difference between number1 and number2.

Display the result in the resultField.

Multiplication Button:

When the multiplication button is clicked,

Read the values of number1 and number2 from the text fields.

Calculate the product of number1 and number2.

Display the result in the resultField.

Division Button:

When the division button is clicked,

Read the values of number1 and number2 from the text fields.

Check if number2 is not equal to 0 (to avoid division by zero).

Calculate the quotient of number1 divided by number2.

Display the result in the resultField if division is possible; otherwise, display an


error message.

STEP-5:

End
PROGRAM:

import [Link].*;

import [Link].*;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class JobPortalApp extends JFrame implements ActionListener {

private JTextField searchField;

private JTextArea resultArea;

private JButton searchButton;

public JobPortalApp() {

setTitle("Job Portal");

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();

[Link](new BorderLayout());

searchField = new JTextField();

searchButton = new JButton("Search");


resultArea = new JTextArea(10, 30);

[Link](false);

[Link](this);

[Link](searchField, [Link]);

[Link](searchButton, [Link]);

[Link](resultArea, [Link]);

add(panel);

public void actionPerformed(ActionEvent e) {

if ([Link]() == searchButton) {

String searchTerm = [Link]();

// Replace these values with your database credentials and query

String url = "jdbc:mysql://localhost:3306/jobportal";

String user = "your_username";

String password = "your_password";

try {

Connection connection = [Link](url, user, password);

Statement statement = [Link]();

String query = "SELECT * FROM jobs WHERE title LIKE '%" + searchTerm +
"%'";

ResultSet resultSet = [Link](query);


StringBuilder result = new StringBuilder();

while ([Link]()) {

[Link]("Title: ").append([Link]("title")).append("\n");

[Link]("Company:
").append([Link]("company")).append("\n");

[Link]("Salary:
").append([Link]("salary")).append("\n\n");

[Link]([Link]());

[Link]();

[Link]();

[Link]();

} catch (Exception ex) {

[Link]();

[Link]("Error: " + [Link]());

public static void main(String[] args) {

[Link](() -> {

JobPortalApp app = new JobPortalApp();

[Link](true);
});

}
OUTPUT:

---------------------------------------

| Simple Calculator X|

---------------------------------------

|[ ] [ ]|

|[7][8][9][+] [=]|

|[4][5][6][-] [C]|

|[1][2][3][*] [ ]|

|[0][.][/] [ ]|

---------------------------------------

| Result: [ ] [ ]|

---------------------------------------

RESULT:

Thus the program was executed successfully.


8. Average Calculator: Calculate the Average of a List of Numbers

Aim:

The aim of the "Average Calculator" program is to calculate and display the
average of a list of numbers provided by the user.

Algorithm:

STEP-1:

Start

STEP-2:

Initialize variables:

total to 0 (to keep track of the sum of numbers)

count to 0 (to keep track of the number of input values)

STEP-3:

Prompt the user to enter a number or 'q' to quit.

STEP-4:

Read the input.

STEP-5:

Check if the input is 'q':

If 'q', go to step 7 (display the average and end the program).

If not 'q', proceed to the next step.

STEP-6:

Convert the input to a numeric value (e.g., float or integer) and add it to the total.

STEP-7:

Increment the count by 1.

STEP-8:
Repeat from step 3 to continue entering numbers or 'q' to quit.

STEP-9:

Calculate the average by dividing total by count.

STEP-10:

Display the calculated average to the user.

STEP-11:

End
PROGRAM:

import [Link];

public class AverageCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Average Calculator");

double total = 0.0;

int count = 0;

while (true) {

[Link]("Enter a number (or 'q' to quit): ");

String input = [Link]();

if ([Link]("q")) {

break;

try {

double number = [Link](input);

total += number;

count++;

} catch (NumberFormatException e) {
[Link]("Invalid input. Please enter a valid number or 'q' to quit.");

if (count > 0) {

double average = total / count;

[Link]("The average of the numbers is: " + average);

} else {

[Link]("No numbers entered. Exiting.");

[Link]();

}
OUTPUT:

Average Calculator

Enter a number (or 'q' to quit): 10

Enter a number (or 'q' to quit): 20

Enter a number (or 'q' to quit): 30

Enter a number (or 'q' to quit): q

The average of the numbers is: 20.0

RESULT:

Thus the program was executed successfully.

You might also like