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

Bsc Java Practical Programs (1)

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
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views21 pages

Bsc Java Practical Programs (1)

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
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 21

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
System.out.println(
"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)
System.out.print(x + " ");
}
}
public static void main(String[] args)
{
int N = 45;
prime_N(N);
}
}

USING BUFFERED READER


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class prime
{
static void prime_N(int N)
{
int x, y, flg;
System.out.println("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)
System.out.print(x + " ");
}
System.out.println(); // New line after printing primes
}

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


{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter an integer: ");
int N = Integer.parseInt(reader.readLine()); // 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 java.util.Scanner;

public class MatrixMultiplication {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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


System.out.print("Enter the number of rows and columns of the first matrix: ");
int m1 = scanner.nextInt(); // Number of rows for matrix 1
int n1 = scanner.nextInt(); // Number of columns for matrix 1

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


System.out.print("Enter the number of rows and columns of the second matrix: ");
int m2 = scanner.nextInt(); // Number of rows for matrix 2
int n2 = scanner.nextInt(); // Number of columns for matrix 2

// Matrix multiplication is possible only if columns of first matrix equals rows of second
matrix
if (n1 != m2) {
System.out.println("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


System.out.println("Enter elements of the first matrix:");
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n1; j++) {
matrix1[i][j] = scanner.nextInt();
}
}

// Input elements for the second matrix


System.out.println("Enter elements of the second matrix:");
for (int i = 0; i < m2; i++) {
for (int j = 0; j < n2; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

// 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


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

scanner.close();
}
}
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 line.length()).
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 java.util.Scanner;

public class TextAnalyzer {

public static void main(String[] args) {


// Create a scanner object to read input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the text


System.out.println("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 (scanner.hasNextLine()) {
line = scanner.nextLine();

if (line.isEmpty()) {
break; // End the input when a blank line is encountered
}

inputText.append(line).append("\n");
}

// Convert input text to a string


String text = inputText.toString();

// Initialize counters for characters, words, and lines


int characterCount = text.length();
int wordCount = 0;
int lineCount = 0;

// Count the number of lines


lineCount = text.split("\n").length;

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

// Output the results


System.out.println("Number of characters: " + characterCount);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of lines: " + lineCount);

scanner.close(); // 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 java.io.*;
import java.util.Random;
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]=r.nextInt(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;
}
}
System.out.println("Random numbers in ascending order");
for(i=0;i<5;i++)
{
System.out.println(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 java.util.Scanner;

public class StringManipulation


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

// Prompt user to input the first string


System.out.println("Enter the first string: ");
String str1 = sc.nextLine();

// Convert the first string to a character array


char[] charArray1 = str1.toCharArray();

// Perform string length operation


int length1 = charArray1.length;
System.out.println("Length of the first string: " + length1);

// Prompt user to input the second string


System.out.println("Enter the second string: ");
String str2 = sc.nextLine();

// Convert the second string to a character array


char[] charArray2 = str2.toCharArray();

// Perform string length operation for second string


int length2 = charArray2.length;
System.out.println("Length of the second string: " + length2);

// Finding a character at a particular position


System.out.println("Enter the position to find the character in the first string (0 to " +
(length1 - 1) + "): ");
int position = sc.nextInt();

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


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

// Concatenating the two strings


String concatenatedString = str1 + str2;
System.out.println("Concatenated string: " + concatenatedString);

// Close the scanner object


sc.close();
}
}

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
6.Write 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();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}

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()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}

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()
{
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("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()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}

OUTPUT:

No parameters
a: 10
a and b: 10 20
Result of ob.test(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()
{
System.out.println("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() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // 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 AccountBalance.java inside MyPack folder

Compile: javac AccountBalance.java (To compile the prg)


javac –d . AccountBalance.java (To Compile Package)

To run: java MyPack.AccountBalance

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)
System.out.print("NIL");
System.out.println(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:
K.J.Fielding $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 this.amount.
Print "withdraw completed...".

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

Print "going to deposit...".


Add the amount to this.amount.
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 c.withdraw(15000).
Create a new deposit thread that calls c.deposit(10000).
Start both threads.

Program:

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

OUTPUT:

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

You might also like