0% found this document useful (0 votes)
4 views

Java

The document is a practical file for a Java course (BCA203C) submitted by a student at Hindu Institute of Management. It includes an index of various Java programs covering topics such as prime number calculation, string manipulation, array operations, matrix multiplication, and object counting. Each program is accompanied by code snippets and expected outputs, demonstrating fundamental Java programming concepts.

Uploaded by

yosik58501
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)
4 views

Java

The document is a practical file for a Java course (BCA203C) submitted by a student at Hindu Institute of Management. It includes an index of various Java programs covering topics such as prime number calculation, string manipulation, array operations, matrix multiplication, and object counting. Each program is accompanied by code snippets and expected outputs, demonstrating fundamental Java programming concepts.

Uploaded by

yosik58501
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
You are on page 1/ 54

Department of Computer Application

HINDU INSTITUTE OF MANGEMENT


(Affiliated to DCRUST, Murthal | Approved by AICTE, New Delhi)

JAVA
BCA203C
Practical File
(2023-2024)

Submitted to: Submitted by:


Mr. Ajay Bajaj Vishesh
BCA(4th Sem.)
2301204105
INDEX
S.n Program Name P.no Sign
o
1 Prime Number b/w n1 and n2 1-5
2 Convert Integer to String 5-6
3 Display Inputed Values 7-8
4 Concatenation of 2 Strings 9-10
5 String Operations 11-13
6 Largest in Array 14-16
7 Second Largest in Array 17-19
8 Multiplication of 3x3 Array 20-23
9 Area of different shapes 24-25
10 Initialize Private Variable 26-27
11 Initialize Var. without public 28-30
12 Display private variables i and j 31-32
13 Count number of Objects 33-34
14 Addition of 2 Objects 35-37
15 Access Modifiers 38-41
16 Abstract Class 42-43
17 Super keyword to show Variables 44-45
18 Super keyword to show Methods 46-47
19 Exception Handling 48-49
20 Multithreading using Thread class 50-51
21 Multithreading using Runnable Int. 52-53
1.) Program to Print “Hello World” in Java.

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

Output:
2.) Program to find Prime Number between two
numbers.

import java.util.Scanner;

