0% found this document useful (0 votes)
19 views39 pages

Java Programming Practical Exercises

Uploaded by

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

Java Programming Practical Exercises

Uploaded by

p00098188
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

DEPARTMENT OF B.

COM (e-commerce)
COMPUTER APPLICATION PRACTICAL VI – PROGRAMMING WITH JAVA
SUBJECT CODE: EC22CP6

1
PSGR KRISHNAMMAL COLLEGE FOR WOMEN
DEPARTMENT OF [Link] (e-commerce)
COMPUTER APPLICATION PRACTICAL VI – PROGRAMMING WITH JAVA

This is to certify that it is a bonafide record of work done by ___________________ with


register number ________________ of III [Link] (e-Commerce) during the year 2022-2025

STAFF-IN-CHARGE HEAD OF THE DEPARTMENT

Submitted for the practical examination held on ____________

INTERNAL EXAMINER EXTERNAL EXAMINER

2
CONTENTS

[Link] LIST OF EXPERIMENTS PAGE NO


1 Multi-Shape Area Finder 4

2 Calculate Depreciation in Java 6

3 Concatenate Strings Using for Loop 8

4 Find and Display Array of Strings in Java 10

5 Java String Manipulation 12

6 Find Sum and Product of Digits 14

7 Inheritance Implementation for Banking Operations 18

8 Exception Handling in Java 20

9 Interactive Applet for Shapes and Images in Java 22

10 Text Summarization Integration Using Java with AI 25

11 AI-Powered Stock Price Prediction Using Java Time series 27

12 Java Email Classifier with AI Detection Technology 33

3
[Link]: 1
MULTI-SHAPE AREA FINDER
AIM:
To write a java program to calculate the area of triangle, parallelogram, and rectangle.

ALGORITHM:
STEP 1: Initialize the program using start all program Notepad.
STEP 2: To set path using cd:/jdk 1.3/bin/
STEP 3: Create a class with the required variables
STEP 4: Select the shape Triangle, Parallelogram and Rectangle.
STEP 5: Select the appropriate dimensions based on the user’s choice.
STEP 6: Use the formula for the area of a triangle, Parallelogram and Rectangle as follows
i) (base × height) / 2, ii) base × height , iii) length × breadth.
STEP 7: Compile and run the program using the command prompt
STEP 8: Save the file using [Link] and display the results

SOURCE CODE:
import [Link];

public class AreaCalculator {


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

// Triangle Area
[Link]("Enter base of the triangle: ");
double base = [Link]();
[Link]("Enter height of the triangle: ");
double height = [Link]();
double triangleArea = 0.5 * base * height;

4
// Parallelogram Area
[Link]("Enter base of the parallelogram: ");
double pBase = [Link]();
[Link]("Enter height of the parallelogram: ");
double pHeight = [Link]();
double parallelogramArea = pBase * pHeight;

// Rectangle Area
[Link]("Enter length of the rectangle: ");
double length = [Link]();
[Link]("Enter width of the rectangle: ");
double width = [Link]();
double rectangleArea = length * width;

// Display results
[Link]("Area of triangle: " + triangleArea);
[Link]("Area of parallelogram: " + parallelogramArea);
[Link]("Area of rectangle: " + rectangleArea);
}
}
OUTPUT:
Enter base of the triangle: 5
Enter height of the triangle: 8
Enter base of the parallelogram: 6
Enter height of the parallelogram: 4
Enter length of the rectangle: 7
Enter width of the rectangle: 3
Area of triangle: 20.0
Area of parallelogram: 24.0
Area of rectangle: 21.0

RESULT:
Thus, the program has been executed and the output is verified.

5
[Link]
CALCULATE DEPRECIATION IN JAVA

AIM:
To create a Java program that calculates the depreciation of an asset using a chosen method, such
as the Straight-Line Method.

ALGORITHM:
STEP 1: Initialize the program using start all program Notepad.
STEP 2: To set path using cd:/jdk 1.3/bin/
STEP 3: Create a class with the required variables
STEP 4: Use a scanner to take user input for cost, salvage value, and useful life.
STEP 5: Use the Straight-Line Method formula
STEP 6: Depreciation per Year = (Cost - Salvage Value/Useful Life)
STEP 7: Compile and run the program using the command prompt.
STEP 8: Save the file using [Link] and display the results.

