0% found this document useful (0 votes)
15 views21 pages

Java Programs for Primes, Matrices, and Text Analysis

The document contains multiple Java practical programs covering various topics such as finding prime numbers, matrix multiplication, text analysis, random number generation, string manipulation, and inheritance. Each program includes a detailed algorithm and corresponding Java code, demonstrating the implementation of the described functionality. The document also provides example outputs for each program to illustrate their behavior.

Uploaded by

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

Java Programs for Primes, Matrices, and Text Analysis

The document contains multiple Java practical programs covering various topics such as finding prime numbers, matrix multiplication, text analysis, random number generation, string manipulation, and inheritance. Each program includes a detailed algorithm and corresponding Java code, demonstrating the implementation of the described functionality. The document also provides example outputs for each program to illustrate their behavior.

Uploaded by

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

Java Practical Programs

Program 1: Write a Java program that prompts the user for an integer and then prints out all
the prime numbers up to that Integer?

Algorithm

1. Import the needed files.


2. Prompt the user for an integer and store the input in a variable N.
3. Define a method printPrimes(int N) that:
Iterates through numbers from 2 to N.
For each number, checks if it is a prime using a helper method isPrime(int
num).
4. Define the helper method isPrime(int num):
Returns true if the number is prime and false otherwise by checking divisors
up to the square root of the number.
5. Print all prime numbers within the range.

class prime
{
static void prime_N(int N)
{
// Declaring the variables
int x, y, flg;
// Printing display message
[Link](
"All the Prime numbers within 1 and " + N
+ " are:");
for (x = 1; x <= N; x++)
{
if (x == 1 || x == 0)
continue;
flg = 1;

for (y = 2; y <= x / 2; ++y) {


if (x % y == 0) {
flg = 0;
break;
}
}

// If flag is 1 then x is prime but


// if flag is 0 then x is not prime
if (flg == 1)
[Link](x + " ");
}
}
public static void main(String[] args)
{
int N = 45;
prime_N(N);
}
}

USING BUFFERED READER


import [Link];
import [Link];
import [Link];
class prime
{
static void prime_N(int N)
{
int x, y, flg;
[Link]("All the Prime numbers within 1 and " + N + " are:");
for (x = 1; x <= N; x++) {
if (x == 1 || x == 0)
continue; // Skip 0 and 1 as they are not prime
flg = 1;
for (y = 2; y <= x / 2; ++y) {
if (x % y == 0) {
flg = 0; // Not prime
break;
}
}

// Print the number if it is prime


if (flg == 1)
[Link](x + " ");
}
[Link](); // New line after printing primes
}

public static void main(String[] args) throws IOException


{
BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter an integer: ");
int N = [Link]([Link]()); // Read and parse the integer input
prime_N(N);
}
}

OUTPUT:

All the Prime numbers within 1 and 45 are:


2 3 5 7 11 13 17 19 23 29 31 37 41 43
Program 2: Write a Java program to multiply two given matrices.

Algorithm:

1. Input the dimensions of matrices AAA and BBB


2. Check if multiplication is possible:
 If n1≠m2n_1 \neq m_2n1=m2, print an error message and stop.
3. Input elements of matrix AAA and matrix BBB
4. Initialize result matrix CCC with size m1×n2m_1 \times n_2m1×n2
5. Perform matrix multiplication:
 For each element C[i][j]C[i][j]C[i][j] in result matrix CCC:
 Set C[i][j]=0C[i][j] = 0C[i][j]=0
 Sum products of corresponding elements from row iii of AAA and
column jjj of BBB.
6. Print the result matrix CCC

import [Link];

public class MatrixMultiplication {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Get the order of the first matrix (rows and columns)


[Link]("Enter the number of rows and columns of the first matrix: ");
int m1 = [Link](); // Number of rows for matrix 1
int n1 = [Link](); // Number of columns for matrix 1

// Get the order of the second matrix (rows and columns)


[Link]("Enter the number of rows and columns of the second matrix: ");
int m2 = [Link](); // Number of rows for matrix 2
int n2 = [Link](); // Number of columns for matrix 2

// Matrix multiplication is possible only if columns of first matrix equals rows of second
matrix
if (n1 != m2) {
[Link]("Matrix multiplication is not possible. Number of columns of first
matrix must equal number of rows of second matrix.");
return;
}

// Declare matrices
int[][] matrix1 = new int[m1][n1];
int[][] matrix2 = new int[m2][n2];
int[][] result = new int[m1][n2];

// Input elements for the first matrix


[Link]("Enter elements of the first matrix:");
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n1; j++) {
matrix1[i][j] = [Link]();
}
}

// Input elements for the second matrix


[Link]("Enter elements of the second matrix:");
for (int i = 0; i < m2; i++) {
for (int j = 0; j < n2; j++) {
matrix2[i][j] = [Link]();
}
}