public class PrimeNumbersRange {

// Method to check if a number is prime

public static boolean isPrime(int num) {

if (num <= 1) {

return false;

for (int i = 2; i <= Math.sqrt(num); i++) {

if (num % i == 0) {

return false;

return true;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input from the user


System.out.print("Enter the starting number (n1): ");

int n1 = scanner.nextInt();

System.out.print("Enter the ending number (n2): ");

int n2 = scanner.nextInt();

if (n1 > n2) {

System.out.println("Invalid range. Ensure n1 <= n2.");

} else {

System.out.println("Prime numbers between " + n1 + " and " + n2 + ":");

boolean found = false;

for (int i = n1; i <= n2; i++) {

if (isPrime(i)) {

System.out.print(i + " ");

found = true;

if (!found) {

System.out.println("There are no prime numbers in this range.");

} scanner.close();

}
Output:
3.) Program to Convert String to Integer and
Integer to String.

import java.util.Scanner;

public class StringIntegerConversion {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Convert String to Integer

System.out.print("Enter a number as a string: ");

String numberAsString = scanner.nextLine();

try {

int stringToInt = Integer.parseInt(numberAsString);

System.out.println("Converted String to Integer: " + stringToInt);

} catch (NumberFormatException e) {

System.out.println("Invalid input! The string cannot be converted to an


integer.");

// Convert Integer to String

System.out.print("Enter a number as an integer: ");

int numberAsInt = scanner.nextInt();


String intToString = Integer.toString(numberAsInt);

System.out.println("Converted Integer to String: " + intToString);

scanner.close();

Output:
4.) Program to display Input in Variables of
different data type.

import java.util.Scanner;

public class ExcludeSpecificDataTypes {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Accept inputs for the specified data types

System.out.print("Enter an int value: ");

int intValue = scanner.nextInt();

System.out.print("Enter a float value: ");

float floatValue = scanner.nextFloat();

System.out.print("Enter a char value: ");

char charValue = scanner.next().charAt(0);

System.out.print("Enter a string: ");

scanner.nextLine(); // Consume the leftover newline

String stringValue = scanner.nextLine();


// Display the entered values

System.out.println("\nYou entered:");

System.out.println("Int: " + intValue);

System.out.println("Float: " + floatValue);

System.out.println("Char: " + charValue);

System.out.println("String: " + stringValue);

scanner.close();

Output:
5.) Program to concatenate two Strings.

import java.util.Scanner;

public class StringConcatenation {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input for the first string

System.out.print("Enter the first string: ");

String firstString = scanner.nextLine();

// Input for the second string

System.out.print("Enter the second string: ");

String secondString = scanner.nextLine();

// Concatenate the two strings

String concatenatedString = firstString + secondString;

// Display the concatenated string


System.out.println("Concatenated String: " + concatenatedString);

scanner.close();

Output:
6.) Program to check whether a string is empty,
length of string, remove the white spaces, compare
two string, convert the upper case string to lower
case.

import java.util.Scanner;

public class StringOperations {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Check if a string is empty

System.out.print("Enter a string to check if it's empty: ");

String inputString = scanner.nextLine();

if (inputString.isEmpty()) {

System.out.println("The string is empty.");

} else {

System.out.println("The string is not empty.");

// Length of the string


System.out.println("The length of the string is: " + inputString.length());

// Remove white spaces

String stringWithoutSpaces = inputString.replaceAll("\\s", "");

System.out.println("String without white spaces: " + stringWithoutSpaces);

// Compare two strings

System.out.print("Enter the first string to compare: ");

String firstString = scanner.nextLine();

System.out.print("Enter the second string to compare: ");

String secondString = scanner.nextLine();

if (firstString.equals(secondString)) {

System.out.println("The two strings are equal.");

} else {

System.out.println("The two strings are not equal.");

// Convert uppercase string to lowercase

System.out.print("Enter a string in uppercase: ");

String upperCaseString = scanner.nextLine();

String lowerCaseString = upperCaseString.toLowerCase();

System.out.println("The string in lowercase is: " + lowerCaseString);


scanner.close();

Output:
7.) Program to find Largest number in an Array.

import java.util.Scanner;

public class LargestElementInArray {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input array size

System.out.print("Enter the size of the array: ");

int size = scanner.nextInt();

if (size <= 0) {

System.out.println("Array size must be greater than 0.");

return;

int[] array = new int[size];

// Input array elements


System.out.println("Enter the elements of the array:");

for (int i = 0; i < size; i++) {

array[i] = scanner.nextInt();

// Initialize the largest element

int largest = array[0];

// Find the largest element

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

if (array[i] > largest) {

largest = array[i];

// Display the largest element

System.out.println("The largest element in the array is: " + largest);

scanner.close();

}
 Output:
8.) Program to find 2nd largest number in an Array.

import java.util.Scanner;

public class SecondMaximum {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input array size

System.out.print("Enter the size of the array: ");

int size = scanner.nextInt();

if (size < 2) {

System.out.println("Array must have at least two elements to find the


second maximum.");

return;

int[] array = new int[size];

// Input array elements

System.out.println("Enter the elements of the array:");

for (int i = 0; i < size; i++) {


array[i] = scanner.nextInt();

// Initialize maximum and second maximum

int max = Integer.MIN_VALUE;

int secondMax = Integer.MIN_VALUE;

// Find maximum and second maximum

for (int num : array) {

if (num > max) {

secondMax = max;

max = num;

} else if (num > secondMax && num < max) {

secondMax = num;

// Check if a valid second maximum exists

if (secondMax == Integer.MIN_VALUE) {

System.out.println("There is no second maximum number in the


array.");

} else {
System.out.println("The second maximum number in the array is: " +
secondMax);

scanner.close();

Output:
9.) Write a program to multiply two matrix of 3 X 3
and print the result in matrix format.

import java.util.Scanner;

public class MatrixMultiplication {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Define two 3x3 matrices

int[][] matrix1 = new int[3][3];

int[][] matrix2 = new int[3][3];

int[][] resultMatrix = new int[3][3];

// Input for the first matrix

System.out.println("Enter elements of the first 3x3 matrix:");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

System.out.print("Enter element at [" + i + "][" + j + "]: ");

matrix1[i][j] = scanner.nextInt();

}
}

// Input for the second matrix

System.out.println("Enter elements of the second 3x3 matrix:");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

System.out.print("Enter element at [" + i + "][" + j + "]: ");

matrix2[i][j] = scanner.nextInt();

// Multiply the matrices

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

resultMatrix[i][j] = 0; // Initialize result element

for (int k = 0; k < 3; k++) {

resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j];

// Print the resulting matrix


System.out.println("\nThe resultant matrix after multiplication is:");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

System.out.print(resultMatrix[i][j] + "\t");

System.out.println();

scanner.close();

}
Output:
10.) Program to calculate Area of different Shapes.
(Method Overloading)
class CalculateArea {

// Method to calculate the area of a rectangle

public double Area(double length, double width) {

return length * width;

// Method to calculate the area of a circle

public double Area(double radius) {

return Math.PI * radius * radius;

// Method to calculate the area of a triangle

public double Area(double base, double height, boolean isTriangle) {

return 0.5 * base * height;

public class Main {

public static void main(String[] args) {


CalculateArea calculateArea = new CalculateArea();

// Calculate the area of a rectangle

double rectangleArea = calculateArea.Area(5.0, 3.0);

System.out.println("Area of Rectangle: " + rectangleArea);

// Calculate the area of a circle

double circleArea = calculateArea.Area(4.0);

System.out.println("Area of Circle: " + circleArea);

// Calculate the area of a triangle

double triangleArea = calculateArea.Area(6.0, 4.0, true);

System.out.println("Area of Triangle: " + triangleArea);

Output:
11.) Write a program to initialize the private integer
variable of a class.
import java.util.Scanner;

class MyClass {

// Private integer variable

private int number;

// Method to set the value of the private variable

public void setNumber(int number) {

this.number = number;

// Method to get the value of the private variable

public int getNumber() {

return number;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

MyClass obj = new MyClass();


// Accept input from the user

System.out.print("Enter an integer: ");

int userInput = scanner.nextInt();

// Set the value of the private variable using the setter method

obj.setNumber(userInput);

// Get and print the value of the private variable using the getter method

System.out.println("The value of the variable is: " + obj.getNumber());

scanner.close();

Output:
12.) Program to initialize the private variable of a
class without the use of public functions.
(Constructor)

import java.util.Scanner;

class MyClass {

// Private variable

private int number;

// Constructor to initialize the private variable

MyClass(int number) {

this.number = number;

// Method to display the value of the private variable

void displayNumber() {

System.out.println("The value of the variable is: " + number);

public class Main {


public static void main(String[] args) {

System.out.println("Enter value of Integer");

Scanner sc = new Scanner(System.in);

int a = sc.nextInt();

// Initialize the private variable using the constructor

MyClass obj = new MyClass(a);

// Print the value of the private variable

obj.displayNumber();

Output:
13.) Program with a Test class containing a
display method that prints private variables i and
j.
class Test {

private int i; // Private variable i

private int j; // Private variable j

// Constructor to initialize i and j

Test(int i, int j) {

this.i = i;

this.j = j;

// Display function to print the values of i and j

void display() {

System.out.println("i: " + i + ", j: " + j);

public class Main {

public static void main(String[] args) {

// Object obj1: i = 0, j = 0

Test obj1 = new Test(0, 0);


obj1.display();

// Object obj2: i = 10, j = 0

Test obj2 = new Test(10, 0);

obj2.display();

// Object obj3: i = 20, j = 30

Test obj3 = new Test(20, 30);

obj3.display();

Output:
14.) Program to count the number of object
created of a class.

class Test {

// Static variable to count objects

private static int objectCount = 0;

// Constructor increments objectCount each time an object is created

Test() {

objectCount++;

// Method to get the total count of objects

public static int getObjectCount() {

return objectCount;

public class Main {

public static void main(String[] args) {

// Create objects of Test class


Test obj1 = new Test();

Test obj2 = new Test();

Test obj3 = new Test();

// Print the total number of objects created

System.out.println("Total number of objects created: " +


Test.getObjectCount());

Output:
15.) Program to add 2 objects and store the result
in third object where all objects in same class.
class Test {

// Private variables

private int i;

private int j;

// Constructor to initialize variables

Test(int i, int j) {

this.i = i;

this.j = j;

// Method to add the values of two objects and return a new object

public Test add(Test other) {

int newI = this.i + other.i;

int newJ = this.j + other.j;

return new Test(newI, newJ);

// Method to display the values of i and j


public void display() {

System.out.println("i: " + i + ", j: " + j);

public class Main {

public static void main(String[] args) {

// Create objects obj1 and obj2

Test obj1 = new Test(5, 10);

Test obj2 = new Test(15, 20);

// Add values of obj1 and obj2, store the result in obj3

Test obj3 = obj1.add(obj2);

// Display the values of all three objects

System.out.println("Values in obj1:");

obj1.display();

System.out.println("Values in obj2:");

obj2.display();

System.out.println("Values in obj3 (result of addition):");


obj3.display();

Output:
16.) Program having Access modifiers which store
and print the values by making objects of 2 classes.

class A {

int defaultVar; // Default access

private int privateVar; // Private access

protected int protectedVar; // Protected access

public int publicVar; // Public access

// Constructor to initialize all variables

A() {

defaultVar = 10;

privateVar = 20;

protectedVar = 30;

publicVar = 40;

// Public method to access and print all variables

public void AccessAll() {

System.out.println("Class A - defaultVar: " + defaultVar);

System.out.println("Class A - privateVar: " + privateVar);


System.out.println("Class A - protectedVar: " + protectedVar);

System.out.println("Class A - publicVar: " + publicVar);

// Getter for private variable

public int getPrivateVar() {

return privateVar;

// Class B derived from Class A

class B extends A {

// Public method to access all variables from Class A

public void accessFromB() {

System.out.println("Class B - defaultVar: " + defaultVar); // Accessible

// System.out.println("Class B - privateVar: " + privateVar); // Not accessible

System.out.println("Class B - protectedVar: " + protectedVar); // Accessible

System.out.println("Class B - publicVar: " + publicVar); // Accessible

public class Main {


public static void main(String[] args) {

// Object of Class A

A objA = new A();

System.out.println("Accessing from Class A:");

objA.AccessAll();

// Object of Class B

B objB = new B();

System.out.println("\nAccessing from Class B:");

objB.accessFromB();

// Accessing privateVar using getter

System.out.println("\nAccessing privateVar of Class A using getter: " +


objA.getPrivateVar());

}
Output:
17.) Program for division of 2 numbers using
Abstract Function and multiplication of 2
numbers using derived functions.

// Abstract class
abstract class Abst {
// Abstract method
abstract int calculate(int a, int b);
}

// Derived class for division


class Divide extends Abst {
@Override
int calculate(int a, int b) {
if (b == 0) {
System.out.println("Division by zero is not allowed.");
return 0;
}
return a / b;
}
}

// Derived class for multiplication


class Multiply extends Abst {
@Override
int calculate(int a, int b) {
return a * b;
}
}

// Main class
public class Calculator {
public static void main(String[] args) {
Abst calculator;

// Perform division
calculator = new Divide();
System.out.println("Division Result: " +
calculator.calculate(20, 4));

// Perform multiplication
calculator = new Multiply();
System.out.println("Multiplication Result: " +
calculator.calculate(20, 4));
}
}

Output:
18.) Program using Super keyword to show hidden
Variables of Base class.

// Base class

class Base {

String message = "Message from Base class";

// Derived class

class Derived extends Base {

String message = "Message from Derived class";

void displayMessages() {

System.out.println("Accessing hidden variable in Derived class: " + message);

System.out.println("Accessing hidden variable in Base class using super: " +


super.message);

// Main class

public class SuperKeywordExample {


public static void main(String[] args) {

Derived obj = new Derived();

obj.displayMessages();

Output:
19.) Program of using Super keyword to show
methods of base class.

// Base class
class Base {
void display() {
System.out.println("This is the Base class method.");
}
}

// Derived class
class Derived extends Base {
@Override
void display() {
System.out.println("This is the Derived class method.");
}

void showMethods() {
System.out.println("Calling Derived class method:");
this.display(); // Calls the Derived class method

System.out.println("Calling Base class method using super:");


super.display(); // Calls the Base class method
}
}

// Main class
public class SuperMethodExample {
public static void main(String[] args) {
Derived obj = new Derived();
obj.showMethods();
}
}

Output:
20.) Program of Exception handling with Checked
and Unchecked Exception.
import java.io.File;

import java.io.FileReader;

public class ExceptionHandlingExample {

public static void main(String[] args) {

// Handling an unchecked exception (ArithmeticException)

try {

int result = 10 / 0; // This will throw an ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Unchecked Exception Caught: " + e.getMessage());

// Handling a checked exception (FileNotFoundException)

try {

File file = new File("nonexistentfile.txt");

FileReader fr = new FileReader(file); // This will throw a


FileNotFoundException

} catch (java.io.FileNotFoundException e) {
System.out.println("Checked Exception Caught: " + e.getMessage());

System.out.println("Program execution continues...");

Output:
21.) Program for Multithreading using Thread class.
class MyThread extends Thread {

public void run() {

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

System.out.println(Thread.currentThread().getName() + " - Count: " + i);

try {

Thread.sleep(500); // Pause for 500ms

} catch (InterruptedException e) {

System.out.println(e.getMessage());

public class ThreadExample {

public static void main(String[] args) {

MyThread thread1 = new MyThread();

MyThread thread2 = new MyThread();

thread1.setName("Thread 1");
thread2.setName("Thread 2");

thread1.start();

thread2.start();

Output:
22.) Program for Multithreading using Runnable
Interface.
class MyRunnable implements Runnable {

public void run() {

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

System.out.println(Thread.currentThread().getName() + " - Count: " + i);

try {

Thread.sleep(500); // Pause for 500ms

} catch (InterruptedException e) {

System.out.println(e.getMessage());

public class RunnableExample {

public static void main(String[] args) {

MyRunnable myRunnable = new MyRunnable();

Thread thread1 = new Thread(myRunnable, "Thread 1");

Thread thread2 = new Thread(myRunnable, "Thread 2");


thread1.start();

thread2.start();

Output:

You might also like