CODING:
import [Link];

public class DepreciationCalculator {


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

// Step 2: Define Variables


double cost, salvageValue, usefulLife, depreciation;

6
// Step 3: Input Values
[Link]("Enter the initial cost of the asset: ");
cost = [Link]();

[Link]("Enter the salvage value of the asset: ");


salvageValue = [Link]();

[Link]("Enter the useful life of the asset (in years): ");


usefulLife = [Link]();

// Step 5: Perform Calculation


depreciation = (cost - salvageValue) / usefulLife;

// Step 6: Display Results


[Link]("Annual Depreciation using the Straight-Line Method: " + depreciation);

// Step 7: End Program


[Link]();
}
}

INPUT:
Enter the initial cost of the asset: 10000
Enter the salvage value of the asset: 2000
Enter the useful life of the asset (in years): 5

OUTPUT
Annual Depreciation using the Straight-Line Method: 1600.0

7
RESULT:
Thus, the program has been executed and the output is verified.

[Link]
CONCATENATE STRINGS USING FOR LOOP

AIM:
To write a Java program to concatenate strings using a for loop.

ALGORITHM:
STEP 1: Initialize the program using Start All Program Notepad.
STEP 2: To set path using cd:/jdk 1.3/bin/
STEP 3: Create a class with the required variables
STEP 4: Declare an array of strings to store multiple string values.
STEP 5: Initialize a variable to hold the concatenated result, starting with an empty string.
STEP 6: Use a for loop to iterate through each string in the array.
STEP 7: Concatenate each string to the result using the + operator inside the loop.
STEP 8: Save the file using [Link] and display the results

CODING
public class StringConcatenation {
public static void main(String[] args) {
// Step 2: Declare and initialize the array of strings
String[] strings = {"Hello", " ", "World", "!", " Have", " a", " great", " day!"};

// Step 3: Initialize an empty string for concatenation


String result = "";

8
// Step 4 & 5: Iterate through the array and concatenate
for (int i = 0; i < [Link]; i++) {
result += strings[i];
}

// Step 6: Print the concatenated string


[Link]("Concatenated String: " + result);
}
}

OUTPUT
Concatenated String: Hello World! Have a great day!

RESULT:
Thus, the program has been executed and the output is verified.

9
[Link].4
FIND AND DISPLAY ARRAY OF STRINGS IN JAVA

AIM:
To write a java to find and display Array of Strings in Java

ALGORITHM:
STEP 1: Initialize the program using start all program Notepad.
STEP 2: To set path using cd:/jdk 1.3/bin/
STEP 3: Create a class with the required variables
STEP 4: Declare and initialize an array of strings with predefined values.
STEP 5: Print a message to indicate the start of the array display process.
STEP 6: Use a for loop to iterate through each element in the array.
STEP 7: In each iteration, print the element and its position.
STEP 8: Save the file using [Link] and display the results

CODING
public class ArrayOfStrings {
public static void main(String[] args) {
// Step 1: Declare and initialize an array of strings
String[] strings = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};

// Step 2: Print a message indicating the start of array display


[Link]("Displaying the array of strings:");

// Step 3: Use a for loop to iterate over the array


for (int i = 0; i < [Link]; i++) {
// Step 4: Print each element of the array
[Link]("Element " + (i + 1) + ": " + strings[i]);

10
}

// Step 5: Indicate the completion of the program


[Link]("Array display complete.");
}
}
OUTPUT

Displaying the array of strings:


Element 1: Apple
Element 2: Banana
Element 3: Cherry
Element 4: Date
Element 5: Elderberry
Array display complete.

RESULT:
Thus the program has been executed and the output is verified.

11
[Link].5
JAVA STRING MANIPULATION
AIM:
To Write a java program to perform string manipulation.

ALGORITHM:
STEP 1: Initialize the program using start all program Notepad.
STEP 2: To set path using cd:/jdk 1.3/bin/
STEP 3: Create a class with the required variables
STEP 4: Start by taking a string as input from the user or initialize a string in the program.
STEP 5: Find and print the length of the string and Extract and print a part of the string (sub
string).
STEP 6: Convert the string to both uppercase and lowercase, then print them.
STEP 7: Replace a specific character or word in the string and print the modified string and
check if the string contains a specific sub string
STEP 8: Save the file using [Link] and display the results