// Matrix multiplication
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n2; j++) {
result[i][j] = 0;
for (int k = 0; k < n1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Output the result


[Link]("Resultant Matrix after multiplication:");
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n2; j++) {
[Link](result[i][j] + " ");
}
[Link]();
}

[Link]();
}
}
OUTPUT:

Enter the number of rows and columns of the first matrix:


23
Enter the number of rows and columns of the second matrix:
32
Enter elements of the first matrix:
123456
Enter elements of the second matrix:
7 8 9 10 11 12
Resultant Matrix after multiplication:
58 64
139 154
3. Write a Java program that displays the number of characters, lines and words in a
text?

Algorithm

Step 1: Initialize counters for characters, words, and lines.


Step 2: Continuously read each line of input until an empty line is entered.
Step 3: For each non-empty line, count the number of characters (using [Link]()).
Step 4: Split the line into words (using spaces or whitespace as delimiters) and count how
many words exist in that line.
Step 5: After processing the input, display the total number of characters, words, and
lines.

import [Link];

public class TextAnalyzer {

public static void main(String[] args) {


// Create a scanner object to read input from the user
Scanner scanner = new Scanner([Link]);

// Prompt the user to enter the text


[Link]("Enter your text (press Enter twice to end the input):");

// Variable to store the entire input text


StringBuilder inputText = new StringBuilder();

// Reading multiple lines of input until user presses Enter twice


String line;
while ([Link]()) {
line = [Link]();

if ([Link]()) {
break; // End the input when a blank line is encountered
}

[Link](line).append("\n");
}

// Convert input text to a string


String text = [Link]();

// Initialize counters for characters, words, and lines


int characterCount = [Link]();
int wordCount = 0;
int lineCount = 0;

// Count the number of lines


lineCount = [Link]("\n").length;

// Count the number of words (split by spaces and other word delimiters)
String[] words = [Link]("\\s+");
wordCount = [Link];

// Output the results


[Link]("Number of characters: " + characterCount);
[Link]("Number of words: " + wordCount);
[Link]("Number of lines: " + lineCount);

[Link](); // Close the scanner


}
}

OUTPUT :

Enter your text (press Enter twice to end the input):


Hello world! This is a test.
This is the second line of the text.
Number of characters: 47
Number of words: 9
Number of lines: 3
4. Generate random numbers between two given limits using Random class and print
messages according to the range of the value generated.

Algorithm:
Step 1. Create a Random object to generate random numbers.
Step 2. Initialize an integer array `k` of size 5.
Step 3. For i = 0 to 4:
- Generate a random integer between 0 and 9.
- Store the generated number in the `k[i]` array.
Step 4. For i = 0 to 4:
For j = 0 to 4:
- If k[i] > k[j], then swap k[i] and k[j] using a temporary variable `t`.
Step 5. Print the sorted array `k` (ascending order).

Program:

import [Link].*;
import [Link];
public class Rand1
{
public static void main(String s[])
{
Random r=new Random ();
int k[ ]=new int[5];
int i,j,t;
for(i=0;i<5;i++)
{
k[i]=[Link](10);
}
for(i=0;i<5;i++)
for(j=0;j<5;j++)
{
if(k[i]>k[j])
{
t=k[i];
k[i]=k[j];
k[j]=t;
}
}
[Link]("Random numbers in ascending order");
for(i=0;i<5;i++)
{
[Link](k[i]);
}
}
}

OUTPUT:

0
2
5
6
9
(The o/p will vary everytime when we run the prg)
5. Write a program to do String Manipulation using Character Array and perform
the following string operations:
a. String length
b. Finding a character at a particular position
c. Concatenating two strings

Algorithm:

Step 1:
Input Strings:
The program first takes two strings as input from the user using a Scanner object.
It converts the strings into character arrays using toCharArray().
Step 2:
String Length:
The length of the strings is calculated using the length property of the character array.
Step 3:
Character at a Particular Position:
The program prompts the user to enter a position (index) and then checks if the position is
valid.
If the position is valid, it retrieves the character at that position from the character array.
Step 4:
Concatenate Strings:
The two input strings are concatenated using the + operator and displayed.

import [Link];

public class StringManipulation


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

// Prompt user to input the first string


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

// Convert the first string to a character array


char[] charArray1 = [Link]();

// Perform string length operation


int length1 = [Link];
[Link]("Length of the first string: " + length1);

// Prompt user to input the second string


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

// Convert the second string to a character array


char[] charArray2 = [Link]();

// Perform string length operation for second string


int length2 = [Link];
[Link]("Length of the second string: " + length2);

// Finding a character at a particular position


[Link]("Enter the position to find the character in the first string (0 to " +
(length1 - 1) + "): ");
int position = [Link]();

