Java Programming Practical Exercises
Java Programming Practical Exercises
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
2
CONTENTS
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];
// 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];
6
// Step 3: Input Values
[Link]("Enter the initial cost of the asset: ");
cost = [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!"};
8
// Step 4 & 5: Iterate through the array and concatenate
for (int i = 0; i < [Link]; i++) {
result += strings[i];
}
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"};
10
}
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];
12
[Link]("Length of the string: " + length);
// 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);
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
AIM:
ALGORITHM:
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];
15
int number = [Link]();
[Link]();
RESULT:
Thus, the program has been executed and the output is verified
16
EX NO: 7
To Write a java program to implement the concept of inheritance with bank operations.
ALGORITHM:
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 8: Save the file using [Link] and display the results
CODING
class BankAccount {
17
// Constructor to initialize the bank account details
[Link] = accountNumber;
[Link] = accountHolder;
[Link] = initialBalance;
if (amount > 0) {
balance += amount;
} else {
balance -= amount;
} else {
18
}
[Link] = interestRate;
balance += interest;
19
// Overriding displayBalance method to show interest rate
@Override
[Link]();
[Link]();
[Link](1500.00);
[Link](2000.00);
[Link]();
[Link]();
20
[Link]();
[Link](2000.00);
[Link](1500.00);
[Link]();
OUTPUT
Deposited: Rs.1500.0
Withdrawn: Rs.2000.0
Deposited: Rs.2000.0
Withdrawn: Rs.1500.0
RESULT:
Thus, the program has been executed and the output is verified.
21
[Link].8
AIM:
ALGORITHM:
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 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];
try {
22
// Step 2: Take two integers as input for arithmetic operation
[Link]("Enter the first number: ");
int num1 = [Link](); // Read first number
} 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.");
}
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 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];
25
// Declare an image variable
Image img;
// Load an image from a file (ensure the image file is in the right directory)
// Drawing a rectangle
// Drawing a line
26
[Link](img, 300, 200, this); // x, y, this (for the applet context)
OUTPUT
RESULT:
Thus, the program has been executed and the output is verified.
27
[Link]
ALGORITHM:
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 8: Save the file using [Link] and display the results
CODING
import [Link].*;
import [Link];
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.
""";
int score = 0;
29
score += [Link](word, 0);
[Link]([Link](), score);
.stream()
.collect([Link]());
[Link]([Link](i).getKey()).append(". ");
return [Link]().trim();
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:
Summarized Text:
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 4: Parse the input data and clean it for missing values and normalize the data if needed.
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];
32
[Link]("Historical Stock Prices:");
for (double price : stockPrices) {
[Link](price + " ");
}
[Link]("\n");
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
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 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 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];
36
// Count words from spam emails
for (String email : spamEmails) {
for (String word : [Link](email).getTokens()) {
[Link]([Link](), index++);
}
}
37
private static DataSet createDataSet(String[] spam, String[] nonSpam, Map<String, Integer>
wordIndex, DefaultTokenizerFactory tokenizer) {
int totalEmails = [Link] + [Link];
int vocabSize = [Link]();
int row = 0;
38
for (String word : [Link](email).getTokens()) {
int idx = [Link]([Link](), -1);
if (idx != -1) {
featureVector[idx]++;
}
}
}
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