CODING
import [Link];

public class StringManipulation {


public static void main(String[] args) {
// Step 1: Initialize a Scanner object for user input
Scanner scanner = new Scanner([Link]);

// Step 2: Take a string input from the user


[Link]("Enter a string: ");
String inputString = [Link]();

// Step 3: Find and print the length of the string


int length = [Link]();

12
[Link]("Length of the string: " + length);

// Step 4: Extract a substring from the string


String substring = [Link](0, 5); // Get the first 5 characters
[Link]("Substring (first 5 characters): " + substring);

// Step 5: Convert the string to uppercase and lowercase


String upperCaseString = [Link]();
String lowerCaseString = [Link]();
[Link]("Uppercase: " + upperCaseString);
[Link]("Lowercase: " + lowerCaseString);

// Step 6: Replace a character in the string (example: replace 'a' with 'z')
String replacedString = [Link]('a', 'z');
[Link]("String after replacing 'a' with 'z': " + replacedString);

// Step 7: Check if the string contains a specific substring


[Link]("Enter a word to check if it's contained in the string: ");
String wordToCheck = [Link]();
boolean containsWord = [Link](wordToCheck);
[Link]("Does the string contain '" + wordToCheck + "'? " + containsWord);

// Step 8: Trim leading and trailing whitespaces from the string


String trimmedString = [Link]();
[Link]("Trimmed string: '" + trimmedString + "'");

// Close the scanner to avoid resource leaks


[Link]();
}
}

13
OUTPUT
Enter a string: Java Programming
Enter a word to check if it's contained in the string: Python
Length of the string: 16
Substring (first 5 characters): Java
Uppercase: JAVA PROGRAMMING
Lowercase: java programming
String after replacing 'a' with 'z': Jzvz Progrzmming
Does the string contain 'Python'? false
Trimmed string: 'Java Programming'

RESULT:
Thus, the program has been executed and the output is verified.

14
[Link].6

FIND SUM AND PRODUCTS OF DIGITS

AIM:

To Write a java program to find sum and product of a given digit.

ALGORITHM:

STEP 1: Initialize the program using start all programNotepad.

STEP 2: To set path using cd:/jdk 1.3/bin/

STEP 3: Create a class with the required variables

STEP 4: Take a number as input.

STEP 5: Use a loop to extract each digit from the number.

STEP 6: Use two variables to store the sum and product of the digits.

STEP 7: Add each digit to the sum and multiply it to the product.

STEP 8: Save the file using [Link] and display the results

CODING

import [Link];