if (position >= 0 && position < length1)


{
[Link]("Character at position " + position + " in the first string: " +
charArray1[position]);
}
else
{
[Link]("Invalid position.");
}

// Concatenating the two strings


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

// Close the scanner object


[Link]();
}
}

OUTPUT:

Enter the first string: Hello


Length of the first string: 5
Enter the second string: World
Length of the second string: 5
Enter the position to find the character in the first string (0 to 4): 1
Character at position 1 in the first string: e
Concatenated string: HelloWorld
[Link] a program to implement
a. Single inheritance
b. Multilevel Inheritance

a. Single inheritance
Algorithm:

Step1: Executive class inherits the Employee class (extends Employee).


Step2: The salary variable is inherited from Employee and accessed directly.
Step3: The displaySalary() method from Employee is called using an object of
Executive.
Step4: The bonus variable and displayBonus() method are part of Executive.
Step5: The main method instantiates Executive and demonstrates inheritance.

Program:

class Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
[Link]("Total salary credited: "+[Link]);
[Link]("Bonus of six months: "+[Link]);
}
}

Output:

Total salary credited: 414408.0


Bonus of six months: 18000.0
b. Multi level inheritance:

Algorithm:

Step1: Define the Base Class (Student)

 Declare an integer reg_no


 Define a method getNo(int no) to set the registration number
 Define a method putNo() to display the registration number

Step2: Define an Intermediate Class (Marks) that extends Student

 Declare a float variable marks


 Define a method getMarks(float m) to set marks
 Define a method putMarks() to display marks

Step3: Define the Derived Class (Sports) that extends Marks

 Declare a float variable score


 Define a method getScore(float scr) to set the sports score
 Define a method putScore() to display the sports score

Step4: Define the Main Class (Multilevel InheritanceExample)

 Create an object of Sports


 Call methods to set and display registration number, marks, and sports score

Program:
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
[Link]("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
[Link]("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
[Link]("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
[Link](0987);
[Link]();
[Link](78);
[Link]();
[Link](68.7);
[Link]();
}

OUTPUT:

registration number= 0987


marks= 78.0
score= 68.7
7. Write a program to implement
a. Method overloading
b. Method Overriding

a. Method Overloading

Algorithm:

Step 1: Define a class (OverloadDemo)

Create a method test() with no parameters.


Create a method test(int a) with one integer parameter.
Create a method test(int a, int b) with two integer parameters.
Create a method test(double a) with one double parameter, returning a double.

Step 2: Define another class (Overload) containing the main method

Create an object of OverloadDemo.


Call all versions of the test() method with different arguments:
test() (no arguments)
test(int) (single integer)
test(int, int) (two integers)
test(double) (single double, stores the return value)
Step 3:
Print the result of test(double)

Program:

class OverloadDemo
{
void test()
{
[Link]("No parameters");
}
void test(int a) {
[Link]("a: " + a);
}
void test(int a, int b) {
[Link]("a and b: " + a + " " + b);
}
double test(double a) {
[Link]("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
[Link]();
[Link](10);
[Link](10, 20);
result = [Link](123.25);
[Link]("Result of [Link](123.25): " + result);
}
}

OUTPUT:

No parameters
a: 10
a and b: 10 20
Result of [Link](123.25): 123.25

b. Method Overriding
Algorithm:

Step1: Define a Parent Class (A)

Declare two integer variables i and j.


Create a constructor A(int a, int b) to initialize i and j.
Define a method show() to display i and j.

Step 2:Define a Child Class (B) that Extends A

Declare an integer variable k.


Create a constructor B(int a, int b, int c):
Call the parent class constructor using super(a, b).
Initialize k with c.
Override the show() method to display k instead of i and j.

Step 3: Define a Main Class (Override)

Create an object of B and initialize it with values (1, 2, 3).


Call the show() method on the object.
Since show() is overridden in B, it displays k.
Program:

class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
// display i and j
void show()
{
[Link]("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
[Link]("k: " + k);
}
}
class Override {
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
[Link](); // this calls show() in B
}
}

OUTPUT:
k: 3
8. Write a program to create a package

Directory: Create a folder MyPack in C:\ or D:\ where the jdk1.8 is


downloaded

File Name: Save [Link] inside MyPack folder

Compile: javac [Link] (To compile the prg)


javac –d . [Link] (To Compile Package)

To run: java [Link]

Algorithm:

Step1:Create a package named MyPack


Step 2:Define a class Balance inside the package MyPack
Step 3: Declare a String variable name for the account holder’s name.
Step 4: Declare a double variable bal for the account balance.
Step5: Define a constructor Balance(String n, double b):
Assign name = n and bal = b.
Step 6: Define a method show():
If bal < 0, print --> before the balance.
Display the name and balance.
Step 7: Create another class AccountBalance outside the package
Step 8: Define the main method:
Create an array current[] of three Balance objects.
Initialize each object with a name and balance.
Use a loop to call show() for each object.

Program:

package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
[Link]("NIL");
[Link](name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}

OUTPUT:
[Link] $123.23
Will Tell $157.02
Tom Jackson NIL
9. Write a program to implement Inter thread communication

Algorithm:

Step 1:Define a class Customer

Step 2: Initialize an account balance (amount = 10000).

Step 3: Define a synchronized method withdraw(int amount):


Print "going to withdraw...".
If the requested amount is greater than the balance:
Print "Less balance; waiting for deposit...".
Call wait() to pause the thread.
Deduct the requested amount from [Link].
Print "withdraw completed...".

Step 4: Define a synchronized method deposit(int amount):

Print "going to deposit...".


Add the amount to [Link].
Print "deposit completed...".
Call notify() to wake up the waiting thread.
Step 5: Define a Test class with main method
Step 6: Create a Customer object c.
Create a new withdraw thread that calls [Link](15000).
Create a new deposit thread that calls [Link](10000).
Start both threads.

Program:

class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
[Link](“going to withdraw...”);
if([Link]&lt;amount)
{
[Link](“Less balance; waiting for deposit...”);
try
{
wait();
}
catch(Exception e)
{
}
}
[Link]-=amount;
[Link](“withdraw completed...”);
}
synchronized void deposit(int amount)
{
[Link](“going to deposit...”);
[Link]+=amount;
[Link](“deposit completed... “);
notify();
}
}
public class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{
[Link](15000);
}
}.start();
new Thread()
{
public void run()
{
[Link](10000);
}
}.start();
}
}
}