public class Digits{

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

// Prompt the user for input

[Link]("Enter a number: ");

15
int number = [Link]();

// Initialize sum and product

int sum = 0, product = 1;

// Process each digit of the number

while (number > 0) {

int digit = number % 10; // Get the last digit

sum += digit; // Add to sum

product *= digit; // Multiply for product

number /= 10; // Remove the last digit

// Display the results

[Link]("Sum of digits: " + sum);

[Link]("Product of digits: " + product);

[Link]();

RESULT:

Thus, the program has been executed and the output is verified

16
EX NO: 7

INHERITANCE IMPLEMENTATION FOR BANK OPERATIONS


AIM:

To Write a java program to implement the concept of inheritance with bank operations.

ALGORITHM:

STEP 1: Initialize the program using start all programNotepad.


STEP 2: To set path using cd:/jdk 1.3/bin/

STEP 3: Create a class with the required variables

STEP 4: Create a BankAccount class which will have common attributes like account number,
account holder's name, and balance.

STEP 5: Define methods in the BankAccount class for basic operations such as deposit,
withdraw, and display balance.

STEP 6: Create a subclass called SavingsAccount that extends the BankAccount class and adds
specific functionality, such as applying interest on the balance.

STEP 7: In the main method, create objects of BankAccount and SavingsAccount

STEP 8: Save the file using [Link] and display the results

CODING

// Parent class BankAccount

class BankAccount {

// Attributes common to all bank accounts

private String accountNumber;

private String accountHolder;

protected double balance;

17
// Constructor to initialize the bank account details

public BankAccount(String accountNumber, String accountHolder, double initialBalance) {

[Link] = accountNumber;

[Link] = accountHolder;

[Link] = initialBalance;

// Method to deposit money into the account

public void deposit(double amount) {

if (amount > 0) {

balance += amount;

[Link]("Deposited: $" + amount);

} else {

[Link]("Deposit amount must be positive.");

// Method to withdraw money from the account

public void withdraw(double amount) {

if (amount > 0 && amount <= balance) {

balance -= amount;

[Link]("Withdrawn: $" + amount);

} else {

[Link]("Insufficient balance or invalid amount.");

18
}

// Method to display the current balance of the account

public void displayBalance() {

[Link]("Account Balance: $" + balance);

// Child class SavingsAccount, inherits from BankAccount

class SavingsAccount extends BankAccount {

private double interestRate; // Interest rate specific to savings account

// Constructor for savings account

public SavingsAccount(String accountNumber, String accountHolder, double initialBalance,


double interestRate) {

super(accountNumber, accountHolder, initialBalance);

[Link] = interestRate;

// Method to apply interest to the balance

public void applyInterest() {

double interest = (balance * interestRate) / 100;

balance += interest;

[Link]("Interest Applied: $" + interest);

19
// Overriding displayBalance method to show interest rate

@Override

public void displayBalance() {

[Link]();

[Link]("Interest Rate: " + interestRate + "%");

public class BankOperations {

public static void main(String[] args) {

// Creating a regular BankAccount object

BankAccount account1 = new BankAccount("A12345", "John Doe", 5000.00);

// Performing operations on regular account

[Link]("Regular Bank Account Operations:");

[Link]();

[Link](1500.00);

[Link](2000.00);

[Link]();

[Link]();

// Creating a SavingsAccount object

SavingsAccount account2 = new SavingsAccount("S67890", "Jane Doe", 10000.00, 5.0);

// Performing operations on savings account

[Link]("Savings Bank Account Operations:");

20
[Link]();

[Link](2000.00);

[Link](1500.00);

[Link](); // Apply interest to savings account

[Link]();

OUTPUT

Regular Bank Account Operations:

Account Balance: Rs.5000.0

Deposited: Rs.1500.0

Withdrawn: Rs.2000.0

Account Balance: Rs.4500.0

Savings Bank Account Operations:

Account Balance: Rs.10000.0

Interest Rate: 5.0%

Deposited: Rs.2000.0

Withdrawn: Rs.1500.0

Interest Applied: Rs.275.0

Account Balance: Rs.10775.0

Interest Rate: 5.0%

RESULT:
Thus, the program has been executed and the output is verified.

21
[Link].8

EXCEPTION HANDLING IN JAVA

AIM:

To Write a java program to perform the exception handling

ALGORITHM:

STEP 1: Initialize the program using start all program Notepad.

STEP 2: To set path using cd:/jdk 1.3/bin/

STEP 3: Create a class with the required variables

STEP 4: Take two numbers from the user for performing arithmetic operations.

STEP 5: Use a try block to perform division and handle division by zero using a catch block.

STEP 6: Handle invalid input exceptions (e.g., non-numeric input)

STEP 7: Ensure certain statements (like closing resources or displaying messages) are always
executed, regardless of whether an exception occurs or not.

STEP 8: Save the file using [Link] and display the results

CODING
import [Link];

public class ExceptionHandlingExample {


public static void main(String[] args) {
// Step 1: Create a scanner object to take user input
Scanner scanner = new Scanner([Link]);

try {

22
// Step 2: Take two integers as input for arithmetic operation
[Link]("Enter the first number: ");
int num1 = [Link](); // Read first number

[Link]("Enter the second number: ");


int num2 = [Link](); // Read second number

// Step 3: Perform arithmetic operation (division)


int result = num1 / num2; // This might cause ArithmeticException (divide by zero)
[Link]("The result of division is: " + result);

} catch (ArithmeticException e) {
// Step 4: Handle division by zero exception
[Link]("Error: Division by zero is not allowed.");
} catch ([Link] e) {
// Step 5: Handle invalid input exception (non-integer input)
[Link]("Error: Please enter valid integer values.");
} finally {
// Step 6: The finally block will always execute
[Link]("This will always be executed, whether an exception occurs or not.");
}

// Step 7: Closing the scanner object to avoid resource leak


[Link]();
}
}

23
OUTPUT
Enter the first number: 10
Enter the second number: 2
The result of division is: 5
This will always be executed, whether an exception occurs or not.
Enter the first number: 10
Enter the second number: 0
Error: Division by zero is not allowed.
This will always be executed, whether an exception occurs or not.
Enter the first number: 10
Enter the second number: abc
Error: Please enter valid integer values.
This will always be executed, whether an exception occurs or not.

RESULT:
Thus, the program has been executed and the output is verified.

24
[Link]: 9
INTERACTIVE APPLET FOR SHAPES AND IMAGES IN JAVA
AIM:

To Write a java program to draw shapes and to display image using applet.

ALGORITHM:

STEP 1: Initialize the program using start all program Notepad.

STEP 2: To set path using cd:/jdk 1.3/bin/

STEP 3: Create a Java applet using Applet class or JApplet class

STEP 4: This method is called automatically when the applet is displayed and you will use this
method to draw shapes and display the image.

STEP 5: Use methods like drawRect(), drawOval(), and drawLine() to draw shapes on the
applet.

STEP 6:Load and display an image using the getImage() method and then use the drawImage()
method to display it on the applet.

STEP 7:To test the applet, run it in an applet viewer or a web browser with applet support
(though applets are deprecated in modern browsers).

STEP 8: Save the file using [Link] and display the results

CODING

import [Link];

import [Link];

import [Link];

import [Link];

public class ShapeAndImageApplet extends Applet {

25
// Declare an image variable

Image img;

// Method to initialize the applet

public void init() {

// Load an image from a file (ensure the image file is in the right directory)

img = [Link]().getImage("[Link]"); // Replace "[Link]" with the


path to your image

// Method to draw shapes and display the image

public void paint(Graphics g) {

// Drawing a rectangle

[Link](50, 50, 150, 100); // x, y, width, height

[Link]("Rectangle", 100, 40);

// Drawing an oval (circle)

[Link](250, 50, 100, 100); // x, y, width, height

[Link]("Oval", 285, 40);

// Drawing a line

[Link](50, 200, 200, 300); // x1, y1, x2, y2

[Link]("Line", 125, 350);

// Displaying the image

26
[Link](img, 300, 200, this); // x, y, this (for the applet context)

[Link]("Image", 350, 340);

OUTPUT

Applet viewer [Link]

RESULT:
Thus, the program has been executed and the output is verified.

27
[Link]

TEXT SUMMARIZATION INTEGRATION USING JAVA WITH AI


AIM:

To Develop an Java program to display text summarization integrated with AI.

ALGORITHM:

STEP 1: Initialize the program using start all program Notepad.

STEP 2: To set path using cd:/jdk 1.3/bin/

STEP 3: Take a block of text as input.

STEP 4: Split the text into sentences, tokenize each sentence into words and Remove stop words
and perform stemming.

STEP 5: Calculate the frequency of each word in the text and assign a score to each sentence
based on the frequency of the words it contains.

STEP 6: Sort the sentences by their scores in descending order.

STEP 7: Select the top N sentences as the summary.

STEP 8: Save the file using [Link] and display the results

CODING

import [Link].*;

import [Link];

public class TextSummarization {

public static void main(String[] args) {

String text = """

28
Artificial intelligence (AI) refers to the simulation of human intelligence in
machines.

These machines are programmed to think like humans and mimic their actions.

The term may also be applied to any machine that exhibits traits associated with a
human mind.

Examples include learning and problem-solving.

AI is an interdisciplinary science with multiple approaches.

Recent advancements in deep learning and machine learning are creating a


paradigm shift in virtually every sector.

""";

[Link]("Original Text:\n" + text);

[Link]("\nSummarized Text:\n" + summarizeText(text, 2)); // Summarize into 2


sentences

public static String summarizeText(String text, int summaryLength) {

// Split the text into sentences

String[] sentences = [Link]("\\.");

Map<String, Integer> wordFrequency = calculateWordFrequency(text);

// Calculate scores for each sentence

Map<String, Integer> sentenceScores = new HashMap<>();

for (String sentence : sentences) {

int score = 0;

String[] words = [Link]().split("\\W+");

for (String word : words) {

29
score += [Link](word, 0);

[Link]([Link](), score);

// Sort sentences by score

List<[Link]<String, Integer>> sortedSentences = [Link]()

.stream()

.sorted((a, b) -> [Link]().compareTo([Link]()))

.collect([Link]());

// Select top N sentences

StringBuilder summary = new StringBuilder();

for (int i = 0; i < [Link](summaryLength, [Link]()); i++) {

[Link]([Link](i).getKey()).append(". ");

return [Link]().trim();

public static Map<String, Integer> calculateWordFrequency(String text) {

Map<String, Integer> wordFrequency = new HashMap<>();

String[] words = [Link]().split("\\W+");

for (String word : words) {

[Link](word, [Link](word, 0) + 1);

30
}

return wordFrequency;

OUTPUT

INPUT TEXT

Artificial intelligence (AI) refers to the simulation of human intelligence in machines. These
machines are programmed to think like humans and mimic their actions. The term may also be
applied to any machine that exhibits traits associated with a human mind. Examples include
learning and problem-solving. AI is an interdisciplinary science with multiple approaches.
Recent advancements in deep learning and machine learning are creating a paradigm shift in
virtually every sector.

Original Text:

Artificial intelligence (AI) refers to the simulation of human intelligence in machines...

[remaining input text]

Summarized Text:

AI is an interdisciplinary science with multiple approaches. Recent advancements in deep


learning and machine learning are creating a paradigm shift in virtually every sector.

RESULT:
Thus, the program has been executed and the output is verified.

31
EX NO 11
AI-POWERED STOCK PRICE PREDICTION USING JAVA TIME SERIES

AIM:

To develop a Java program that predicts stock prices using time series forecasting techniques and
integrates AI-based predictions.

ALGORITHM:

STEP 1: Initialize the program using start all programNotepad.

STEP 2: To set path using cd:/jdk 1.3/bin/

STEP 3: Collect historical stock price data..

STEP 4: Parse the input data and clean it for missing values and normalize the data if needed.

STEP 5: Calculate moving averages, trends, and seasonality.

STEP 6: Use ARIMA or similar algorithms to model the time series.

STEP 7: Generate predictions for the next time steps using the trained model..

STEP 8: Save the file using [Link] and display the results

CODING
import [Link];

import [Link];
import [Link];

public class StockPricePrediction {

public static void main(String[] args) {


// Example historical stock prices (daily closing prices)
double[] stockPrices = {100, 102, 101, 105, 107, 110, 115, 117, 120, 125};

32
[Link]("Historical Stock Prices:");
for (double price : stockPrices) {
[Link](price + " ");
}
[Link]("\n");

// Predict the next 3 days of stock prices


int futureDays = 3;
double[] predictions = predictStockPrices(stockPrices, futureDays);

[Link]("Predicted Stock Prices:");


for (int i = 0; i < [Link]; i++) {
[Link]("Day %d: %.2f\n", [Link] + i + 1, predictions[i]);
}
}

public static double[] predictStockPrices(double[] prices, int futureDays) {


// Use simple linear regression to predict future prices
SimpleRegression regression = new SimpleRegression();
for (int i = 0; i < [Link]; i++) {
[Link](i, prices[i]);
}

double[] predictions = new double[futureDays];


for (int i = 0; i < futureDays; i++) {
int day = [Link] + i; // Future day index
predictions[i] = [Link](day);
}
return predictions;
}
}

33
INPUT:
Historical stock prices: [100, 102, 101, 105, 107, 110, 115, 117, 120, 125]
Future days to predict: 3
OUTPUT
Historical Stock Prices:
100.0 102.0 101.0 105.0 107.0 110.0 115.0 117.0 120.0 125.0

Predicted Stock Prices:


Day 11: 129.50
Day 12: 134.00
Day 13: 138.50

RESULT:
Thus, the program has been executed and the output is verified.

34
EX NO 12
JAVA EMAIL CLASSIFIER WITH AI DETECTION TECHNOLOGY
AIM:

To develop an AI-integrated Java program to classify emails into categories such as "Spam" or
"Not Spam" using machine learning techniques.

ALGORITHM:
STEP 1: Initialize the program using start all program Notepad.

STEP 2: To set path using cd:/jdk 1.3/bin/

STEP 3: Collect and preprocess email datasets (e.g., labeled as spam or not spam).

STEP 4: Tokenize the email content and convert it into numerical features (e.g., using bag-of-
words or TF-IDF).

STEP 5: Use a machine learning algorithm such as Naive Bayes or Logistic Regression for text
classification.

STEP 6: Input a new email, preprocess it, and pass it to the trained model for classification.

STEP 7: Display whether the email is classified as "Spam" or "Not Spam."

STEP 8: Save the file using [Link] and display the results

CODING
<dependencies>
<dependency>
<groupId>org.deeplearning4j</groupId>
<artifactId>deeplearning4j-core</artifactId>
<version>1.0.0-M2</version>
</dependency>
<dependency>
<groupId>org.nd4j</groupId>
<artifactId>nd4j-native-platform</artifactId>

35
<version>1.0.0-M2</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>opennlp-tools</artifactId>
<version>1.9.3</version>
</dependency>
</dependencies>
CODE IMPLEMENTATION
import [Link];
import [Link];
import [Link];
import [Link].Nd4j;

import [Link];
import [Link];
import [Link];

public class EmailClassifier {

public static void main(String[] args) {


// Sample dataset: Word frequencies for "Spam" and "Not Spam" emails
String[] spamEmails = {"Win a lottery now", "Free money for you", "Congratulations,
claim your prize"};
String[] nonSpamEmails = {"Meeting at 10 AM", "Project update", "Lunch at 1 PM"};

// Tokenizer and Word Counts


DefaultTokenizerFactory tokenizer = new DefaultTokenizerFactory();
Map<String, Integer> wordIndex = new HashMap<>();
int index = 0;

36
// Count words from spam emails
for (String email : spamEmails) {
for (String word : [Link](email).getTokens()) {
[Link]([Link](), index++);
}
}

// Count words from non-spam emails


for (String email : nonSpamEmails) {
for (String word : [Link](email).getTokens()) {
[Link]([Link](), index++);
}
}

// Create training data


DataSet trainingData = createDataSet(spamEmails, nonSpamEmails, wordIndex, tokenizer);

// Train the model


NaiveBayesClassifier classifier = new NaiveBayesClassifier();
[Link](trainingData);

// Test the classifier


[Link]("Enter an email to classify: ");
Scanner scanner = new Scanner([Link]);
String email = [Link]();

DataSet testData = emailToDataSet(email, wordIndex, tokenizer);


String result = [Link](testData) == 1 ? "Spam" : "Not Spam";

[Link]("The email is classified as: " + result);


}

37
private static DataSet createDataSet(String[] spam, String[] nonSpam, Map<String, Integer>
wordIndex, DefaultTokenizerFactory tokenizer) {
int totalEmails = [Link] + [Link];
int vocabSize = [Link]();

// Features and Labels


double[][] features = new double[totalEmails][vocabSize];
double[][] labels = new double[totalEmails][1];

int row = 0;

// Process spam emails


for (String email : spam) {
processEmail(email, features[row], wordIndex, tokenizer);
labels[row][0] = 1; // Spam
row++;
}

// Process non-spam emails


for (String email : nonSpam) {
processEmail(email, features[row], wordIndex, tokenizer);
labels[row][0] = 0; // Not Spam
row++;
}

return new DataSet([Link](features), [Link](labels));


}

private static void processEmail(String email, double[] featureVector, Map<String, Integer>


wordIndex, DefaultTokenizerFactory tokenizer) {

38
for (String word : [Link](email).getTokens()) {
int idx = [Link]([Link](), -1);
if (idx != -1) {
featureVector[idx]++;
}
}
}

private static DataSet emailToDataSet(String email, Map<String, Integer> wordIndex,


DefaultTokenizerFactory tokenizer) {
int vocabSize = [Link]();
double[] features = new double[vocabSize];
processEmail(email, features, wordIndex, tokenizer);

return new DataSet([Link](new double[][]{features}), [Link](1, 1));


}
}

OUTPUT
Win a free car today!
The email is classified as: Spam
Team meeting scheduled at 3 PM.
The email is classified as: Not Spam

RESULT:
Thus, the program has been executed and the output is verified.

39

You might also like