OUTPUT:

going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

Common questions

Powered by AI

Method overloading enhances a class's flexibility by allowing multiple methods with the same name but different parameter lists, enabling the same function to be executed in multiple ways based on varying input. This reduces the need for unique method names for similar actions, simplifies the API, and increases code readability by enabling intuitive method usage for operations involving different data types or number of inputs .

Synchronized methods are crucial in inter-thread communication to avoid concurrent access issues and ensure data consistency. They prevent multiple threads from accessing a method at the same time, which is necessary when several threads work with shared variables like account balances. In the program, synchronized methods are used for the deposit and withdraw operations to ensure that updates to the balance are done safely and in order, preventing race conditions .

Method overriding allows a subclass to provide a specific implementation for a method that is already defined in its superclass. This is significant because it enables polymorphic behavior, where a subclass can tailor or extend the functionality of methods to fit its needs. In the example, the subclass B overrides the show() method to display a different output than that of the superclass A, demonstrating how subclasses can modify inherited behaviors to perform specific tasks .

The Java program uses a simple sorting algorithm (bubble sort) to demonstrate fundamental algorithm principles such as selection, comparison, and swapping. This process involves iteratively comparing adjacent elements and rearranging them until the entire set is sorted. It showcases basic control structures and iterative processing, which are foundational concepts in algorithm design and implementation, illustrating how data can be ordered efficiently .

Matrix multiplication is defined such that for two matrices A and B to be multiplied, the number of columns in A must equal the number of rows in B. This corresponds to the need for each element of a row in A to have a corresponding element in the column of B to perform the dot product operation, which is essential in computing each element of the resultant matrix .

Encapsulation is demonstrated in the Balance and AccountBalance classes by restricting direct access to sensitive data attributes like `name` and `balance`. Instead, the program uses methods such as constructors and `show()` to manipulate and display the data securely. This encapsulation ensures that changes to the internal data representation don't affect external code that uses the class, reinforcing data security and integrity .

The helper method `isPrime(int num)` is used to determine if a number is prime by checking for divisors up to the square root of the number. This is a more efficient approach than checking all numbers up to the number itself, as it reduces the number of potential divisors and thus decreases the computational complexity .

The program counts the number of words, lines, and characters by reading lines of input until a blank line is entered. Characters are counted by adding up their lengths from each line, lines are counted by splitting the string by newline characters, and words are counted by splitting each line using whitespace as delimiters .

The Java program multiplies matrices using three nested loops. The outer loop iterates over each row of the first matrix, the middle loop iterates over each column of the second matrix, and the innermost loop calculates the dot product of the current row of the first matrix and the current column of the second matrix. This sum is assigned to the respective element in the result matrix, effectively computing each entry of the resultant matrix through these nested operations .

Inheritance allows the re-use of code from a parent class in the child class, reducing redundancy and improving maintainability. In the program, the Executive class inherits the salary attribute and displaySalary() method from the Employee class, allowing Executive to utilize these properties without redefining them. Inheritance also enhances code understanding by establishing hierarchical relationships between classes .

You might also like